MIPS: Add microMIPS XPA support
[external/binutils.git] / gas / config / tc-mips.c
1 /* tc-mips.c -- assemble code for a MIPS chip.
2    Copyright (C) 1993-2017 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 static char *mips_flags_frag;
93
94 #define ZERO 0
95 #define ATREG 1
96 #define S0  16
97 #define S7  23
98 #define TREG 24
99 #define PIC_CALL_REG 25
100 #define KT0 26
101 #define KT1 27
102 #define GP  28
103 #define SP  29
104 #define FP  30
105 #define RA  31
106
107 #define ILLEGAL_REG (32)
108
109 #define AT  mips_opts.at
110
111 extern int target_big_endian;
112
113 /* The name of the readonly data section.  */
114 #define RDATA_SECTION_NAME ".rodata"
115
116 /* Ways in which an instruction can be "appended" to the output.  */
117 enum append_method {
118   /* Just add it normally.  */
119   APPEND_ADD,
120
121   /* Add it normally and then add a nop.  */
122   APPEND_ADD_WITH_NOP,
123
124   /* Turn an instruction with a delay slot into a "compact" version.  */
125   APPEND_ADD_COMPACT,
126
127   /* Insert the instruction before the last one.  */
128   APPEND_SWAP
129 };
130
131 /* Information about an instruction, including its format, operands
132    and fixups.  */
133 struct mips_cl_insn
134 {
135   /* The opcode's entry in mips_opcodes or mips16_opcodes.  */
136   const struct mips_opcode *insn_mo;
137
138   /* The 16-bit or 32-bit bitstring of the instruction itself.  This is
139      a copy of INSN_MO->match with the operands filled in.  If we have
140      decided to use an extended MIPS16 instruction, this includes the
141      extension.  */
142   unsigned long insn_opcode;
143
144   /* The frag that contains the instruction.  */
145   struct frag *frag;
146
147   /* The offset into FRAG of the first instruction byte.  */
148   long where;
149
150   /* The relocs associated with the instruction, if any.  */
151   fixS *fixp[3];
152
153   /* True if this entry cannot be moved from its current position.  */
154   unsigned int fixed_p : 1;
155
156   /* True if this instruction occurred in a .set noreorder block.  */
157   unsigned int noreorder_p : 1;
158
159   /* True for mips16 instructions that jump to an absolute address.  */
160   unsigned int mips16_absolute_jump_p : 1;
161
162   /* True if this instruction is complete.  */
163   unsigned int complete_p : 1;
164
165   /* True if this instruction is cleared from history by unconditional
166      branch.  */
167   unsigned int cleared_p : 1;
168 };
169
170 /* The ABI to use.  */
171 enum mips_abi_level
172 {
173   NO_ABI = 0,
174   O32_ABI,
175   O64_ABI,
176   N32_ABI,
177   N64_ABI,
178   EABI_ABI
179 };
180
181 /* MIPS ABI we are using for this output file.  */
182 static enum mips_abi_level mips_abi = NO_ABI;
183
184 /* Whether or not we have code that can call pic code.  */
185 int mips_abicalls = FALSE;
186
187 /* Whether or not we have code which can be put into a shared
188    library.  */
189 static bfd_boolean mips_in_shared = TRUE;
190
191 /* This is the set of options which may be modified by the .set
192    pseudo-op.  We use a struct so that .set push and .set pop are more
193    reliable.  */
194
195 struct mips_set_options
196 {
197   /* MIPS ISA (Instruction Set Architecture) level.  This is set to -1
198      if it has not been initialized.  Changed by `.set mipsN', and the
199      -mipsN command line option, and the default CPU.  */
200   int isa;
201   /* Enabled Application Specific Extensions (ASEs).  Changed by `.set
202      <asename>', by command line options, and based on the default
203      architecture.  */
204   int ase;
205   /* Whether we are assembling for the mips16 processor.  0 if we are
206      not, 1 if we are, and -1 if the value has not been initialized.
207      Changed by `.set mips16' and `.set nomips16', and the -mips16 and
208      -nomips16 command line options, and the default CPU.  */
209   int mips16;
210   /* Whether we are assembling for the mipsMIPS ASE.  0 if we are not,
211      1 if we are, and -1 if the value has not been initialized.  Changed
212      by `.set micromips' and `.set nomicromips', and the -mmicromips
213      and -mno-micromips command line options, and the default CPU.  */
214   int micromips;
215   /* Non-zero if we should not reorder instructions.  Changed by `.set
216      reorder' and `.set noreorder'.  */
217   int noreorder;
218   /* Non-zero if we should not permit the register designated "assembler
219      temporary" to be used in instructions.  The value is the register
220      number, normally $at ($1).  Changed by `.set at=REG', `.set noat'
221      (same as `.set at=$0') and `.set at' (same as `.set at=$1').  */
222   unsigned int at;
223   /* Non-zero if we should warn when a macro instruction expands into
224      more than one machine instruction.  Changed by `.set nomacro' and
225      `.set macro'.  */
226   int warn_about_macros;
227   /* Non-zero if we should not move instructions.  Changed by `.set
228      move', `.set volatile', `.set nomove', and `.set novolatile'.  */
229   int nomove;
230   /* Non-zero if we should not optimize branches by moving the target
231      of the branch into the delay slot.  Actually, we don't perform
232      this optimization anyhow.  Changed by `.set bopt' and `.set
233      nobopt'.  */
234   int nobopt;
235   /* Non-zero if we should not autoextend mips16 instructions.
236      Changed by `.set autoextend' and `.set noautoextend'.  */
237   int noautoextend;
238   /* True if we should only emit 32-bit microMIPS instructions.
239      Changed by `.set insn32' and `.set noinsn32', and the -minsn32
240      and -mno-insn32 command line options.  */
241   bfd_boolean insn32;
242   /* Restrict general purpose registers and floating point registers
243      to 32 bit.  This is initially determined when -mgp32 or -mfp32
244      is passed but can changed if the assembler code uses .set mipsN.  */
245   int gp;
246   int fp;
247   /* MIPS architecture (CPU) type.  Changed by .set arch=FOO, the -march
248      command line option, and the default CPU.  */
249   int arch;
250   /* True if ".set sym32" is in effect.  */
251   bfd_boolean sym32;
252   /* True if floating-point operations are not allowed.  Changed by .set
253      softfloat or .set hardfloat, by command line options -msoft-float or
254      -mhard-float.  The default is false.  */
255   bfd_boolean soft_float;
256
257   /* True if only single-precision floating-point operations are allowed.
258      Changed by .set singlefloat or .set doublefloat, command-line options
259      -msingle-float or -mdouble-float.  The default is false.  */
260   bfd_boolean single_float;
261
262   /* 1 if single-precision operations on odd-numbered registers are
263      allowed.  */
264   int oddspreg;
265 };
266
267 /* Specifies whether module level options have been checked yet.  */
268 static bfd_boolean file_mips_opts_checked = FALSE;
269
270 /* Do we support nan2008?  0 if we don't, 1 if we do, and -1 if the
271    value has not been initialized.  Changed by `.nan legacy' and
272    `.nan 2008', and the -mnan=legacy and -mnan=2008 command line
273    options, and the default CPU.  */
274 static int mips_nan2008 = -1;
275
276 /* This is the struct we use to hold the module level set of options.
277    Note that we must set the isa field to ISA_UNKNOWN and the ASE, gp and
278    fp fields to -1 to indicate that they have not been initialized.  */
279
280 static struct mips_set_options file_mips_opts =
281 {
282   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
283   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
284   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ FALSE,
285   /* gp */ -1, /* fp */ -1, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
286   /* soft_float */ FALSE, /* single_float */ FALSE, /* oddspreg */ -1
287 };
288
289 /* This is similar to file_mips_opts, but for the current set of options.  */
290
291 static struct mips_set_options mips_opts =
292 {
293   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
294   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
295   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ FALSE,
296   /* gp */ -1, /* fp */ -1, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
297   /* soft_float */ FALSE, /* single_float */ FALSE, /* oddspreg */ -1
298 };
299
300 /* Which bits of file_ase were explicitly set or cleared by ASE options.  */
301 static unsigned int file_ase_explicit;
302
303 /* These variables are filled in with the masks of registers used.
304    The object format code reads them and puts them in the appropriate
305    place.  */
306 unsigned long mips_gprmask;
307 unsigned long mips_cprmask[4];
308
309 /* True if any MIPS16 code was produced.  */
310 static int file_ase_mips16;
311
312 #define ISA_SUPPORTS_MIPS16E (mips_opts.isa == ISA_MIPS32               \
313                               || mips_opts.isa == ISA_MIPS32R2          \
314                               || mips_opts.isa == ISA_MIPS32R3          \
315                               || mips_opts.isa == ISA_MIPS32R5          \
316                               || mips_opts.isa == ISA_MIPS64            \
317                               || mips_opts.isa == ISA_MIPS64R2          \
318                               || mips_opts.isa == ISA_MIPS64R3          \
319                               || mips_opts.isa == ISA_MIPS64R5)
320
321 /* True if any microMIPS code was produced.  */
322 static int file_ase_micromips;
323
324 /* True if we want to create R_MIPS_JALR for jalr $25.  */
325 #ifdef TE_IRIX
326 #define MIPS_JALR_HINT_P(EXPR) HAVE_NEWABI
327 #else
328 /* As a GNU extension, we use R_MIPS_JALR for o32 too.  However,
329    because there's no place for any addend, the only acceptable
330    expression is a bare symbol.  */
331 #define MIPS_JALR_HINT_P(EXPR) \
332   (!HAVE_IN_PLACE_ADDENDS \
333    || ((EXPR)->X_op == O_symbol && (EXPR)->X_add_number == 0))
334 #endif
335
336 /* The argument of the -march= flag.  The architecture we are assembling.  */
337 static const char *mips_arch_string;
338
339 /* The argument of the -mtune= flag.  The architecture for which we
340    are optimizing.  */
341 static int mips_tune = CPU_UNKNOWN;
342 static const char *mips_tune_string;
343
344 /* True when generating 32-bit code for a 64-bit processor.  */
345 static int mips_32bitmode = 0;
346
347 /* True if the given ABI requires 32-bit registers.  */
348 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
349
350 /* Likewise 64-bit registers.  */
351 #define ABI_NEEDS_64BIT_REGS(ABI)       \
352   ((ABI) == N32_ABI                     \
353    || (ABI) == N64_ABI                  \
354    || (ABI) == O64_ABI)
355
356 #define ISA_IS_R6(ISA)                  \
357   ((ISA) == ISA_MIPS32R6                \
358    || (ISA) == ISA_MIPS64R6)
359
360 /*  Return true if ISA supports 64 bit wide gp registers.  */
361 #define ISA_HAS_64BIT_REGS(ISA)         \
362   ((ISA) == ISA_MIPS3                   \
363    || (ISA) == ISA_MIPS4                \
364    || (ISA) == ISA_MIPS5                \
365    || (ISA) == ISA_MIPS64               \
366    || (ISA) == ISA_MIPS64R2             \
367    || (ISA) == ISA_MIPS64R3             \
368    || (ISA) == ISA_MIPS64R5             \
369    || (ISA) == ISA_MIPS64R6)
370
371 /*  Return true if ISA supports 64 bit wide float registers.  */
372 #define ISA_HAS_64BIT_FPRS(ISA)         \
373   ((ISA) == ISA_MIPS3                   \
374    || (ISA) == ISA_MIPS4                \
375    || (ISA) == ISA_MIPS5                \
376    || (ISA) == ISA_MIPS32R2             \
377    || (ISA) == ISA_MIPS32R3             \
378    || (ISA) == ISA_MIPS32R5             \
379    || (ISA) == ISA_MIPS32R6             \
380    || (ISA) == ISA_MIPS64               \
381    || (ISA) == ISA_MIPS64R2             \
382    || (ISA) == ISA_MIPS64R3             \
383    || (ISA) == ISA_MIPS64R5             \
384    || (ISA) == ISA_MIPS64R6)
385
386 /* Return true if ISA supports 64-bit right rotate (dror et al.)
387    instructions.  */
388 #define ISA_HAS_DROR(ISA)               \
389   ((ISA) == ISA_MIPS64R2                \
390    || (ISA) == ISA_MIPS64R3             \
391    || (ISA) == ISA_MIPS64R5             \
392    || (ISA) == ISA_MIPS64R6             \
393    || (mips_opts.micromips              \
394        && ISA_HAS_64BIT_REGS (ISA))     \
395    )
396
397 /* Return true if ISA supports 32-bit right rotate (ror et al.)
398    instructions.  */
399 #define ISA_HAS_ROR(ISA)                \
400   ((ISA) == ISA_MIPS32R2                \
401    || (ISA) == ISA_MIPS32R3             \
402    || (ISA) == ISA_MIPS32R5             \
403    || (ISA) == ISA_MIPS32R6             \
404    || (ISA) == ISA_MIPS64R2             \
405    || (ISA) == ISA_MIPS64R3             \
406    || (ISA) == ISA_MIPS64R5             \
407    || (ISA) == ISA_MIPS64R6             \
408    || (mips_opts.ase & ASE_SMARTMIPS)   \
409    || mips_opts.micromips               \
410    )
411
412 /* Return true if ISA supports single-precision floats in odd registers.  */
413 #define ISA_HAS_ODD_SINGLE_FPR(ISA, CPU)\
414   (((ISA) == ISA_MIPS32                 \
415     || (ISA) == ISA_MIPS32R2            \
416     || (ISA) == ISA_MIPS32R3            \
417     || (ISA) == ISA_MIPS32R5            \
418     || (ISA) == ISA_MIPS32R6            \
419     || (ISA) == ISA_MIPS64              \
420     || (ISA) == ISA_MIPS64R2            \
421     || (ISA) == ISA_MIPS64R3            \
422     || (ISA) == ISA_MIPS64R5            \
423     || (ISA) == ISA_MIPS64R6            \
424     || (CPU) == CPU_R5900)              \
425    && (CPU) != CPU_LOONGSON_3A)
426
427 /* Return true if ISA supports move to/from high part of a 64-bit
428    floating-point register. */
429 #define ISA_HAS_MXHC1(ISA)              \
430   ((ISA) == ISA_MIPS32R2                \
431    || (ISA) == ISA_MIPS32R3             \
432    || (ISA) == ISA_MIPS32R5             \
433    || (ISA) == ISA_MIPS32R6             \
434    || (ISA) == ISA_MIPS64R2             \
435    || (ISA) == ISA_MIPS64R3             \
436    || (ISA) == ISA_MIPS64R5             \
437    || (ISA) == ISA_MIPS64R6)
438
439 /*  Return true if ISA supports legacy NAN.  */
440 #define ISA_HAS_LEGACY_NAN(ISA)         \
441   ((ISA) == ISA_MIPS1                   \
442    || (ISA) == ISA_MIPS2                \
443    || (ISA) == ISA_MIPS3                \
444    || (ISA) == ISA_MIPS4                \
445    || (ISA) == ISA_MIPS5                \
446    || (ISA) == ISA_MIPS32               \
447    || (ISA) == ISA_MIPS32R2             \
448    || (ISA) == ISA_MIPS32R3             \
449    || (ISA) == ISA_MIPS32R5             \
450    || (ISA) == ISA_MIPS64               \
451    || (ISA) == ISA_MIPS64R2             \
452    || (ISA) == ISA_MIPS64R3             \
453    || (ISA) == ISA_MIPS64R5)
454
455 #define GPR_SIZE \
456     (mips_opts.gp == 64 && !ISA_HAS_64BIT_REGS (mips_opts.isa) \
457      ? 32 \
458      : mips_opts.gp)
459
460 #define FPR_SIZE \
461     (mips_opts.fp == 64 && !ISA_HAS_64BIT_FPRS (mips_opts.isa) \
462      ? 32 \
463      : mips_opts.fp)
464
465 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
466
467 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
468
469 /* True if relocations are stored in-place.  */
470 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
471
472 /* The ABI-derived address size.  */
473 #define HAVE_64BIT_ADDRESSES \
474   (GPR_SIZE == 64 && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
475 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
476
477 /* The size of symbolic constants (i.e., expressions of the form
478    "SYMBOL" or "SYMBOL + OFFSET").  */
479 #define HAVE_32BIT_SYMBOLS \
480   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
481 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
482
483 /* Addresses are loaded in different ways, depending on the address size
484    in use.  The n32 ABI Documentation also mandates the use of additions
485    with overflow checking, but existing implementations don't follow it.  */
486 #define ADDRESS_ADD_INSN                                                \
487    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
488
489 #define ADDRESS_ADDI_INSN                                               \
490    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
491
492 #define ADDRESS_LOAD_INSN                                               \
493    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
494
495 #define ADDRESS_STORE_INSN                                              \
496    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
497
498 /* Return true if the given CPU supports the MIPS16 ASE.  */
499 #define CPU_HAS_MIPS16(cpu)                                             \
500    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
501     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
502
503 /* Return true if the given CPU supports the microMIPS ASE.  */
504 #define CPU_HAS_MICROMIPS(cpu)  0
505
506 /* True if CPU has a dror instruction.  */
507 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
508
509 /* True if CPU has a ror instruction.  */
510 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
511
512 /* True if CPU is in the Octeon family */
513 #define CPU_IS_OCTEON(CPU) ((CPU) == CPU_OCTEON || (CPU) == CPU_OCTEONP \
514                             || (CPU) == CPU_OCTEON2 || (CPU) == CPU_OCTEON3)
515
516 /* True if CPU has seq/sne and seqi/snei instructions.  */
517 #define CPU_HAS_SEQ(CPU)        (CPU_IS_OCTEON (CPU))
518
519 /* True, if CPU has support for ldc1 and sdc1. */
520 #define CPU_HAS_LDC1_SDC1(CPU)  \
521    ((mips_opts.isa != ISA_MIPS1) && ((CPU) != CPU_R5900))
522
523 /* True if mflo and mfhi can be immediately followed by instructions
524    which write to the HI and LO registers.
525
526    According to MIPS specifications, MIPS ISAs I, II, and III need
527    (at least) two instructions between the reads of HI/LO and
528    instructions which write them, and later ISAs do not.  Contradicting
529    the MIPS specifications, some MIPS IV processor user manuals (e.g.
530    the UM for the NEC Vr5000) document needing the instructions between
531    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
532    MIPS64 and later ISAs to have the interlocks, plus any specific
533    earlier-ISA CPUs for which CPU documentation declares that the
534    instructions are really interlocked.  */
535 #define hilo_interlocks \
536   (mips_opts.isa == ISA_MIPS32                        \
537    || mips_opts.isa == ISA_MIPS32R2                   \
538    || mips_opts.isa == ISA_MIPS32R3                   \
539    || mips_opts.isa == ISA_MIPS32R5                   \
540    || mips_opts.isa == ISA_MIPS32R6                   \
541    || mips_opts.isa == ISA_MIPS64                     \
542    || mips_opts.isa == ISA_MIPS64R2                   \
543    || mips_opts.isa == ISA_MIPS64R3                   \
544    || mips_opts.isa == ISA_MIPS64R5                   \
545    || mips_opts.isa == ISA_MIPS64R6                   \
546    || mips_opts.arch == CPU_R4010                     \
547    || mips_opts.arch == CPU_R5900                     \
548    || mips_opts.arch == CPU_R10000                    \
549    || mips_opts.arch == CPU_R12000                    \
550    || mips_opts.arch == CPU_R14000                    \
551    || mips_opts.arch == CPU_R16000                    \
552    || mips_opts.arch == CPU_RM7000                    \
553    || mips_opts.arch == CPU_VR5500                    \
554    || mips_opts.micromips                             \
555    )
556
557 /* Whether the processor uses hardware interlocks to protect reads
558    from the GPRs after they are loaded from memory, and thus does not
559    require nops to be inserted.  This applies to instructions marked
560    INSN_LOAD_MEMORY.  These nops are only required at MIPS ISA
561    level I and microMIPS mode instructions are always interlocked.  */
562 #define gpr_interlocks                                \
563   (mips_opts.isa != ISA_MIPS1                         \
564    || mips_opts.arch == CPU_R3900                     \
565    || mips_opts.arch == CPU_R5900                     \
566    || mips_opts.micromips                             \
567    )
568
569 /* Whether the processor uses hardware interlocks to avoid delays
570    required by coprocessor instructions, and thus does not require
571    nops to be inserted.  This applies to instructions marked
572    INSN_LOAD_COPROC, INSN_COPROC_MOVE, and to delays between
573    instructions marked INSN_WRITE_COND_CODE and ones marked
574    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
575    levels I, II, and III and microMIPS mode instructions are always
576    interlocked.  */
577 /* Itbl support may require additional care here.  */
578 #define cop_interlocks                                \
579   ((mips_opts.isa != ISA_MIPS1                        \
580     && mips_opts.isa != ISA_MIPS2                     \
581     && mips_opts.isa != ISA_MIPS3)                    \
582    || mips_opts.arch == CPU_R4300                     \
583    || mips_opts.micromips                             \
584    )
585
586 /* Whether the processor uses hardware interlocks to protect reads
587    from coprocessor registers after they are loaded from memory, and
588    thus does not require nops to be inserted.  This applies to
589    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
590    requires at MIPS ISA level I and microMIPS mode instructions are
591    always interlocked.  */
592 #define cop_mem_interlocks                            \
593   (mips_opts.isa != ISA_MIPS1                         \
594    || mips_opts.micromips                             \
595    )
596
597 /* Is this a mfhi or mflo instruction?  */
598 #define MF_HILO_INSN(PINFO) \
599   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
600
601 /* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
602    has been selected.  This implies, in particular, that addresses of text
603    labels have their LSB set.  */
604 #define HAVE_CODE_COMPRESSION                                           \
605   ((mips_opts.mips16 | mips_opts.micromips) != 0)
606
607 /* The minimum and maximum signed values that can be stored in a GPR.  */
608 #define GPR_SMAX ((offsetT) (((valueT) 1 << (GPR_SIZE - 1)) - 1))
609 #define GPR_SMIN (-GPR_SMAX - 1)
610
611 /* MIPS PIC level.  */
612
613 enum mips_pic_level mips_pic;
614
615 /* 1 if we should generate 32 bit offsets from the $gp register in
616    SVR4_PIC mode.  Currently has no meaning in other modes.  */
617 static int mips_big_got = 0;
618
619 /* 1 if trap instructions should used for overflow rather than break
620    instructions.  */
621 static int mips_trap = 0;
622
623 /* 1 if double width floating point constants should not be constructed
624    by assembling two single width halves into two single width floating
625    point registers which just happen to alias the double width destination
626    register.  On some architectures this aliasing can be disabled by a bit
627    in the status register, and the setting of this bit cannot be determined
628    automatically at assemble time.  */
629 static int mips_disable_float_construction;
630
631 /* Non-zero if any .set noreorder directives were used.  */
632
633 static int mips_any_noreorder;
634
635 /* Non-zero if nops should be inserted when the register referenced in
636    an mfhi/mflo instruction is read in the next two instructions.  */
637 static int mips_7000_hilo_fix;
638
639 /* The size of objects in the small data section.  */
640 static unsigned int g_switch_value = 8;
641 /* Whether the -G option was used.  */
642 static int g_switch_seen = 0;
643
644 #define N_RMASK 0xc4
645 #define N_VFP   0xd4
646
647 /* If we can determine in advance that GP optimization won't be
648    possible, we can skip the relaxation stuff that tries to produce
649    GP-relative references.  This makes delay slot optimization work
650    better.
651
652    This function can only provide a guess, but it seems to work for
653    gcc output.  It needs to guess right for gcc, otherwise gcc
654    will put what it thinks is a GP-relative instruction in a branch
655    delay slot.
656
657    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
658    fixed it for the non-PIC mode.  KR 95/04/07  */
659 static int nopic_need_relax (symbolS *, int);
660
661 /* handle of the OPCODE hash table */
662 static struct hash_control *op_hash = NULL;
663
664 /* The opcode hash table we use for the mips16.  */
665 static struct hash_control *mips16_op_hash = NULL;
666
667 /* The opcode hash table we use for the microMIPS ASE.  */
668 static struct hash_control *micromips_op_hash = NULL;
669
670 /* This array holds the chars that always start a comment.  If the
671     pre-processor is disabled, these aren't very useful */
672 const char comment_chars[] = "#";
673
674 /* This array holds the chars that only start a comment at the beginning of
675    a line.  If the line seems to have the form '# 123 filename'
676    .line and .file directives will appear in the pre-processed output */
677 /* Note that input_file.c hand checks for '#' at the beginning of the
678    first line of the input file.  This is because the compiler outputs
679    #NO_APP at the beginning of its output.  */
680 /* Also note that C style comments are always supported.  */
681 const char line_comment_chars[] = "#";
682
683 /* This array holds machine specific line separator characters.  */
684 const char line_separator_chars[] = ";";
685
686 /* Chars that can be used to separate mant from exp in floating point nums */
687 const char EXP_CHARS[] = "eE";
688
689 /* Chars that mean this number is a floating point constant */
690 /* As in 0f12.456 */
691 /* or    0d1.2345e12 */
692 const char FLT_CHARS[] = "rRsSfFdDxXpP";
693
694 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
695    changed in read.c .  Ideally it shouldn't have to know about it at all,
696    but nothing is ideal around here.
697  */
698
699 /* Types of printf format used for instruction-related error messages.
700    "I" means int ("%d") and "S" means string ("%s"). */
701 enum mips_insn_error_format {
702   ERR_FMT_PLAIN,
703   ERR_FMT_I,
704   ERR_FMT_SS,
705 };
706
707 /* Information about an error that was found while assembling the current
708    instruction.  */
709 struct mips_insn_error {
710   /* We sometimes need to match an instruction against more than one
711      opcode table entry.  Errors found during this matching are reported
712      against a particular syntactic argument rather than against the
713      instruction as a whole.  We grade these messages so that errors
714      against argument N have a greater priority than an error against
715      any argument < N, since the former implies that arguments up to N
716      were acceptable and that the opcode entry was therefore a closer match.
717      If several matches report an error against the same argument,
718      we only use that error if it is the same in all cases.
719
720      min_argnum is the minimum argument number for which an error message
721      should be accepted.  It is 0 if MSG is against the instruction as
722      a whole.  */
723   int min_argnum;
724
725   /* The printf()-style message, including its format and arguments.  */
726   enum mips_insn_error_format format;
727   const char *msg;
728   union {
729     int i;
730     const char *ss[2];
731   } u;
732 };
733
734 /* The error that should be reported for the current instruction.  */
735 static struct mips_insn_error insn_error;
736
737 static int auto_align = 1;
738
739 /* When outputting SVR4 PIC code, the assembler needs to know the
740    offset in the stack frame from which to restore the $gp register.
741    This is set by the .cprestore pseudo-op, and saved in this
742    variable.  */
743 static offsetT mips_cprestore_offset = -1;
744
745 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
746    more optimizations, it can use a register value instead of a memory-saved
747    offset and even an other register than $gp as global pointer.  */
748 static offsetT mips_cpreturn_offset = -1;
749 static int mips_cpreturn_register = -1;
750 static int mips_gp_register = GP;
751 static int mips_gprel_offset = 0;
752
753 /* Whether mips_cprestore_offset has been set in the current function
754    (or whether it has already been warned about, if not).  */
755 static int mips_cprestore_valid = 0;
756
757 /* This is the register which holds the stack frame, as set by the
758    .frame pseudo-op.  This is needed to implement .cprestore.  */
759 static int mips_frame_reg = SP;
760
761 /* Whether mips_frame_reg has been set in the current function
762    (or whether it has already been warned about, if not).  */
763 static int mips_frame_reg_valid = 0;
764
765 /* To output NOP instructions correctly, we need to keep information
766    about the previous two instructions.  */
767
768 /* Whether we are optimizing.  The default value of 2 means to remove
769    unneeded NOPs and swap branch instructions when possible.  A value
770    of 1 means to not swap branches.  A value of 0 means to always
771    insert NOPs.  */
772 static int mips_optimize = 2;
773
774 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
775    equivalent to seeing no -g option at all.  */
776 static int mips_debug = 0;
777
778 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
779 #define MAX_VR4130_NOPS 4
780
781 /* The maximum number of NOPs needed to fill delay slots.  */
782 #define MAX_DELAY_NOPS 2
783
784 /* The maximum number of NOPs needed for any purpose.  */
785 #define MAX_NOPS 4
786
787 /* A list of previous instructions, with index 0 being the most recent.
788    We need to look back MAX_NOPS instructions when filling delay slots
789    or working around processor errata.  We need to look back one
790    instruction further if we're thinking about using history[0] to
791    fill a branch delay slot.  */
792 static struct mips_cl_insn history[1 + MAX_NOPS];
793
794 /* Arrays of operands for each instruction.  */
795 #define MAX_OPERANDS 6
796 struct mips_operand_array {
797   const struct mips_operand *operand[MAX_OPERANDS];
798 };
799 static struct mips_operand_array *mips_operands;
800 static struct mips_operand_array *mips16_operands;
801 static struct mips_operand_array *micromips_operands;
802
803 /* Nop instructions used by emit_nop.  */
804 static struct mips_cl_insn nop_insn;
805 static struct mips_cl_insn mips16_nop_insn;
806 static struct mips_cl_insn micromips_nop16_insn;
807 static struct mips_cl_insn micromips_nop32_insn;
808
809 /* The appropriate nop for the current mode.  */
810 #define NOP_INSN (mips_opts.mips16                                      \
811                   ? &mips16_nop_insn                                    \
812                   : (mips_opts.micromips                                \
813                      ? (mips_opts.insn32                                \
814                         ? &micromips_nop32_insn                         \
815                         : &micromips_nop16_insn)                        \
816                      : &nop_insn))
817
818 /* The size of NOP_INSN in bytes.  */
819 #define NOP_INSN_SIZE ((mips_opts.mips16                                \
820                         || (mips_opts.micromips && !mips_opts.insn32))  \
821                        ? 2 : 4)
822
823 /* If this is set, it points to a frag holding nop instructions which
824    were inserted before the start of a noreorder section.  If those
825    nops turn out to be unnecessary, the size of the frag can be
826    decreased.  */
827 static fragS *prev_nop_frag;
828
829 /* The number of nop instructions we created in prev_nop_frag.  */
830 static int prev_nop_frag_holds;
831
832 /* The number of nop instructions that we know we need in
833    prev_nop_frag.  */
834 static int prev_nop_frag_required;
835
836 /* The number of instructions we've seen since prev_nop_frag.  */
837 static int prev_nop_frag_since;
838
839 /* Relocations against symbols are sometimes done in two parts, with a HI
840    relocation and a LO relocation.  Each relocation has only 16 bits of
841    space to store an addend.  This means that in order for the linker to
842    handle carries correctly, it must be able to locate both the HI and
843    the LO relocation.  This means that the relocations must appear in
844    order in the relocation table.
845
846    In order to implement this, we keep track of each unmatched HI
847    relocation.  We then sort them so that they immediately precede the
848    corresponding LO relocation.  */
849
850 struct mips_hi_fixup
851 {
852   /* Next HI fixup.  */
853   struct mips_hi_fixup *next;
854   /* This fixup.  */
855   fixS *fixp;
856   /* The section this fixup is in.  */
857   segT seg;
858 };
859
860 /* The list of unmatched HI relocs.  */
861
862 static struct mips_hi_fixup *mips_hi_fixup_list;
863
864 /* The frag containing the last explicit relocation operator.
865    Null if explicit relocations have not been used.  */
866
867 static fragS *prev_reloc_op_frag;
868
869 /* Map mips16 register numbers to normal MIPS register numbers.  */
870
871 static const unsigned int mips16_to_32_reg_map[] =
872 {
873   16, 17, 2, 3, 4, 5, 6, 7
874 };
875
876 /* Map microMIPS register numbers to normal MIPS register numbers.  */
877
878 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
879
880 /* The microMIPS registers with type h.  */
881 static const unsigned int micromips_to_32_reg_h_map1[] =
882 {
883   5, 5, 6, 4, 4, 4, 4, 4
884 };
885 static const unsigned int micromips_to_32_reg_h_map2[] =
886 {
887   6, 7, 7, 21, 22, 5, 6, 7
888 };
889
890 /* The microMIPS registers with type m.  */
891 static const unsigned int micromips_to_32_reg_m_map[] =
892 {
893   0, 17, 2, 3, 16, 18, 19, 20
894 };
895
896 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
897
898 /* Classifies the kind of instructions we're interested in when
899    implementing -mfix-vr4120.  */
900 enum fix_vr4120_class
901 {
902   FIX_VR4120_MACC,
903   FIX_VR4120_DMACC,
904   FIX_VR4120_MULT,
905   FIX_VR4120_DMULT,
906   FIX_VR4120_DIV,
907   FIX_VR4120_MTHILO,
908   NUM_FIX_VR4120_CLASSES
909 };
910
911 /* ...likewise -mfix-loongson2f-jump.  */
912 static bfd_boolean mips_fix_loongson2f_jump;
913
914 /* ...likewise -mfix-loongson2f-nop.  */
915 static bfd_boolean mips_fix_loongson2f_nop;
916
917 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
918 static bfd_boolean mips_fix_loongson2f;
919
920 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
921    there must be at least one other instruction between an instruction
922    of type X and an instruction of type Y.  */
923 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
924
925 /* True if -mfix-vr4120 is in force.  */
926 static int mips_fix_vr4120;
927
928 /* ...likewise -mfix-vr4130.  */
929 static int mips_fix_vr4130;
930
931 /* ...likewise -mfix-24k.  */
932 static int mips_fix_24k;
933
934 /* ...likewise -mfix-rm7000  */
935 static int mips_fix_rm7000;
936
937 /* ...likewise -mfix-cn63xxp1 */
938 static bfd_boolean mips_fix_cn63xxp1;
939
940 /* We don't relax branches by default, since this causes us to expand
941    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
942    fail to compute the offset before expanding the macro to the most
943    efficient expansion.  */
944
945 static int mips_relax_branch;
946
947 /* TRUE if checks are suppressed for invalid branches between ISA modes.
948    Needed for broken assembly produced by some GCC versions and some
949    sloppy code out there, where branches to data labels are present.  */
950 static bfd_boolean mips_ignore_branch_isa;
951 \f
952 /* The expansion of many macros depends on the type of symbol that
953    they refer to.  For example, when generating position-dependent code,
954    a macro that refers to a symbol may have two different expansions,
955    one which uses GP-relative addresses and one which uses absolute
956    addresses.  When generating SVR4-style PIC, a macro may have
957    different expansions for local and global symbols.
958
959    We handle these situations by generating both sequences and putting
960    them in variant frags.  In position-dependent code, the first sequence
961    will be the GP-relative one and the second sequence will be the
962    absolute one.  In SVR4 PIC, the first sequence will be for global
963    symbols and the second will be for local symbols.
964
965    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
966    SECOND are the lengths of the two sequences in bytes.  These fields
967    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
968    the subtype has the following flags:
969
970    RELAX_PIC
971         Set if generating PIC code.
972
973    RELAX_USE_SECOND
974         Set if it has been decided that we should use the second
975         sequence instead of the first.
976
977    RELAX_SECOND_LONGER
978         Set in the first variant frag if the macro's second implementation
979         is longer than its first.  This refers to the macro as a whole,
980         not an individual relaxation.
981
982    RELAX_NOMACRO
983         Set in the first variant frag if the macro appeared in a .set nomacro
984         block and if one alternative requires a warning but the other does not.
985
986    RELAX_DELAY_SLOT
987         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
988         delay slot.
989
990    RELAX_DELAY_SLOT_16BIT
991         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
992         16-bit instruction.
993
994    RELAX_DELAY_SLOT_SIZE_FIRST
995         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
996         the macro is of the wrong size for the branch delay slot.
997
998    RELAX_DELAY_SLOT_SIZE_SECOND
999         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
1000         the macro is of the wrong size for the branch delay slot.
1001
1002    The frag's "opcode" points to the first fixup for relaxable code.
1003
1004    Relaxable macros are generated using a sequence such as:
1005
1006       relax_start (SYMBOL);
1007       ... generate first expansion ...
1008       relax_switch ();
1009       ... generate second expansion ...
1010       relax_end ();
1011
1012    The code and fixups for the unwanted alternative are discarded
1013    by md_convert_frag.  */
1014 #define RELAX_ENCODE(FIRST, SECOND, PIC)                        \
1015   (((FIRST) << 8) | (SECOND) | ((PIC) ? 0x10000 : 0))
1016
1017 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
1018 #define RELAX_SECOND(X) ((X) & 0xff)
1019 #define RELAX_PIC(X) (((X) & 0x10000) != 0)
1020 #define RELAX_USE_SECOND 0x20000
1021 #define RELAX_SECOND_LONGER 0x40000
1022 #define RELAX_NOMACRO 0x80000
1023 #define RELAX_DELAY_SLOT 0x100000
1024 #define RELAX_DELAY_SLOT_16BIT 0x200000
1025 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x400000
1026 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x800000
1027
1028 /* Branch without likely bit.  If label is out of range, we turn:
1029
1030         beq reg1, reg2, label
1031         delay slot
1032
1033    into
1034
1035         bne reg1, reg2, 0f
1036         nop
1037         j label
1038      0: delay slot
1039
1040    with the following opcode replacements:
1041
1042         beq <-> bne
1043         blez <-> bgtz
1044         bltz <-> bgez
1045         bc1f <-> bc1t
1046
1047         bltzal <-> bgezal  (with jal label instead of j label)
1048
1049    Even though keeping the delay slot instruction in the delay slot of
1050    the branch would be more efficient, it would be very tricky to do
1051    correctly, because we'd have to introduce a variable frag *after*
1052    the delay slot instruction, and expand that instead.  Let's do it
1053    the easy way for now, even if the branch-not-taken case now costs
1054    one additional instruction.  Out-of-range branches are not supposed
1055    to be common, anyway.
1056
1057    Branch likely.  If label is out of range, we turn:
1058
1059         beql reg1, reg2, label
1060         delay slot (annulled if branch not taken)
1061
1062    into
1063
1064         beql reg1, reg2, 1f
1065         nop
1066         beql $0, $0, 2f
1067         nop
1068      1: j[al] label
1069         delay slot (executed only if branch taken)
1070      2:
1071
1072    It would be possible to generate a shorter sequence by losing the
1073    likely bit, generating something like:
1074
1075         bne reg1, reg2, 0f
1076         nop
1077         j[al] label
1078         delay slot (executed only if branch taken)
1079      0:
1080
1081         beql -> bne
1082         bnel -> beq
1083         blezl -> bgtz
1084         bgtzl -> blez
1085         bltzl -> bgez
1086         bgezl -> bltz
1087         bc1fl -> bc1t
1088         bc1tl -> bc1f
1089
1090         bltzall -> bgezal  (with jal label instead of j label)
1091         bgezall -> bltzal  (ditto)
1092
1093
1094    but it's not clear that it would actually improve performance.  */
1095 #define RELAX_BRANCH_ENCODE(at, pic,                            \
1096                             uncond, likely, link, toofar)       \
1097   ((relax_substateT)                                            \
1098    (0xc0000000                                                  \
1099     | ((at) & 0x1f)                                             \
1100     | ((pic) ? 0x20 : 0)                                        \
1101     | ((toofar) ? 0x40 : 0)                                     \
1102     | ((link) ? 0x80 : 0)                                       \
1103     | ((likely) ? 0x100 : 0)                                    \
1104     | ((uncond) ? 0x200 : 0)))
1105 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1106 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x200) != 0)
1107 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x100) != 0)
1108 #define RELAX_BRANCH_LINK(i) (((i) & 0x80) != 0)
1109 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x40) != 0)
1110 #define RELAX_BRANCH_PIC(i) (((i) & 0x20) != 0)
1111 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1112
1113 /* For mips16 code, we use an entirely different form of relaxation.
1114    mips16 supports two versions of most instructions which take
1115    immediate values: a small one which takes some small value, and a
1116    larger one which takes a 16 bit value.  Since branches also follow
1117    this pattern, relaxing these values is required.
1118
1119    We can assemble both mips16 and normal MIPS code in a single
1120    object.  Therefore, we need to support this type of relaxation at
1121    the same time that we support the relaxation described above.  We
1122    use the high bit of the subtype field to distinguish these cases.
1123
1124    The information we store for this type of relaxation is the
1125    argument code found in the opcode file for this relocation, whether
1126    the user explicitly requested a small or extended form, and whether
1127    the relocation is in a jump or jal delay slot.  That tells us the
1128    size of the value, and how it should be stored.  We also store
1129    whether the fragment is considered to be extended or not.  We also
1130    store whether this is known to be a branch to a different section,
1131    whether we have tried to relax this frag yet, and whether we have
1132    ever extended a PC relative fragment because of a shift count.  */
1133 #define RELAX_MIPS16_ENCODE(type, e2, pic, sym32, nomacro,      \
1134                             small, ext,                         \
1135                             dslot, jal_dslot)                   \
1136   (0x80000000                                                   \
1137    | ((type) & 0xff)                                            \
1138    | ((e2) ? 0x100 : 0)                                         \
1139    | ((pic) ? 0x200 : 0)                                        \
1140    | ((sym32) ? 0x400 : 0)                                      \
1141    | ((nomacro) ? 0x800 : 0)                                    \
1142    | ((small) ? 0x1000 : 0)                                     \
1143    | ((ext) ? 0x2000 : 0)                                       \
1144    | ((dslot) ? 0x4000 : 0)                                     \
1145    | ((jal_dslot) ? 0x8000 : 0))
1146
1147 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1148 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1149 #define RELAX_MIPS16_E2(i) (((i) & 0x100) != 0)
1150 #define RELAX_MIPS16_PIC(i) (((i) & 0x200) != 0)
1151 #define RELAX_MIPS16_SYM32(i) (((i) & 0x400) != 0)
1152 #define RELAX_MIPS16_NOMACRO(i) (((i) & 0x800) != 0)
1153 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x1000) != 0)
1154 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x2000) != 0)
1155 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x4000) != 0)
1156 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x8000) != 0)
1157
1158 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x10000) != 0)
1159 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x10000)
1160 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) & ~0x10000)
1161 #define RELAX_MIPS16_ALWAYS_EXTENDED(i) (((i) & 0x20000) != 0)
1162 #define RELAX_MIPS16_MARK_ALWAYS_EXTENDED(i) ((i) | 0x20000)
1163 #define RELAX_MIPS16_CLEAR_ALWAYS_EXTENDED(i) ((i) & ~0x20000)
1164 #define RELAX_MIPS16_MACRO(i) (((i) & 0x40000) != 0)
1165 #define RELAX_MIPS16_MARK_MACRO(i) ((i) | 0x40000)
1166 #define RELAX_MIPS16_CLEAR_MACRO(i) ((i) & ~0x40000)
1167
1168 /* For microMIPS code, we use relaxation similar to one we use for
1169    MIPS16 code.  Some instructions that take immediate values support
1170    two encodings: a small one which takes some small value, and a
1171    larger one which takes a 16 bit value.  As some branches also follow
1172    this pattern, relaxing these values is required.
1173
1174    We can assemble both microMIPS and normal MIPS code in a single
1175    object.  Therefore, we need to support this type of relaxation at
1176    the same time that we support the relaxation described above.  We
1177    use one of the high bits of the subtype field to distinguish these
1178    cases.
1179
1180    The information we store for this type of relaxation is the argument
1181    code found in the opcode file for this relocation, the register
1182    selected as the assembler temporary, whether in the 32-bit
1183    instruction mode, whether the branch is unconditional, whether it is
1184    compact, whether there is no delay-slot instruction available to fill
1185    in, whether it stores the link address implicitly in $ra, whether
1186    relaxation of out-of-range 32-bit branches to a sequence of
1187    instructions is enabled, and whether the displacement of a branch is
1188    too large to fit as an immediate argument of a 16-bit and a 32-bit
1189    branch, respectively.  */
1190 #define RELAX_MICROMIPS_ENCODE(type, at, insn32, pic,           \
1191                                uncond, compact, link, nods,     \
1192                                relax32, toofar16, toofar32)     \
1193   (0x40000000                                                   \
1194    | ((type) & 0xff)                                            \
1195    | (((at) & 0x1f) << 8)                                       \
1196    | ((insn32) ? 0x2000 : 0)                                    \
1197    | ((pic) ? 0x4000 : 0)                                       \
1198    | ((uncond) ? 0x8000 : 0)                                    \
1199    | ((compact) ? 0x10000 : 0)                                  \
1200    | ((link) ? 0x20000 : 0)                                     \
1201    | ((nods) ? 0x40000 : 0)                                     \
1202    | ((relax32) ? 0x80000 : 0)                                  \
1203    | ((toofar16) ? 0x100000 : 0)                                \
1204    | ((toofar32) ? 0x200000 : 0))
1205 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1206 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1207 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1208 #define RELAX_MICROMIPS_INSN32(i) (((i) & 0x2000) != 0)
1209 #define RELAX_MICROMIPS_PIC(i) (((i) & 0x4000) != 0)
1210 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x8000) != 0)
1211 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x10000) != 0)
1212 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x20000) != 0)
1213 #define RELAX_MICROMIPS_NODS(i) (((i) & 0x40000) != 0)
1214 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x80000) != 0)
1215
1216 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x100000) != 0)
1217 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x100000)
1218 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x100000)
1219 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x200000) != 0)
1220 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x200000)
1221 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x200000)
1222
1223 /* Sign-extend 16-bit value X.  */
1224 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1225
1226 /* Is the given value a sign-extended 32-bit value?  */
1227 #define IS_SEXT_32BIT_NUM(x)                                            \
1228   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1229    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1230
1231 /* Is the given value a sign-extended 16-bit value?  */
1232 #define IS_SEXT_16BIT_NUM(x)                                            \
1233   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1234    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1235
1236 /* Is the given value a sign-extended 12-bit value?  */
1237 #define IS_SEXT_12BIT_NUM(x)                                            \
1238   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1239
1240 /* Is the given value a sign-extended 9-bit value?  */
1241 #define IS_SEXT_9BIT_NUM(x)                                             \
1242   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1243
1244 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1245 #define IS_ZEXT_32BIT_NUM(x)                                            \
1246   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1247    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1248
1249 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1250    SHIFT places.  */
1251 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1252   (((STRUCT) >> (SHIFT)) & (MASK))
1253
1254 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1255 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1256   (!(MICROMIPS) \
1257    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1258    : EXTRACT_BITS ((INSN).insn_opcode, \
1259                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1260 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1261   EXTRACT_BITS ((INSN).insn_opcode, \
1262                 MIPS16OP_MASK_##FIELD, \
1263                 MIPS16OP_SH_##FIELD)
1264
1265 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1266 #define MIPS16_EXTEND (0xf000U << 16)
1267 \f
1268 /* Whether or not we are emitting a branch-likely macro.  */
1269 static bfd_boolean emit_branch_likely_macro = FALSE;
1270
1271 /* Global variables used when generating relaxable macros.  See the
1272    comment above RELAX_ENCODE for more details about how relaxation
1273    is used.  */
1274 static struct {
1275   /* 0 if we're not emitting a relaxable macro.
1276      1 if we're emitting the first of the two relaxation alternatives.
1277      2 if we're emitting the second alternative.  */
1278   int sequence;
1279
1280   /* The first relaxable fixup in the current frag.  (In other words,
1281      the first fixup that refers to relaxable code.)  */
1282   fixS *first_fixup;
1283
1284   /* sizes[0] says how many bytes of the first alternative are stored in
1285      the current frag.  Likewise sizes[1] for the second alternative.  */
1286   unsigned int sizes[2];
1287
1288   /* The symbol on which the choice of sequence depends.  */
1289   symbolS *symbol;
1290 } mips_relax;
1291 \f
1292 /* Global variables used to decide whether a macro needs a warning.  */
1293 static struct {
1294   /* True if the macro is in a branch delay slot.  */
1295   bfd_boolean delay_slot_p;
1296
1297   /* Set to the length in bytes required if the macro is in a delay slot
1298      that requires a specific length of instruction, otherwise zero.  */
1299   unsigned int delay_slot_length;
1300
1301   /* For relaxable macros, sizes[0] is the length of the first alternative
1302      in bytes and sizes[1] is the length of the second alternative.
1303      For non-relaxable macros, both elements give the length of the
1304      macro in bytes.  */
1305   unsigned int sizes[2];
1306
1307   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1308      instruction of the first alternative in bytes and first_insn_sizes[1]
1309      is the length of the first instruction of the second alternative.
1310      For non-relaxable macros, both elements give the length of the first
1311      instruction in bytes.
1312
1313      Set to zero if we haven't yet seen the first instruction.  */
1314   unsigned int first_insn_sizes[2];
1315
1316   /* For relaxable macros, insns[0] is the number of instructions for the
1317      first alternative and insns[1] is the number of instructions for the
1318      second alternative.
1319
1320      For non-relaxable macros, both elements give the number of
1321      instructions for the macro.  */
1322   unsigned int insns[2];
1323
1324   /* The first variant frag for this macro.  */
1325   fragS *first_frag;
1326 } mips_macro_warning;
1327 \f
1328 /* Prototypes for static functions.  */
1329
1330 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1331
1332 static void append_insn
1333   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1334    bfd_boolean expansionp);
1335 static void mips_no_prev_insn (void);
1336 static void macro_build (expressionS *, const char *, const char *, ...);
1337 static void mips16_macro_build
1338   (expressionS *, const char *, const char *, va_list *);
1339 static void load_register (int, expressionS *, int);
1340 static void macro_start (void);
1341 static void macro_end (void);
1342 static void macro (struct mips_cl_insn *ip, char *str);
1343 static void mips16_macro (struct mips_cl_insn * ip);
1344 static void mips_ip (char *str, struct mips_cl_insn * ip);
1345 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1346 static unsigned long mips16_immed_extend (offsetT, unsigned int);
1347 static void mips16_immed
1348   (const char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1349    unsigned int, unsigned long *);
1350 static size_t my_getSmallExpression
1351   (expressionS *, bfd_reloc_code_real_type *, char *);
1352 static void my_getExpression (expressionS *, char *);
1353 static void s_align (int);
1354 static void s_change_sec (int);
1355 static void s_change_section (int);
1356 static void s_cons (int);
1357 static void s_float_cons (int);
1358 static void s_mips_globl (int);
1359 static void s_option (int);
1360 static void s_mipsset (int);
1361 static void s_abicalls (int);
1362 static void s_cpload (int);
1363 static void s_cpsetup (int);
1364 static void s_cplocal (int);
1365 static void s_cprestore (int);
1366 static void s_cpreturn (int);
1367 static void s_dtprelword (int);
1368 static void s_dtpreldword (int);
1369 static void s_tprelword (int);
1370 static void s_tpreldword (int);
1371 static void s_gpvalue (int);
1372 static void s_gpword (int);
1373 static void s_gpdword (int);
1374 static void s_ehword (int);
1375 static void s_cpadd (int);
1376 static void s_insn (int);
1377 static void s_nan (int);
1378 static void s_module (int);
1379 static void s_mips_ent (int);
1380 static void s_mips_end (int);
1381 static void s_mips_frame (int);
1382 static void s_mips_mask (int reg_type);
1383 static void s_mips_stab (int);
1384 static void s_mips_weakext (int);
1385 static void s_mips_file (int);
1386 static void s_mips_loc (int);
1387 static bfd_boolean pic_need_relax (symbolS *);
1388 static int relaxed_branch_length (fragS *, asection *, int);
1389 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1390 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1391 static void file_mips_check_options (void);
1392
1393 /* Table and functions used to map between CPU/ISA names, and
1394    ISA levels, and CPU numbers.  */
1395
1396 struct mips_cpu_info
1397 {
1398   const char *name;           /* CPU or ISA name.  */
1399   int flags;                  /* MIPS_CPU_* flags.  */
1400   int ase;                    /* Set of ASEs implemented by the CPU.  */
1401   int isa;                    /* ISA level.  */
1402   int cpu;                    /* CPU number (default CPU if ISA).  */
1403 };
1404
1405 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1406
1407 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1408 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1409 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1410 \f
1411 /* Command-line options.  */
1412 const char *md_shortopts = "O::g::G:";
1413
1414 enum options
1415   {
1416     OPTION_MARCH = OPTION_MD_BASE,
1417     OPTION_MTUNE,
1418     OPTION_MIPS1,
1419     OPTION_MIPS2,
1420     OPTION_MIPS3,
1421     OPTION_MIPS4,
1422     OPTION_MIPS5,
1423     OPTION_MIPS32,
1424     OPTION_MIPS64,
1425     OPTION_MIPS32R2,
1426     OPTION_MIPS32R3,
1427     OPTION_MIPS32R5,
1428     OPTION_MIPS32R6,
1429     OPTION_MIPS64R2,
1430     OPTION_MIPS64R3,
1431     OPTION_MIPS64R5,
1432     OPTION_MIPS64R6,
1433     OPTION_MIPS16,
1434     OPTION_NO_MIPS16,
1435     OPTION_MIPS3D,
1436     OPTION_NO_MIPS3D,
1437     OPTION_MDMX,
1438     OPTION_NO_MDMX,
1439     OPTION_DSP,
1440     OPTION_NO_DSP,
1441     OPTION_MT,
1442     OPTION_NO_MT,
1443     OPTION_VIRT,
1444     OPTION_NO_VIRT,
1445     OPTION_MSA,
1446     OPTION_NO_MSA,
1447     OPTION_SMARTMIPS,
1448     OPTION_NO_SMARTMIPS,
1449     OPTION_DSPR2,
1450     OPTION_NO_DSPR2,
1451     OPTION_DSPR3,
1452     OPTION_NO_DSPR3,
1453     OPTION_EVA,
1454     OPTION_NO_EVA,
1455     OPTION_XPA,
1456     OPTION_NO_XPA,
1457     OPTION_MICROMIPS,
1458     OPTION_NO_MICROMIPS,
1459     OPTION_MCU,
1460     OPTION_NO_MCU,
1461     OPTION_MIPS16E2,
1462     OPTION_NO_MIPS16E2,
1463     OPTION_COMPAT_ARCH_BASE,
1464     OPTION_M4650,
1465     OPTION_NO_M4650,
1466     OPTION_M4010,
1467     OPTION_NO_M4010,
1468     OPTION_M4100,
1469     OPTION_NO_M4100,
1470     OPTION_M3900,
1471     OPTION_NO_M3900,
1472     OPTION_M7000_HILO_FIX,
1473     OPTION_MNO_7000_HILO_FIX,
1474     OPTION_FIX_24K,
1475     OPTION_NO_FIX_24K,
1476     OPTION_FIX_RM7000,
1477     OPTION_NO_FIX_RM7000,
1478     OPTION_FIX_LOONGSON2F_JUMP,
1479     OPTION_NO_FIX_LOONGSON2F_JUMP,
1480     OPTION_FIX_LOONGSON2F_NOP,
1481     OPTION_NO_FIX_LOONGSON2F_NOP,
1482     OPTION_FIX_VR4120,
1483     OPTION_NO_FIX_VR4120,
1484     OPTION_FIX_VR4130,
1485     OPTION_NO_FIX_VR4130,
1486     OPTION_FIX_CN63XXP1,
1487     OPTION_NO_FIX_CN63XXP1,
1488     OPTION_TRAP,
1489     OPTION_BREAK,
1490     OPTION_EB,
1491     OPTION_EL,
1492     OPTION_FP32,
1493     OPTION_GP32,
1494     OPTION_CONSTRUCT_FLOATS,
1495     OPTION_NO_CONSTRUCT_FLOATS,
1496     OPTION_FP64,
1497     OPTION_FPXX,
1498     OPTION_GP64,
1499     OPTION_RELAX_BRANCH,
1500     OPTION_NO_RELAX_BRANCH,
1501     OPTION_IGNORE_BRANCH_ISA,
1502     OPTION_NO_IGNORE_BRANCH_ISA,
1503     OPTION_INSN32,
1504     OPTION_NO_INSN32,
1505     OPTION_MSHARED,
1506     OPTION_MNO_SHARED,
1507     OPTION_MSYM32,
1508     OPTION_MNO_SYM32,
1509     OPTION_SOFT_FLOAT,
1510     OPTION_HARD_FLOAT,
1511     OPTION_SINGLE_FLOAT,
1512     OPTION_DOUBLE_FLOAT,
1513     OPTION_32,
1514     OPTION_CALL_SHARED,
1515     OPTION_CALL_NONPIC,
1516     OPTION_NON_SHARED,
1517     OPTION_XGOT,
1518     OPTION_MABI,
1519     OPTION_N32,
1520     OPTION_64,
1521     OPTION_MDEBUG,
1522     OPTION_NO_MDEBUG,
1523     OPTION_PDR,
1524     OPTION_NO_PDR,
1525     OPTION_MVXWORKS_PIC,
1526     OPTION_NAN,
1527     OPTION_ODD_SPREG,
1528     OPTION_NO_ODD_SPREG,
1529     OPTION_END_OF_ENUM
1530   };
1531
1532 struct option md_longopts[] =
1533 {
1534   /* Options which specify architecture.  */
1535   {"march", required_argument, NULL, OPTION_MARCH},
1536   {"mtune", required_argument, NULL, OPTION_MTUNE},
1537   {"mips0", no_argument, NULL, OPTION_MIPS1},
1538   {"mips1", no_argument, NULL, OPTION_MIPS1},
1539   {"mips2", no_argument, NULL, OPTION_MIPS2},
1540   {"mips3", no_argument, NULL, OPTION_MIPS3},
1541   {"mips4", no_argument, NULL, OPTION_MIPS4},
1542   {"mips5", no_argument, NULL, OPTION_MIPS5},
1543   {"mips32", no_argument, NULL, OPTION_MIPS32},
1544   {"mips64", no_argument, NULL, OPTION_MIPS64},
1545   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1546   {"mips32r3", no_argument, NULL, OPTION_MIPS32R3},
1547   {"mips32r5", no_argument, NULL, OPTION_MIPS32R5},
1548   {"mips32r6", no_argument, NULL, OPTION_MIPS32R6},
1549   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1550   {"mips64r3", no_argument, NULL, OPTION_MIPS64R3},
1551   {"mips64r5", no_argument, NULL, OPTION_MIPS64R5},
1552   {"mips64r6", no_argument, NULL, OPTION_MIPS64R6},
1553
1554   /* Options which specify Application Specific Extensions (ASEs).  */
1555   {"mips16", no_argument, NULL, OPTION_MIPS16},
1556   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1557   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1558   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1559   {"mdmx", no_argument, NULL, OPTION_MDMX},
1560   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1561   {"mdsp", no_argument, NULL, OPTION_DSP},
1562   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1563   {"mmt", no_argument, NULL, OPTION_MT},
1564   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1565   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1566   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1567   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1568   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1569   {"mdspr3", no_argument, NULL, OPTION_DSPR3},
1570   {"mno-dspr3", no_argument, NULL, OPTION_NO_DSPR3},
1571   {"meva", no_argument, NULL, OPTION_EVA},
1572   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1573   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1574   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1575   {"mmcu", no_argument, NULL, OPTION_MCU},
1576   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1577   {"mvirt", no_argument, NULL, OPTION_VIRT},
1578   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1579   {"mmsa", no_argument, NULL, OPTION_MSA},
1580   {"mno-msa", no_argument, NULL, OPTION_NO_MSA},
1581   {"mxpa", no_argument, NULL, OPTION_XPA},
1582   {"mno-xpa", no_argument, NULL, OPTION_NO_XPA},
1583   {"mmips16e2", no_argument, NULL, OPTION_MIPS16E2},
1584   {"mno-mips16e2", no_argument, NULL, OPTION_NO_MIPS16E2},
1585
1586   /* Old-style architecture options.  Don't add more of these.  */
1587   {"m4650", no_argument, NULL, OPTION_M4650},
1588   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1589   {"m4010", no_argument, NULL, OPTION_M4010},
1590   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1591   {"m4100", no_argument, NULL, OPTION_M4100},
1592   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1593   {"m3900", no_argument, NULL, OPTION_M3900},
1594   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1595
1596   /* Options which enable bug fixes.  */
1597   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1598   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1599   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1600   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1601   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1602   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1603   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1604   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1605   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1606   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1607   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1608   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1609   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1610   {"mfix-rm7000",    no_argument, NULL, OPTION_FIX_RM7000},
1611   {"mno-fix-rm7000", no_argument, NULL, OPTION_NO_FIX_RM7000},
1612   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1613   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1614
1615   /* Miscellaneous options.  */
1616   {"trap", no_argument, NULL, OPTION_TRAP},
1617   {"no-break", no_argument, NULL, OPTION_TRAP},
1618   {"break", no_argument, NULL, OPTION_BREAK},
1619   {"no-trap", no_argument, NULL, OPTION_BREAK},
1620   {"EB", no_argument, NULL, OPTION_EB},
1621   {"EL", no_argument, NULL, OPTION_EL},
1622   {"mfp32", no_argument, NULL, OPTION_FP32},
1623   {"mgp32", no_argument, NULL, OPTION_GP32},
1624   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1625   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1626   {"mfp64", no_argument, NULL, OPTION_FP64},
1627   {"mfpxx", no_argument, NULL, OPTION_FPXX},
1628   {"mgp64", no_argument, NULL, OPTION_GP64},
1629   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1630   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1631   {"mignore-branch-isa", no_argument, NULL, OPTION_IGNORE_BRANCH_ISA},
1632   {"mno-ignore-branch-isa", no_argument, NULL, OPTION_NO_IGNORE_BRANCH_ISA},
1633   {"minsn32", no_argument, NULL, OPTION_INSN32},
1634   {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1635   {"mshared", no_argument, NULL, OPTION_MSHARED},
1636   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1637   {"msym32", no_argument, NULL, OPTION_MSYM32},
1638   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1639   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1640   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1641   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1642   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1643   {"modd-spreg", no_argument, NULL, OPTION_ODD_SPREG},
1644   {"mno-odd-spreg", no_argument, NULL, OPTION_NO_ODD_SPREG},
1645
1646   /* Strictly speaking this next option is ELF specific,
1647      but we allow it for other ports as well in order to
1648      make testing easier.  */
1649   {"32", no_argument, NULL, OPTION_32},
1650
1651   /* ELF-specific options.  */
1652   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1653   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1654   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1655   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1656   {"xgot", no_argument, NULL, OPTION_XGOT},
1657   {"mabi", required_argument, NULL, OPTION_MABI},
1658   {"n32", no_argument, NULL, OPTION_N32},
1659   {"64", no_argument, NULL, OPTION_64},
1660   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1661   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1662   {"mpdr", no_argument, NULL, OPTION_PDR},
1663   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1664   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1665   {"mnan", required_argument, NULL, OPTION_NAN},
1666
1667   {NULL, no_argument, NULL, 0}
1668 };
1669 size_t md_longopts_size = sizeof (md_longopts);
1670 \f
1671 /* Information about either an Application Specific Extension or an
1672    optional architecture feature that, for simplicity, we treat in the
1673    same way as an ASE.  */
1674 struct mips_ase
1675 {
1676   /* The name of the ASE, used in both the command-line and .set options.  */
1677   const char *name;
1678
1679   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1680      and 64-bit architectures, the flags here refer to the subset that
1681      is available on both.  */
1682   unsigned int flags;
1683
1684   /* The ASE_* flag used for instructions that are available on 64-bit
1685      architectures but that are not included in FLAGS.  */
1686   unsigned int flags64;
1687
1688   /* The command-line options that turn the ASE on and off.  */
1689   int option_on;
1690   int option_off;
1691
1692   /* The minimum required architecture revisions for MIPS32, MIPS64,
1693      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1694   int mips32_rev;
1695   int mips64_rev;
1696   int micromips32_rev;
1697   int micromips64_rev;
1698
1699   /* The architecture where the ASE was removed or -1 if the extension has not
1700      been removed.  */
1701   int rem_rev;
1702 };
1703
1704 /* A table of all supported ASEs.  */
1705 static const struct mips_ase mips_ases[] = {
1706   { "dsp", ASE_DSP, ASE_DSP64,
1707     OPTION_DSP, OPTION_NO_DSP,
1708     2, 2, 2, 2,
1709     -1 },
1710
1711   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1712     OPTION_DSPR2, OPTION_NO_DSPR2,
1713     2, 2, 2, 2,
1714     -1 },
1715
1716   { "dspr3", ASE_DSP | ASE_DSPR2 | ASE_DSPR3, 0,
1717     OPTION_DSPR3, OPTION_NO_DSPR3,
1718     6, 6, -1, -1,
1719     -1 },
1720
1721   { "eva", ASE_EVA, 0,
1722     OPTION_EVA, OPTION_NO_EVA,
1723      2,  2,  2,  2,
1724     -1 },
1725
1726   { "mcu", ASE_MCU, 0,
1727     OPTION_MCU, OPTION_NO_MCU,
1728      2,  2,  2,  2,
1729     -1 },
1730
1731   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1732   { "mdmx", ASE_MDMX, 0,
1733     OPTION_MDMX, OPTION_NO_MDMX,
1734     -1, 1, -1, -1,
1735      6 },
1736
1737   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1738   { "mips3d", ASE_MIPS3D, 0,
1739     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1740     2, 1, -1, -1,
1741     6 },
1742
1743   { "mt", ASE_MT, 0,
1744     OPTION_MT, OPTION_NO_MT,
1745      2,  2, -1, -1,
1746     -1 },
1747
1748   { "smartmips", ASE_SMARTMIPS, 0,
1749     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1750     1, -1, -1, -1,
1751     6 },
1752
1753   { "virt", ASE_VIRT, ASE_VIRT64,
1754     OPTION_VIRT, OPTION_NO_VIRT,
1755      2,  2,  2,  2,
1756     -1 },
1757
1758   { "msa", ASE_MSA, ASE_MSA64,
1759     OPTION_MSA, OPTION_NO_MSA,
1760      2,  2,  2,  2,
1761     -1 },
1762
1763   { "xpa", ASE_XPA, 0,
1764     OPTION_XPA, OPTION_NO_XPA,
1765     2, 2, 2, 2,
1766     -1 },
1767
1768   { "mips16e2", ASE_MIPS16E2, 0,
1769     OPTION_MIPS16E2, OPTION_NO_MIPS16E2,
1770     2,  2, -1, -1,
1771     6 },
1772 };
1773
1774 /* The set of ASEs that require -mfp64.  */
1775 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX | ASE_MSA)
1776
1777 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1778 static const unsigned int mips_ase_groups[] = {
1779   ASE_DSP | ASE_DSPR2 | ASE_DSPR3
1780 };
1781 \f
1782 /* Pseudo-op table.
1783
1784    The following pseudo-ops from the Kane and Heinrich MIPS book
1785    should be defined here, but are currently unsupported: .alias,
1786    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1787
1788    The following pseudo-ops from the Kane and Heinrich MIPS book are
1789    specific to the type of debugging information being generated, and
1790    should be defined by the object format: .aent, .begin, .bend,
1791    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1792    .vreg.
1793
1794    The following pseudo-ops from the Kane and Heinrich MIPS book are
1795    not MIPS CPU specific, but are also not specific to the object file
1796    format.  This file is probably the best place to define them, but
1797    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1798
1799 static const pseudo_typeS mips_pseudo_table[] =
1800 {
1801   /* MIPS specific pseudo-ops.  */
1802   {"option", s_option, 0},
1803   {"set", s_mipsset, 0},
1804   {"rdata", s_change_sec, 'r'},
1805   {"sdata", s_change_sec, 's'},
1806   {"livereg", s_ignore, 0},
1807   {"abicalls", s_abicalls, 0},
1808   {"cpload", s_cpload, 0},
1809   {"cpsetup", s_cpsetup, 0},
1810   {"cplocal", s_cplocal, 0},
1811   {"cprestore", s_cprestore, 0},
1812   {"cpreturn", s_cpreturn, 0},
1813   {"dtprelword", s_dtprelword, 0},
1814   {"dtpreldword", s_dtpreldword, 0},
1815   {"tprelword", s_tprelword, 0},
1816   {"tpreldword", s_tpreldword, 0},
1817   {"gpvalue", s_gpvalue, 0},
1818   {"gpword", s_gpword, 0},
1819   {"gpdword", s_gpdword, 0},
1820   {"ehword", s_ehword, 0},
1821   {"cpadd", s_cpadd, 0},
1822   {"insn", s_insn, 0},
1823   {"nan", s_nan, 0},
1824   {"module", s_module, 0},
1825
1826   /* Relatively generic pseudo-ops that happen to be used on MIPS
1827      chips.  */
1828   {"asciiz", stringer, 8 + 1},
1829   {"bss", s_change_sec, 'b'},
1830   {"err", s_err, 0},
1831   {"half", s_cons, 1},
1832   {"dword", s_cons, 3},
1833   {"weakext", s_mips_weakext, 0},
1834   {"origin", s_org, 0},
1835   {"repeat", s_rept, 0},
1836
1837   /* For MIPS this is non-standard, but we define it for consistency.  */
1838   {"sbss", s_change_sec, 'B'},
1839
1840   /* These pseudo-ops are defined in read.c, but must be overridden
1841      here for one reason or another.  */
1842   {"align", s_align, 0},
1843   {"byte", s_cons, 0},
1844   {"data", s_change_sec, 'd'},
1845   {"double", s_float_cons, 'd'},
1846   {"float", s_float_cons, 'f'},
1847   {"globl", s_mips_globl, 0},
1848   {"global", s_mips_globl, 0},
1849   {"hword", s_cons, 1},
1850   {"int", s_cons, 2},
1851   {"long", s_cons, 2},
1852   {"octa", s_cons, 4},
1853   {"quad", s_cons, 3},
1854   {"section", s_change_section, 0},
1855   {"short", s_cons, 1},
1856   {"single", s_float_cons, 'f'},
1857   {"stabd", s_mips_stab, 'd'},
1858   {"stabn", s_mips_stab, 'n'},
1859   {"stabs", s_mips_stab, 's'},
1860   {"text", s_change_sec, 't'},
1861   {"word", s_cons, 2},
1862
1863   { "extern", ecoff_directive_extern, 0},
1864
1865   { NULL, NULL, 0 },
1866 };
1867
1868 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1869 {
1870   /* These pseudo-ops should be defined by the object file format.
1871      However, a.out doesn't support them, so we have versions here.  */
1872   {"aent", s_mips_ent, 1},
1873   {"bgnb", s_ignore, 0},
1874   {"end", s_mips_end, 0},
1875   {"endb", s_ignore, 0},
1876   {"ent", s_mips_ent, 0},
1877   {"file", s_mips_file, 0},
1878   {"fmask", s_mips_mask, 'F'},
1879   {"frame", s_mips_frame, 0},
1880   {"loc", s_mips_loc, 0},
1881   {"mask", s_mips_mask, 'R'},
1882   {"verstamp", s_ignore, 0},
1883   { NULL, NULL, 0 },
1884 };
1885
1886 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1887    purpose of the `.dc.a' internal pseudo-op.  */
1888
1889 int
1890 mips_address_bytes (void)
1891 {
1892   file_mips_check_options ();
1893   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1894 }
1895
1896 extern void pop_insert (const pseudo_typeS *);
1897
1898 void
1899 mips_pop_insert (void)
1900 {
1901   pop_insert (mips_pseudo_table);
1902   if (! ECOFF_DEBUGGING)
1903     pop_insert (mips_nonecoff_pseudo_table);
1904 }
1905 \f
1906 /* Symbols labelling the current insn.  */
1907
1908 struct insn_label_list
1909 {
1910   struct insn_label_list *next;
1911   symbolS *label;
1912 };
1913
1914 static struct insn_label_list *free_insn_labels;
1915 #define label_list tc_segment_info_data.labels
1916
1917 static void mips_clear_insn_labels (void);
1918 static void mips_mark_labels (void);
1919 static void mips_compressed_mark_labels (void);
1920
1921 static inline void
1922 mips_clear_insn_labels (void)
1923 {
1924   struct insn_label_list **pl;
1925   segment_info_type *si;
1926
1927   if (now_seg)
1928     {
1929       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1930         ;
1931
1932       si = seg_info (now_seg);
1933       *pl = si->label_list;
1934       si->label_list = NULL;
1935     }
1936 }
1937
1938 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1939
1940 static inline void
1941 mips_mark_labels (void)
1942 {
1943   if (HAVE_CODE_COMPRESSION)
1944     mips_compressed_mark_labels ();
1945 }
1946 \f
1947 static char *expr_end;
1948
1949 /* An expression in a macro instruction.  This is set by mips_ip and
1950    mips16_ip and when populated is always an O_constant.  */
1951
1952 static expressionS imm_expr;
1953
1954 /* The relocatable field in an instruction and the relocs associated
1955    with it.  These variables are used for instructions like LUI and
1956    JAL as well as true offsets.  They are also used for address
1957    operands in macros.  */
1958
1959 static expressionS offset_expr;
1960 static bfd_reloc_code_real_type offset_reloc[3]
1961   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1962
1963 /* This is set to the resulting size of the instruction to be produced
1964    by mips16_ip if an explicit extension is used or by mips_ip if an
1965    explicit size is supplied.  */
1966
1967 static unsigned int forced_insn_length;
1968
1969 /* True if we are assembling an instruction.  All dot symbols defined during
1970    this time should be treated as code labels.  */
1971
1972 static bfd_boolean mips_assembling_insn;
1973
1974 /* The pdr segment for per procedure frame/regmask info.  Not used for
1975    ECOFF debugging.  */
1976
1977 static segT pdr_seg;
1978
1979 /* The default target format to use.  */
1980
1981 #if defined (TE_FreeBSD)
1982 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1983 #elif defined (TE_TMIPS)
1984 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1985 #else
1986 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1987 #endif
1988
1989 const char *
1990 mips_target_format (void)
1991 {
1992   switch (OUTPUT_FLAVOR)
1993     {
1994     case bfd_target_elf_flavour:
1995 #ifdef TE_VXWORKS
1996       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1997         return (target_big_endian
1998                 ? "elf32-bigmips-vxworks"
1999                 : "elf32-littlemips-vxworks");
2000 #endif
2001       return (target_big_endian
2002               ? (HAVE_64BIT_OBJECTS
2003                  ? ELF_TARGET ("elf64-", "big")
2004                  : (HAVE_NEWABI
2005                     ? ELF_TARGET ("elf32-n", "big")
2006                     : ELF_TARGET ("elf32-", "big")))
2007               : (HAVE_64BIT_OBJECTS
2008                  ? ELF_TARGET ("elf64-", "little")
2009                  : (HAVE_NEWABI
2010                     ? ELF_TARGET ("elf32-n", "little")
2011                     : ELF_TARGET ("elf32-", "little"))));
2012     default:
2013       abort ();
2014       return NULL;
2015     }
2016 }
2017
2018 /* Return the ISA revision that is currently in use, or 0 if we are
2019    generating code for MIPS V or below.  */
2020
2021 static int
2022 mips_isa_rev (void)
2023 {
2024   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
2025     return 2;
2026
2027   if (mips_opts.isa == ISA_MIPS32R3 || mips_opts.isa == ISA_MIPS64R3)
2028     return 3;
2029
2030   if (mips_opts.isa == ISA_MIPS32R5 || mips_opts.isa == ISA_MIPS64R5)
2031     return 5;
2032
2033   if (mips_opts.isa == ISA_MIPS32R6 || mips_opts.isa == ISA_MIPS64R6)
2034     return 6;
2035
2036   /* microMIPS implies revision 2 or above.  */
2037   if (mips_opts.micromips)
2038     return 2;
2039
2040   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
2041     return 1;
2042
2043   return 0;
2044 }
2045
2046 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
2047
2048 static unsigned int
2049 mips_ase_mask (unsigned int flags)
2050 {
2051   unsigned int i;
2052
2053   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
2054     if (flags & mips_ase_groups[i])
2055       flags |= mips_ase_groups[i];
2056   return flags;
2057 }
2058
2059 /* Check whether the current ISA supports ASE.  Issue a warning if
2060    appropriate.  */
2061
2062 static void
2063 mips_check_isa_supports_ase (const struct mips_ase *ase)
2064 {
2065   const char *base;
2066   int min_rev, size;
2067   static unsigned int warned_isa;
2068   static unsigned int warned_fp32;
2069
2070   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
2071     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
2072   else
2073     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
2074   if ((min_rev < 0 || mips_isa_rev () < min_rev)
2075       && (warned_isa & ase->flags) != ase->flags)
2076     {
2077       warned_isa |= ase->flags;
2078       base = mips_opts.micromips ? "microMIPS" : "MIPS";
2079       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
2080       if (min_rev < 0)
2081         as_warn (_("the %d-bit %s architecture does not support the"
2082                    " `%s' extension"), size, base, ase->name);
2083       else
2084         as_warn (_("the `%s' extension requires %s%d revision %d or greater"),
2085                  ase->name, base, size, min_rev);
2086     }
2087   else if ((ase->rem_rev > 0 && mips_isa_rev () >= ase->rem_rev)
2088            && (warned_isa & ase->flags) != ase->flags)
2089     {
2090       warned_isa |= ase->flags;
2091       base = mips_opts.micromips ? "microMIPS" : "MIPS";
2092       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
2093       as_warn (_("the `%s' extension was removed in %s%d revision %d"),
2094                ase->name, base, size, ase->rem_rev);
2095     }
2096
2097   if ((ase->flags & FP64_ASES)
2098       && mips_opts.fp != 64
2099       && (warned_fp32 & ase->flags) != ase->flags)
2100     {
2101       warned_fp32 |= ase->flags;
2102       as_warn (_("the `%s' extension requires 64-bit FPRs"), ase->name);
2103     }
2104 }
2105
2106 /* Check all enabled ASEs to see whether they are supported by the
2107    chosen architecture.  */
2108
2109 static void
2110 mips_check_isa_supports_ases (void)
2111 {
2112   unsigned int i, mask;
2113
2114   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2115     {
2116       mask = mips_ase_mask (mips_ases[i].flags);
2117       if ((mips_opts.ase & mask) == mips_ases[i].flags)
2118         mips_check_isa_supports_ase (&mips_ases[i]);
2119     }
2120 }
2121
2122 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
2123    that were affected.  */
2124
2125 static unsigned int
2126 mips_set_ase (const struct mips_ase *ase, struct mips_set_options *opts,
2127               bfd_boolean enabled_p)
2128 {
2129   unsigned int mask;
2130
2131   mask = mips_ase_mask (ase->flags);
2132   opts->ase &= ~mask;
2133
2134   /* Clear combination ASE flags, which need to be recalculated based on
2135      updated regular ASE settings.  */
2136   opts->ase &= ~(ASE_MIPS16E2_MT | ASE_XPA_VIRT);
2137
2138   if (enabled_p)
2139     opts->ase |= ase->flags;
2140
2141   /* The Virtualization ASE has eXtended Physical Addressing (XPA)
2142      instructions which are only valid when both ASEs are enabled.
2143      This sets the ASE_XPA_VIRT flag when both ASEs are present.  */
2144   if ((opts->ase & (ASE_XPA | ASE_VIRT)) == (ASE_XPA | ASE_VIRT))
2145     {
2146       opts->ase |= ASE_XPA_VIRT;
2147       mask |= ASE_XPA_VIRT;
2148     }
2149   if ((opts->ase & (ASE_MIPS16E2 | ASE_MT)) == (ASE_MIPS16E2 | ASE_MT))
2150     {
2151       opts->ase |= ASE_MIPS16E2_MT;
2152       mask |= ASE_MIPS16E2_MT;
2153     }
2154
2155   return mask;
2156 }
2157
2158 /* Return the ASE called NAME, or null if none.  */
2159
2160 static const struct mips_ase *
2161 mips_lookup_ase (const char *name)
2162 {
2163   unsigned int i;
2164
2165   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2166     if (strcmp (name, mips_ases[i].name) == 0)
2167       return &mips_ases[i];
2168   return NULL;
2169 }
2170
2171 /* Return the length of a microMIPS instruction in bytes.  If bits of
2172    the mask beyond the low 16 are 0, then it is a 16-bit instruction,
2173    otherwise it is a 32-bit instruction.  */
2174
2175 static inline unsigned int
2176 micromips_insn_length (const struct mips_opcode *mo)
2177 {
2178   return mips_opcode_32bit_p (mo) ? 4 : 2;
2179 }
2180
2181 /* Return the length of MIPS16 instruction OPCODE.  */
2182
2183 static inline unsigned int
2184 mips16_opcode_length (unsigned long opcode)
2185 {
2186   return (opcode >> 16) == 0 ? 2 : 4;
2187 }
2188
2189 /* Return the length of instruction INSN.  */
2190
2191 static inline unsigned int
2192 insn_length (const struct mips_cl_insn *insn)
2193 {
2194   if (mips_opts.micromips)
2195     return micromips_insn_length (insn->insn_mo);
2196   else if (mips_opts.mips16)
2197     return mips16_opcode_length (insn->insn_opcode);
2198   else
2199     return 4;
2200 }
2201
2202 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
2203
2204 static void
2205 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
2206 {
2207   size_t i;
2208
2209   insn->insn_mo = mo;
2210   insn->insn_opcode = mo->match;
2211   insn->frag = NULL;
2212   insn->where = 0;
2213   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2214     insn->fixp[i] = NULL;
2215   insn->fixed_p = (mips_opts.noreorder > 0);
2216   insn->noreorder_p = (mips_opts.noreorder > 0);
2217   insn->mips16_absolute_jump_p = 0;
2218   insn->complete_p = 0;
2219   insn->cleared_p = 0;
2220 }
2221
2222 /* Get a list of all the operands in INSN.  */
2223
2224 static const struct mips_operand_array *
2225 insn_operands (const struct mips_cl_insn *insn)
2226 {
2227   if (insn->insn_mo >= &mips_opcodes[0]
2228       && insn->insn_mo < &mips_opcodes[NUMOPCODES])
2229     return &mips_operands[insn->insn_mo - &mips_opcodes[0]];
2230
2231   if (insn->insn_mo >= &mips16_opcodes[0]
2232       && insn->insn_mo < &mips16_opcodes[bfd_mips16_num_opcodes])
2233     return &mips16_operands[insn->insn_mo - &mips16_opcodes[0]];
2234
2235   if (insn->insn_mo >= &micromips_opcodes[0]
2236       && insn->insn_mo < &micromips_opcodes[bfd_micromips_num_opcodes])
2237     return &micromips_operands[insn->insn_mo - &micromips_opcodes[0]];
2238
2239   abort ();
2240 }
2241
2242 /* Get a description of operand OPNO of INSN.  */
2243
2244 static const struct mips_operand *
2245 insn_opno (const struct mips_cl_insn *insn, unsigned opno)
2246 {
2247   const struct mips_operand_array *operands;
2248
2249   operands = insn_operands (insn);
2250   if (opno >= MAX_OPERANDS || !operands->operand[opno])
2251     abort ();
2252   return operands->operand[opno];
2253 }
2254
2255 /* Install UVAL as the value of OPERAND in INSN.  */
2256
2257 static inline void
2258 insn_insert_operand (struct mips_cl_insn *insn,
2259                      const struct mips_operand *operand, unsigned int uval)
2260 {
2261   if (mips_opts.mips16
2262       && operand->type == OP_INT && operand->lsb == 0
2263       && mips_opcode_32bit_p (insn->insn_mo))
2264     insn->insn_opcode |= mips16_immed_extend (uval, operand->size);
2265   else
2266     insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
2267 }
2268
2269 /* Extract the value of OPERAND from INSN.  */
2270
2271 static inline unsigned
2272 insn_extract_operand (const struct mips_cl_insn *insn,
2273                       const struct mips_operand *operand)
2274 {
2275   return mips_extract_operand (operand, insn->insn_opcode);
2276 }
2277
2278 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2279
2280 static void
2281 mips_record_compressed_mode (void)
2282 {
2283   segment_info_type *si;
2284
2285   si = seg_info (now_seg);
2286   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2287     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2288   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2289     si->tc_segment_info_data.micromips = mips_opts.micromips;
2290 }
2291
2292 /* Read a standard MIPS instruction from BUF.  */
2293
2294 static unsigned long
2295 read_insn (char *buf)
2296 {
2297   if (target_big_endian)
2298     return bfd_getb32 ((bfd_byte *) buf);
2299   else
2300     return bfd_getl32 ((bfd_byte *) buf);
2301 }
2302
2303 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2304    the next byte.  */
2305
2306 static char *
2307 write_insn (char *buf, unsigned int insn)
2308 {
2309   md_number_to_chars (buf, insn, 4);
2310   return buf + 4;
2311 }
2312
2313 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2314    has length LENGTH.  */
2315
2316 static unsigned long
2317 read_compressed_insn (char *buf, unsigned int length)
2318 {
2319   unsigned long insn;
2320   unsigned int i;
2321
2322   insn = 0;
2323   for (i = 0; i < length; i += 2)
2324     {
2325       insn <<= 16;
2326       if (target_big_endian)
2327         insn |= bfd_getb16 ((char *) buf);
2328       else
2329         insn |= bfd_getl16 ((char *) buf);
2330       buf += 2;
2331     }
2332   return insn;
2333 }
2334
2335 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2336    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2337
2338 static char *
2339 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2340 {
2341   unsigned int i;
2342
2343   for (i = 0; i < length; i += 2)
2344     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2345   return buf + length;
2346 }
2347
2348 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2349
2350 static void
2351 install_insn (const struct mips_cl_insn *insn)
2352 {
2353   char *f = insn->frag->fr_literal + insn->where;
2354   if (HAVE_CODE_COMPRESSION)
2355     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2356   else
2357     write_insn (f, insn->insn_opcode);
2358   mips_record_compressed_mode ();
2359 }
2360
2361 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2362    and install the opcode in the new location.  */
2363
2364 static void
2365 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2366 {
2367   size_t i;
2368
2369   insn->frag = frag;
2370   insn->where = where;
2371   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2372     if (insn->fixp[i] != NULL)
2373       {
2374         insn->fixp[i]->fx_frag = frag;
2375         insn->fixp[i]->fx_where = where;
2376       }
2377   install_insn (insn);
2378 }
2379
2380 /* Add INSN to the end of the output.  */
2381
2382 static void
2383 add_fixed_insn (struct mips_cl_insn *insn)
2384 {
2385   char *f = frag_more (insn_length (insn));
2386   move_insn (insn, frag_now, f - frag_now->fr_literal);
2387 }
2388
2389 /* Start a variant frag and move INSN to the start of the variant part,
2390    marking it as fixed.  The other arguments are as for frag_var.  */
2391
2392 static void
2393 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2394                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2395 {
2396   frag_grow (max_chars);
2397   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2398   insn->fixed_p = 1;
2399   frag_var (rs_machine_dependent, max_chars, var,
2400             subtype, symbol, offset, NULL);
2401 }
2402
2403 /* Insert N copies of INSN into the history buffer, starting at
2404    position FIRST.  Neither FIRST nor N need to be clipped.  */
2405
2406 static void
2407 insert_into_history (unsigned int first, unsigned int n,
2408                      const struct mips_cl_insn *insn)
2409 {
2410   if (mips_relax.sequence != 2)
2411     {
2412       unsigned int i;
2413
2414       for (i = ARRAY_SIZE (history); i-- > first;)
2415         if (i >= first + n)
2416           history[i] = history[i - n];
2417         else
2418           history[i] = *insn;
2419     }
2420 }
2421
2422 /* Clear the error in insn_error.  */
2423
2424 static void
2425 clear_insn_error (void)
2426 {
2427   memset (&insn_error, 0, sizeof (insn_error));
2428 }
2429
2430 /* Possibly record error message MSG for the current instruction.
2431    If the error is about a particular argument, ARGNUM is the 1-based
2432    number of that argument, otherwise it is 0.  FORMAT is the format
2433    of MSG.  Return true if MSG was used, false if the current message
2434    was kept.  */
2435
2436 static bfd_boolean
2437 set_insn_error_format (int argnum, enum mips_insn_error_format format,
2438                        const char *msg)
2439 {
2440   if (argnum == 0)
2441     {
2442       /* Give priority to errors against specific arguments, and to
2443          the first whole-instruction message.  */
2444       if (insn_error.msg)
2445         return FALSE;
2446     }
2447   else
2448     {
2449       /* Keep insn_error if it is against a later argument.  */
2450       if (argnum < insn_error.min_argnum)
2451         return FALSE;
2452
2453       /* If both errors are against the same argument but are different,
2454          give up on reporting a specific error for this argument.
2455          See the comment about mips_insn_error for details.  */
2456       if (argnum == insn_error.min_argnum
2457           && insn_error.msg
2458           && strcmp (insn_error.msg, msg) != 0)
2459         {
2460           insn_error.msg = 0;
2461           insn_error.min_argnum += 1;
2462           return FALSE;
2463         }
2464     }
2465   insn_error.min_argnum = argnum;
2466   insn_error.format = format;
2467   insn_error.msg = msg;
2468   return TRUE;
2469 }
2470
2471 /* Record an instruction error with no % format fields.  ARGNUM and MSG are
2472    as for set_insn_error_format.  */
2473
2474 static void
2475 set_insn_error (int argnum, const char *msg)
2476 {
2477   set_insn_error_format (argnum, ERR_FMT_PLAIN, msg);
2478 }
2479
2480 /* Record an instruction error with one %d field I.  ARGNUM and MSG are
2481    as for set_insn_error_format.  */
2482
2483 static void
2484 set_insn_error_i (int argnum, const char *msg, int i)
2485 {
2486   if (set_insn_error_format (argnum, ERR_FMT_I, msg))
2487     insn_error.u.i = i;
2488 }
2489
2490 /* Record an instruction error with two %s fields S1 and S2.  ARGNUM and MSG
2491    are as for set_insn_error_format.  */
2492
2493 static void
2494 set_insn_error_ss (int argnum, const char *msg, const char *s1, const char *s2)
2495 {
2496   if (set_insn_error_format (argnum, ERR_FMT_SS, msg))
2497     {
2498       insn_error.u.ss[0] = s1;
2499       insn_error.u.ss[1] = s2;
2500     }
2501 }
2502
2503 /* Report the error in insn_error, which is against assembly code STR.  */
2504
2505 static void
2506 report_insn_error (const char *str)
2507 {
2508   const char *msg = concat (insn_error.msg, " `%s'", NULL);
2509
2510   switch (insn_error.format)
2511     {
2512     case ERR_FMT_PLAIN:
2513       as_bad (msg, str);
2514       break;
2515
2516     case ERR_FMT_I:
2517       as_bad (msg, insn_error.u.i, str);
2518       break;
2519
2520     case ERR_FMT_SS:
2521       as_bad (msg, insn_error.u.ss[0], insn_error.u.ss[1], str);
2522       break;
2523     }
2524
2525   free ((char *) msg);
2526 }
2527
2528 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2529    the idea is to make it obvious at a glance that each errata is
2530    included.  */
2531
2532 static void
2533 init_vr4120_conflicts (void)
2534 {
2535 #define CONFLICT(FIRST, SECOND) \
2536     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2537
2538   /* Errata 21 - [D]DIV[U] after [D]MACC */
2539   CONFLICT (MACC, DIV);
2540   CONFLICT (DMACC, DIV);
2541
2542   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2543   CONFLICT (DMULT, DMULT);
2544   CONFLICT (DMULT, DMACC);
2545   CONFLICT (DMACC, DMULT);
2546   CONFLICT (DMACC, DMACC);
2547
2548   /* Errata 24 - MT{LO,HI} after [D]MACC */
2549   CONFLICT (MACC, MTHILO);
2550   CONFLICT (DMACC, MTHILO);
2551
2552   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2553      instruction is executed immediately after a MACC or DMACC
2554      instruction, the result of [either instruction] is incorrect."  */
2555   CONFLICT (MACC, MULT);
2556   CONFLICT (MACC, DMULT);
2557   CONFLICT (DMACC, MULT);
2558   CONFLICT (DMACC, DMULT);
2559
2560   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2561      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2562      DDIV or DDIVU instruction, the result of the MACC or
2563      DMACC instruction is incorrect.".  */
2564   CONFLICT (DMULT, MACC);
2565   CONFLICT (DMULT, DMACC);
2566   CONFLICT (DIV, MACC);
2567   CONFLICT (DIV, DMACC);
2568
2569 #undef CONFLICT
2570 }
2571
2572 struct regname {
2573   const char *name;
2574   unsigned int num;
2575 };
2576
2577 #define RNUM_MASK       0x00000ff
2578 #define RTYPE_MASK      0x0ffff00
2579 #define RTYPE_NUM       0x0000100
2580 #define RTYPE_FPU       0x0000200
2581 #define RTYPE_FCC       0x0000400
2582 #define RTYPE_VEC       0x0000800
2583 #define RTYPE_GP        0x0001000
2584 #define RTYPE_CP0       0x0002000
2585 #define RTYPE_PC        0x0004000
2586 #define RTYPE_ACC       0x0008000
2587 #define RTYPE_CCC       0x0010000
2588 #define RTYPE_VI        0x0020000
2589 #define RTYPE_VF        0x0040000
2590 #define RTYPE_R5900_I   0x0080000
2591 #define RTYPE_R5900_Q   0x0100000
2592 #define RTYPE_R5900_R   0x0200000
2593 #define RTYPE_R5900_ACC 0x0400000
2594 #define RTYPE_MSA       0x0800000
2595 #define RWARN           0x8000000
2596
2597 #define GENERIC_REGISTER_NUMBERS \
2598     {"$0",      RTYPE_NUM | 0},  \
2599     {"$1",      RTYPE_NUM | 1},  \
2600     {"$2",      RTYPE_NUM | 2},  \
2601     {"$3",      RTYPE_NUM | 3},  \
2602     {"$4",      RTYPE_NUM | 4},  \
2603     {"$5",      RTYPE_NUM | 5},  \
2604     {"$6",      RTYPE_NUM | 6},  \
2605     {"$7",      RTYPE_NUM | 7},  \
2606     {"$8",      RTYPE_NUM | 8},  \
2607     {"$9",      RTYPE_NUM | 9},  \
2608     {"$10",     RTYPE_NUM | 10}, \
2609     {"$11",     RTYPE_NUM | 11}, \
2610     {"$12",     RTYPE_NUM | 12}, \
2611     {"$13",     RTYPE_NUM | 13}, \
2612     {"$14",     RTYPE_NUM | 14}, \
2613     {"$15",     RTYPE_NUM | 15}, \
2614     {"$16",     RTYPE_NUM | 16}, \
2615     {"$17",     RTYPE_NUM | 17}, \
2616     {"$18",     RTYPE_NUM | 18}, \
2617     {"$19",     RTYPE_NUM | 19}, \
2618     {"$20",     RTYPE_NUM | 20}, \
2619     {"$21",     RTYPE_NUM | 21}, \
2620     {"$22",     RTYPE_NUM | 22}, \
2621     {"$23",     RTYPE_NUM | 23}, \
2622     {"$24",     RTYPE_NUM | 24}, \
2623     {"$25",     RTYPE_NUM | 25}, \
2624     {"$26",     RTYPE_NUM | 26}, \
2625     {"$27",     RTYPE_NUM | 27}, \
2626     {"$28",     RTYPE_NUM | 28}, \
2627     {"$29",     RTYPE_NUM | 29}, \
2628     {"$30",     RTYPE_NUM | 30}, \
2629     {"$31",     RTYPE_NUM | 31}
2630
2631 #define FPU_REGISTER_NAMES       \
2632     {"$f0",     RTYPE_FPU | 0},  \
2633     {"$f1",     RTYPE_FPU | 1},  \
2634     {"$f2",     RTYPE_FPU | 2},  \
2635     {"$f3",     RTYPE_FPU | 3},  \
2636     {"$f4",     RTYPE_FPU | 4},  \
2637     {"$f5",     RTYPE_FPU | 5},  \
2638     {"$f6",     RTYPE_FPU | 6},  \
2639     {"$f7",     RTYPE_FPU | 7},  \
2640     {"$f8",     RTYPE_FPU | 8},  \
2641     {"$f9",     RTYPE_FPU | 9},  \
2642     {"$f10",    RTYPE_FPU | 10}, \
2643     {"$f11",    RTYPE_FPU | 11}, \
2644     {"$f12",    RTYPE_FPU | 12}, \
2645     {"$f13",    RTYPE_FPU | 13}, \
2646     {"$f14",    RTYPE_FPU | 14}, \
2647     {"$f15",    RTYPE_FPU | 15}, \
2648     {"$f16",    RTYPE_FPU | 16}, \
2649     {"$f17",    RTYPE_FPU | 17}, \
2650     {"$f18",    RTYPE_FPU | 18}, \
2651     {"$f19",    RTYPE_FPU | 19}, \
2652     {"$f20",    RTYPE_FPU | 20}, \
2653     {"$f21",    RTYPE_FPU | 21}, \
2654     {"$f22",    RTYPE_FPU | 22}, \
2655     {"$f23",    RTYPE_FPU | 23}, \
2656     {"$f24",    RTYPE_FPU | 24}, \
2657     {"$f25",    RTYPE_FPU | 25}, \
2658     {"$f26",    RTYPE_FPU | 26}, \
2659     {"$f27",    RTYPE_FPU | 27}, \
2660     {"$f28",    RTYPE_FPU | 28}, \
2661     {"$f29",    RTYPE_FPU | 29}, \
2662     {"$f30",    RTYPE_FPU | 30}, \
2663     {"$f31",    RTYPE_FPU | 31}
2664
2665 #define FPU_CONDITION_CODE_NAMES \
2666     {"$fcc0",   RTYPE_FCC | 0},  \
2667     {"$fcc1",   RTYPE_FCC | 1},  \
2668     {"$fcc2",   RTYPE_FCC | 2},  \
2669     {"$fcc3",   RTYPE_FCC | 3},  \
2670     {"$fcc4",   RTYPE_FCC | 4},  \
2671     {"$fcc5",   RTYPE_FCC | 5},  \
2672     {"$fcc6",   RTYPE_FCC | 6},  \
2673     {"$fcc7",   RTYPE_FCC | 7}
2674
2675 #define COPROC_CONDITION_CODE_NAMES         \
2676     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2677     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2678     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2679     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2680     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2681     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2682     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2683     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2684
2685 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2686     {"$a4",     RTYPE_GP | 8},  \
2687     {"$a5",     RTYPE_GP | 9},  \
2688     {"$a6",     RTYPE_GP | 10}, \
2689     {"$a7",     RTYPE_GP | 11}, \
2690     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2691     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2692     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2693     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2694     {"$t0",     RTYPE_GP | 12}, \
2695     {"$t1",     RTYPE_GP | 13}, \
2696     {"$t2",     RTYPE_GP | 14}, \
2697     {"$t3",     RTYPE_GP | 15}
2698
2699 #define O32_SYMBOLIC_REGISTER_NAMES \
2700     {"$t0",     RTYPE_GP | 8},  \
2701     {"$t1",     RTYPE_GP | 9},  \
2702     {"$t2",     RTYPE_GP | 10}, \
2703     {"$t3",     RTYPE_GP | 11}, \
2704     {"$t4",     RTYPE_GP | 12}, \
2705     {"$t5",     RTYPE_GP | 13}, \
2706     {"$t6",     RTYPE_GP | 14}, \
2707     {"$t7",     RTYPE_GP | 15}, \
2708     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2709     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2710     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2711     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */
2712
2713 /* Remaining symbolic register names */
2714 #define SYMBOLIC_REGISTER_NAMES \
2715     {"$zero",   RTYPE_GP | 0},  \
2716     {"$at",     RTYPE_GP | 1},  \
2717     {"$AT",     RTYPE_GP | 1},  \
2718     {"$v0",     RTYPE_GP | 2},  \
2719     {"$v1",     RTYPE_GP | 3},  \
2720     {"$a0",     RTYPE_GP | 4},  \
2721     {"$a1",     RTYPE_GP | 5},  \
2722     {"$a2",     RTYPE_GP | 6},  \
2723     {"$a3",     RTYPE_GP | 7},  \
2724     {"$s0",     RTYPE_GP | 16}, \
2725     {"$s1",     RTYPE_GP | 17}, \
2726     {"$s2",     RTYPE_GP | 18}, \
2727     {"$s3",     RTYPE_GP | 19}, \
2728     {"$s4",     RTYPE_GP | 20}, \
2729     {"$s5",     RTYPE_GP | 21}, \
2730     {"$s6",     RTYPE_GP | 22}, \
2731     {"$s7",     RTYPE_GP | 23}, \
2732     {"$t8",     RTYPE_GP | 24}, \
2733     {"$t9",     RTYPE_GP | 25}, \
2734     {"$k0",     RTYPE_GP | 26}, \
2735     {"$kt0",    RTYPE_GP | 26}, \
2736     {"$k1",     RTYPE_GP | 27}, \
2737     {"$kt1",    RTYPE_GP | 27}, \
2738     {"$gp",     RTYPE_GP | 28}, \
2739     {"$sp",     RTYPE_GP | 29}, \
2740     {"$s8",     RTYPE_GP | 30}, \
2741     {"$fp",     RTYPE_GP | 30}, \
2742     {"$ra",     RTYPE_GP | 31}
2743
2744 #define MIPS16_SPECIAL_REGISTER_NAMES \
2745     {"$pc",     RTYPE_PC | 0}
2746
2747 #define MDMX_VECTOR_REGISTER_NAMES \
2748     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2749     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2750     {"$v2",     RTYPE_VEC | 2},  \
2751     {"$v3",     RTYPE_VEC | 3},  \
2752     {"$v4",     RTYPE_VEC | 4},  \
2753     {"$v5",     RTYPE_VEC | 5},  \
2754     {"$v6",     RTYPE_VEC | 6},  \
2755     {"$v7",     RTYPE_VEC | 7},  \
2756     {"$v8",     RTYPE_VEC | 8},  \
2757     {"$v9",     RTYPE_VEC | 9},  \
2758     {"$v10",    RTYPE_VEC | 10}, \
2759     {"$v11",    RTYPE_VEC | 11}, \
2760     {"$v12",    RTYPE_VEC | 12}, \
2761     {"$v13",    RTYPE_VEC | 13}, \
2762     {"$v14",    RTYPE_VEC | 14}, \
2763     {"$v15",    RTYPE_VEC | 15}, \
2764     {"$v16",    RTYPE_VEC | 16}, \
2765     {"$v17",    RTYPE_VEC | 17}, \
2766     {"$v18",    RTYPE_VEC | 18}, \
2767     {"$v19",    RTYPE_VEC | 19}, \
2768     {"$v20",    RTYPE_VEC | 20}, \
2769     {"$v21",    RTYPE_VEC | 21}, \
2770     {"$v22",    RTYPE_VEC | 22}, \
2771     {"$v23",    RTYPE_VEC | 23}, \
2772     {"$v24",    RTYPE_VEC | 24}, \
2773     {"$v25",    RTYPE_VEC | 25}, \
2774     {"$v26",    RTYPE_VEC | 26}, \
2775     {"$v27",    RTYPE_VEC | 27}, \
2776     {"$v28",    RTYPE_VEC | 28}, \
2777     {"$v29",    RTYPE_VEC | 29}, \
2778     {"$v30",    RTYPE_VEC | 30}, \
2779     {"$v31",    RTYPE_VEC | 31}
2780
2781 #define R5900_I_NAMES \
2782     {"$I",      RTYPE_R5900_I | 0}
2783
2784 #define R5900_Q_NAMES \
2785     {"$Q",      RTYPE_R5900_Q | 0}
2786
2787 #define R5900_R_NAMES \
2788     {"$R",      RTYPE_R5900_R | 0}
2789
2790 #define R5900_ACC_NAMES \
2791     {"$ACC",    RTYPE_R5900_ACC | 0 }
2792
2793 #define MIPS_DSP_ACCUMULATOR_NAMES \
2794     {"$ac0",    RTYPE_ACC | 0}, \
2795     {"$ac1",    RTYPE_ACC | 1}, \
2796     {"$ac2",    RTYPE_ACC | 2}, \
2797     {"$ac3",    RTYPE_ACC | 3}
2798
2799 static const struct regname reg_names[] = {
2800   GENERIC_REGISTER_NUMBERS,
2801   FPU_REGISTER_NAMES,
2802   FPU_CONDITION_CODE_NAMES,
2803   COPROC_CONDITION_CODE_NAMES,
2804
2805   /* The $txx registers depends on the abi,
2806      these will be added later into the symbol table from
2807      one of the tables below once mips_abi is set after
2808      parsing of arguments from the command line. */
2809   SYMBOLIC_REGISTER_NAMES,
2810
2811   MIPS16_SPECIAL_REGISTER_NAMES,
2812   MDMX_VECTOR_REGISTER_NAMES,
2813   R5900_I_NAMES,
2814   R5900_Q_NAMES,
2815   R5900_R_NAMES,
2816   R5900_ACC_NAMES,
2817   MIPS_DSP_ACCUMULATOR_NAMES,
2818   {0, 0}
2819 };
2820
2821 static const struct regname reg_names_o32[] = {
2822   O32_SYMBOLIC_REGISTER_NAMES,
2823   {0, 0}
2824 };
2825
2826 static const struct regname reg_names_n32n64[] = {
2827   N32N64_SYMBOLIC_REGISTER_NAMES,
2828   {0, 0}
2829 };
2830
2831 /* Register symbols $v0 and $v1 map to GPRs 2 and 3, but they can also be
2832    interpreted as vector registers 0 and 1.  If SYMVAL is the value of one
2833    of these register symbols, return the associated vector register,
2834    otherwise return SYMVAL itself.  */
2835
2836 static unsigned int
2837 mips_prefer_vec_regno (unsigned int symval)
2838 {
2839   if ((symval & -2) == (RTYPE_GP | 2))
2840     return RTYPE_VEC | (symval & 1);
2841   return symval;
2842 }
2843
2844 /* Return true if string [S, E) is a valid register name, storing its
2845    symbol value in *SYMVAL_PTR if so.  */
2846
2847 static bfd_boolean
2848 mips_parse_register_1 (char *s, char *e, unsigned int *symval_ptr)
2849 {
2850   char save_c;
2851   symbolS *symbol;
2852
2853   /* Terminate name.  */
2854   save_c = *e;
2855   *e = '\0';
2856
2857   /* Look up the name.  */
2858   symbol = symbol_find (s);
2859   *e = save_c;
2860
2861   if (!symbol || S_GET_SEGMENT (symbol) != reg_section)
2862     return FALSE;
2863
2864   *symval_ptr = S_GET_VALUE (symbol);
2865   return TRUE;
2866 }
2867
2868 /* Return true if the string at *SPTR is a valid register name.  Allow it
2869    to have a VU0-style channel suffix of the form x?y?z?w? if CHANNELS_PTR
2870    is nonnull.
2871
2872    When returning true, move *SPTR past the register, store the
2873    register's symbol value in *SYMVAL_PTR and the channel mask in
2874    *CHANNELS_PTR (if nonnull).  The symbol value includes the register
2875    number (RNUM_MASK) and register type (RTYPE_MASK).  The channel mask
2876    is a 4-bit value of the form XYZW and is 0 if no suffix was given.  */
2877
2878 static bfd_boolean
2879 mips_parse_register (char **sptr, unsigned int *symval_ptr,
2880                      unsigned int *channels_ptr)
2881 {
2882   char *s, *e, *m;
2883   const char *q;
2884   unsigned int channels, symval, bit;
2885
2886   /* Find end of name.  */
2887   s = e = *sptr;
2888   if (is_name_beginner (*e))
2889     ++e;
2890   while (is_part_of_name (*e))
2891     ++e;
2892
2893   channels = 0;
2894   if (!mips_parse_register_1 (s, e, &symval))
2895     {
2896       if (!channels_ptr)
2897         return FALSE;
2898
2899       /* Eat characters from the end of the string that are valid
2900          channel suffixes.  The preceding register must be $ACC or
2901          end with a digit, so there is no ambiguity.  */
2902       bit = 1;
2903       m = e;
2904       for (q = "wzyx"; *q; q++, bit <<= 1)
2905         if (m > s && m[-1] == *q)
2906           {
2907             --m;
2908             channels |= bit;
2909           }
2910
2911       if (channels == 0
2912           || !mips_parse_register_1 (s, m, &symval)
2913           || (symval & (RTYPE_VI | RTYPE_VF | RTYPE_R5900_ACC)) == 0)
2914         return FALSE;
2915     }
2916
2917   *sptr = e;
2918   *symval_ptr = symval;
2919   if (channels_ptr)
2920     *channels_ptr = channels;
2921   return TRUE;
2922 }
2923
2924 /* Check if SPTR points at a valid register specifier according to TYPES.
2925    If so, then return 1, advance S to consume the specifier and store
2926    the register's number in REGNOP, otherwise return 0.  */
2927
2928 static int
2929 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2930 {
2931   unsigned int regno;
2932
2933   if (mips_parse_register (s, &regno, NULL))
2934     {
2935       if (types & RTYPE_VEC)
2936         regno = mips_prefer_vec_regno (regno);
2937       if (regno & types)
2938         regno &= RNUM_MASK;
2939       else
2940         regno = ~0;
2941     }
2942   else
2943     {
2944       if (types & RWARN)
2945         as_warn (_("unrecognized register name `%s'"), *s);
2946       regno = ~0;
2947     }
2948   if (regnop)
2949     *regnop = regno;
2950   return regno <= RNUM_MASK;
2951 }
2952
2953 /* Parse a VU0 "x?y?z?w?" channel mask at S and store the associated
2954    mask in *CHANNELS.  Return a pointer to the first unconsumed character.  */
2955
2956 static char *
2957 mips_parse_vu0_channels (char *s, unsigned int *channels)
2958 {
2959   unsigned int i;
2960
2961   *channels = 0;
2962   for (i = 0; i < 4; i++)
2963     if (*s == "xyzw"[i])
2964       {
2965         *channels |= 1 << (3 - i);
2966         ++s;
2967       }
2968   return s;
2969 }
2970
2971 /* Token types for parsed operand lists.  */
2972 enum mips_operand_token_type {
2973   /* A plain register, e.g. $f2.  */
2974   OT_REG,
2975
2976   /* A 4-bit XYZW channel mask.  */
2977   OT_CHANNELS,
2978
2979   /* A constant vector index, e.g. [1].  */
2980   OT_INTEGER_INDEX,
2981
2982   /* A register vector index, e.g. [$2].  */
2983   OT_REG_INDEX,
2984
2985   /* A continuous range of registers, e.g. $s0-$s4.  */
2986   OT_REG_RANGE,
2987
2988   /* A (possibly relocated) expression.  */
2989   OT_INTEGER,
2990
2991   /* A floating-point value.  */
2992   OT_FLOAT,
2993
2994   /* A single character.  This can be '(', ')' or ',', but '(' only appears
2995      before OT_REGs.  */
2996   OT_CHAR,
2997
2998   /* A doubled character, either "--" or "++".  */
2999   OT_DOUBLE_CHAR,
3000
3001   /* The end of the operand list.  */
3002   OT_END
3003 };
3004
3005 /* A parsed operand token.  */
3006 struct mips_operand_token
3007 {
3008   /* The type of token.  */
3009   enum mips_operand_token_type type;
3010   union
3011   {
3012     /* The register symbol value for an OT_REG or OT_REG_INDEX.  */
3013     unsigned int regno;
3014
3015     /* The 4-bit channel mask for an OT_CHANNEL_SUFFIX.  */
3016     unsigned int channels;
3017
3018     /* The integer value of an OT_INTEGER_INDEX.  */
3019     addressT index;
3020
3021     /* The two register symbol values involved in an OT_REG_RANGE.  */
3022     struct {
3023       unsigned int regno1;
3024       unsigned int regno2;
3025     } reg_range;
3026
3027     /* The value of an OT_INTEGER.  The value is represented as an
3028        expression and the relocation operators that were applied to
3029        that expression.  The reloc entries are BFD_RELOC_UNUSED if no
3030        relocation operators were used.  */
3031     struct {
3032       expressionS value;
3033       bfd_reloc_code_real_type relocs[3];
3034     } integer;
3035
3036     /* The binary data for an OT_FLOAT constant, and the number of bytes
3037        in the constant.  */
3038     struct {
3039       unsigned char data[8];
3040       int length;
3041     } flt;
3042
3043     /* The character represented by an OT_CHAR or OT_DOUBLE_CHAR.  */
3044     char ch;
3045   } u;
3046 };
3047
3048 /* An obstack used to construct lists of mips_operand_tokens.  */
3049 static struct obstack mips_operand_tokens;
3050
3051 /* Give TOKEN type TYPE and add it to mips_operand_tokens.  */
3052
3053 static void
3054 mips_add_token (struct mips_operand_token *token,
3055                 enum mips_operand_token_type type)
3056 {
3057   token->type = type;
3058   obstack_grow (&mips_operand_tokens, token, sizeof (*token));
3059 }
3060
3061 /* Check whether S is '(' followed by a register name.  Add OT_CHAR
3062    and OT_REG tokens for them if so, and return a pointer to the first
3063    unconsumed character.  Return null otherwise.  */
3064
3065 static char *
3066 mips_parse_base_start (char *s)
3067 {
3068   struct mips_operand_token token;
3069   unsigned int regno, channels;
3070   bfd_boolean decrement_p;
3071
3072   if (*s != '(')
3073     return 0;
3074
3075   ++s;
3076   SKIP_SPACE_TABS (s);
3077
3078   /* Only match "--" as part of a base expression.  In other contexts "--X"
3079      is a double negative.  */
3080   decrement_p = (s[0] == '-' && s[1] == '-');
3081   if (decrement_p)
3082     {
3083       s += 2;
3084       SKIP_SPACE_TABS (s);
3085     }
3086
3087   /* Allow a channel specifier because that leads to better error messages
3088      than treating something like "$vf0x++" as an expression.  */
3089   if (!mips_parse_register (&s, &regno, &channels))
3090     return 0;
3091
3092   token.u.ch = '(';
3093   mips_add_token (&token, OT_CHAR);
3094
3095   if (decrement_p)
3096     {
3097       token.u.ch = '-';
3098       mips_add_token (&token, OT_DOUBLE_CHAR);
3099     }
3100
3101   token.u.regno = regno;
3102   mips_add_token (&token, OT_REG);
3103
3104   if (channels)
3105     {
3106       token.u.channels = channels;
3107       mips_add_token (&token, OT_CHANNELS);
3108     }
3109
3110   /* For consistency, only match "++" as part of base expressions too.  */
3111   SKIP_SPACE_TABS (s);
3112   if (s[0] == '+' && s[1] == '+')
3113     {
3114       s += 2;
3115       token.u.ch = '+';
3116       mips_add_token (&token, OT_DOUBLE_CHAR);
3117     }
3118
3119   return s;
3120 }
3121
3122 /* Parse one or more tokens from S.  Return a pointer to the first
3123    unconsumed character on success.  Return null if an error was found
3124    and store the error text in insn_error.  FLOAT_FORMAT is as for
3125    mips_parse_arguments.  */
3126
3127 static char *
3128 mips_parse_argument_token (char *s, char float_format)
3129 {
3130   char *end, *save_in;
3131   const char *err;
3132   unsigned int regno1, regno2, channels;
3133   struct mips_operand_token token;
3134
3135   /* First look for "($reg", since we want to treat that as an
3136      OT_CHAR and OT_REG rather than an expression.  */
3137   end = mips_parse_base_start (s);
3138   if (end)
3139     return end;
3140
3141   /* Handle other characters that end up as OT_CHARs.  */
3142   if (*s == ')' || *s == ',')
3143     {
3144       token.u.ch = *s;
3145       mips_add_token (&token, OT_CHAR);
3146       ++s;
3147       return s;
3148     }
3149
3150   /* Handle tokens that start with a register.  */
3151   if (mips_parse_register (&s, &regno1, &channels))
3152     {
3153       if (channels)
3154         {
3155           /* A register and a VU0 channel suffix.  */
3156           token.u.regno = regno1;
3157           mips_add_token (&token, OT_REG);
3158
3159           token.u.channels = channels;
3160           mips_add_token (&token, OT_CHANNELS);
3161           return s;
3162         }
3163
3164       SKIP_SPACE_TABS (s);
3165       if (*s == '-')
3166         {
3167           /* A register range.  */
3168           ++s;
3169           SKIP_SPACE_TABS (s);
3170           if (!mips_parse_register (&s, &regno2, NULL))
3171             {
3172               set_insn_error (0, _("invalid register range"));
3173               return 0;
3174             }
3175
3176           token.u.reg_range.regno1 = regno1;
3177           token.u.reg_range.regno2 = regno2;
3178           mips_add_token (&token, OT_REG_RANGE);
3179           return s;
3180         }
3181
3182       /* Add the register itself.  */
3183       token.u.regno = regno1;
3184       mips_add_token (&token, OT_REG);
3185
3186       /* Check for a vector index.  */
3187       if (*s == '[')
3188         {
3189           ++s;
3190           SKIP_SPACE_TABS (s);
3191           if (mips_parse_register (&s, &token.u.regno, NULL))
3192             mips_add_token (&token, OT_REG_INDEX);
3193           else
3194             {
3195               expressionS element;
3196
3197               my_getExpression (&element, s);
3198               if (element.X_op != O_constant)
3199                 {
3200                   set_insn_error (0, _("vector element must be constant"));
3201                   return 0;
3202                 }
3203               s = expr_end;
3204               token.u.index = element.X_add_number;
3205               mips_add_token (&token, OT_INTEGER_INDEX);
3206             }
3207           SKIP_SPACE_TABS (s);
3208           if (*s != ']')
3209             {
3210               set_insn_error (0, _("missing `]'"));
3211               return 0;
3212             }
3213           ++s;
3214         }
3215       return s;
3216     }
3217
3218   if (float_format)
3219     {
3220       /* First try to treat expressions as floats.  */
3221       save_in = input_line_pointer;
3222       input_line_pointer = s;
3223       err = md_atof (float_format, (char *) token.u.flt.data,
3224                      &token.u.flt.length);
3225       end = input_line_pointer;
3226       input_line_pointer = save_in;
3227       if (err && *err)
3228         {
3229           set_insn_error (0, err);
3230           return 0;
3231         }
3232       if (s != end)
3233         {
3234           mips_add_token (&token, OT_FLOAT);
3235           return end;
3236         }
3237     }
3238
3239   /* Treat everything else as an integer expression.  */
3240   token.u.integer.relocs[0] = BFD_RELOC_UNUSED;
3241   token.u.integer.relocs[1] = BFD_RELOC_UNUSED;
3242   token.u.integer.relocs[2] = BFD_RELOC_UNUSED;
3243   my_getSmallExpression (&token.u.integer.value, token.u.integer.relocs, s);
3244   s = expr_end;
3245   mips_add_token (&token, OT_INTEGER);
3246   return s;
3247 }
3248
3249 /* S points to the operand list for an instruction.  FLOAT_FORMAT is 'f'
3250    if expressions should be treated as 32-bit floating-point constants,
3251    'd' if they should be treated as 64-bit floating-point constants,
3252    or 0 if they should be treated as integer expressions (the usual case).
3253
3254    Return a list of tokens on success, otherwise return 0.  The caller
3255    must obstack_free the list after use.  */
3256
3257 static struct mips_operand_token *
3258 mips_parse_arguments (char *s, char float_format)
3259 {
3260   struct mips_operand_token token;
3261
3262   SKIP_SPACE_TABS (s);
3263   while (*s)
3264     {
3265       s = mips_parse_argument_token (s, float_format);
3266       if (!s)
3267         {
3268           obstack_free (&mips_operand_tokens,
3269                         obstack_finish (&mips_operand_tokens));
3270           return 0;
3271         }
3272       SKIP_SPACE_TABS (s);
3273     }
3274   mips_add_token (&token, OT_END);
3275   return (struct mips_operand_token *) obstack_finish (&mips_operand_tokens);
3276 }
3277
3278 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
3279    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
3280
3281 static bfd_boolean
3282 is_opcode_valid (const struct mips_opcode *mo)
3283 {
3284   int isa = mips_opts.isa;
3285   int ase = mips_opts.ase;
3286   int fp_s, fp_d;
3287   unsigned int i;
3288
3289   if (ISA_HAS_64BIT_REGS (isa))
3290     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
3291       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
3292         ase |= mips_ases[i].flags64;
3293
3294   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
3295     return FALSE;
3296
3297   /* Check whether the instruction or macro requires single-precision or
3298      double-precision floating-point support.  Note that this information is
3299      stored differently in the opcode table for insns and macros.  */
3300   if (mo->pinfo == INSN_MACRO)
3301     {
3302       fp_s = mo->pinfo2 & INSN2_M_FP_S;
3303       fp_d = mo->pinfo2 & INSN2_M_FP_D;
3304     }
3305   else
3306     {
3307       fp_s = mo->pinfo & FP_S;
3308       fp_d = mo->pinfo & FP_D;
3309     }
3310
3311   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
3312     return FALSE;
3313
3314   if (fp_s && mips_opts.soft_float)
3315     return FALSE;
3316
3317   return TRUE;
3318 }
3319
3320 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
3321    selected ISA and architecture.  */
3322
3323 static bfd_boolean
3324 is_opcode_valid_16 (const struct mips_opcode *mo)
3325 {
3326   int isa = mips_opts.isa;
3327   int ase = mips_opts.ase;
3328   unsigned int i;
3329
3330   if (ISA_HAS_64BIT_REGS (isa))
3331     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
3332       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
3333         ase |= mips_ases[i].flags64;
3334
3335   return opcode_is_member (mo, isa, ase, mips_opts.arch);
3336 }
3337
3338 /* Return TRUE if the size of the microMIPS opcode MO matches one
3339    explicitly requested.  Always TRUE in the standard MIPS mode.
3340    Use is_size_valid_16 for MIPS16 opcodes.  */
3341
3342 static bfd_boolean
3343 is_size_valid (const struct mips_opcode *mo)
3344 {
3345   if (!mips_opts.micromips)
3346     return TRUE;
3347
3348   if (mips_opts.insn32)
3349     {
3350       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
3351         return FALSE;
3352       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
3353         return FALSE;
3354     }
3355   if (!forced_insn_length)
3356     return TRUE;
3357   if (mo->pinfo == INSN_MACRO)
3358     return FALSE;
3359   return forced_insn_length == micromips_insn_length (mo);
3360 }
3361
3362 /* Return TRUE if the size of the MIPS16 opcode MO matches one
3363    explicitly requested.  */
3364
3365 static bfd_boolean
3366 is_size_valid_16 (const struct mips_opcode *mo)
3367 {
3368   if (!forced_insn_length)
3369     return TRUE;
3370   if (mo->pinfo == INSN_MACRO)
3371     return FALSE;
3372   if (forced_insn_length == 2 && mips_opcode_32bit_p (mo))
3373     return FALSE;
3374   if (forced_insn_length == 4 && (mo->pinfo2 & INSN2_SHORT_ONLY))
3375     return FALSE;
3376   return TRUE;
3377 }
3378
3379 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
3380    of the preceding instruction.  Always TRUE in the standard MIPS mode.
3381
3382    We don't accept macros in 16-bit delay slots to avoid a case where
3383    a macro expansion fails because it relies on a preceding 32-bit real
3384    instruction to have matched and does not handle the operands correctly.
3385    The only macros that may expand to 16-bit instructions are JAL that
3386    cannot be placed in a delay slot anyway, and corner cases of BALIGN
3387    and BGT (that likewise cannot be placed in a delay slot) that decay to
3388    a NOP.  In all these cases the macros precede any corresponding real
3389    instruction definitions in the opcode table, so they will match in the
3390    second pass where the size of the delay slot is ignored and therefore
3391    produce correct code.  */
3392
3393 static bfd_boolean
3394 is_delay_slot_valid (const struct mips_opcode *mo)
3395 {
3396   if (!mips_opts.micromips)
3397     return TRUE;
3398
3399   if (mo->pinfo == INSN_MACRO)
3400     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
3401   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
3402       && micromips_insn_length (mo) != 4)
3403     return FALSE;
3404   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
3405       && micromips_insn_length (mo) != 2)
3406     return FALSE;
3407
3408   return TRUE;
3409 }
3410
3411 /* For consistency checking, verify that all bits of OPCODE are specified
3412    either by the match/mask part of the instruction definition, or by the
3413    operand list.  Also build up a list of operands in OPERANDS.
3414
3415    INSN_BITS says which bits of the instruction are significant.
3416    If OPCODE is a standard or microMIPS instruction, DECODE_OPERAND
3417    provides the mips_operand description of each operand.  DECODE_OPERAND
3418    is null for MIPS16 instructions.  */
3419
3420 static int
3421 validate_mips_insn (const struct mips_opcode *opcode,
3422                     unsigned long insn_bits,
3423                     const struct mips_operand *(*decode_operand) (const char *),
3424                     struct mips_operand_array *operands)
3425 {
3426   const char *s;
3427   unsigned long used_bits, doubled, undefined, opno, mask;
3428   const struct mips_operand *operand;
3429
3430   mask = (opcode->pinfo == INSN_MACRO ? 0 : opcode->mask);
3431   if ((mask & opcode->match) != opcode->match)
3432     {
3433       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
3434               opcode->name, opcode->args);
3435       return 0;
3436     }
3437   used_bits = 0;
3438   opno = 0;
3439   if (opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX)
3440     used_bits = mips_insert_operand (&mips_vu0_channel_mask, used_bits, -1);
3441   for (s = opcode->args; *s; ++s)
3442     switch (*s)
3443       {
3444       case ',':
3445       case '(':
3446       case ')':
3447         break;
3448
3449       case '#':
3450         s++;
3451         break;
3452
3453       default:
3454         if (!decode_operand)
3455           operand = decode_mips16_operand (*s, mips_opcode_32bit_p (opcode));
3456         else
3457           operand = decode_operand (s);
3458         if (!operand && opcode->pinfo != INSN_MACRO)
3459           {
3460             as_bad (_("internal: unknown operand type: %s %s"),
3461                     opcode->name, opcode->args);
3462             return 0;
3463           }
3464         gas_assert (opno < MAX_OPERANDS);
3465         operands->operand[opno] = operand;
3466         if (!decode_operand && operand
3467             && operand->type == OP_INT && operand->lsb == 0
3468             && mips_opcode_32bit_p (opcode))
3469           used_bits |= mips16_immed_extend (-1, operand->size);
3470         else if (operand && operand->type != OP_VU0_MATCH_SUFFIX)
3471           {
3472             used_bits = mips_insert_operand (operand, used_bits, -1);
3473             if (operand->type == OP_MDMX_IMM_REG)
3474               /* Bit 5 is the format selector (OB vs QH).  The opcode table
3475                  has separate entries for each format.  */
3476               used_bits &= ~(1 << (operand->lsb + 5));
3477             if (operand->type == OP_ENTRY_EXIT_LIST)
3478               used_bits &= ~(mask & 0x700);
3479             /* interAptiv MR2 SAVE/RESTORE instructions have a discontiguous
3480                operand field that cannot be fully described with LSB/SIZE.  */
3481             if (operand->type == OP_SAVE_RESTORE_LIST && operand->lsb == 6)
3482               used_bits &= ~0x6000;
3483           }
3484         /* Skip prefix characters.  */
3485         if (decode_operand && (*s == '+' || *s == 'm' || *s == '-'))
3486           ++s;
3487         opno += 1;
3488         break;
3489       }
3490   doubled = used_bits & mask & insn_bits;
3491   if (doubled)
3492     {
3493       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
3494                 " %s %s"), doubled, opcode->name, opcode->args);
3495       return 0;
3496     }
3497   used_bits |= mask;
3498   undefined = ~used_bits & insn_bits;
3499   if (opcode->pinfo != INSN_MACRO && undefined)
3500     {
3501       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
3502               undefined, opcode->name, opcode->args);
3503       return 0;
3504     }
3505   used_bits &= ~insn_bits;
3506   if (used_bits)
3507     {
3508       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
3509               used_bits, opcode->name, opcode->args);
3510       return 0;
3511     }
3512   return 1;
3513 }
3514
3515 /* The MIPS16 version of validate_mips_insn.  */
3516
3517 static int
3518 validate_mips16_insn (const struct mips_opcode *opcode,
3519                       struct mips_operand_array *operands)
3520 {
3521   unsigned long insn_bits = mips_opcode_32bit_p (opcode) ? 0xffffffff : 0xffff;
3522
3523   return validate_mips_insn (opcode, insn_bits, 0, operands);
3524 }
3525
3526 /* The microMIPS version of validate_mips_insn.  */
3527
3528 static int
3529 validate_micromips_insn (const struct mips_opcode *opc,
3530                          struct mips_operand_array *operands)
3531 {
3532   unsigned long insn_bits;
3533   unsigned long major;
3534   unsigned int length;
3535
3536   if (opc->pinfo == INSN_MACRO)
3537     return validate_mips_insn (opc, 0xffffffff, decode_micromips_operand,
3538                                operands);
3539
3540   length = micromips_insn_length (opc);
3541   if (length != 2 && length != 4)
3542     {
3543       as_bad (_("internal error: bad microMIPS opcode (incorrect length: %u): "
3544                 "%s %s"), length, opc->name, opc->args);
3545       return 0;
3546     }
3547   major = opc->match >> (10 + 8 * (length - 2));
3548   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
3549       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
3550     {
3551       as_bad (_("internal error: bad microMIPS opcode "
3552                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
3553       return 0;
3554     }
3555
3556   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
3557   insn_bits = 1 << 4 * length;
3558   insn_bits <<= 4 * length;
3559   insn_bits -= 1;
3560   return validate_mips_insn (opc, insn_bits, decode_micromips_operand,
3561                              operands);
3562 }
3563
3564 /* This function is called once, at assembler startup time.  It should set up
3565    all the tables, etc. that the MD part of the assembler will need.  */
3566
3567 void
3568 md_begin (void)
3569 {
3570   const char *retval = NULL;
3571   int i = 0;
3572   int broken = 0;
3573
3574   if (mips_pic != NO_PIC)
3575     {
3576       if (g_switch_seen && g_switch_value != 0)
3577         as_bad (_("-G may not be used in position-independent code"));
3578       g_switch_value = 0;
3579     }
3580   else if (mips_abicalls)
3581     {
3582       if (g_switch_seen && g_switch_value != 0)
3583         as_bad (_("-G may not be used with abicalls"));
3584       g_switch_value = 0;
3585     }
3586
3587   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_opts.arch))
3588     as_warn (_("could not set architecture and machine"));
3589
3590   op_hash = hash_new ();
3591
3592   mips_operands = XCNEWVEC (struct mips_operand_array, NUMOPCODES);
3593   for (i = 0; i < NUMOPCODES;)
3594     {
3595       const char *name = mips_opcodes[i].name;
3596
3597       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
3598       if (retval != NULL)
3599         {
3600           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
3601                    mips_opcodes[i].name, retval);
3602           /* Probably a memory allocation problem?  Give up now.  */
3603           as_fatal (_("broken assembler, no assembly attempted"));
3604         }
3605       do
3606         {
3607           if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
3608                                    decode_mips_operand, &mips_operands[i]))
3609             broken = 1;
3610           if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3611             {
3612               create_insn (&nop_insn, mips_opcodes + i);
3613               if (mips_fix_loongson2f_nop)
3614                 nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
3615               nop_insn.fixed_p = 1;
3616             }
3617           ++i;
3618         }
3619       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
3620     }
3621
3622   mips16_op_hash = hash_new ();
3623   mips16_operands = XCNEWVEC (struct mips_operand_array,
3624                               bfd_mips16_num_opcodes);
3625
3626   i = 0;
3627   while (i < bfd_mips16_num_opcodes)
3628     {
3629       const char *name = mips16_opcodes[i].name;
3630
3631       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
3632       if (retval != NULL)
3633         as_fatal (_("internal: can't hash `%s': %s"),
3634                   mips16_opcodes[i].name, retval);
3635       do
3636         {
3637           if (!validate_mips16_insn (&mips16_opcodes[i], &mips16_operands[i]))
3638             broken = 1;
3639           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3640             {
3641               create_insn (&mips16_nop_insn, mips16_opcodes + i);
3642               mips16_nop_insn.fixed_p = 1;
3643             }
3644           ++i;
3645         }
3646       while (i < bfd_mips16_num_opcodes
3647              && strcmp (mips16_opcodes[i].name, name) == 0);
3648     }
3649
3650   micromips_op_hash = hash_new ();
3651   micromips_operands = XCNEWVEC (struct mips_operand_array,
3652                                  bfd_micromips_num_opcodes);
3653
3654   i = 0;
3655   while (i < bfd_micromips_num_opcodes)
3656     {
3657       const char *name = micromips_opcodes[i].name;
3658
3659       retval = hash_insert (micromips_op_hash, name,
3660                             (void *) &micromips_opcodes[i]);
3661       if (retval != NULL)
3662         as_fatal (_("internal: can't hash `%s': %s"),
3663                   micromips_opcodes[i].name, retval);
3664       do
3665         {
3666           struct mips_cl_insn *micromips_nop_insn;
3667
3668           if (!validate_micromips_insn (&micromips_opcodes[i],
3669                                         &micromips_operands[i]))
3670             broken = 1;
3671
3672           if (micromips_opcodes[i].pinfo != INSN_MACRO)
3673             {
3674               if (micromips_insn_length (micromips_opcodes + i) == 2)
3675                 micromips_nop_insn = &micromips_nop16_insn;
3676               else if (micromips_insn_length (micromips_opcodes + i) == 4)
3677                 micromips_nop_insn = &micromips_nop32_insn;
3678               else
3679                 continue;
3680
3681               if (micromips_nop_insn->insn_mo == NULL
3682                   && strcmp (name, "nop") == 0)
3683                 {
3684                   create_insn (micromips_nop_insn, micromips_opcodes + i);
3685                   micromips_nop_insn->fixed_p = 1;
3686                 }
3687             }
3688         }
3689       while (++i < bfd_micromips_num_opcodes
3690              && strcmp (micromips_opcodes[i].name, name) == 0);
3691     }
3692
3693   if (broken)
3694     as_fatal (_("broken assembler, no assembly attempted"));
3695
3696   /* We add all the general register names to the symbol table.  This
3697      helps us detect invalid uses of them.  */
3698   for (i = 0; reg_names[i].name; i++)
3699     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
3700                                      reg_names[i].num, /* & RNUM_MASK, */
3701                                      &zero_address_frag));
3702   if (HAVE_NEWABI)
3703     for (i = 0; reg_names_n32n64[i].name; i++)
3704       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
3705                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
3706                                        &zero_address_frag));
3707   else
3708     for (i = 0; reg_names_o32[i].name; i++)
3709       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
3710                                        reg_names_o32[i].num, /* & RNUM_MASK, */
3711                                        &zero_address_frag));
3712
3713   for (i = 0; i < 32; i++)
3714     {
3715       char regname[6];
3716
3717       /* R5900 VU0 floating-point register.  */
3718       sprintf (regname, "$vf%d", i);
3719       symbol_table_insert (symbol_new (regname, reg_section,
3720                                        RTYPE_VF | i, &zero_address_frag));
3721
3722       /* R5900 VU0 integer register.  */
3723       sprintf (regname, "$vi%d", i);
3724       symbol_table_insert (symbol_new (regname, reg_section,
3725                                        RTYPE_VI | i, &zero_address_frag));
3726
3727       /* MSA register.  */
3728       sprintf (regname, "$w%d", i);
3729       symbol_table_insert (symbol_new (regname, reg_section,
3730                                        RTYPE_MSA | i, &zero_address_frag));
3731     }
3732
3733   obstack_init (&mips_operand_tokens);
3734
3735   mips_no_prev_insn ();
3736
3737   mips_gprmask = 0;
3738   mips_cprmask[0] = 0;
3739   mips_cprmask[1] = 0;
3740   mips_cprmask[2] = 0;
3741   mips_cprmask[3] = 0;
3742
3743   /* set the default alignment for the text section (2**2) */
3744   record_alignment (text_section, 2);
3745
3746   bfd_set_gp_size (stdoutput, g_switch_value);
3747
3748   /* On a native system other than VxWorks, sections must be aligned
3749      to 16 byte boundaries.  When configured for an embedded ELF
3750      target, we don't bother.  */
3751   if (strncmp (TARGET_OS, "elf", 3) != 0
3752       && strncmp (TARGET_OS, "vxworks", 7) != 0)
3753     {
3754       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
3755       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
3756       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
3757     }
3758
3759   /* Create a .reginfo section for register masks and a .mdebug
3760      section for debugging information.  */
3761   {
3762     segT seg;
3763     subsegT subseg;
3764     flagword flags;
3765     segT sec;
3766
3767     seg = now_seg;
3768     subseg = now_subseg;
3769
3770     /* The ABI says this section should be loaded so that the
3771        running program can access it.  However, we don't load it
3772        if we are configured for an embedded target */
3773     flags = SEC_READONLY | SEC_DATA;
3774     if (strncmp (TARGET_OS, "elf", 3) != 0)
3775       flags |= SEC_ALLOC | SEC_LOAD;
3776
3777     if (mips_abi != N64_ABI)
3778       {
3779         sec = subseg_new (".reginfo", (subsegT) 0);
3780
3781         bfd_set_section_flags (stdoutput, sec, flags);
3782         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
3783
3784         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
3785       }
3786     else
3787       {
3788         /* The 64-bit ABI uses a .MIPS.options section rather than
3789            .reginfo section.  */
3790         sec = subseg_new (".MIPS.options", (subsegT) 0);
3791         bfd_set_section_flags (stdoutput, sec, flags);
3792         bfd_set_section_alignment (stdoutput, sec, 3);
3793
3794         /* Set up the option header.  */
3795         {
3796           Elf_Internal_Options opthdr;
3797           char *f;
3798
3799           opthdr.kind = ODK_REGINFO;
3800           opthdr.size = (sizeof (Elf_External_Options)
3801                          + sizeof (Elf64_External_RegInfo));
3802           opthdr.section = 0;
3803           opthdr.info = 0;
3804           f = frag_more (sizeof (Elf_External_Options));
3805           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
3806                                          (Elf_External_Options *) f);
3807
3808           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
3809         }
3810       }
3811
3812     sec = subseg_new (".MIPS.abiflags", (subsegT) 0);
3813     bfd_set_section_flags (stdoutput, sec,
3814                            SEC_READONLY | SEC_DATA | SEC_ALLOC | SEC_LOAD);
3815     bfd_set_section_alignment (stdoutput, sec, 3);
3816     mips_flags_frag = frag_more (sizeof (Elf_External_ABIFlags_v0));
3817
3818     if (ECOFF_DEBUGGING)
3819       {
3820         sec = subseg_new (".mdebug", (subsegT) 0);
3821         (void) bfd_set_section_flags (stdoutput, sec,
3822                                       SEC_HAS_CONTENTS | SEC_READONLY);
3823         (void) bfd_set_section_alignment (stdoutput, sec, 2);
3824       }
3825     else if (mips_flag_pdr)
3826       {
3827         pdr_seg = subseg_new (".pdr", (subsegT) 0);
3828         (void) bfd_set_section_flags (stdoutput, pdr_seg,
3829                                       SEC_READONLY | SEC_RELOC
3830                                       | SEC_DEBUGGING);
3831         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
3832       }
3833
3834     subseg_set (seg, subseg);
3835   }
3836
3837   if (mips_fix_vr4120)
3838     init_vr4120_conflicts ();
3839 }
3840
3841 static inline void
3842 fpabi_incompatible_with (int fpabi, const char *what)
3843 {
3844   as_warn (_(".gnu_attribute %d,%d is incompatible with `%s'"),
3845            Tag_GNU_MIPS_ABI_FP, fpabi, what);
3846 }
3847
3848 static inline void
3849 fpabi_requires (int fpabi, const char *what)
3850 {
3851   as_warn (_(".gnu_attribute %d,%d requires `%s'"),
3852            Tag_GNU_MIPS_ABI_FP, fpabi, what);
3853 }
3854
3855 /* Check -mabi and register sizes against the specified FP ABI.  */
3856 static void
3857 check_fpabi (int fpabi)
3858 {
3859   switch (fpabi)
3860     {
3861     case Val_GNU_MIPS_ABI_FP_DOUBLE:
3862       if (file_mips_opts.soft_float)
3863         fpabi_incompatible_with (fpabi, "softfloat");
3864       else if (file_mips_opts.single_float)
3865         fpabi_incompatible_with (fpabi, "singlefloat");
3866       if (file_mips_opts.gp == 64 && file_mips_opts.fp == 32)
3867         fpabi_incompatible_with (fpabi, "gp=64 fp=32");
3868       else if (file_mips_opts.gp == 32 && file_mips_opts.fp == 64)
3869         fpabi_incompatible_with (fpabi, "gp=32 fp=64");
3870       break;
3871
3872     case Val_GNU_MIPS_ABI_FP_XX:
3873       if (mips_abi != O32_ABI)
3874         fpabi_requires (fpabi, "-mabi=32");
3875       else if (file_mips_opts.soft_float)
3876         fpabi_incompatible_with (fpabi, "softfloat");
3877       else if (file_mips_opts.single_float)
3878         fpabi_incompatible_with (fpabi, "singlefloat");
3879       else if (file_mips_opts.fp != 0)
3880         fpabi_requires (fpabi, "fp=xx");
3881       break;
3882
3883     case Val_GNU_MIPS_ABI_FP_64A:
3884     case Val_GNU_MIPS_ABI_FP_64:
3885       if (mips_abi != O32_ABI)
3886         fpabi_requires (fpabi, "-mabi=32");
3887       else if (file_mips_opts.soft_float)
3888         fpabi_incompatible_with (fpabi, "softfloat");
3889       else if (file_mips_opts.single_float)
3890         fpabi_incompatible_with (fpabi, "singlefloat");
3891       else if (file_mips_opts.fp != 64)
3892         fpabi_requires (fpabi, "fp=64");
3893       else if (fpabi == Val_GNU_MIPS_ABI_FP_64 && !file_mips_opts.oddspreg)
3894         fpabi_incompatible_with (fpabi, "nooddspreg");
3895       else if (fpabi == Val_GNU_MIPS_ABI_FP_64A && file_mips_opts.oddspreg)
3896         fpabi_requires (fpabi, "nooddspreg");
3897       break;
3898
3899     case Val_GNU_MIPS_ABI_FP_SINGLE:
3900       if (file_mips_opts.soft_float)
3901         fpabi_incompatible_with (fpabi, "softfloat");
3902       else if (!file_mips_opts.single_float)
3903         fpabi_requires (fpabi, "singlefloat");
3904       break;
3905
3906     case Val_GNU_MIPS_ABI_FP_SOFT:
3907       if (!file_mips_opts.soft_float)
3908         fpabi_requires (fpabi, "softfloat");
3909       break;
3910
3911     case Val_GNU_MIPS_ABI_FP_OLD_64:
3912       as_warn (_(".gnu_attribute %d,%d is no longer supported"),
3913                Tag_GNU_MIPS_ABI_FP, fpabi);
3914       break;
3915
3916     case Val_GNU_MIPS_ABI_FP_NAN2008:
3917       /* Silently ignore compatibility value.  */
3918       break;
3919
3920     default:
3921       as_warn (_(".gnu_attribute %d,%d is not a recognized"
3922                  " floating-point ABI"), Tag_GNU_MIPS_ABI_FP, fpabi);
3923       break;
3924     }
3925 }
3926
3927 /* Perform consistency checks on the current options.  */
3928
3929 static void
3930 mips_check_options (struct mips_set_options *opts, bfd_boolean abi_checks)
3931 {
3932   /* Check the size of integer registers agrees with the ABI and ISA.  */
3933   if (opts->gp == 64 && !ISA_HAS_64BIT_REGS (opts->isa))
3934     as_bad (_("`gp=64' used with a 32-bit processor"));
3935   else if (abi_checks
3936            && opts->gp == 32 && ABI_NEEDS_64BIT_REGS (mips_abi))
3937     as_bad (_("`gp=32' used with a 64-bit ABI"));
3938   else if (abi_checks
3939            && opts->gp == 64 && ABI_NEEDS_32BIT_REGS (mips_abi))
3940     as_bad (_("`gp=64' used with a 32-bit ABI"));
3941
3942   /* Check the size of the float registers agrees with the ABI and ISA.  */
3943   switch (opts->fp)
3944     {
3945     case 0:
3946       if (!CPU_HAS_LDC1_SDC1 (opts->arch))
3947         as_bad (_("`fp=xx' used with a cpu lacking ldc1/sdc1 instructions"));
3948       else if (opts->single_float == 1)
3949         as_bad (_("`fp=xx' cannot be used with `singlefloat'"));
3950       break;
3951     case 64:
3952       if (!ISA_HAS_64BIT_FPRS (opts->isa))
3953         as_bad (_("`fp=64' used with a 32-bit fpu"));
3954       else if (abi_checks
3955                && ABI_NEEDS_32BIT_REGS (mips_abi)
3956                && !ISA_HAS_MXHC1 (opts->isa))
3957         as_warn (_("`fp=64' used with a 32-bit ABI"));
3958       break;
3959     case 32:
3960       if (abi_checks
3961           && ABI_NEEDS_64BIT_REGS (mips_abi))
3962         as_warn (_("`fp=32' used with a 64-bit ABI"));
3963       if (ISA_IS_R6 (opts->isa) && opts->single_float == 0)
3964         as_bad (_("`fp=32' used with a MIPS R6 cpu"));
3965       break;
3966     default:
3967       as_bad (_("Unknown size of floating point registers"));
3968       break;
3969     }
3970
3971   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !opts->oddspreg)
3972     as_bad (_("`nooddspreg` cannot be used with a 64-bit ABI"));
3973
3974   if (opts->micromips == 1 && opts->mips16 == 1)
3975     as_bad (_("`%s' cannot be used with `%s'"), "mips16", "micromips");
3976   else if (ISA_IS_R6 (opts->isa)
3977            && (opts->micromips == 1
3978                || opts->mips16 == 1))
3979     as_fatal (_("`%s' cannot be used with `%s'"),
3980               opts->micromips ? "micromips" : "mips16",
3981               mips_cpu_info_from_isa (opts->isa)->name);
3982
3983   if (ISA_IS_R6 (opts->isa) && mips_relax_branch)
3984     as_fatal (_("branch relaxation is not supported in `%s'"),
3985               mips_cpu_info_from_isa (opts->isa)->name);
3986 }
3987
3988 /* Perform consistency checks on the module level options exactly once.
3989    This is a deferred check that happens:
3990      at the first .set directive
3991      or, at the first pseudo op that generates code (inc .dc.a)
3992      or, at the first instruction
3993      or, at the end.  */
3994
3995 static void
3996 file_mips_check_options (void)
3997 {
3998   const struct mips_cpu_info *arch_info = 0;
3999
4000   if (file_mips_opts_checked)
4001     return;
4002
4003   /* The following code determines the register size.
4004      Similar code was added to GCC 3.3 (see override_options() in
4005      config/mips/mips.c).  The GAS and GCC code should be kept in sync
4006      as much as possible.  */
4007
4008   if (file_mips_opts.gp < 0)
4009     {
4010       /* Infer the integer register size from the ABI and processor.
4011          Restrict ourselves to 32-bit registers if that's all the
4012          processor has, or if the ABI cannot handle 64-bit registers.  */
4013       file_mips_opts.gp = (ABI_NEEDS_32BIT_REGS (mips_abi)
4014                            || !ISA_HAS_64BIT_REGS (file_mips_opts.isa))
4015                           ? 32 : 64;
4016     }
4017
4018   if (file_mips_opts.fp < 0)
4019     {
4020       /* No user specified float register size.
4021          ??? GAS treats single-float processors as though they had 64-bit
4022          float registers (although it complains when double-precision
4023          instructions are used).  As things stand, saying they have 32-bit
4024          registers would lead to spurious "register must be even" messages.
4025          So here we assume float registers are never smaller than the
4026          integer ones.  */
4027       if (file_mips_opts.gp == 64)
4028         /* 64-bit integer registers implies 64-bit float registers.  */
4029         file_mips_opts.fp = 64;
4030       else if ((file_mips_opts.ase & FP64_ASES)
4031                && ISA_HAS_64BIT_FPRS (file_mips_opts.isa))
4032         /* Handle ASEs that require 64-bit float registers, if possible.  */
4033         file_mips_opts.fp = 64;
4034       else if (ISA_IS_R6 (mips_opts.isa))
4035         /* R6 implies 64-bit float registers.  */
4036         file_mips_opts.fp = 64;
4037       else
4038         /* 32-bit float registers.  */
4039         file_mips_opts.fp = 32;
4040     }
4041
4042   arch_info = mips_cpu_info_from_arch (file_mips_opts.arch);
4043
4044   /* Disable operations on odd-numbered floating-point registers by default
4045      when using the FPXX ABI.  */
4046   if (file_mips_opts.oddspreg < 0)
4047     {
4048       if (file_mips_opts.fp == 0)
4049         file_mips_opts.oddspreg = 0;
4050       else
4051         file_mips_opts.oddspreg = 1;
4052     }
4053
4054   /* End of GCC-shared inference code.  */
4055
4056   /* This flag is set when we have a 64-bit capable CPU but use only
4057      32-bit wide registers.  Note that EABI does not use it.  */
4058   if (ISA_HAS_64BIT_REGS (file_mips_opts.isa)
4059       && ((mips_abi == NO_ABI && file_mips_opts.gp == 32)
4060           || mips_abi == O32_ABI))
4061     mips_32bitmode = 1;
4062
4063   if (file_mips_opts.isa == ISA_MIPS1 && mips_trap)
4064     as_bad (_("trap exception not supported at ISA 1"));
4065
4066   /* If the selected architecture includes support for ASEs, enable
4067      generation of code for them.  */
4068   if (file_mips_opts.mips16 == -1)
4069     file_mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_opts.arch)) ? 1 : 0;
4070   if (file_mips_opts.micromips == -1)
4071     file_mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_opts.arch))
4072                                 ? 1 : 0;
4073
4074   if (mips_nan2008 == -1)
4075     mips_nan2008 = (ISA_HAS_LEGACY_NAN (file_mips_opts.isa)) ? 0 : 1;
4076   else if (!ISA_HAS_LEGACY_NAN (file_mips_opts.isa) && mips_nan2008 == 0)
4077     as_fatal (_("`%s' does not support legacy NaN"),
4078               mips_cpu_info_from_arch (file_mips_opts.arch)->name);
4079
4080   /* Some ASEs require 64-bit FPRs, so -mfp32 should stop those ASEs from
4081      being selected implicitly.  */
4082   if (file_mips_opts.fp != 64)
4083     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX | ASE_MSA;
4084
4085   /* If the user didn't explicitly select or deselect a particular ASE,
4086      use the default setting for the CPU.  */
4087   file_mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
4088
4089   /* Set up the current options.  These may change throughout assembly.  */
4090   mips_opts = file_mips_opts;
4091
4092   mips_check_isa_supports_ases ();
4093   mips_check_options (&file_mips_opts, TRUE);
4094   file_mips_opts_checked = TRUE;
4095
4096   if (!bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_opts.arch))
4097     as_warn (_("could not set architecture and machine"));
4098 }
4099
4100 void
4101 md_assemble (char *str)
4102 {
4103   struct mips_cl_insn insn;
4104   bfd_reloc_code_real_type unused_reloc[3]
4105     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
4106
4107   file_mips_check_options ();
4108
4109   imm_expr.X_op = O_absent;
4110   offset_expr.X_op = O_absent;
4111   offset_reloc[0] = BFD_RELOC_UNUSED;
4112   offset_reloc[1] = BFD_RELOC_UNUSED;
4113   offset_reloc[2] = BFD_RELOC_UNUSED;
4114
4115   mips_mark_labels ();
4116   mips_assembling_insn = TRUE;
4117   clear_insn_error ();
4118
4119   if (mips_opts.mips16)
4120     mips16_ip (str, &insn);
4121   else
4122     {
4123       mips_ip (str, &insn);
4124       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
4125             str, insn.insn_opcode));
4126     }
4127
4128   if (insn_error.msg)
4129     report_insn_error (str);
4130   else if (insn.insn_mo->pinfo == INSN_MACRO)
4131     {
4132       macro_start ();
4133       if (mips_opts.mips16)
4134         mips16_macro (&insn);
4135       else
4136         macro (&insn, str);
4137       macro_end ();
4138     }
4139   else
4140     {
4141       if (offset_expr.X_op != O_absent)
4142         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
4143       else
4144         append_insn (&insn, NULL, unused_reloc, FALSE);
4145     }
4146
4147   mips_assembling_insn = FALSE;
4148 }
4149
4150 /* Convenience functions for abstracting away the differences between
4151    MIPS16 and non-MIPS16 relocations.  */
4152
4153 static inline bfd_boolean
4154 mips16_reloc_p (bfd_reloc_code_real_type reloc)
4155 {
4156   switch (reloc)
4157     {
4158     case BFD_RELOC_MIPS16_JMP:
4159     case BFD_RELOC_MIPS16_GPREL:
4160     case BFD_RELOC_MIPS16_GOT16:
4161     case BFD_RELOC_MIPS16_CALL16:
4162     case BFD_RELOC_MIPS16_HI16_S:
4163     case BFD_RELOC_MIPS16_HI16:
4164     case BFD_RELOC_MIPS16_LO16:
4165     case BFD_RELOC_MIPS16_16_PCREL_S1:
4166       return TRUE;
4167
4168     default:
4169       return FALSE;
4170     }
4171 }
4172
4173 static inline bfd_boolean
4174 micromips_reloc_p (bfd_reloc_code_real_type reloc)
4175 {
4176   switch (reloc)
4177     {
4178     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
4179     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
4180     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
4181     case BFD_RELOC_MICROMIPS_GPREL16:
4182     case BFD_RELOC_MICROMIPS_JMP:
4183     case BFD_RELOC_MICROMIPS_HI16:
4184     case BFD_RELOC_MICROMIPS_HI16_S:
4185     case BFD_RELOC_MICROMIPS_LO16:
4186     case BFD_RELOC_MICROMIPS_LITERAL:
4187     case BFD_RELOC_MICROMIPS_GOT16:
4188     case BFD_RELOC_MICROMIPS_CALL16:
4189     case BFD_RELOC_MICROMIPS_GOT_HI16:
4190     case BFD_RELOC_MICROMIPS_GOT_LO16:
4191     case BFD_RELOC_MICROMIPS_CALL_HI16:
4192     case BFD_RELOC_MICROMIPS_CALL_LO16:
4193     case BFD_RELOC_MICROMIPS_SUB:
4194     case BFD_RELOC_MICROMIPS_GOT_PAGE:
4195     case BFD_RELOC_MICROMIPS_GOT_OFST:
4196     case BFD_RELOC_MICROMIPS_GOT_DISP:
4197     case BFD_RELOC_MICROMIPS_HIGHEST:
4198     case BFD_RELOC_MICROMIPS_HIGHER:
4199     case BFD_RELOC_MICROMIPS_SCN_DISP:
4200     case BFD_RELOC_MICROMIPS_JALR:
4201       return TRUE;
4202
4203     default:
4204       return FALSE;
4205     }
4206 }
4207
4208 static inline bfd_boolean
4209 jmp_reloc_p (bfd_reloc_code_real_type reloc)
4210 {
4211   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
4212 }
4213
4214 static inline bfd_boolean
4215 b_reloc_p (bfd_reloc_code_real_type reloc)
4216 {
4217   return (reloc == BFD_RELOC_MIPS_26_PCREL_S2
4218           || reloc == BFD_RELOC_MIPS_21_PCREL_S2
4219           || reloc == BFD_RELOC_16_PCREL_S2
4220           || reloc == BFD_RELOC_MIPS16_16_PCREL_S1
4221           || reloc == BFD_RELOC_MICROMIPS_16_PCREL_S1
4222           || reloc == BFD_RELOC_MICROMIPS_10_PCREL_S1
4223           || reloc == BFD_RELOC_MICROMIPS_7_PCREL_S1);
4224 }
4225
4226 static inline bfd_boolean
4227 got16_reloc_p (bfd_reloc_code_real_type reloc)
4228 {
4229   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
4230           || reloc == BFD_RELOC_MICROMIPS_GOT16);
4231 }
4232
4233 static inline bfd_boolean
4234 hi16_reloc_p (bfd_reloc_code_real_type reloc)
4235 {
4236   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
4237           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
4238 }
4239
4240 static inline bfd_boolean
4241 lo16_reloc_p (bfd_reloc_code_real_type reloc)
4242 {
4243   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
4244           || reloc == BFD_RELOC_MICROMIPS_LO16);
4245 }
4246
4247 static inline bfd_boolean
4248 jalr_reloc_p (bfd_reloc_code_real_type reloc)
4249 {
4250   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
4251 }
4252
4253 static inline bfd_boolean
4254 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
4255 {
4256   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
4257           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
4258 }
4259
4260 /* Return true if RELOC is a PC-relative relocation that does not have
4261    full address range.  */
4262
4263 static inline bfd_boolean
4264 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
4265 {
4266   switch (reloc)
4267     {
4268     case BFD_RELOC_16_PCREL_S2:
4269     case BFD_RELOC_MIPS16_16_PCREL_S1:
4270     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
4271     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
4272     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
4273     case BFD_RELOC_MIPS_21_PCREL_S2:
4274     case BFD_RELOC_MIPS_26_PCREL_S2:
4275     case BFD_RELOC_MIPS_18_PCREL_S3:
4276     case BFD_RELOC_MIPS_19_PCREL_S2:
4277       return TRUE;
4278
4279     case BFD_RELOC_32_PCREL:
4280     case BFD_RELOC_HI16_S_PCREL:
4281     case BFD_RELOC_LO16_PCREL:
4282       return HAVE_64BIT_ADDRESSES;
4283
4284     default:
4285       return FALSE;
4286     }
4287 }
4288
4289 /* Return true if the given relocation might need a matching %lo().
4290    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
4291    need a matching %lo() when applied to local symbols.  */
4292
4293 static inline bfd_boolean
4294 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
4295 {
4296   return (HAVE_IN_PLACE_ADDENDS
4297           && (hi16_reloc_p (reloc)
4298               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
4299                  all GOT16 relocations evaluate to "G".  */
4300               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
4301 }
4302
4303 /* Return the type of %lo() reloc needed by RELOC, given that
4304    reloc_needs_lo_p.  */
4305
4306 static inline bfd_reloc_code_real_type
4307 matching_lo_reloc (bfd_reloc_code_real_type reloc)
4308 {
4309   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
4310           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
4311              : BFD_RELOC_LO16));
4312 }
4313
4314 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
4315    relocation.  */
4316
4317 static inline bfd_boolean
4318 fixup_has_matching_lo_p (fixS *fixp)
4319 {
4320   return (fixp->fx_next != NULL
4321           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
4322           && fixp->fx_addsy == fixp->fx_next->fx_addsy
4323           && fixp->fx_offset == fixp->fx_next->fx_offset);
4324 }
4325
4326 /* Move all labels in LABELS to the current insertion point.  TEXT_P
4327    says whether the labels refer to text or data.  */
4328
4329 static void
4330 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
4331 {
4332   struct insn_label_list *l;
4333   valueT val;
4334
4335   for (l = labels; l != NULL; l = l->next)
4336     {
4337       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
4338       symbol_set_frag (l->label, frag_now);
4339       val = (valueT) frag_now_fix ();
4340       /* MIPS16/microMIPS text labels are stored as odd.  */
4341       if (text_p && HAVE_CODE_COMPRESSION)
4342         ++val;
4343       S_SET_VALUE (l->label, val);
4344     }
4345 }
4346
4347 /* Move all labels in insn_labels to the current insertion point
4348    and treat them as text labels.  */
4349
4350 static void
4351 mips_move_text_labels (void)
4352 {
4353   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
4354 }
4355
4356 /* Duplicate the test for LINK_ONCE sections as in `adjust_reloc_syms'.  */
4357
4358 static bfd_boolean
4359 s_is_linkonce (symbolS *sym, segT from_seg)
4360 {
4361   bfd_boolean linkonce = FALSE;
4362   segT symseg = S_GET_SEGMENT (sym);
4363
4364   if (symseg != from_seg && !S_IS_LOCAL (sym))
4365     {
4366       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
4367         linkonce = TRUE;
4368       /* The GNU toolchain uses an extension for ELF: a section
4369          beginning with the magic string .gnu.linkonce is a
4370          linkonce section.  */
4371       if (strncmp (segment_name (symseg), ".gnu.linkonce",
4372                    sizeof ".gnu.linkonce" - 1) == 0)
4373         linkonce = TRUE;
4374     }
4375   return linkonce;
4376 }
4377
4378 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
4379    linker to handle them specially, such as generating jalx instructions
4380    when needed.  We also make them odd for the duration of the assembly,
4381    in order to generate the right sort of code.  We will make them even
4382    in the adjust_symtab routine, while leaving them marked.  This is
4383    convenient for the debugger and the disassembler.  The linker knows
4384    to make them odd again.  */
4385
4386 static void
4387 mips_compressed_mark_label (symbolS *label)
4388 {
4389   gas_assert (HAVE_CODE_COMPRESSION);
4390
4391   if (mips_opts.mips16)
4392     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
4393   else
4394     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
4395   if ((S_GET_VALUE (label) & 1) == 0
4396       /* Don't adjust the address if the label is global or weak, or
4397          in a link-once section, since we'll be emitting symbol reloc
4398          references to it which will be patched up by the linker, and
4399          the final value of the symbol may or may not be MIPS16/microMIPS.  */
4400       && !S_IS_WEAK (label)
4401       && !S_IS_EXTERNAL (label)
4402       && !s_is_linkonce (label, now_seg))
4403     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
4404 }
4405
4406 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
4407
4408 static void
4409 mips_compressed_mark_labels (void)
4410 {
4411   struct insn_label_list *l;
4412
4413   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
4414     mips_compressed_mark_label (l->label);
4415 }
4416
4417 /* End the current frag.  Make it a variant frag and record the
4418    relaxation info.  */
4419
4420 static void
4421 relax_close_frag (void)
4422 {
4423   mips_macro_warning.first_frag = frag_now;
4424   frag_var (rs_machine_dependent, 0, 0,
4425             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1],
4426                           mips_pic != NO_PIC),
4427             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
4428
4429   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
4430   mips_relax.first_fixup = 0;
4431 }
4432
4433 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
4434    See the comment above RELAX_ENCODE for more details.  */
4435
4436 static void
4437 relax_start (symbolS *symbol)
4438 {
4439   gas_assert (mips_relax.sequence == 0);
4440   mips_relax.sequence = 1;
4441   mips_relax.symbol = symbol;
4442 }
4443
4444 /* Start generating the second version of a relaxable sequence.
4445    See the comment above RELAX_ENCODE for more details.  */
4446
4447 static void
4448 relax_switch (void)
4449 {
4450   gas_assert (mips_relax.sequence == 1);
4451   mips_relax.sequence = 2;
4452 }
4453
4454 /* End the current relaxable sequence.  */
4455
4456 static void
4457 relax_end (void)
4458 {
4459   gas_assert (mips_relax.sequence == 2);
4460   relax_close_frag ();
4461   mips_relax.sequence = 0;
4462 }
4463
4464 /* Return true if IP is a delayed branch or jump.  */
4465
4466 static inline bfd_boolean
4467 delayed_branch_p (const struct mips_cl_insn *ip)
4468 {
4469   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
4470                                 | INSN_COND_BRANCH_DELAY
4471                                 | INSN_COND_BRANCH_LIKELY)) != 0;
4472 }
4473
4474 /* Return true if IP is a compact branch or jump.  */
4475
4476 static inline bfd_boolean
4477 compact_branch_p (const struct mips_cl_insn *ip)
4478 {
4479   return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
4480                                  | INSN2_COND_BRANCH)) != 0;
4481 }
4482
4483 /* Return true if IP is an unconditional branch or jump.  */
4484
4485 static inline bfd_boolean
4486 uncond_branch_p (const struct mips_cl_insn *ip)
4487 {
4488   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
4489           || (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0);
4490 }
4491
4492 /* Return true if IP is a branch-likely instruction.  */
4493
4494 static inline bfd_boolean
4495 branch_likely_p (const struct mips_cl_insn *ip)
4496 {
4497   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
4498 }
4499
4500 /* Return the type of nop that should be used to fill the delay slot
4501    of delayed branch IP.  */
4502
4503 static struct mips_cl_insn *
4504 get_delay_slot_nop (const struct mips_cl_insn *ip)
4505 {
4506   if (mips_opts.micromips
4507       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
4508     return &micromips_nop32_insn;
4509   return NOP_INSN;
4510 }
4511
4512 /* Return a mask that has bit N set if OPCODE reads the register(s)
4513    in operand N.  */
4514
4515 static unsigned int
4516 insn_read_mask (const struct mips_opcode *opcode)
4517 {
4518   return (opcode->pinfo & INSN_READ_ALL) >> INSN_READ_SHIFT;
4519 }
4520
4521 /* Return a mask that has bit N set if OPCODE writes to the register(s)
4522    in operand N.  */
4523
4524 static unsigned int
4525 insn_write_mask (const struct mips_opcode *opcode)
4526 {
4527   return (opcode->pinfo & INSN_WRITE_ALL) >> INSN_WRITE_SHIFT;
4528 }
4529
4530 /* Return a mask of the registers specified by operand OPERAND of INSN.
4531    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4532    is set.  */
4533
4534 static unsigned int
4535 operand_reg_mask (const struct mips_cl_insn *insn,
4536                   const struct mips_operand *operand,
4537                   unsigned int type_mask)
4538 {
4539   unsigned int uval, vsel;
4540
4541   switch (operand->type)
4542     {
4543     case OP_INT:
4544     case OP_MAPPED_INT:
4545     case OP_MSB:
4546     case OP_PCREL:
4547     case OP_PERF_REG:
4548     case OP_ADDIUSP_INT:
4549     case OP_ENTRY_EXIT_LIST:
4550     case OP_REPEAT_DEST_REG:
4551     case OP_REPEAT_PREV_REG:
4552     case OP_PC:
4553     case OP_VU0_SUFFIX:
4554     case OP_VU0_MATCH_SUFFIX:
4555     case OP_IMM_INDEX:
4556       abort ();
4557
4558     case OP_REG28:
4559       return 1 << 28;
4560
4561     case OP_REG:
4562     case OP_OPTIONAL_REG:
4563       {
4564         const struct mips_reg_operand *reg_op;
4565
4566         reg_op = (const struct mips_reg_operand *) operand;
4567         if (!(type_mask & (1 << reg_op->reg_type)))
4568           return 0;
4569         uval = insn_extract_operand (insn, operand);
4570         return 1 << mips_decode_reg_operand (reg_op, uval);
4571       }
4572
4573     case OP_REG_PAIR:
4574       {
4575         const struct mips_reg_pair_operand *pair_op;
4576
4577         pair_op = (const struct mips_reg_pair_operand *) operand;
4578         if (!(type_mask & (1 << pair_op->reg_type)))
4579           return 0;
4580         uval = insn_extract_operand (insn, operand);
4581         return (1 << pair_op->reg1_map[uval]) | (1 << pair_op->reg2_map[uval]);
4582       }
4583
4584     case OP_CLO_CLZ_DEST:
4585       if (!(type_mask & (1 << OP_REG_GP)))
4586         return 0;
4587       uval = insn_extract_operand (insn, operand);
4588       return (1 << (uval & 31)) | (1 << (uval >> 5));
4589
4590     case OP_SAME_RS_RT:
4591       if (!(type_mask & (1 << OP_REG_GP)))
4592         return 0;
4593       uval = insn_extract_operand (insn, operand);
4594       gas_assert ((uval & 31) == (uval >> 5));
4595       return 1 << (uval & 31);
4596
4597     case OP_CHECK_PREV:
4598     case OP_NON_ZERO_REG:
4599       if (!(type_mask & (1 << OP_REG_GP)))
4600         return 0;
4601       uval = insn_extract_operand (insn, operand);
4602       return 1 << (uval & 31);
4603
4604     case OP_LWM_SWM_LIST:
4605       abort ();
4606
4607     case OP_SAVE_RESTORE_LIST:
4608       abort ();
4609
4610     case OP_MDMX_IMM_REG:
4611       if (!(type_mask & (1 << OP_REG_VEC)))
4612         return 0;
4613       uval = insn_extract_operand (insn, operand);
4614       vsel = uval >> 5;
4615       if ((vsel & 0x18) == 0x18)
4616         return 0;
4617       return 1 << (uval & 31);
4618
4619     case OP_REG_INDEX:
4620       if (!(type_mask & (1 << OP_REG_GP)))
4621         return 0;
4622       return 1 << insn_extract_operand (insn, operand);
4623     }
4624   abort ();
4625 }
4626
4627 /* Return a mask of the registers specified by operands OPNO_MASK of INSN,
4628    where bit N of OPNO_MASK is set if operand N should be included.
4629    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4630    is set.  */
4631
4632 static unsigned int
4633 insn_reg_mask (const struct mips_cl_insn *insn,
4634                unsigned int type_mask, unsigned int opno_mask)
4635 {
4636   unsigned int opno, reg_mask;
4637
4638   opno = 0;
4639   reg_mask = 0;
4640   while (opno_mask != 0)
4641     {
4642       if (opno_mask & 1)
4643         reg_mask |= operand_reg_mask (insn, insn_opno (insn, opno), type_mask);
4644       opno_mask >>= 1;
4645       opno += 1;
4646     }
4647   return reg_mask;
4648 }
4649
4650 /* Return the mask of core registers that IP reads.  */
4651
4652 static unsigned int
4653 gpr_read_mask (const struct mips_cl_insn *ip)
4654 {
4655   unsigned long pinfo, pinfo2;
4656   unsigned int mask;
4657
4658   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_read_mask (ip->insn_mo));
4659   pinfo = ip->insn_mo->pinfo;
4660   pinfo2 = ip->insn_mo->pinfo2;
4661   if (pinfo & INSN_UDI)
4662     {
4663       /* UDI instructions have traditionally been assumed to read RS
4664          and RT.  */
4665       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
4666       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
4667     }
4668   if (pinfo & INSN_READ_GPR_24)
4669     mask |= 1 << 24;
4670   if (pinfo2 & INSN2_READ_GPR_16)
4671     mask |= 1 << 16;
4672   if (pinfo2 & INSN2_READ_SP)
4673     mask |= 1 << SP;
4674   if (pinfo2 & INSN2_READ_GPR_31)
4675     mask |= 1 << 31;
4676   /* Don't include register 0.  */
4677   return mask & ~1;
4678 }
4679
4680 /* Return the mask of core registers that IP writes.  */
4681
4682 static unsigned int
4683 gpr_write_mask (const struct mips_cl_insn *ip)
4684 {
4685   unsigned long pinfo, pinfo2;
4686   unsigned int mask;
4687
4688   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_write_mask (ip->insn_mo));
4689   pinfo = ip->insn_mo->pinfo;
4690   pinfo2 = ip->insn_mo->pinfo2;
4691   if (pinfo & INSN_WRITE_GPR_24)
4692     mask |= 1 << 24;
4693   if (pinfo & INSN_WRITE_GPR_31)
4694     mask |= 1 << 31;
4695   if (pinfo & INSN_UDI)
4696     /* UDI instructions have traditionally been assumed to write to RD.  */
4697     mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
4698   if (pinfo2 & INSN2_WRITE_SP)
4699     mask |= 1 << SP;
4700   /* Don't include register 0.  */
4701   return mask & ~1;
4702 }
4703
4704 /* Return the mask of floating-point registers that IP reads.  */
4705
4706 static unsigned int
4707 fpr_read_mask (const struct mips_cl_insn *ip)
4708 {
4709   unsigned long pinfo;
4710   unsigned int mask;
4711
4712   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4713                              | (1 << OP_REG_MSA)),
4714                         insn_read_mask (ip->insn_mo));
4715   pinfo = ip->insn_mo->pinfo;
4716   /* Conservatively treat all operands to an FP_D instruction are doubles.
4717      (This is overly pessimistic for things like cvt.d.s.)  */
4718   if (FPR_SIZE != 64 && (pinfo & FP_D))
4719     mask |= mask << 1;
4720   return mask;
4721 }
4722
4723 /* Return the mask of floating-point registers that IP writes.  */
4724
4725 static unsigned int
4726 fpr_write_mask (const struct mips_cl_insn *ip)
4727 {
4728   unsigned long pinfo;
4729   unsigned int mask;
4730
4731   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4732                              | (1 << OP_REG_MSA)),
4733                         insn_write_mask (ip->insn_mo));
4734   pinfo = ip->insn_mo->pinfo;
4735   /* Conservatively treat all operands to an FP_D instruction are doubles.
4736      (This is overly pessimistic for things like cvt.s.d.)  */
4737   if (FPR_SIZE != 64 && (pinfo & FP_D))
4738     mask |= mask << 1;
4739   return mask;
4740 }
4741
4742 /* Operand OPNUM of INSN is an odd-numbered floating-point register.
4743    Check whether that is allowed.  */
4744
4745 static bfd_boolean
4746 mips_oddfpreg_ok (const struct mips_opcode *insn, int opnum)
4747 {
4748   const char *s = insn->name;
4749   bfd_boolean oddspreg = (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa, mips_opts.arch)
4750                           || FPR_SIZE == 64)
4751                          && mips_opts.oddspreg;
4752
4753   if (insn->pinfo == INSN_MACRO)
4754     /* Let a macro pass, we'll catch it later when it is expanded.  */
4755     return TRUE;
4756
4757   /* Single-precision coprocessor loads and moves are OK for 32-bit registers,
4758      otherwise it depends on oddspreg.  */
4759   if ((insn->pinfo & FP_S)
4760       && (insn->pinfo & (INSN_LOAD_MEMORY | INSN_STORE_MEMORY
4761                          | INSN_LOAD_COPROC | INSN_COPROC_MOVE)))
4762     return FPR_SIZE == 32 || oddspreg;
4763
4764   /* Allow odd registers for single-precision ops and double-precision if the
4765      floating-point registers are 64-bit wide.  */
4766   switch (insn->pinfo & (FP_S | FP_D))
4767     {
4768     case FP_S:
4769     case 0:
4770       return oddspreg;
4771     case FP_D:
4772       return FPR_SIZE == 64;
4773     default:
4774       break;
4775     }
4776
4777   /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
4778   s = strchr (insn->name, '.');
4779   if (s != NULL && opnum == 2)
4780     s = strchr (s + 1, '.');
4781   if (s != NULL && (s[1] == 'w' || s[1] == 's'))
4782     return oddspreg;
4783
4784   return FPR_SIZE == 64;
4785 }
4786
4787 /* Information about an instruction argument that we're trying to match.  */
4788 struct mips_arg_info
4789 {
4790   /* The instruction so far.  */
4791   struct mips_cl_insn *insn;
4792
4793   /* The first unconsumed operand token.  */
4794   struct mips_operand_token *token;
4795
4796   /* The 1-based operand number, in terms of insn->insn_mo->args.  */
4797   int opnum;
4798
4799   /* The 1-based argument number, for error reporting.  This does not
4800      count elided optional registers, etc..  */
4801   int argnum;
4802
4803   /* The last OP_REG operand seen, or ILLEGAL_REG if none.  */
4804   unsigned int last_regno;
4805
4806   /* If the first operand was an OP_REG, this is the register that it
4807      specified, otherwise it is ILLEGAL_REG.  */
4808   unsigned int dest_regno;
4809
4810   /* The value of the last OP_INT operand.  Only used for OP_MSB,
4811      where it gives the lsb position.  */
4812   unsigned int last_op_int;
4813
4814   /* If true, match routines should assume that no later instruction
4815      alternative matches and should therefore be as accommodating as
4816      possible.  Match routines should not report errors if something
4817      is only invalid for !LAX_MATCH.  */
4818   bfd_boolean lax_match;
4819
4820   /* True if a reference to the current AT register was seen.  */
4821   bfd_boolean seen_at;
4822 };
4823
4824 /* Record that the argument is out of range.  */
4825
4826 static void
4827 match_out_of_range (struct mips_arg_info *arg)
4828 {
4829   set_insn_error_i (arg->argnum, _("operand %d out of range"), arg->argnum);
4830 }
4831
4832 /* Record that the argument isn't constant but needs to be.  */
4833
4834 static void
4835 match_not_constant (struct mips_arg_info *arg)
4836 {
4837   set_insn_error_i (arg->argnum, _("operand %d must be constant"),
4838                     arg->argnum);
4839 }
4840
4841 /* Try to match an OT_CHAR token for character CH.  Consume the token
4842    and return true on success, otherwise return false.  */
4843
4844 static bfd_boolean
4845 match_char (struct mips_arg_info *arg, char ch)
4846 {
4847   if (arg->token->type == OT_CHAR && arg->token->u.ch == ch)
4848     {
4849       ++arg->token;
4850       if (ch == ',')
4851         arg->argnum += 1;
4852       return TRUE;
4853     }
4854   return FALSE;
4855 }
4856
4857 /* Try to get an expression from the next tokens in ARG.  Consume the
4858    tokens and return true on success, storing the expression value in
4859    VALUE and relocation types in R.  */
4860
4861 static bfd_boolean
4862 match_expression (struct mips_arg_info *arg, expressionS *value,
4863                   bfd_reloc_code_real_type *r)
4864 {
4865   /* If the next token is a '(' that was parsed as being part of a base
4866      expression, assume we have an elided offset.  The later match will fail
4867      if this turns out to be wrong.  */
4868   if (arg->token->type == OT_CHAR && arg->token->u.ch == '(')
4869     {
4870       value->X_op = O_constant;
4871       value->X_add_number = 0;
4872       r[0] = r[1] = r[2] = BFD_RELOC_UNUSED;
4873       return TRUE;
4874     }
4875
4876   /* Reject register-based expressions such as "0+$2" and "(($2))".
4877      For plain registers the default error seems more appropriate.  */
4878   if (arg->token->type == OT_INTEGER
4879       && arg->token->u.integer.value.X_op == O_register)
4880     {
4881       set_insn_error (arg->argnum, _("register value used as expression"));
4882       return FALSE;
4883     }
4884
4885   if (arg->token->type == OT_INTEGER)
4886     {
4887       *value = arg->token->u.integer.value;
4888       memcpy (r, arg->token->u.integer.relocs, 3 * sizeof (*r));
4889       ++arg->token;
4890       return TRUE;
4891     }
4892
4893   set_insn_error_i
4894     (arg->argnum, _("operand %d must be an immediate expression"),
4895      arg->argnum);
4896   return FALSE;
4897 }
4898
4899 /* Try to get a constant expression from the next tokens in ARG.  Consume
4900    the tokens and return return true on success, storing the constant value
4901    in *VALUE.  */
4902
4903 static bfd_boolean
4904 match_const_int (struct mips_arg_info *arg, offsetT *value)
4905 {
4906   expressionS ex;
4907   bfd_reloc_code_real_type r[3];
4908
4909   if (!match_expression (arg, &ex, r))
4910     return FALSE;
4911
4912   if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_constant)
4913     *value = ex.X_add_number;
4914   else
4915     {
4916       if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_big)
4917         match_out_of_range (arg);
4918       else
4919         match_not_constant (arg);
4920       return FALSE;
4921     }
4922   return TRUE;
4923 }
4924
4925 /* Return the RTYPE_* flags for a register operand of type TYPE that
4926    appears in instruction OPCODE.  */
4927
4928 static unsigned int
4929 convert_reg_type (const struct mips_opcode *opcode,
4930                   enum mips_reg_operand_type type)
4931 {
4932   switch (type)
4933     {
4934     case OP_REG_GP:
4935       return RTYPE_NUM | RTYPE_GP;
4936
4937     case OP_REG_FP:
4938       /* Allow vector register names for MDMX if the instruction is a 64-bit
4939          FPR load, store or move (including moves to and from GPRs).  */
4940       if ((mips_opts.ase & ASE_MDMX)
4941           && (opcode->pinfo & FP_D)
4942           && (opcode->pinfo & (INSN_COPROC_MOVE
4943                                | INSN_COPROC_MEMORY_DELAY
4944                                | INSN_LOAD_COPROC
4945                                | INSN_LOAD_MEMORY
4946                                | INSN_STORE_MEMORY)))
4947         return RTYPE_FPU | RTYPE_VEC;
4948       return RTYPE_FPU;
4949
4950     case OP_REG_CCC:
4951       if (opcode->pinfo & (FP_D | FP_S))
4952         return RTYPE_CCC | RTYPE_FCC;
4953       return RTYPE_CCC;
4954
4955     case OP_REG_VEC:
4956       if (opcode->membership & INSN_5400)
4957         return RTYPE_FPU;
4958       return RTYPE_FPU | RTYPE_VEC;
4959
4960     case OP_REG_ACC:
4961       return RTYPE_ACC;
4962
4963     case OP_REG_COPRO:
4964       if (opcode->name[strlen (opcode->name) - 1] == '0')
4965         return RTYPE_NUM | RTYPE_CP0;
4966       return RTYPE_NUM;
4967
4968     case OP_REG_HW:
4969       return RTYPE_NUM;
4970
4971     case OP_REG_VI:
4972       return RTYPE_NUM | RTYPE_VI;
4973
4974     case OP_REG_VF:
4975       return RTYPE_NUM | RTYPE_VF;
4976
4977     case OP_REG_R5900_I:
4978       return RTYPE_R5900_I;
4979
4980     case OP_REG_R5900_Q:
4981       return RTYPE_R5900_Q;
4982
4983     case OP_REG_R5900_R:
4984       return RTYPE_R5900_R;
4985
4986     case OP_REG_R5900_ACC:
4987       return RTYPE_R5900_ACC;
4988
4989     case OP_REG_MSA:
4990       return RTYPE_MSA;
4991
4992     case OP_REG_MSA_CTRL:
4993       return RTYPE_NUM;
4994     }
4995   abort ();
4996 }
4997
4998 /* ARG is register REGNO, of type TYPE.  Warn about any dubious registers.  */
4999
5000 static void
5001 check_regno (struct mips_arg_info *arg,
5002              enum mips_reg_operand_type type, unsigned int regno)
5003 {
5004   if (AT && type == OP_REG_GP && regno == AT)
5005     arg->seen_at = TRUE;
5006
5007   if (type == OP_REG_FP
5008       && (regno & 1) != 0
5009       && !mips_oddfpreg_ok (arg->insn->insn_mo, arg->opnum))
5010     {
5011       /* This was a warning prior to introducing O32 FPXX and FP64 support
5012          so maintain a warning for FP32 but raise an error for the new
5013          cases.  */
5014       if (FPR_SIZE == 32)
5015         as_warn (_("float register should be even, was %d"), regno);
5016       else
5017         as_bad (_("float register should be even, was %d"), regno);
5018     }
5019
5020   if (type == OP_REG_CCC)
5021     {
5022       const char *name;
5023       size_t length;
5024
5025       name = arg->insn->insn_mo->name;
5026       length = strlen (name);
5027       if ((regno & 1) != 0
5028           && ((length >= 3 && strcmp (name + length - 3, ".ps") == 0)
5029               || (length >= 5 && strncmp (name + length - 5, "any2", 4) == 0)))
5030         as_warn (_("condition code register should be even for %s, was %d"),
5031                  name, regno);
5032
5033       if ((regno & 3) != 0
5034           && (length >= 5 && strncmp (name + length - 5, "any4", 4) == 0))
5035         as_warn (_("condition code register should be 0 or 4 for %s, was %d"),
5036                  name, regno);
5037     }
5038 }
5039
5040 /* ARG is a register with symbol value SYMVAL.  Try to interpret it as
5041    a register of type TYPE.  Return true on success, storing the register
5042    number in *REGNO and warning about any dubious uses.  */
5043
5044 static bfd_boolean
5045 match_regno (struct mips_arg_info *arg, enum mips_reg_operand_type type,
5046              unsigned int symval, unsigned int *regno)
5047 {
5048   if (type == OP_REG_VEC)
5049     symval = mips_prefer_vec_regno (symval);
5050   if (!(symval & convert_reg_type (arg->insn->insn_mo, type)))
5051     return FALSE;
5052
5053   *regno = symval & RNUM_MASK;
5054   check_regno (arg, type, *regno);
5055   return TRUE;
5056 }
5057
5058 /* Try to interpret the next token in ARG as a register of type TYPE.
5059    Consume the token and return true on success, storing the register
5060    number in *REGNO.  Return false on failure.  */
5061
5062 static bfd_boolean
5063 match_reg (struct mips_arg_info *arg, enum mips_reg_operand_type type,
5064            unsigned int *regno)
5065 {
5066   if (arg->token->type == OT_REG
5067       && match_regno (arg, type, arg->token->u.regno, regno))
5068     {
5069       ++arg->token;
5070       return TRUE;
5071     }
5072   return FALSE;
5073 }
5074
5075 /* Try to interpret the next token in ARG as a range of registers of type TYPE.
5076    Consume the token and return true on success, storing the register numbers
5077    in *REGNO1 and *REGNO2.  Return false on failure.  */
5078
5079 static bfd_boolean
5080 match_reg_range (struct mips_arg_info *arg, enum mips_reg_operand_type type,
5081                  unsigned int *regno1, unsigned int *regno2)
5082 {
5083   if (match_reg (arg, type, regno1))
5084     {
5085       *regno2 = *regno1;
5086       return TRUE;
5087     }
5088   if (arg->token->type == OT_REG_RANGE
5089       && match_regno (arg, type, arg->token->u.reg_range.regno1, regno1)
5090       && match_regno (arg, type, arg->token->u.reg_range.regno2, regno2)
5091       && *regno1 <= *regno2)
5092     {
5093       ++arg->token;
5094       return TRUE;
5095     }
5096   return FALSE;
5097 }
5098
5099 /* OP_INT matcher.  */
5100
5101 static bfd_boolean
5102 match_int_operand (struct mips_arg_info *arg,
5103                    const struct mips_operand *operand_base)
5104 {
5105   const struct mips_int_operand *operand;
5106   unsigned int uval;
5107   int min_val, max_val, factor;
5108   offsetT sval;
5109
5110   operand = (const struct mips_int_operand *) operand_base;
5111   factor = 1 << operand->shift;
5112   min_val = mips_int_operand_min (operand);
5113   max_val = mips_int_operand_max (operand);
5114
5115   if (operand_base->lsb == 0
5116       && operand_base->size == 16
5117       && operand->shift == 0
5118       && operand->bias == 0
5119       && (operand->max_val == 32767 || operand->max_val == 65535))
5120     {
5121       /* The operand can be relocated.  */
5122       if (!match_expression (arg, &offset_expr, offset_reloc))
5123         return FALSE;
5124
5125       if (offset_expr.X_op == O_big)
5126         {
5127           match_out_of_range (arg);
5128           return FALSE;
5129         }
5130
5131       if (offset_reloc[0] != BFD_RELOC_UNUSED)
5132         /* Relocation operators were used.  Accept the argument and
5133            leave the relocation value in offset_expr and offset_relocs
5134            for the caller to process.  */
5135         return TRUE;
5136
5137       if (offset_expr.X_op != O_constant)
5138         {
5139           /* Accept non-constant operands if no later alternative matches,
5140              leaving it for the caller to process.  */
5141           if (!arg->lax_match)
5142             {
5143               match_not_constant (arg);
5144               return FALSE;
5145             }
5146           offset_reloc[0] = BFD_RELOC_LO16;
5147           return TRUE;
5148         }
5149
5150       /* Clear the global state; we're going to install the operand
5151          ourselves.  */
5152       sval = offset_expr.X_add_number;
5153       offset_expr.X_op = O_absent;
5154
5155       /* For compatibility with older assemblers, we accept
5156          0x8000-0xffff as signed 16-bit numbers when only
5157          signed numbers are allowed.  */
5158       if (sval > max_val)
5159         {
5160           max_val = ((1 << operand_base->size) - 1) << operand->shift;
5161           if (!arg->lax_match && sval <= max_val)
5162             {
5163               match_out_of_range (arg);
5164               return FALSE;
5165             }
5166         }
5167     }
5168   else
5169     {
5170       if (!match_const_int (arg, &sval))
5171         return FALSE;
5172     }
5173
5174   arg->last_op_int = sval;
5175
5176   if (sval < min_val || sval > max_val || sval % factor)
5177     {
5178       match_out_of_range (arg);
5179       return FALSE;
5180     }
5181
5182   uval = (unsigned int) sval >> operand->shift;
5183   uval -= operand->bias;
5184
5185   /* Handle -mfix-cn63xxp1.  */
5186   if (arg->opnum == 1
5187       && mips_fix_cn63xxp1
5188       && !mips_opts.micromips
5189       && strcmp ("pref", arg->insn->insn_mo->name) == 0)
5190     switch (uval)
5191       {
5192       case 5:
5193       case 25:
5194       case 26:
5195       case 27:
5196       case 28:
5197       case 29:
5198       case 30:
5199       case 31:
5200         /* These are ok.  */
5201         break;
5202
5203       default:
5204         /* The rest must be changed to 28.  */
5205         uval = 28;
5206         break;
5207       }
5208
5209   insn_insert_operand (arg->insn, operand_base, uval);
5210   return TRUE;
5211 }
5212
5213 /* OP_MAPPED_INT matcher.  */
5214
5215 static bfd_boolean
5216 match_mapped_int_operand (struct mips_arg_info *arg,
5217                           const struct mips_operand *operand_base)
5218 {
5219   const struct mips_mapped_int_operand *operand;
5220   unsigned int uval, num_vals;
5221   offsetT sval;
5222
5223   operand = (const struct mips_mapped_int_operand *) operand_base;
5224   if (!match_const_int (arg, &sval))
5225     return FALSE;
5226
5227   num_vals = 1 << operand_base->size;
5228   for (uval = 0; uval < num_vals; uval++)
5229     if (operand->int_map[uval] == sval)
5230       break;
5231   if (uval == num_vals)
5232     {
5233       match_out_of_range (arg);
5234       return FALSE;
5235     }
5236
5237   insn_insert_operand (arg->insn, operand_base, uval);
5238   return TRUE;
5239 }
5240
5241 /* OP_MSB matcher.  */
5242
5243 static bfd_boolean
5244 match_msb_operand (struct mips_arg_info *arg,
5245                    const struct mips_operand *operand_base)
5246 {
5247   const struct mips_msb_operand *operand;
5248   int min_val, max_val, max_high;
5249   offsetT size, sval, high;
5250
5251   operand = (const struct mips_msb_operand *) operand_base;
5252   min_val = operand->bias;
5253   max_val = min_val + (1 << operand_base->size) - 1;
5254   max_high = operand->opsize;
5255
5256   if (!match_const_int (arg, &size))
5257     return FALSE;
5258
5259   high = size + arg->last_op_int;
5260   sval = operand->add_lsb ? high : size;
5261
5262   if (size < 0 || high > max_high || sval < min_val || sval > max_val)
5263     {
5264       match_out_of_range (arg);
5265       return FALSE;
5266     }
5267   insn_insert_operand (arg->insn, operand_base, sval - min_val);
5268   return TRUE;
5269 }
5270
5271 /* OP_REG matcher.  */
5272
5273 static bfd_boolean
5274 match_reg_operand (struct mips_arg_info *arg,
5275                    const struct mips_operand *operand_base)
5276 {
5277   const struct mips_reg_operand *operand;
5278   unsigned int regno, uval, num_vals;
5279
5280   operand = (const struct mips_reg_operand *) operand_base;
5281   if (!match_reg (arg, operand->reg_type, &regno))
5282     return FALSE;
5283
5284   if (operand->reg_map)
5285     {
5286       num_vals = 1 << operand->root.size;
5287       for (uval = 0; uval < num_vals; uval++)
5288         if (operand->reg_map[uval] == regno)
5289           break;
5290       if (num_vals == uval)
5291         return FALSE;
5292     }
5293   else
5294     uval = regno;
5295
5296   arg->last_regno = regno;
5297   if (arg->opnum == 1)
5298     arg->dest_regno = regno;
5299   insn_insert_operand (arg->insn, operand_base, uval);
5300   return TRUE;
5301 }
5302
5303 /* OP_REG_PAIR matcher.  */
5304
5305 static bfd_boolean
5306 match_reg_pair_operand (struct mips_arg_info *arg,
5307                         const struct mips_operand *operand_base)
5308 {
5309   const struct mips_reg_pair_operand *operand;
5310   unsigned int regno1, regno2, uval, num_vals;
5311
5312   operand = (const struct mips_reg_pair_operand *) operand_base;
5313   if (!match_reg (arg, operand->reg_type, &regno1)
5314       || !match_char (arg, ',')
5315       || !match_reg (arg, operand->reg_type, &regno2))
5316     return FALSE;
5317
5318   num_vals = 1 << operand_base->size;
5319   for (uval = 0; uval < num_vals; uval++)
5320     if (operand->reg1_map[uval] == regno1 && operand->reg2_map[uval] == regno2)
5321       break;
5322   if (uval == num_vals)
5323     return FALSE;
5324
5325   insn_insert_operand (arg->insn, operand_base, uval);
5326   return TRUE;
5327 }
5328
5329 /* OP_PCREL matcher.  The caller chooses the relocation type.  */
5330
5331 static bfd_boolean
5332 match_pcrel_operand (struct mips_arg_info *arg)
5333 {
5334   bfd_reloc_code_real_type r[3];
5335
5336   return match_expression (arg, &offset_expr, r) && r[0] == BFD_RELOC_UNUSED;
5337 }
5338
5339 /* OP_PERF_REG matcher.  */
5340
5341 static bfd_boolean
5342 match_perf_reg_operand (struct mips_arg_info *arg,
5343                         const struct mips_operand *operand)
5344 {
5345   offsetT sval;
5346
5347   if (!match_const_int (arg, &sval))
5348     return FALSE;
5349
5350   if (sval != 0
5351       && (sval != 1
5352           || (mips_opts.arch == CPU_R5900
5353               && (strcmp (arg->insn->insn_mo->name, "mfps") == 0
5354                   || strcmp (arg->insn->insn_mo->name, "mtps") == 0))))
5355     {
5356       set_insn_error (arg->argnum, _("invalid performance register"));
5357       return FALSE;
5358     }
5359
5360   insn_insert_operand (arg->insn, operand, sval);
5361   return TRUE;
5362 }
5363
5364 /* OP_ADDIUSP matcher.  */
5365
5366 static bfd_boolean
5367 match_addiusp_operand (struct mips_arg_info *arg,
5368                        const struct mips_operand *operand)
5369 {
5370   offsetT sval;
5371   unsigned int uval;
5372
5373   if (!match_const_int (arg, &sval))
5374     return FALSE;
5375
5376   if (sval % 4)
5377     {
5378       match_out_of_range (arg);
5379       return FALSE;
5380     }
5381
5382   sval /= 4;
5383   if (!(sval >= -258 && sval <= 257) || (sval >= -2 && sval <= 1))
5384     {
5385       match_out_of_range (arg);
5386       return FALSE;
5387     }
5388
5389   uval = (unsigned int) sval;
5390   uval = ((uval >> 1) & ~0xff) | (uval & 0xff);
5391   insn_insert_operand (arg->insn, operand, uval);
5392   return TRUE;
5393 }
5394
5395 /* OP_CLO_CLZ_DEST matcher.  */
5396
5397 static bfd_boolean
5398 match_clo_clz_dest_operand (struct mips_arg_info *arg,
5399                             const struct mips_operand *operand)
5400 {
5401   unsigned int regno;
5402
5403   if (!match_reg (arg, OP_REG_GP, &regno))
5404     return FALSE;
5405
5406   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
5407   return TRUE;
5408 }
5409
5410 /* OP_CHECK_PREV matcher.  */
5411
5412 static bfd_boolean
5413 match_check_prev_operand (struct mips_arg_info *arg,
5414                           const struct mips_operand *operand_base)
5415 {
5416   const struct mips_check_prev_operand *operand;
5417   unsigned int regno;
5418
5419   operand = (const struct mips_check_prev_operand *) operand_base;
5420
5421   if (!match_reg (arg, OP_REG_GP, &regno))
5422     return FALSE;
5423
5424   if (!operand->zero_ok && regno == 0)
5425     return FALSE;
5426
5427   if ((operand->less_than_ok && regno < arg->last_regno)
5428       || (operand->greater_than_ok && regno > arg->last_regno)
5429       || (operand->equal_ok && regno == arg->last_regno))
5430     {
5431       arg->last_regno = regno;
5432       insn_insert_operand (arg->insn, operand_base, regno);
5433       return TRUE;
5434     }
5435
5436   return FALSE;
5437 }
5438
5439 /* OP_SAME_RS_RT matcher.  */
5440
5441 static bfd_boolean
5442 match_same_rs_rt_operand (struct mips_arg_info *arg,
5443                           const struct mips_operand *operand)
5444 {
5445   unsigned int regno;
5446
5447   if (!match_reg (arg, OP_REG_GP, &regno))
5448     return FALSE;
5449
5450   if (regno == 0)
5451     {
5452       set_insn_error (arg->argnum, _("the source register must not be $0"));
5453       return FALSE;
5454     }
5455
5456   arg->last_regno = regno;
5457
5458   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
5459   return TRUE;
5460 }
5461
5462 /* OP_LWM_SWM_LIST matcher.  */
5463
5464 static bfd_boolean
5465 match_lwm_swm_list_operand (struct mips_arg_info *arg,
5466                             const struct mips_operand *operand)
5467 {
5468   unsigned int reglist, sregs, ra, regno1, regno2;
5469   struct mips_arg_info reset;
5470
5471   reglist = 0;
5472   if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5473     return FALSE;
5474   do
5475     {
5476       if (regno2 == FP && regno1 >= S0 && regno1 <= S7)
5477         {
5478           reglist |= 1 << FP;
5479           regno2 = S7;
5480         }
5481       reglist |= ((1U << regno2 << 1) - 1) & -(1U << regno1);
5482       reset = *arg;
5483     }
5484   while (match_char (arg, ',')
5485          && match_reg_range (arg, OP_REG_GP, &regno1, &regno2));
5486   *arg = reset;
5487
5488   if (operand->size == 2)
5489     {
5490       /* The list must include both ra and s0-sN, for 0 <= N <= 3.  E.g.:
5491
5492          s0, ra
5493          s0, s1, ra, s2, s3
5494          s0-s2, ra
5495
5496          and any permutations of these.  */
5497       if ((reglist & 0xfff1ffff) != 0x80010000)
5498         return FALSE;
5499
5500       sregs = (reglist >> 17) & 7;
5501       ra = 0;
5502     }
5503   else
5504     {
5505       /* The list must include at least one of ra and s0-sN,
5506          for 0 <= N <= 8.  (Note that there is a gap between s7 and s8,
5507          which are $23 and $30 respectively.)  E.g.:
5508
5509          ra
5510          s0
5511          ra, s0, s1, s2
5512          s0-s8
5513          s0-s5, ra
5514
5515          and any permutations of these.  */
5516       if ((reglist & 0x3f00ffff) != 0)
5517         return FALSE;
5518
5519       ra = (reglist >> 27) & 0x10;
5520       sregs = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
5521     }
5522   sregs += 1;
5523   if ((sregs & -sregs) != sregs)
5524     return FALSE;
5525
5526   insn_insert_operand (arg->insn, operand, (ffs (sregs) - 1) | ra);
5527   return TRUE;
5528 }
5529
5530 /* OP_ENTRY_EXIT_LIST matcher.  */
5531
5532 static unsigned int
5533 match_entry_exit_operand (struct mips_arg_info *arg,
5534                           const struct mips_operand *operand)
5535 {
5536   unsigned int mask;
5537   bfd_boolean is_exit;
5538
5539   /* The format is the same for both ENTRY and EXIT, but the constraints
5540      are different.  */
5541   is_exit = strcmp (arg->insn->insn_mo->name, "exit") == 0;
5542   mask = (is_exit ? 7 << 3 : 0);
5543   do
5544     {
5545       unsigned int regno1, regno2;
5546       bfd_boolean is_freg;
5547
5548       if (match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5549         is_freg = FALSE;
5550       else if (match_reg_range (arg, OP_REG_FP, &regno1, &regno2))
5551         is_freg = TRUE;
5552       else
5553         return FALSE;
5554
5555       if (is_exit && is_freg && regno1 == 0 && regno2 < 2)
5556         {
5557           mask &= ~(7 << 3);
5558           mask |= (5 + regno2) << 3;
5559         }
5560       else if (!is_exit && regno1 == 4 && regno2 >= 4 && regno2 <= 7)
5561         mask |= (regno2 - 3) << 3;
5562       else if (regno1 == 16 && regno2 >= 16 && regno2 <= 17)
5563         mask |= (regno2 - 15) << 1;
5564       else if (regno1 == RA && regno2 == RA)
5565         mask |= 1;
5566       else
5567         return FALSE;
5568     }
5569   while (match_char (arg, ','));
5570
5571   insn_insert_operand (arg->insn, operand, mask);
5572   return TRUE;
5573 }
5574
5575 /* Encode regular MIPS SAVE/RESTORE instruction operands according to
5576    the argument register mask AMASK, the number of static registers
5577    saved NSREG, the $ra, $s0 and $s1 register specifiers RA, S0 and S1
5578    respectively, and the frame size FRAME_SIZE.  */
5579
5580 static unsigned int
5581 mips_encode_save_restore (unsigned int amask, unsigned int nsreg,
5582                           unsigned int ra, unsigned int s0, unsigned int s1,
5583                           unsigned int frame_size)
5584 {
5585   return ((nsreg << 23) | ((frame_size & 0xf0) << 15) | (amask << 15)
5586           | (ra << 12) | (s0 << 11) | (s1 << 10) | ((frame_size & 0xf) << 6));
5587 }
5588
5589 /* Encode MIPS16 SAVE/RESTORE instruction operands according to the
5590    argument register mask AMASK, the number of static registers saved
5591    NSREG, the $ra, $s0 and $s1 register specifiers RA, S0 and S1
5592    respectively, and the frame size FRAME_SIZE.  */
5593
5594 static unsigned int
5595 mips16_encode_save_restore (unsigned int amask, unsigned int nsreg,
5596                             unsigned int ra, unsigned int s0, unsigned int s1,
5597                             unsigned int frame_size)
5598 {
5599   unsigned int args;
5600
5601   args = (ra << 6) | (s0 << 5) | (s1 << 4) | (frame_size & 0xf);
5602   if (nsreg || amask || frame_size == 0 || frame_size > 16)
5603     args |= (MIPS16_EXTEND | (nsreg << 24) | (amask << 16)
5604              | ((frame_size & 0xf0) << 16));
5605   return args;
5606 }
5607
5608 /* OP_SAVE_RESTORE_LIST matcher.  */
5609
5610 static bfd_boolean
5611 match_save_restore_list_operand (struct mips_arg_info *arg)
5612 {
5613   unsigned int opcode, args, statics, sregs;
5614   unsigned int num_frame_sizes, num_args, num_statics, num_sregs;
5615   unsigned int arg_mask, ra, s0, s1;
5616   offsetT frame_size;
5617
5618   opcode = arg->insn->insn_opcode;
5619   frame_size = 0;
5620   num_frame_sizes = 0;
5621   args = 0;
5622   statics = 0;
5623   sregs = 0;
5624   ra = 0;
5625   s0 = 0;
5626   s1 = 0;
5627   do
5628     {
5629       unsigned int regno1, regno2;
5630
5631       if (arg->token->type == OT_INTEGER)
5632         {
5633           /* Handle the frame size.  */
5634           if (!match_const_int (arg, &frame_size))
5635             return FALSE;
5636           num_frame_sizes += 1;
5637         }
5638       else
5639         {
5640           if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5641             return FALSE;
5642
5643           while (regno1 <= regno2)
5644             {
5645               if (regno1 >= 4 && regno1 <= 7)
5646                 {
5647                   if (num_frame_sizes == 0)
5648                     /* args $a0-$a3 */
5649                     args |= 1 << (regno1 - 4);
5650                   else
5651                     /* statics $a0-$a3 */
5652                     statics |= 1 << (regno1 - 4);
5653                 }
5654               else if (regno1 >= 16 && regno1 <= 23)
5655                 /* $s0-$s7 */
5656                 sregs |= 1 << (regno1 - 16);
5657               else if (regno1 == 30)
5658                 /* $s8 */
5659                 sregs |= 1 << 8;
5660               else if (regno1 == 31)
5661                 /* Add $ra to insn.  */
5662                 ra = 1;
5663               else
5664                 return FALSE;
5665               regno1 += 1;
5666               if (regno1 == 24)
5667                 regno1 = 30;
5668             }
5669         }
5670     }
5671   while (match_char (arg, ','));
5672
5673   /* Encode args/statics combination.  */
5674   if (args & statics)
5675     return FALSE;
5676   else if (args == 0xf)
5677     /* All $a0-$a3 are args.  */
5678     arg_mask = MIPS_SVRS_ALL_ARGS;
5679   else if (statics == 0xf)
5680     /* All $a0-$a3 are statics.  */
5681     arg_mask = MIPS_SVRS_ALL_STATICS;
5682   else
5683     {
5684       /* Count arg registers.  */
5685       num_args = 0;
5686       while (args & 0x1)
5687         {
5688           args >>= 1;
5689           num_args += 1;
5690         }
5691       if (args != 0)
5692         return FALSE;
5693
5694       /* Count static registers.  */
5695       num_statics = 0;
5696       while (statics & 0x8)
5697         {
5698           statics = (statics << 1) & 0xf;
5699           num_statics += 1;
5700         }
5701       if (statics != 0)
5702         return FALSE;
5703
5704       /* Encode args/statics.  */
5705       arg_mask = (num_args << 2) | num_statics;
5706     }
5707
5708   /* Encode $s0/$s1.  */
5709   if (sregs & (1 << 0))         /* $s0 */
5710     s0 = 1;
5711   if (sregs & (1 << 1))         /* $s1 */
5712     s1 = 1;
5713   sregs >>= 2;
5714
5715   /* Encode $s2-$s8. */
5716   num_sregs = 0;
5717   while (sregs & 1)
5718     {
5719       sregs >>= 1;
5720       num_sregs += 1;
5721     }
5722   if (sregs != 0)
5723     return FALSE;
5724
5725   /* Encode frame size.  */
5726   if (num_frame_sizes == 0)
5727     {
5728       set_insn_error (arg->argnum, _("missing frame size"));
5729       return FALSE;
5730     }
5731   if (num_frame_sizes > 1)
5732     {
5733       set_insn_error (arg->argnum, _("frame size specified twice"));
5734       return FALSE;
5735     }
5736   if ((frame_size & 7) != 0 || frame_size < 0 || frame_size > 0xff * 8)
5737     {
5738       set_insn_error (arg->argnum, _("invalid frame size"));
5739       return FALSE;
5740     }
5741   frame_size /= 8;
5742
5743   /* Finally build the instruction.  */
5744   if (mips_opts.mips16)
5745     opcode |= mips16_encode_save_restore (arg_mask, num_sregs, ra, s0, s1,
5746                                           frame_size);
5747   else if (!mips_opts.micromips)
5748     opcode |= mips_encode_save_restore (arg_mask, num_sregs, ra, s0, s1,
5749                                         frame_size);
5750   else
5751     abort ();
5752
5753   arg->insn->insn_opcode = opcode;
5754   return TRUE;
5755 }
5756
5757 /* OP_MDMX_IMM_REG matcher.  */
5758
5759 static bfd_boolean
5760 match_mdmx_imm_reg_operand (struct mips_arg_info *arg,
5761                             const struct mips_operand *operand)
5762 {
5763   unsigned int regno, uval;
5764   bfd_boolean is_qh;
5765   const struct mips_opcode *opcode;
5766
5767   /* The mips_opcode records whether this is an octobyte or quadhalf
5768      instruction.  Start out with that bit in place.  */
5769   opcode = arg->insn->insn_mo;
5770   uval = mips_extract_operand (operand, opcode->match);
5771   is_qh = (uval != 0);
5772
5773   if (arg->token->type == OT_REG)
5774     {
5775       if ((opcode->membership & INSN_5400)
5776           && strcmp (opcode->name, "rzu.ob") == 0)
5777         {
5778           set_insn_error_i (arg->argnum, _("operand %d must be an immediate"),
5779                             arg->argnum);
5780           return FALSE;
5781         }
5782
5783       if (!match_regno (arg, OP_REG_VEC, arg->token->u.regno, &regno))
5784         return FALSE;
5785       ++arg->token;
5786
5787       /* Check whether this is a vector register or a broadcast of
5788          a single element.  */
5789       if (arg->token->type == OT_INTEGER_INDEX)
5790         {
5791           if (arg->token->u.index > (is_qh ? 3 : 7))
5792             {
5793               set_insn_error (arg->argnum, _("invalid element selector"));
5794               return FALSE;
5795             }
5796           uval |= arg->token->u.index << (is_qh ? 2 : 1) << 5;
5797           ++arg->token;
5798         }
5799       else
5800         {
5801           /* A full vector.  */
5802           if ((opcode->membership & INSN_5400)
5803               && (strcmp (opcode->name, "sll.ob") == 0
5804                   || strcmp (opcode->name, "srl.ob") == 0))
5805             {
5806               set_insn_error_i (arg->argnum, _("operand %d must be scalar"),
5807                                 arg->argnum);
5808               return FALSE;
5809             }
5810
5811           if (is_qh)
5812             uval |= MDMX_FMTSEL_VEC_QH << 5;
5813           else
5814             uval |= MDMX_FMTSEL_VEC_OB << 5;
5815         }
5816       uval |= regno;
5817     }
5818   else
5819     {
5820       offsetT sval;
5821
5822       if (!match_const_int (arg, &sval))
5823         return FALSE;
5824       if (sval < 0 || sval > 31)
5825         {
5826           match_out_of_range (arg);
5827           return FALSE;
5828         }
5829       uval |= (sval & 31);
5830       if (is_qh)
5831         uval |= MDMX_FMTSEL_IMM_QH << 5;
5832       else
5833         uval |= MDMX_FMTSEL_IMM_OB << 5;
5834     }
5835   insn_insert_operand (arg->insn, operand, uval);
5836   return TRUE;
5837 }
5838
5839 /* OP_IMM_INDEX matcher.  */
5840
5841 static bfd_boolean
5842 match_imm_index_operand (struct mips_arg_info *arg,
5843                          const struct mips_operand *operand)
5844 {
5845   unsigned int max_val;
5846
5847   if (arg->token->type != OT_INTEGER_INDEX)
5848     return FALSE;
5849
5850   max_val = (1 << operand->size) - 1;
5851   if (arg->token->u.index > max_val)
5852     {
5853       match_out_of_range (arg);
5854       return FALSE;
5855     }
5856   insn_insert_operand (arg->insn, operand, arg->token->u.index);
5857   ++arg->token;
5858   return TRUE;
5859 }
5860
5861 /* OP_REG_INDEX matcher.  */
5862
5863 static bfd_boolean
5864 match_reg_index_operand (struct mips_arg_info *arg,
5865                          const struct mips_operand *operand)
5866 {
5867   unsigned int regno;
5868
5869   if (arg->token->type != OT_REG_INDEX)
5870     return FALSE;
5871
5872   if (!match_regno (arg, OP_REG_GP, arg->token->u.regno, &regno))
5873     return FALSE;
5874
5875   insn_insert_operand (arg->insn, operand, regno);
5876   ++arg->token;
5877   return TRUE;
5878 }
5879
5880 /* OP_PC matcher.  */
5881
5882 static bfd_boolean
5883 match_pc_operand (struct mips_arg_info *arg)
5884 {
5885   if (arg->token->type == OT_REG && (arg->token->u.regno & RTYPE_PC))
5886     {
5887       ++arg->token;
5888       return TRUE;
5889     }
5890   return FALSE;
5891 }
5892
5893 /* OP_REG28 matcher.  */
5894
5895 static bfd_boolean
5896 match_reg28_operand (struct mips_arg_info *arg)
5897 {
5898   unsigned int regno;
5899
5900   if (arg->token->type == OT_REG
5901       && match_regno (arg, OP_REG_GP, arg->token->u.regno, &regno)
5902       && regno == GP)
5903     {
5904       ++arg->token;
5905       return TRUE;
5906     }
5907   return FALSE;
5908 }
5909
5910 /* OP_NON_ZERO_REG matcher.  */
5911
5912 static bfd_boolean
5913 match_non_zero_reg_operand (struct mips_arg_info *arg,
5914                             const struct mips_operand *operand)
5915 {
5916   unsigned int regno;
5917
5918   if (!match_reg (arg, OP_REG_GP, &regno))
5919     return FALSE;
5920
5921   if (regno == 0)
5922     return FALSE;
5923
5924   arg->last_regno = regno;
5925   insn_insert_operand (arg->insn, operand, regno);
5926   return TRUE;
5927 }
5928
5929 /* OP_REPEAT_DEST_REG and OP_REPEAT_PREV_REG matcher.  OTHER_REGNO is the
5930    register that we need to match.  */
5931
5932 static bfd_boolean
5933 match_tied_reg_operand (struct mips_arg_info *arg, unsigned int other_regno)
5934 {
5935   unsigned int regno;
5936
5937   return match_reg (arg, OP_REG_GP, &regno) && regno == other_regno;
5938 }
5939
5940 /* Read a floating-point constant from S for LI.S or LI.D.  LENGTH is
5941    the length of the value in bytes (4 for float, 8 for double) and
5942    USING_GPRS says whether the destination is a GPR rather than an FPR.
5943
5944    Return the constant in IMM and OFFSET as follows:
5945
5946    - If the constant should be loaded via memory, set IMM to O_absent and
5947      OFFSET to the memory address.
5948
5949    - Otherwise, if the constant should be loaded into two 32-bit registers,
5950      set IMM to the O_constant to load into the high register and OFFSET
5951      to the corresponding value for the low register.
5952
5953    - Otherwise, set IMM to the full O_constant and set OFFSET to O_absent.
5954
5955    These constants only appear as the last operand in an instruction,
5956    and every instruction that accepts them in any variant accepts them
5957    in all variants.  This means we don't have to worry about backing out
5958    any changes if the instruction does not match.  We just match
5959    unconditionally and report an error if the constant is invalid.  */
5960
5961 static bfd_boolean
5962 match_float_constant (struct mips_arg_info *arg, expressionS *imm,
5963                       expressionS *offset, int length, bfd_boolean using_gprs)
5964 {
5965   char *p;
5966   segT seg, new_seg;
5967   subsegT subseg;
5968   const char *newname;
5969   unsigned char *data;
5970
5971   /* Where the constant is placed is based on how the MIPS assembler
5972      does things:
5973
5974      length == 4 && using_gprs  -- immediate value only
5975      length == 8 && using_gprs  -- .rdata or immediate value
5976      length == 4 && !using_gprs -- .lit4 or immediate value
5977      length == 8 && !using_gprs -- .lit8 or immediate value
5978
5979      The .lit4 and .lit8 sections are only used if permitted by the
5980      -G argument.  */
5981   if (arg->token->type != OT_FLOAT)
5982     {
5983       set_insn_error (arg->argnum, _("floating-point expression required"));
5984       return FALSE;
5985     }
5986
5987   gas_assert (arg->token->u.flt.length == length);
5988   data = arg->token->u.flt.data;
5989   ++arg->token;
5990
5991   /* Handle 32-bit constants for which an immediate value is best.  */
5992   if (length == 4
5993       && (using_gprs
5994           || g_switch_value < 4
5995           || (data[0] == 0 && data[1] == 0)
5996           || (data[2] == 0 && data[3] == 0)))
5997     {
5998       imm->X_op = O_constant;
5999       if (!target_big_endian)
6000         imm->X_add_number = bfd_getl32 (data);
6001       else
6002         imm->X_add_number = bfd_getb32 (data);
6003       offset->X_op = O_absent;
6004       return TRUE;
6005     }
6006
6007   /* Handle 64-bit constants for which an immediate value is best.  */
6008   if (length == 8
6009       && !mips_disable_float_construction
6010       /* Constants can only be constructed in GPRs and copied to FPRs if the
6011          GPRs are at least as wide as the FPRs or MTHC1 is available.
6012          Unlike most tests for 32-bit floating-point registers this check
6013          specifically looks for GPR_SIZE == 32 as the FPXX ABI does not
6014          permit 64-bit moves without MXHC1.
6015          Force the constant into memory otherwise.  */
6016       && (using_gprs
6017           || GPR_SIZE == 64
6018           || ISA_HAS_MXHC1 (mips_opts.isa)
6019           || FPR_SIZE == 32)
6020       && ((data[0] == 0 && data[1] == 0)
6021           || (data[2] == 0 && data[3] == 0))
6022       && ((data[4] == 0 && data[5] == 0)
6023           || (data[6] == 0 && data[7] == 0)))
6024     {
6025       /* The value is simple enough to load with a couple of instructions.
6026          If using 32-bit registers, set IMM to the high order 32 bits and
6027          OFFSET to the low order 32 bits.  Otherwise, set IMM to the entire
6028          64 bit constant.  */
6029       if (GPR_SIZE == 32 || (!using_gprs && FPR_SIZE != 64))
6030         {
6031           imm->X_op = O_constant;
6032           offset->X_op = O_constant;
6033           if (!target_big_endian)
6034             {
6035               imm->X_add_number = bfd_getl32 (data + 4);
6036               offset->X_add_number = bfd_getl32 (data);
6037             }
6038           else
6039             {
6040               imm->X_add_number = bfd_getb32 (data);
6041               offset->X_add_number = bfd_getb32 (data + 4);
6042             }
6043           if (offset->X_add_number == 0)
6044             offset->X_op = O_absent;
6045         }
6046       else
6047         {
6048           imm->X_op = O_constant;
6049           if (!target_big_endian)
6050             imm->X_add_number = bfd_getl64 (data);
6051           else
6052             imm->X_add_number = bfd_getb64 (data);
6053           offset->X_op = O_absent;
6054         }
6055       return TRUE;
6056     }
6057
6058   /* Switch to the right section.  */
6059   seg = now_seg;
6060   subseg = now_subseg;
6061   if (length == 4)
6062     {
6063       gas_assert (!using_gprs && g_switch_value >= 4);
6064       newname = ".lit4";
6065     }
6066   else
6067     {
6068       if (using_gprs || g_switch_value < 8)
6069         newname = RDATA_SECTION_NAME;
6070       else
6071         newname = ".lit8";
6072     }
6073
6074   new_seg = subseg_new (newname, (subsegT) 0);
6075   bfd_set_section_flags (stdoutput, new_seg,
6076                          SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA);
6077   frag_align (length == 4 ? 2 : 3, 0, 0);
6078   if (strncmp (TARGET_OS, "elf", 3) != 0)
6079     record_alignment (new_seg, 4);
6080   else
6081     record_alignment (new_seg, length == 4 ? 2 : 3);
6082   if (seg == now_seg)
6083     as_bad (_("cannot use `%s' in this section"), arg->insn->insn_mo->name);
6084
6085   /* Set the argument to the current address in the section.  */
6086   imm->X_op = O_absent;
6087   offset->X_op = O_symbol;
6088   offset->X_add_symbol = symbol_temp_new_now ();
6089   offset->X_add_number = 0;
6090
6091   /* Put the floating point number into the section.  */
6092   p = frag_more (length);
6093   memcpy (p, data, length);
6094
6095   /* Switch back to the original section.  */
6096   subseg_set (seg, subseg);
6097   return TRUE;
6098 }
6099
6100 /* OP_VU0_SUFFIX and OP_VU0_MATCH_SUFFIX matcher; MATCH_P selects between
6101    them.  */
6102
6103 static bfd_boolean
6104 match_vu0_suffix_operand (struct mips_arg_info *arg,
6105                           const struct mips_operand *operand,
6106                           bfd_boolean match_p)
6107 {
6108   unsigned int uval;
6109
6110   /* The operand can be an XYZW mask or a single 2-bit channel index
6111      (with X being 0).  */
6112   gas_assert (operand->size == 2 || operand->size == 4);
6113
6114   /* The suffix can be omitted when it is already part of the opcode.  */
6115   if (arg->token->type != OT_CHANNELS)
6116     return match_p;
6117
6118   uval = arg->token->u.channels;
6119   if (operand->size == 2)
6120     {
6121       /* Check that a single bit is set and convert it into a 2-bit index.  */
6122       if ((uval & -uval) != uval)
6123         return FALSE;
6124       uval = 4 - ffs (uval);
6125     }
6126
6127   if (match_p && insn_extract_operand (arg->insn, operand) != uval)
6128     return FALSE;
6129
6130   ++arg->token;
6131   if (!match_p)
6132     insn_insert_operand (arg->insn, operand, uval);
6133   return TRUE;
6134 }
6135
6136 /* S is the text seen for ARG.  Match it against OPERAND.  Return the end
6137    of the argument text if the match is successful, otherwise return null.  */
6138
6139 static bfd_boolean
6140 match_operand (struct mips_arg_info *arg,
6141                const struct mips_operand *operand)
6142 {
6143   switch (operand->type)
6144     {
6145     case OP_INT:
6146       return match_int_operand (arg, operand);
6147
6148     case OP_MAPPED_INT:
6149       return match_mapped_int_operand (arg, operand);
6150
6151     case OP_MSB:
6152       return match_msb_operand (arg, operand);
6153
6154     case OP_REG:
6155     case OP_OPTIONAL_REG:
6156       return match_reg_operand (arg, operand);
6157
6158     case OP_REG_PAIR:
6159       return match_reg_pair_operand (arg, operand);
6160
6161     case OP_PCREL:
6162       return match_pcrel_operand (arg);
6163
6164     case OP_PERF_REG:
6165       return match_perf_reg_operand (arg, operand);
6166
6167     case OP_ADDIUSP_INT:
6168       return match_addiusp_operand (arg, operand);
6169
6170     case OP_CLO_CLZ_DEST:
6171       return match_clo_clz_dest_operand (arg, operand);
6172
6173     case OP_LWM_SWM_LIST:
6174       return match_lwm_swm_list_operand (arg, operand);
6175
6176     case OP_ENTRY_EXIT_LIST:
6177       return match_entry_exit_operand (arg, operand);
6178
6179     case OP_SAVE_RESTORE_LIST:
6180       return match_save_restore_list_operand (arg);
6181
6182     case OP_MDMX_IMM_REG:
6183       return match_mdmx_imm_reg_operand (arg, operand);
6184
6185     case OP_REPEAT_DEST_REG:
6186       return match_tied_reg_operand (arg, arg->dest_regno);
6187
6188     case OP_REPEAT_PREV_REG:
6189       return match_tied_reg_operand (arg, arg->last_regno);
6190
6191     case OP_PC:
6192       return match_pc_operand (arg);
6193
6194     case OP_REG28:
6195       return match_reg28_operand (arg);
6196
6197     case OP_VU0_SUFFIX:
6198       return match_vu0_suffix_operand (arg, operand, FALSE);
6199
6200     case OP_VU0_MATCH_SUFFIX:
6201       return match_vu0_suffix_operand (arg, operand, TRUE);
6202
6203     case OP_IMM_INDEX:
6204       return match_imm_index_operand (arg, operand);
6205
6206     case OP_REG_INDEX:
6207       return match_reg_index_operand (arg, operand);
6208
6209     case OP_SAME_RS_RT:
6210       return match_same_rs_rt_operand (arg, operand);
6211
6212     case OP_CHECK_PREV:
6213       return match_check_prev_operand (arg, operand);
6214
6215     case OP_NON_ZERO_REG:
6216       return match_non_zero_reg_operand (arg, operand);
6217     }
6218   abort ();
6219 }
6220
6221 /* ARG is the state after successfully matching an instruction.
6222    Issue any queued-up warnings.  */
6223
6224 static void
6225 check_completed_insn (struct mips_arg_info *arg)
6226 {
6227   if (arg->seen_at)
6228     {
6229       if (AT == ATREG)
6230         as_warn (_("used $at without \".set noat\""));
6231       else
6232         as_warn (_("used $%u with \".set at=$%u\""), AT, AT);
6233     }
6234 }
6235
6236 /* Return true if modifying general-purpose register REG needs a delay.  */
6237
6238 static bfd_boolean
6239 reg_needs_delay (unsigned int reg)
6240 {
6241   unsigned long prev_pinfo;
6242
6243   prev_pinfo = history[0].insn_mo->pinfo;
6244   if (!mips_opts.noreorder
6245       && (((prev_pinfo & INSN_LOAD_MEMORY) && !gpr_interlocks)
6246           || ((prev_pinfo & INSN_LOAD_COPROC) && !cop_interlocks))
6247       && (gpr_write_mask (&history[0]) & (1 << reg)))
6248     return TRUE;
6249
6250   return FALSE;
6251 }
6252
6253 /* Classify an instruction according to the FIX_VR4120_* enumeration.
6254    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
6255    by VR4120 errata.  */
6256
6257 static unsigned int
6258 classify_vr4120_insn (const char *name)
6259 {
6260   if (strncmp (name, "macc", 4) == 0)
6261     return FIX_VR4120_MACC;
6262   if (strncmp (name, "dmacc", 5) == 0)
6263     return FIX_VR4120_DMACC;
6264   if (strncmp (name, "mult", 4) == 0)
6265     return FIX_VR4120_MULT;
6266   if (strncmp (name, "dmult", 5) == 0)
6267     return FIX_VR4120_DMULT;
6268   if (strstr (name, "div"))
6269     return FIX_VR4120_DIV;
6270   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
6271     return FIX_VR4120_MTHILO;
6272   return NUM_FIX_VR4120_CLASSES;
6273 }
6274
6275 #define INSN_ERET       0x42000018
6276 #define INSN_DERET      0x4200001f
6277 #define INSN_DMULT      0x1c
6278 #define INSN_DMULTU     0x1d
6279
6280 /* Return the number of instructions that must separate INSN1 and INSN2,
6281    where INSN1 is the earlier instruction.  Return the worst-case value
6282    for any INSN2 if INSN2 is null.  */
6283
6284 static unsigned int
6285 insns_between (const struct mips_cl_insn *insn1,
6286                const struct mips_cl_insn *insn2)
6287 {
6288   unsigned long pinfo1, pinfo2;
6289   unsigned int mask;
6290
6291   /* If INFO2 is null, pessimistically assume that all flags are set for
6292      the second instruction.  */
6293   pinfo1 = insn1->insn_mo->pinfo;
6294   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
6295
6296   /* For most targets, write-after-read dependencies on the HI and LO
6297      registers must be separated by at least two instructions.  */
6298   if (!hilo_interlocks)
6299     {
6300       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
6301         return 2;
6302       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
6303         return 2;
6304     }
6305
6306   /* If we're working around r7000 errata, there must be two instructions
6307      between an mfhi or mflo and any instruction that uses the result.  */
6308   if (mips_7000_hilo_fix
6309       && !mips_opts.micromips
6310       && MF_HILO_INSN (pinfo1)
6311       && (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1))))
6312     return 2;
6313
6314   /* If we're working around 24K errata, one instruction is required
6315      if an ERET or DERET is followed by a branch instruction.  */
6316   if (mips_fix_24k && !mips_opts.micromips)
6317     {
6318       if (insn1->insn_opcode == INSN_ERET
6319           || insn1->insn_opcode == INSN_DERET)
6320         {
6321           if (insn2 == NULL
6322               || insn2->insn_opcode == INSN_ERET
6323               || insn2->insn_opcode == INSN_DERET
6324               || delayed_branch_p (insn2))
6325             return 1;
6326         }
6327     }
6328
6329   /* If we're working around PMC RM7000 errata, there must be three
6330      nops between a dmult and a load instruction.  */
6331   if (mips_fix_rm7000 && !mips_opts.micromips)
6332     {
6333       if ((insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULT
6334           || (insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULTU)
6335         {
6336           if (pinfo2 & INSN_LOAD_MEMORY)
6337            return 3;
6338         }
6339     }
6340
6341   /* If working around VR4120 errata, check for combinations that need
6342      a single intervening instruction.  */
6343   if (mips_fix_vr4120 && !mips_opts.micromips)
6344     {
6345       unsigned int class1, class2;
6346
6347       class1 = classify_vr4120_insn (insn1->insn_mo->name);
6348       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
6349         {
6350           if (insn2 == NULL)
6351             return 1;
6352           class2 = classify_vr4120_insn (insn2->insn_mo->name);
6353           if (vr4120_conflicts[class1] & (1 << class2))
6354             return 1;
6355         }
6356     }
6357
6358   if (!HAVE_CODE_COMPRESSION)
6359     {
6360       /* Check for GPR or coprocessor load delays.  All such delays
6361          are on the RT register.  */
6362       /* Itbl support may require additional care here.  */
6363       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY))
6364           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC)))
6365         {
6366           if (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1)))
6367             return 1;
6368         }
6369
6370       /* Check for generic coprocessor hazards.
6371
6372          This case is not handled very well.  There is no special
6373          knowledge of CP0 handling, and the coprocessors other than
6374          the floating point unit are not distinguished at all.  */
6375       /* Itbl support may require additional care here. FIXME!
6376          Need to modify this to include knowledge about
6377          user specified delays!  */
6378       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE))
6379                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
6380         {
6381           /* Handle cases where INSN1 writes to a known general coprocessor
6382              register.  There must be a one instruction delay before INSN2
6383              if INSN2 reads that register, otherwise no delay is needed.  */
6384           mask = fpr_write_mask (insn1);
6385           if (mask != 0)
6386             {
6387               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
6388                 return 1;
6389             }
6390           else
6391             {
6392               /* Read-after-write dependencies on the control registers
6393                  require a two-instruction gap.  */
6394               if ((pinfo1 & INSN_WRITE_COND_CODE)
6395                   && (pinfo2 & INSN_READ_COND_CODE))
6396                 return 2;
6397
6398               /* We don't know exactly what INSN1 does.  If INSN2 is
6399                  also a coprocessor instruction, assume there must be
6400                  a one instruction gap.  */
6401               if (pinfo2 & INSN_COP)
6402                 return 1;
6403             }
6404         }
6405
6406       /* Check for read-after-write dependencies on the coprocessor
6407          control registers in cases where INSN1 does not need a general
6408          coprocessor delay.  This means that INSN1 is a floating point
6409          comparison instruction.  */
6410       /* Itbl support may require additional care here.  */
6411       else if (!cop_interlocks
6412                && (pinfo1 & INSN_WRITE_COND_CODE)
6413                && (pinfo2 & INSN_READ_COND_CODE))
6414         return 1;
6415     }
6416
6417   /* Forbidden slots can not contain Control Transfer Instructions (CTIs)
6418      CTIs include all branches and jumps, nal, eret, eretnc, deret, wait
6419      and pause.  */
6420   if ((insn1->insn_mo->pinfo2 & INSN2_FORBIDDEN_SLOT)
6421       && ((pinfo2 & INSN_NO_DELAY_SLOT)
6422           || (insn2 && delayed_branch_p (insn2))))
6423     return 1;
6424
6425   return 0;
6426 }
6427
6428 /* Return the number of nops that would be needed to work around the
6429    VR4130 mflo/mfhi errata if instruction INSN immediately followed
6430    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
6431    that are contained within the first IGNORE instructions of HIST.  */
6432
6433 static int
6434 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
6435                  const struct mips_cl_insn *insn)
6436 {
6437   int i, j;
6438   unsigned int mask;
6439
6440   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
6441      are not affected by the errata.  */
6442   if (insn != 0
6443       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
6444           || strcmp (insn->insn_mo->name, "mtlo") == 0
6445           || strcmp (insn->insn_mo->name, "mthi") == 0))
6446     return 0;
6447
6448   /* Search for the first MFLO or MFHI.  */
6449   for (i = 0; i < MAX_VR4130_NOPS; i++)
6450     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
6451       {
6452         /* Extract the destination register.  */
6453         mask = gpr_write_mask (&hist[i]);
6454
6455         /* No nops are needed if INSN reads that register.  */
6456         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
6457           return 0;
6458
6459         /* ...or if any of the intervening instructions do.  */
6460         for (j = 0; j < i; j++)
6461           if (gpr_read_mask (&hist[j]) & mask)
6462             return 0;
6463
6464         if (i >= ignore)
6465           return MAX_VR4130_NOPS - i;
6466       }
6467   return 0;
6468 }
6469
6470 #define BASE_REG_EQ(INSN1, INSN2)       \
6471   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
6472       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
6473
6474 /* Return the minimum alignment for this store instruction.  */
6475
6476 static int
6477 fix_24k_align_to (const struct mips_opcode *mo)
6478 {
6479   if (strcmp (mo->name, "sh") == 0)
6480     return 2;
6481
6482   if (strcmp (mo->name, "swc1") == 0
6483       || strcmp (mo->name, "swc2") == 0
6484       || strcmp (mo->name, "sw") == 0
6485       || strcmp (mo->name, "sc") == 0
6486       || strcmp (mo->name, "s.s") == 0)
6487     return 4;
6488
6489   if (strcmp (mo->name, "sdc1") == 0
6490       || strcmp (mo->name, "sdc2") == 0
6491       || strcmp (mo->name, "s.d") == 0)
6492     return 8;
6493
6494   /* sb, swl, swr */
6495   return 1;
6496 }
6497
6498 struct fix_24k_store_info
6499   {
6500     /* Immediate offset, if any, for this store instruction.  */
6501     short off;
6502     /* Alignment required by this store instruction.  */
6503     int align_to;
6504     /* True for register offsets.  */
6505     int register_offset;
6506   };
6507
6508 /* Comparison function used by qsort.  */
6509
6510 static int
6511 fix_24k_sort (const void *a, const void *b)
6512 {
6513   const struct fix_24k_store_info *pos1 = a;
6514   const struct fix_24k_store_info *pos2 = b;
6515
6516   return (pos1->off - pos2->off);
6517 }
6518
6519 /* INSN is a store instruction.  Try to record the store information
6520    in STINFO.  Return false if the information isn't known.  */
6521
6522 static bfd_boolean
6523 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
6524                            const struct mips_cl_insn *insn)
6525 {
6526   /* The instruction must have a known offset.  */
6527   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
6528     return FALSE;
6529
6530   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
6531   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
6532   return TRUE;
6533 }
6534
6535 /* Return the number of nops that would be needed to work around the 24k
6536    "lost data on stores during refill" errata if instruction INSN
6537    immediately followed the 2 instructions described by HIST.
6538    Ignore hazards that are contained within the first IGNORE
6539    instructions of HIST.
6540
6541    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
6542    for the data cache refills and store data. The following describes
6543    the scenario where the store data could be lost.
6544
6545    * A data cache miss, due to either a load or a store, causing fill
6546      data to be supplied by the memory subsystem
6547    * The first three doublewords of fill data are returned and written
6548      into the cache
6549    * A sequence of four stores occurs in consecutive cycles around the
6550      final doubleword of the fill:
6551    * Store A
6552    * Store B
6553    * Store C
6554    * Zero, One or more instructions
6555    * Store D
6556
6557    The four stores A-D must be to different doublewords of the line that
6558    is being filled. The fourth instruction in the sequence above permits
6559    the fill of the final doubleword to be transferred from the FSB into
6560    the cache. In the sequence above, the stores may be either integer
6561    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
6562    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
6563    different doublewords on the line. If the floating point unit is
6564    running in 1:2 mode, it is not possible to create the sequence above
6565    using only floating point store instructions.
6566
6567    In this case, the cache line being filled is incorrectly marked
6568    invalid, thereby losing the data from any store to the line that
6569    occurs between the original miss and the completion of the five
6570    cycle sequence shown above.
6571
6572    The workarounds are:
6573
6574    * Run the data cache in write-through mode.
6575    * Insert a non-store instruction between
6576      Store A and Store B or Store B and Store C.  */
6577
6578 static int
6579 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
6580               const struct mips_cl_insn *insn)
6581 {
6582   struct fix_24k_store_info pos[3];
6583   int align, i, base_offset;
6584
6585   if (ignore >= 2)
6586     return 0;
6587
6588   /* If the previous instruction wasn't a store, there's nothing to
6589      worry about.  */
6590   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
6591     return 0;
6592
6593   /* If the instructions after the previous one are unknown, we have
6594      to assume the worst.  */
6595   if (!insn)
6596     return 1;
6597
6598   /* Check whether we are dealing with three consecutive stores.  */
6599   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
6600       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
6601     return 0;
6602
6603   /* If we don't know the relationship between the store addresses,
6604      assume the worst.  */
6605   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
6606       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
6607     return 1;
6608
6609   if (!fix_24k_record_store_info (&pos[0], insn)
6610       || !fix_24k_record_store_info (&pos[1], &hist[0])
6611       || !fix_24k_record_store_info (&pos[2], &hist[1]))
6612     return 1;
6613
6614   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
6615
6616   /* Pick a value of ALIGN and X such that all offsets are adjusted by
6617      X bytes and such that the base register + X is known to be aligned
6618      to align bytes.  */
6619
6620   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
6621     align = 8;
6622   else
6623     {
6624       align = pos[0].align_to;
6625       base_offset = pos[0].off;
6626       for (i = 1; i < 3; i++)
6627         if (align < pos[i].align_to)
6628           {
6629             align = pos[i].align_to;
6630             base_offset = pos[i].off;
6631           }
6632       for (i = 0; i < 3; i++)
6633         pos[i].off -= base_offset;
6634     }
6635
6636   pos[0].off &= ~align + 1;
6637   pos[1].off &= ~align + 1;
6638   pos[2].off &= ~align + 1;
6639
6640   /* If any two stores write to the same chunk, they also write to the
6641      same doubleword.  The offsets are still sorted at this point.  */
6642   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
6643     return 0;
6644
6645   /* A range of at least 9 bytes is needed for the stores to be in
6646      non-overlapping doublewords.  */
6647   if (pos[2].off - pos[0].off <= 8)
6648     return 0;
6649
6650   if (pos[2].off - pos[1].off >= 24
6651       || pos[1].off - pos[0].off >= 24
6652       || pos[2].off - pos[0].off >= 32)
6653     return 0;
6654
6655   return 1;
6656 }
6657
6658 /* Return the number of nops that would be needed if instruction INSN
6659    immediately followed the MAX_NOPS instructions given by HIST,
6660    where HIST[0] is the most recent instruction.  Ignore hazards
6661    between INSN and the first IGNORE instructions in HIST.
6662
6663    If INSN is null, return the worse-case number of nops for any
6664    instruction.  */
6665
6666 static int
6667 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
6668                const struct mips_cl_insn *insn)
6669 {
6670   int i, nops, tmp_nops;
6671
6672   nops = 0;
6673   for (i = ignore; i < MAX_DELAY_NOPS; i++)
6674     {
6675       tmp_nops = insns_between (hist + i, insn) - i;
6676       if (tmp_nops > nops)
6677         nops = tmp_nops;
6678     }
6679
6680   if (mips_fix_vr4130 && !mips_opts.micromips)
6681     {
6682       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
6683       if (tmp_nops > nops)
6684         nops = tmp_nops;
6685     }
6686
6687   if (mips_fix_24k && !mips_opts.micromips)
6688     {
6689       tmp_nops = nops_for_24k (ignore, hist, insn);
6690       if (tmp_nops > nops)
6691         nops = tmp_nops;
6692     }
6693
6694   return nops;
6695 }
6696
6697 /* The variable arguments provide NUM_INSNS extra instructions that
6698    might be added to HIST.  Return the largest number of nops that
6699    would be needed after the extended sequence, ignoring hazards
6700    in the first IGNORE instructions.  */
6701
6702 static int
6703 nops_for_sequence (int num_insns, int ignore,
6704                    const struct mips_cl_insn *hist, ...)
6705 {
6706   va_list args;
6707   struct mips_cl_insn buffer[MAX_NOPS];
6708   struct mips_cl_insn *cursor;
6709   int nops;
6710
6711   va_start (args, hist);
6712   cursor = buffer + num_insns;
6713   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
6714   while (cursor > buffer)
6715     *--cursor = *va_arg (args, const struct mips_cl_insn *);
6716
6717   nops = nops_for_insn (ignore, buffer, NULL);
6718   va_end (args);
6719   return nops;
6720 }
6721
6722 /* Like nops_for_insn, but if INSN is a branch, take into account the
6723    worst-case delay for the branch target.  */
6724
6725 static int
6726 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
6727                          const struct mips_cl_insn *insn)
6728 {
6729   int nops, tmp_nops;
6730
6731   nops = nops_for_insn (ignore, hist, insn);
6732   if (delayed_branch_p (insn))
6733     {
6734       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
6735                                     hist, insn, get_delay_slot_nop (insn));
6736       if (tmp_nops > nops)
6737         nops = tmp_nops;
6738     }
6739   else if (compact_branch_p (insn))
6740     {
6741       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
6742       if (tmp_nops > nops)
6743         nops = tmp_nops;
6744     }
6745   return nops;
6746 }
6747
6748 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
6749
6750 static void
6751 fix_loongson2f_nop (struct mips_cl_insn * ip)
6752 {
6753   gas_assert (!HAVE_CODE_COMPRESSION);
6754   if (strcmp (ip->insn_mo->name, "nop") == 0)
6755     ip->insn_opcode = LOONGSON2F_NOP_INSN;
6756 }
6757
6758 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
6759                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
6760
6761 static void
6762 fix_loongson2f_jump (struct mips_cl_insn * ip)
6763 {
6764   gas_assert (!HAVE_CODE_COMPRESSION);
6765   if (strcmp (ip->insn_mo->name, "j") == 0
6766       || strcmp (ip->insn_mo->name, "jr") == 0
6767       || strcmp (ip->insn_mo->name, "jalr") == 0)
6768     {
6769       int sreg;
6770       expressionS ep;
6771
6772       if (! mips_opts.at)
6773         return;
6774
6775       sreg = EXTRACT_OPERAND (0, RS, *ip);
6776       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
6777         return;
6778
6779       ep.X_op = O_constant;
6780       ep.X_add_number = 0xcfff0000;
6781       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
6782       ep.X_add_number = 0xffff;
6783       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
6784       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
6785     }
6786 }
6787
6788 static void
6789 fix_loongson2f (struct mips_cl_insn * ip)
6790 {
6791   if (mips_fix_loongson2f_nop)
6792     fix_loongson2f_nop (ip);
6793
6794   if (mips_fix_loongson2f_jump)
6795     fix_loongson2f_jump (ip);
6796 }
6797
6798 /* IP is a branch that has a delay slot, and we need to fill it
6799    automatically.   Return true if we can do that by swapping IP
6800    with the previous instruction.
6801    ADDRESS_EXPR is an operand of the instruction to be used with
6802    RELOC_TYPE.  */
6803
6804 static bfd_boolean
6805 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
6806                    bfd_reloc_code_real_type *reloc_type)
6807 {
6808   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
6809   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
6810   unsigned int fpr_read, prev_fpr_write;
6811
6812   /* -O2 and above is required for this optimization.  */
6813   if (mips_optimize < 2)
6814     return FALSE;
6815
6816   /* If we have seen .set volatile or .set nomove, don't optimize.  */
6817   if (mips_opts.nomove)
6818     return FALSE;
6819
6820   /* We can't swap if the previous instruction's position is fixed.  */
6821   if (history[0].fixed_p)
6822     return FALSE;
6823
6824   /* If the previous previous insn was in a .set noreorder, we can't
6825      swap.  Actually, the MIPS assembler will swap in this situation.
6826      However, gcc configured -with-gnu-as will generate code like
6827
6828         .set    noreorder
6829         lw      $4,XXX
6830         .set    reorder
6831         INSN
6832         bne     $4,$0,foo
6833
6834      in which we can not swap the bne and INSN.  If gcc is not configured
6835      -with-gnu-as, it does not output the .set pseudo-ops.  */
6836   if (history[1].noreorder_p)
6837     return FALSE;
6838
6839   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
6840      This means that the previous instruction was a 4-byte one anyhow.  */
6841   if (mips_opts.mips16 && history[0].fixp[0])
6842     return FALSE;
6843
6844   /* If the branch is itself the target of a branch, we can not swap.
6845      We cheat on this; all we check for is whether there is a label on
6846      this instruction.  If there are any branches to anything other than
6847      a label, users must use .set noreorder.  */
6848   if (seg_info (now_seg)->label_list)
6849     return FALSE;
6850
6851   /* If the previous instruction is in a variant frag other than this
6852      branch's one, we cannot do the swap.  This does not apply to
6853      MIPS16 code, which uses variant frags for different purposes.  */
6854   if (!mips_opts.mips16
6855       && history[0].frag
6856       && history[0].frag->fr_type == rs_machine_dependent)
6857     return FALSE;
6858
6859   /* We do not swap with instructions that cannot architecturally
6860      be placed in a branch delay slot, such as SYNC or ERET.  We
6861      also refrain from swapping with a trap instruction, since it
6862      complicates trap handlers to have the trap instruction be in
6863      a delay slot.  */
6864   prev_pinfo = history[0].insn_mo->pinfo;
6865   if (prev_pinfo & INSN_NO_DELAY_SLOT)
6866     return FALSE;
6867
6868   /* Check for conflicts between the branch and the instructions
6869      before the candidate delay slot.  */
6870   if (nops_for_insn (0, history + 1, ip) > 0)
6871     return FALSE;
6872
6873   /* Check for conflicts between the swapped sequence and the
6874      target of the branch.  */
6875   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
6876     return FALSE;
6877
6878   /* If the branch reads a register that the previous
6879      instruction sets, we can not swap.  */
6880   gpr_read = gpr_read_mask (ip);
6881   prev_gpr_write = gpr_write_mask (&history[0]);
6882   if (gpr_read & prev_gpr_write)
6883     return FALSE;
6884
6885   fpr_read = fpr_read_mask (ip);
6886   prev_fpr_write = fpr_write_mask (&history[0]);
6887   if (fpr_read & prev_fpr_write)
6888     return FALSE;
6889
6890   /* If the branch writes a register that the previous
6891      instruction sets, we can not swap.  */
6892   gpr_write = gpr_write_mask (ip);
6893   if (gpr_write & prev_gpr_write)
6894     return FALSE;
6895
6896   /* If the branch writes a register that the previous
6897      instruction reads, we can not swap.  */
6898   prev_gpr_read = gpr_read_mask (&history[0]);
6899   if (gpr_write & prev_gpr_read)
6900     return FALSE;
6901
6902   /* If one instruction sets a condition code and the
6903      other one uses a condition code, we can not swap.  */
6904   pinfo = ip->insn_mo->pinfo;
6905   if ((pinfo & INSN_READ_COND_CODE)
6906       && (prev_pinfo & INSN_WRITE_COND_CODE))
6907     return FALSE;
6908   if ((pinfo & INSN_WRITE_COND_CODE)
6909       && (prev_pinfo & INSN_READ_COND_CODE))
6910     return FALSE;
6911
6912   /* If the previous instruction uses the PC, we can not swap.  */
6913   prev_pinfo2 = history[0].insn_mo->pinfo2;
6914   if (prev_pinfo2 & INSN2_READ_PC)
6915     return FALSE;
6916
6917   /* If the previous instruction has an incorrect size for a fixed
6918      branch delay slot in microMIPS mode, we cannot swap.  */
6919   pinfo2 = ip->insn_mo->pinfo2;
6920   if (mips_opts.micromips
6921       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
6922       && insn_length (history) != 2)
6923     return FALSE;
6924   if (mips_opts.micromips
6925       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
6926       && insn_length (history) != 4)
6927     return FALSE;
6928
6929   /* On R5900 short loops need to be fixed by inserting a nop in
6930      the branch delay slots.
6931      A short loop can be terminated too early.  */
6932   if (mips_opts.arch == CPU_R5900
6933       /* Check if instruction has a parameter, ignore "j $31". */
6934       && (address_expr != NULL)
6935       /* Parameter must be 16 bit. */
6936       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
6937       /* Branch to same segment. */
6938       && (S_GET_SEGMENT (address_expr->X_add_symbol) == now_seg)
6939       /* Branch to same code fragment. */
6940       && (symbol_get_frag (address_expr->X_add_symbol) == frag_now)
6941       /* Can only calculate branch offset if value is known. */
6942       && symbol_constant_p (address_expr->X_add_symbol)
6943       /* Check if branch is really conditional. */
6944       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
6945         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
6946         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
6947     {
6948       int distance;
6949       /* Check if loop is shorter than 6 instructions including
6950          branch and delay slot.  */
6951       distance = frag_now_fix () - S_GET_VALUE (address_expr->X_add_symbol);
6952       if (distance <= 20)
6953         {
6954           int i;
6955           int rv;
6956
6957           rv = FALSE;
6958           /* When the loop includes branches or jumps,
6959              it is not a short loop. */
6960           for (i = 0; i < (distance / 4); i++)
6961             {
6962               if ((history[i].cleared_p)
6963                   || delayed_branch_p (&history[i]))
6964                 {
6965                   rv = TRUE;
6966                   break;
6967                 }
6968             }
6969           if (!rv)
6970             {
6971               /* Insert nop after branch to fix short loop. */
6972               return FALSE;
6973             }
6974         }
6975     }
6976
6977   return TRUE;
6978 }
6979
6980 /* Decide how we should add IP to the instruction stream.
6981    ADDRESS_EXPR is an operand of the instruction to be used with
6982    RELOC_TYPE.  */
6983
6984 static enum append_method
6985 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
6986                    bfd_reloc_code_real_type *reloc_type)
6987 {
6988   /* The relaxed version of a macro sequence must be inherently
6989      hazard-free.  */
6990   if (mips_relax.sequence == 2)
6991     return APPEND_ADD;
6992
6993   /* We must not dabble with instructions in a ".set noreorder" block.  */
6994   if (mips_opts.noreorder)
6995     return APPEND_ADD;
6996
6997   /* Otherwise, it's our responsibility to fill branch delay slots.  */
6998   if (delayed_branch_p (ip))
6999     {
7000       if (!branch_likely_p (ip)
7001           && can_swap_branch_p (ip, address_expr, reloc_type))
7002         return APPEND_SWAP;
7003
7004       if (mips_opts.mips16
7005           && ISA_SUPPORTS_MIPS16E
7006           && gpr_read_mask (ip) != 0)
7007         return APPEND_ADD_COMPACT;
7008
7009       if (mips_opts.micromips
7010           && ((ip->insn_opcode & 0xffe0) == 0x4580
7011               || (!forced_insn_length
7012                   && ((ip->insn_opcode & 0xfc00) == 0xcc00
7013                       || (ip->insn_opcode & 0xdc00) == 0x8c00))
7014               || (ip->insn_opcode & 0xdfe00000) == 0x94000000
7015               || (ip->insn_opcode & 0xdc1f0000) == 0x94000000))
7016         return APPEND_ADD_COMPACT;
7017
7018       return APPEND_ADD_WITH_NOP;
7019     }
7020
7021   return APPEND_ADD;
7022 }
7023
7024 /* IP is an instruction whose opcode we have just changed, END points
7025    to the end of the opcode table processed.  Point IP->insn_mo to the
7026    new opcode's definition.  */
7027
7028 static void
7029 find_altered_opcode (struct mips_cl_insn *ip, const struct mips_opcode *end)
7030 {
7031   const struct mips_opcode *mo;
7032
7033   for (mo = ip->insn_mo; mo < end; mo++)
7034     if (mo->pinfo != INSN_MACRO
7035         && (ip->insn_opcode & mo->mask) == mo->match)
7036       {
7037         ip->insn_mo = mo;
7038         return;
7039       }
7040   abort ();
7041 }
7042
7043 /* IP is a MIPS16 instruction whose opcode we have just changed.
7044    Point IP->insn_mo to the new opcode's definition.  */
7045
7046 static void
7047 find_altered_mips16_opcode (struct mips_cl_insn *ip)
7048 {
7049   find_altered_opcode (ip, &mips16_opcodes[bfd_mips16_num_opcodes]);
7050 }
7051
7052 /* IP is a microMIPS instruction whose opcode we have just changed.
7053    Point IP->insn_mo to the new opcode's definition.  */
7054
7055 static void
7056 find_altered_micromips_opcode (struct mips_cl_insn *ip)
7057 {
7058   find_altered_opcode (ip, &micromips_opcodes[bfd_micromips_num_opcodes]);
7059 }
7060
7061 /* For microMIPS macros, we need to generate a local number label
7062    as the target of branches.  */
7063 #define MICROMIPS_LABEL_CHAR            '\037'
7064 static unsigned long micromips_target_label;
7065 static char micromips_target_name[32];
7066
7067 static char *
7068 micromips_label_name (void)
7069 {
7070   char *p = micromips_target_name;
7071   char symbol_name_temporary[24];
7072   unsigned long l;
7073   int i;
7074
7075   if (*p)
7076     return p;
7077
7078   i = 0;
7079   l = micromips_target_label;
7080 #ifdef LOCAL_LABEL_PREFIX
7081   *p++ = LOCAL_LABEL_PREFIX;
7082 #endif
7083   *p++ = 'L';
7084   *p++ = MICROMIPS_LABEL_CHAR;
7085   do
7086     {
7087       symbol_name_temporary[i++] = l % 10 + '0';
7088       l /= 10;
7089     }
7090   while (l != 0);
7091   while (i > 0)
7092     *p++ = symbol_name_temporary[--i];
7093   *p = '\0';
7094
7095   return micromips_target_name;
7096 }
7097
7098 static void
7099 micromips_label_expr (expressionS *label_expr)
7100 {
7101   label_expr->X_op = O_symbol;
7102   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
7103   label_expr->X_add_number = 0;
7104 }
7105
7106 static void
7107 micromips_label_inc (void)
7108 {
7109   micromips_target_label++;
7110   *micromips_target_name = '\0';
7111 }
7112
7113 static void
7114 micromips_add_label (void)
7115 {
7116   symbolS *s;
7117
7118   s = colon (micromips_label_name ());
7119   micromips_label_inc ();
7120   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
7121 }
7122
7123 /* If assembling microMIPS code, then return the microMIPS reloc
7124    corresponding to the requested one if any.  Otherwise return
7125    the reloc unchanged.  */
7126
7127 static bfd_reloc_code_real_type
7128 micromips_map_reloc (bfd_reloc_code_real_type reloc)
7129 {
7130   static const bfd_reloc_code_real_type relocs[][2] =
7131     {
7132       /* Keep sorted incrementally by the left-hand key.  */
7133       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
7134       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
7135       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
7136       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
7137       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
7138       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
7139       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
7140       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
7141       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
7142       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
7143       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
7144       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
7145       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
7146       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
7147       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
7148       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
7149       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
7150       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
7151       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
7152       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
7153       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
7154       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
7155       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
7156       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
7157       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
7158       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
7159       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
7160     };
7161   bfd_reloc_code_real_type r;
7162   size_t i;
7163
7164   if (!mips_opts.micromips)
7165     return reloc;
7166   for (i = 0; i < ARRAY_SIZE (relocs); i++)
7167     {
7168       r = relocs[i][0];
7169       if (r > reloc)
7170         return reloc;
7171       if (r == reloc)
7172         return relocs[i][1];
7173     }
7174   return reloc;
7175 }
7176
7177 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
7178    Return true on success, storing the resolved value in RESULT.  */
7179
7180 static bfd_boolean
7181 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
7182                  offsetT *result)
7183 {
7184   switch (reloc)
7185     {
7186     case BFD_RELOC_MIPS_HIGHEST:
7187     case BFD_RELOC_MICROMIPS_HIGHEST:
7188       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
7189       return TRUE;
7190
7191     case BFD_RELOC_MIPS_HIGHER:
7192     case BFD_RELOC_MICROMIPS_HIGHER:
7193       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
7194       return TRUE;
7195
7196     case BFD_RELOC_HI16_S:
7197     case BFD_RELOC_HI16_S_PCREL:
7198     case BFD_RELOC_MICROMIPS_HI16_S:
7199     case BFD_RELOC_MIPS16_HI16_S:
7200       *result = ((operand + 0x8000) >> 16) & 0xffff;
7201       return TRUE;
7202
7203     case BFD_RELOC_HI16:
7204     case BFD_RELOC_MICROMIPS_HI16:
7205     case BFD_RELOC_MIPS16_HI16:
7206       *result = (operand >> 16) & 0xffff;
7207       return TRUE;
7208
7209     case BFD_RELOC_LO16:
7210     case BFD_RELOC_LO16_PCREL:
7211     case BFD_RELOC_MICROMIPS_LO16:
7212     case BFD_RELOC_MIPS16_LO16:
7213       *result = operand & 0xffff;
7214       return TRUE;
7215
7216     case BFD_RELOC_UNUSED:
7217       *result = operand;
7218       return TRUE;
7219
7220     default:
7221       return FALSE;
7222     }
7223 }
7224
7225 /* Output an instruction.  IP is the instruction information.
7226    ADDRESS_EXPR is an operand of the instruction to be used with
7227    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
7228    a macro expansion.  */
7229
7230 static void
7231 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
7232              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
7233 {
7234   unsigned long prev_pinfo2, pinfo;
7235   bfd_boolean relaxed_branch = FALSE;
7236   enum append_method method;
7237   bfd_boolean relax32;
7238   int branch_disp;
7239
7240   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
7241     fix_loongson2f (ip);
7242
7243   file_ase_mips16 |= mips_opts.mips16;
7244   file_ase_micromips |= mips_opts.micromips;
7245
7246   prev_pinfo2 = history[0].insn_mo->pinfo2;
7247   pinfo = ip->insn_mo->pinfo;
7248
7249   /* Don't raise alarm about `nods' frags as they'll fill in the right
7250      kind of nop in relaxation if required.  */
7251   if (mips_opts.micromips
7252       && !expansionp
7253       && !(history[0].frag
7254            && history[0].frag->fr_type == rs_machine_dependent
7255            && RELAX_MICROMIPS_P (history[0].frag->fr_subtype)
7256            && RELAX_MICROMIPS_NODS (history[0].frag->fr_subtype))
7257       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
7258            && micromips_insn_length (ip->insn_mo) != 2)
7259           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
7260               && micromips_insn_length (ip->insn_mo) != 4)))
7261     as_warn (_("wrong size instruction in a %u-bit branch delay slot"),
7262              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
7263
7264   if (address_expr == NULL)
7265     ip->complete_p = 1;
7266   else if (reloc_type[0] <= BFD_RELOC_UNUSED
7267            && reloc_type[1] == BFD_RELOC_UNUSED
7268            && reloc_type[2] == BFD_RELOC_UNUSED
7269            && address_expr->X_op == O_constant)
7270     {
7271       switch (*reloc_type)
7272         {
7273         case BFD_RELOC_MIPS_JMP:
7274           {
7275             int shift;
7276
7277             /* Shift is 2, unusually, for microMIPS JALX.  */
7278             shift = (mips_opts.micromips
7279                      && strcmp (ip->insn_mo->name, "jalx") != 0) ? 1 : 2;
7280             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7281               as_bad (_("jump to misaligned address (0x%lx)"),
7282                       (unsigned long) address_expr->X_add_number);
7283             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7284                                 & 0x3ffffff);
7285             ip->complete_p = 1;
7286           }
7287           break;
7288
7289         case BFD_RELOC_MIPS16_JMP:
7290           if ((address_expr->X_add_number & 3) != 0)
7291             as_bad (_("jump to misaligned address (0x%lx)"),
7292                     (unsigned long) address_expr->X_add_number);
7293           ip->insn_opcode |=
7294             (((address_expr->X_add_number & 0x7c0000) << 3)
7295                | ((address_expr->X_add_number & 0xf800000) >> 7)
7296                | ((address_expr->X_add_number & 0x3fffc) >> 2));
7297           ip->complete_p = 1;
7298           break;
7299
7300         case BFD_RELOC_16_PCREL_S2:
7301           {
7302             int shift;
7303
7304             shift = mips_opts.micromips ? 1 : 2;
7305             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7306               as_bad (_("branch to misaligned address (0x%lx)"),
7307                       (unsigned long) address_expr->X_add_number);
7308             if (!mips_relax_branch)
7309               {
7310                 if ((address_expr->X_add_number + (1 << (shift + 15)))
7311                     & ~((1 << (shift + 16)) - 1))
7312                   as_bad (_("branch address range overflow (0x%lx)"),
7313                           (unsigned long) address_expr->X_add_number);
7314                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7315                                     & 0xffff);
7316               }
7317           }
7318           break;
7319
7320         case BFD_RELOC_MIPS_21_PCREL_S2:
7321           {
7322             int shift;
7323
7324             shift = 2;
7325             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7326               as_bad (_("branch to misaligned address (0x%lx)"),
7327                       (unsigned long) address_expr->X_add_number);
7328             if ((address_expr->X_add_number + (1 << (shift + 20)))
7329                 & ~((1 << (shift + 21)) - 1))
7330               as_bad (_("branch address range overflow (0x%lx)"),
7331                       (unsigned long) address_expr->X_add_number);
7332             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7333                                 & 0x1fffff);
7334           }
7335           break;
7336
7337         case BFD_RELOC_MIPS_26_PCREL_S2:
7338           {
7339             int shift;
7340
7341             shift = 2;
7342             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7343               as_bad (_("branch to misaligned address (0x%lx)"),
7344                       (unsigned long) address_expr->X_add_number);
7345             if ((address_expr->X_add_number + (1 << (shift + 25)))
7346                 & ~((1 << (shift + 26)) - 1))
7347               as_bad (_("branch address range overflow (0x%lx)"),
7348                       (unsigned long) address_expr->X_add_number);
7349             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7350                                 & 0x3ffffff);
7351           }
7352           break;
7353
7354         default:
7355           {
7356             offsetT value;
7357
7358             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
7359                                  &value))
7360               {
7361                 ip->insn_opcode |= value & 0xffff;
7362                 ip->complete_p = 1;
7363               }
7364           }
7365           break;
7366         }
7367     }
7368
7369   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
7370     {
7371       /* There are a lot of optimizations we could do that we don't.
7372          In particular, we do not, in general, reorder instructions.
7373          If you use gcc with optimization, it will reorder
7374          instructions and generally do much more optimization then we
7375          do here; repeating all that work in the assembler would only
7376          benefit hand written assembly code, and does not seem worth
7377          it.  */
7378       int nops = (mips_optimize == 0
7379                   ? nops_for_insn (0, history, NULL)
7380                   : nops_for_insn_or_target (0, history, ip));
7381       if (nops > 0)
7382         {
7383           fragS *old_frag;
7384           unsigned long old_frag_offset;
7385           int i;
7386
7387           old_frag = frag_now;
7388           old_frag_offset = frag_now_fix ();
7389
7390           for (i = 0; i < nops; i++)
7391             add_fixed_insn (NOP_INSN);
7392           insert_into_history (0, nops, NOP_INSN);
7393
7394           if (listing)
7395             {
7396               listing_prev_line ();
7397               /* We may be at the start of a variant frag.  In case we
7398                  are, make sure there is enough space for the frag
7399                  after the frags created by listing_prev_line.  The
7400                  argument to frag_grow here must be at least as large
7401                  as the argument to all other calls to frag_grow in
7402                  this file.  We don't have to worry about being in the
7403                  middle of a variant frag, because the variants insert
7404                  all needed nop instructions themselves.  */
7405               frag_grow (40);
7406             }
7407
7408           mips_move_text_labels ();
7409
7410 #ifndef NO_ECOFF_DEBUGGING
7411           if (ECOFF_DEBUGGING)
7412             ecoff_fix_loc (old_frag, old_frag_offset);
7413 #endif
7414         }
7415     }
7416   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
7417     {
7418       int nops;
7419
7420       /* Work out how many nops in prev_nop_frag are needed by IP,
7421          ignoring hazards generated by the first prev_nop_frag_since
7422          instructions.  */
7423       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
7424       gas_assert (nops <= prev_nop_frag_holds);
7425
7426       /* Enforce NOPS as a minimum.  */
7427       if (nops > prev_nop_frag_required)
7428         prev_nop_frag_required = nops;
7429
7430       if (prev_nop_frag_holds == prev_nop_frag_required)
7431         {
7432           /* Settle for the current number of nops.  Update the history
7433              accordingly (for the benefit of any future .set reorder code).  */
7434           prev_nop_frag = NULL;
7435           insert_into_history (prev_nop_frag_since,
7436                                prev_nop_frag_holds, NOP_INSN);
7437         }
7438       else
7439         {
7440           /* Allow this instruction to replace one of the nops that was
7441              tentatively added to prev_nop_frag.  */
7442           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
7443           prev_nop_frag_holds--;
7444           prev_nop_frag_since++;
7445         }
7446     }
7447
7448   method = get_append_method (ip, address_expr, reloc_type);
7449   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
7450
7451   dwarf2_emit_insn (0);
7452   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
7453      so "move" the instruction address accordingly.
7454
7455      Also, it doesn't seem appropriate for the assembler to reorder .loc
7456      entries.  If this instruction is a branch that we are going to swap
7457      with the previous instruction, the two instructions should be
7458      treated as a unit, and the debug information for both instructions
7459      should refer to the start of the branch sequence.  Using the
7460      current position is certainly wrong when swapping a 32-bit branch
7461      and a 16-bit delay slot, since the current position would then be
7462      in the middle of a branch.  */
7463   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
7464
7465   relax32 = (mips_relax_branch
7466              /* Don't try branch relaxation within .set nomacro, or within
7467                 .set noat if we use $at for PIC computations.  If it turns
7468                 out that the branch was out-of-range, we'll get an error.  */
7469              && !mips_opts.warn_about_macros
7470              && (mips_opts.at || mips_pic == NO_PIC)
7471              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
7472                 as they have no complementing branches.  */
7473              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
7474
7475   if (!HAVE_CODE_COMPRESSION
7476       && address_expr
7477       && relax32
7478       && *reloc_type == BFD_RELOC_16_PCREL_S2
7479       && delayed_branch_p (ip))
7480     {
7481       relaxed_branch = TRUE;
7482       add_relaxed_insn (ip, (relaxed_branch_length
7483                              (NULL, NULL,
7484                               uncond_branch_p (ip) ? -1
7485                               : branch_likely_p (ip) ? 1
7486                               : 0)), 4,
7487                         RELAX_BRANCH_ENCODE
7488                         (AT, mips_pic != NO_PIC,
7489                          uncond_branch_p (ip),
7490                          branch_likely_p (ip),
7491                          pinfo & INSN_WRITE_GPR_31,
7492                          0),
7493                         address_expr->X_add_symbol,
7494                         address_expr->X_add_number);
7495       *reloc_type = BFD_RELOC_UNUSED;
7496     }
7497   else if (mips_opts.micromips
7498            && address_expr
7499            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
7500                || *reloc_type > BFD_RELOC_UNUSED)
7501            && (delayed_branch_p (ip) || compact_branch_p (ip))
7502            /* Don't try branch relaxation when users specify
7503               16-bit/32-bit instructions.  */
7504            && !forced_insn_length)
7505     {
7506       bfd_boolean relax16 = (method != APPEND_ADD_COMPACT
7507                              && *reloc_type > BFD_RELOC_UNUSED);
7508       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
7509       int uncond = uncond_branch_p (ip) ? -1 : 0;
7510       int compact = compact_branch_p (ip) || method == APPEND_ADD_COMPACT;
7511       int nods = method == APPEND_ADD_WITH_NOP;
7512       int al = pinfo & INSN_WRITE_GPR_31;
7513       int length32 = nods ? 8 : 4;
7514
7515       gas_assert (address_expr != NULL);
7516       gas_assert (!mips_relax.sequence);
7517
7518       relaxed_branch = TRUE;
7519       if (nods)
7520         method = APPEND_ADD;
7521       if (relax32)
7522         length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
7523       add_relaxed_insn (ip, length32, relax16 ? 2 : 4,
7524                         RELAX_MICROMIPS_ENCODE (type, AT, mips_opts.insn32,
7525                                                 mips_pic != NO_PIC,
7526                                                 uncond, compact, al, nods,
7527                                                 relax32, 0, 0),
7528                         address_expr->X_add_symbol,
7529                         address_expr->X_add_number);
7530       *reloc_type = BFD_RELOC_UNUSED;
7531     }
7532   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
7533     {
7534       bfd_boolean require_unextended;
7535       bfd_boolean require_extended;
7536       symbolS *symbol;
7537       offsetT offset;
7538
7539       if (forced_insn_length != 0)
7540         {
7541           require_unextended = forced_insn_length == 2;
7542           require_extended = forced_insn_length == 4;
7543         }
7544       else
7545         {
7546           require_unextended = (mips_opts.noautoextend
7547                                 && !mips_opcode_32bit_p (ip->insn_mo));
7548           require_extended = 0;
7549         }
7550
7551       /* We need to set up a variant frag.  */
7552       gas_assert (address_expr != NULL);
7553       /* Pass any `O_symbol' expression unchanged as an `expr_section'
7554          symbol created by `make_expr_symbol' may not get a necessary
7555          external relocation produced.  */
7556       if (address_expr->X_op == O_symbol)
7557         {
7558           symbol = address_expr->X_add_symbol;
7559           offset = address_expr->X_add_number;
7560         }
7561       else
7562         {
7563           symbol = make_expr_symbol (address_expr);
7564           symbol_append (symbol, symbol_lastP, &symbol_rootP, &symbol_lastP);
7565           offset = 0;
7566         }
7567       add_relaxed_insn (ip, 12, 0,
7568                         RELAX_MIPS16_ENCODE
7569                         (*reloc_type - BFD_RELOC_UNUSED,
7570                          mips_opts.ase & ASE_MIPS16E2,
7571                          mips_pic != NO_PIC,
7572                          HAVE_32BIT_SYMBOLS,
7573                          mips_opts.warn_about_macros,
7574                          require_unextended, require_extended,
7575                          delayed_branch_p (&history[0]),
7576                          history[0].mips16_absolute_jump_p),
7577                         symbol, offset);
7578     }
7579   else if (mips_opts.mips16 && insn_length (ip) == 2)
7580     {
7581       if (!delayed_branch_p (ip))
7582         /* Make sure there is enough room to swap this instruction with
7583            a following jump instruction.  */
7584         frag_grow (6);
7585       add_fixed_insn (ip);
7586     }
7587   else
7588     {
7589       if (mips_opts.mips16
7590           && mips_opts.noreorder
7591           && delayed_branch_p (&history[0]))
7592         as_warn (_("extended instruction in delay slot"));
7593
7594       if (mips_relax.sequence)
7595         {
7596           /* If we've reached the end of this frag, turn it into a variant
7597              frag and record the information for the instructions we've
7598              written so far.  */
7599           if (frag_room () < 4)
7600             relax_close_frag ();
7601           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
7602         }
7603
7604       if (mips_relax.sequence != 2)
7605         {
7606           if (mips_macro_warning.first_insn_sizes[0] == 0)
7607             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
7608           mips_macro_warning.sizes[0] += insn_length (ip);
7609           mips_macro_warning.insns[0]++;
7610         }
7611       if (mips_relax.sequence != 1)
7612         {
7613           if (mips_macro_warning.first_insn_sizes[1] == 0)
7614             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
7615           mips_macro_warning.sizes[1] += insn_length (ip);
7616           mips_macro_warning.insns[1]++;
7617         }
7618
7619       if (mips_opts.mips16)
7620         {
7621           ip->fixed_p = 1;
7622           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
7623         }
7624       add_fixed_insn (ip);
7625     }
7626
7627   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
7628     {
7629       bfd_reloc_code_real_type final_type[3];
7630       reloc_howto_type *howto0;
7631       reloc_howto_type *howto;
7632       int i;
7633
7634       /* Perform any necessary conversion to microMIPS relocations
7635          and find out how many relocations there actually are.  */
7636       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
7637         final_type[i] = micromips_map_reloc (reloc_type[i]);
7638
7639       /* In a compound relocation, it is the final (outermost)
7640          operator that determines the relocated field.  */
7641       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
7642       if (!howto)
7643         abort ();
7644
7645       if (i > 1)
7646         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
7647       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
7648                                  bfd_get_reloc_size (howto),
7649                                  address_expr,
7650                                  howto0 && howto0->pc_relative,
7651                                  final_type[0]);
7652       /* Record non-PIC mode in `fx_tcbit2' for `md_apply_fix'.  */
7653       ip->fixp[0]->fx_tcbit2 = mips_pic == NO_PIC;
7654
7655       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
7656       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
7657         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
7658
7659       /* These relocations can have an addend that won't fit in
7660          4 octets for 64bit assembly.  */
7661       if (GPR_SIZE == 64
7662           && ! howto->partial_inplace
7663           && (reloc_type[0] == BFD_RELOC_16
7664               || reloc_type[0] == BFD_RELOC_32
7665               || reloc_type[0] == BFD_RELOC_MIPS_JMP
7666               || reloc_type[0] == BFD_RELOC_GPREL16
7667               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
7668               || reloc_type[0] == BFD_RELOC_GPREL32
7669               || reloc_type[0] == BFD_RELOC_64
7670               || reloc_type[0] == BFD_RELOC_CTOR
7671               || reloc_type[0] == BFD_RELOC_MIPS_SUB
7672               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
7673               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
7674               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
7675               || reloc_type[0] == BFD_RELOC_MIPS_REL16
7676               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
7677               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
7678               || hi16_reloc_p (reloc_type[0])
7679               || lo16_reloc_p (reloc_type[0])))
7680         ip->fixp[0]->fx_no_overflow = 1;
7681
7682       /* These relocations can have an addend that won't fit in 2 octets.  */
7683       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
7684           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
7685         ip->fixp[0]->fx_no_overflow = 1;
7686
7687       if (mips_relax.sequence)
7688         {
7689           if (mips_relax.first_fixup == 0)
7690             mips_relax.first_fixup = ip->fixp[0];
7691         }
7692       else if (reloc_needs_lo_p (*reloc_type))
7693         {
7694           struct mips_hi_fixup *hi_fixup;
7695
7696           /* Reuse the last entry if it already has a matching %lo.  */
7697           hi_fixup = mips_hi_fixup_list;
7698           if (hi_fixup == 0
7699               || !fixup_has_matching_lo_p (hi_fixup->fixp))
7700             {
7701               hi_fixup = XNEW (struct mips_hi_fixup);
7702               hi_fixup->next = mips_hi_fixup_list;
7703               mips_hi_fixup_list = hi_fixup;
7704             }
7705           hi_fixup->fixp = ip->fixp[0];
7706           hi_fixup->seg = now_seg;
7707         }
7708
7709       /* Add fixups for the second and third relocations, if given.
7710          Note that the ABI allows the second relocation to be
7711          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
7712          moment we only use RSS_UNDEF, but we could add support
7713          for the others if it ever becomes necessary.  */
7714       for (i = 1; i < 3; i++)
7715         if (reloc_type[i] != BFD_RELOC_UNUSED)
7716           {
7717             ip->fixp[i] = fix_new (ip->frag, ip->where,
7718                                    ip->fixp[0]->fx_size, NULL, 0,
7719                                    FALSE, final_type[i]);
7720
7721             /* Use fx_tcbit to mark compound relocs.  */
7722             ip->fixp[0]->fx_tcbit = 1;
7723             ip->fixp[i]->fx_tcbit = 1;
7724           }
7725     }
7726
7727   /* Update the register mask information.  */
7728   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
7729   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
7730
7731   switch (method)
7732     {
7733     case APPEND_ADD:
7734       insert_into_history (0, 1, ip);
7735       break;
7736
7737     case APPEND_ADD_WITH_NOP:
7738       {
7739         struct mips_cl_insn *nop;
7740
7741         insert_into_history (0, 1, ip);
7742         nop = get_delay_slot_nop (ip);
7743         add_fixed_insn (nop);
7744         insert_into_history (0, 1, nop);
7745         if (mips_relax.sequence)
7746           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
7747       }
7748       break;
7749
7750     case APPEND_ADD_COMPACT:
7751       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
7752       if (mips_opts.mips16)
7753         {
7754           ip->insn_opcode |= 0x0080;
7755           find_altered_mips16_opcode (ip);
7756         }
7757       /* Convert microMIPS instructions.  */
7758       else if (mips_opts.micromips)
7759         {
7760           /* jr16->jrc */
7761           if ((ip->insn_opcode & 0xffe0) == 0x4580)
7762             ip->insn_opcode |= 0x0020;
7763           /* b16->bc */
7764           else if ((ip->insn_opcode & 0xfc00) == 0xcc00)
7765             ip->insn_opcode = 0x40e00000;
7766           /* beqz16->beqzc, bnez16->bnezc */
7767           else if ((ip->insn_opcode & 0xdc00) == 0x8c00)
7768             {
7769               unsigned long regno;
7770
7771               regno = ip->insn_opcode >> MICROMIPSOP_SH_MD;
7772               regno &= MICROMIPSOP_MASK_MD;
7773               regno = micromips_to_32_reg_d_map[regno];
7774               ip->insn_opcode = (((ip->insn_opcode << 9) & 0x00400000)
7775                                  | (regno << MICROMIPSOP_SH_RS)
7776                                  | 0x40a00000) ^ 0x00400000;
7777             }
7778           /* beqz->beqzc, bnez->bnezc */
7779           else if ((ip->insn_opcode & 0xdfe00000) == 0x94000000)
7780             ip->insn_opcode = ((ip->insn_opcode & 0x001f0000)
7781                                | ((ip->insn_opcode >> 7) & 0x00400000)
7782                                | 0x40a00000) ^ 0x00400000;
7783           /* beq $0->beqzc, bne $0->bnezc */
7784           else if ((ip->insn_opcode & 0xdc1f0000) == 0x94000000)
7785             ip->insn_opcode = (((ip->insn_opcode >>
7786                                  (MICROMIPSOP_SH_RT - MICROMIPSOP_SH_RS))
7787                                 & (MICROMIPSOP_MASK_RS << MICROMIPSOP_SH_RS))
7788                                | ((ip->insn_opcode >> 7) & 0x00400000)
7789                                | 0x40a00000) ^ 0x00400000;
7790           else
7791             abort ();
7792           find_altered_micromips_opcode (ip);
7793         }
7794       else
7795         abort ();
7796       install_insn (ip);
7797       insert_into_history (0, 1, ip);
7798       break;
7799
7800     case APPEND_SWAP:
7801       {
7802         struct mips_cl_insn delay = history[0];
7803
7804         if (relaxed_branch || delay.frag != ip->frag)
7805           {
7806             /* Add the delay slot instruction to the end of the
7807                current frag and shrink the fixed part of the
7808                original frag.  If the branch occupies the tail of
7809                the latter, move it backwards to cover the gap.  */
7810             delay.frag->fr_fix -= branch_disp;
7811             if (delay.frag == ip->frag)
7812               move_insn (ip, ip->frag, ip->where - branch_disp);
7813             add_fixed_insn (&delay);
7814           }
7815         else
7816           {
7817             /* If this is not a relaxed branch and we are in the
7818                same frag, then just swap the instructions.  */
7819             move_insn (ip, delay.frag, delay.where);
7820             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
7821           }
7822         history[0] = *ip;
7823         delay.fixed_p = 1;
7824         insert_into_history (0, 1, &delay);
7825       }
7826       break;
7827     }
7828
7829   /* If we have just completed an unconditional branch, clear the history.  */
7830   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
7831       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
7832     {
7833       unsigned int i;
7834
7835       mips_no_prev_insn ();
7836
7837       for (i = 0; i < ARRAY_SIZE (history); i++)
7838         history[i].cleared_p = 1;
7839     }
7840
7841   /* We need to emit a label at the end of branch-likely macros.  */
7842   if (emit_branch_likely_macro)
7843     {
7844       emit_branch_likely_macro = FALSE;
7845       micromips_add_label ();
7846     }
7847
7848   /* We just output an insn, so the next one doesn't have a label.  */
7849   mips_clear_insn_labels ();
7850 }
7851
7852 /* Forget that there was any previous instruction or label.
7853    When BRANCH is true, the branch history is also flushed.  */
7854
7855 static void
7856 mips_no_prev_insn (void)
7857 {
7858   prev_nop_frag = NULL;
7859   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
7860   mips_clear_insn_labels ();
7861 }
7862
7863 /* This function must be called before we emit something other than
7864    instructions.  It is like mips_no_prev_insn except that it inserts
7865    any NOPS that might be needed by previous instructions.  */
7866
7867 void
7868 mips_emit_delays (void)
7869 {
7870   if (! mips_opts.noreorder)
7871     {
7872       int nops = nops_for_insn (0, history, NULL);
7873       if (nops > 0)
7874         {
7875           while (nops-- > 0)
7876             add_fixed_insn (NOP_INSN);
7877           mips_move_text_labels ();
7878         }
7879     }
7880   mips_no_prev_insn ();
7881 }
7882
7883 /* Start a (possibly nested) noreorder block.  */
7884
7885 static void
7886 start_noreorder (void)
7887 {
7888   if (mips_opts.noreorder == 0)
7889     {
7890       unsigned int i;
7891       int nops;
7892
7893       /* None of the instructions before the .set noreorder can be moved.  */
7894       for (i = 0; i < ARRAY_SIZE (history); i++)
7895         history[i].fixed_p = 1;
7896
7897       /* Insert any nops that might be needed between the .set noreorder
7898          block and the previous instructions.  We will later remove any
7899          nops that turn out not to be needed.  */
7900       nops = nops_for_insn (0, history, NULL);
7901       if (nops > 0)
7902         {
7903           if (mips_optimize != 0)
7904             {
7905               /* Record the frag which holds the nop instructions, so
7906                  that we can remove them if we don't need them.  */
7907               frag_grow (nops * NOP_INSN_SIZE);
7908               prev_nop_frag = frag_now;
7909               prev_nop_frag_holds = nops;
7910               prev_nop_frag_required = 0;
7911               prev_nop_frag_since = 0;
7912             }
7913
7914           for (; nops > 0; --nops)
7915             add_fixed_insn (NOP_INSN);
7916
7917           /* Move on to a new frag, so that it is safe to simply
7918              decrease the size of prev_nop_frag.  */
7919           frag_wane (frag_now);
7920           frag_new (0);
7921           mips_move_text_labels ();
7922         }
7923       mips_mark_labels ();
7924       mips_clear_insn_labels ();
7925     }
7926   mips_opts.noreorder++;
7927   mips_any_noreorder = 1;
7928 }
7929
7930 /* End a nested noreorder block.  */
7931
7932 static void
7933 end_noreorder (void)
7934 {
7935   mips_opts.noreorder--;
7936   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
7937     {
7938       /* Commit to inserting prev_nop_frag_required nops and go back to
7939          handling nop insertion the .set reorder way.  */
7940       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
7941                                 * NOP_INSN_SIZE);
7942       insert_into_history (prev_nop_frag_since,
7943                            prev_nop_frag_required, NOP_INSN);
7944       prev_nop_frag = NULL;
7945     }
7946 }
7947
7948 /* Sign-extend 32-bit mode constants that have bit 31 set and all
7949    higher bits unset.  */
7950
7951 static void
7952 normalize_constant_expr (expressionS *ex)
7953 {
7954   if (ex->X_op == O_constant
7955       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7956     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7957                         - 0x80000000);
7958 }
7959
7960 /* Sign-extend 32-bit mode address offsets that have bit 31 set and
7961    all higher bits unset.  */
7962
7963 static void
7964 normalize_address_expr (expressionS *ex)
7965 {
7966   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
7967         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
7968       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7969     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7970                         - 0x80000000);
7971 }
7972
7973 /* Try to match TOKENS against OPCODE, storing the result in INSN.
7974    Return true if the match was successful.
7975
7976    OPCODE_EXTRA is a value that should be ORed into the opcode
7977    (used for VU0 channel suffixes, etc.).  MORE_ALTS is true if
7978    there are more alternatives after OPCODE and SOFT_MATCH is
7979    as for mips_arg_info.  */
7980
7981 static bfd_boolean
7982 match_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7983             struct mips_operand_token *tokens, unsigned int opcode_extra,
7984             bfd_boolean lax_match, bfd_boolean complete_p)
7985 {
7986   const char *args;
7987   struct mips_arg_info arg;
7988   const struct mips_operand *operand;
7989   char c;
7990
7991   imm_expr.X_op = O_absent;
7992   offset_expr.X_op = O_absent;
7993   offset_reloc[0] = BFD_RELOC_UNUSED;
7994   offset_reloc[1] = BFD_RELOC_UNUSED;
7995   offset_reloc[2] = BFD_RELOC_UNUSED;
7996
7997   create_insn (insn, opcode);
7998   /* When no opcode suffix is specified, assume ".xyzw". */
7999   if ((opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0 && opcode_extra == 0)
8000     insn->insn_opcode |= 0xf << mips_vu0_channel_mask.lsb;
8001   else
8002     insn->insn_opcode |= opcode_extra;
8003   memset (&arg, 0, sizeof (arg));
8004   arg.insn = insn;
8005   arg.token = tokens;
8006   arg.argnum = 1;
8007   arg.last_regno = ILLEGAL_REG;
8008   arg.dest_regno = ILLEGAL_REG;
8009   arg.lax_match = lax_match;
8010   for (args = opcode->args;; ++args)
8011     {
8012       if (arg.token->type == OT_END)
8013         {
8014           /* Handle unary instructions in which only one operand is given.
8015              The source is then the same as the destination.  */
8016           if (arg.opnum == 1 && *args == ',')
8017             {
8018               operand = (mips_opts.micromips
8019                          ? decode_micromips_operand (args + 1)
8020                          : decode_mips_operand (args + 1));
8021               if (operand && mips_optional_operand_p (operand))
8022                 {
8023                   arg.token = tokens;
8024                   arg.argnum = 1;
8025                   continue;
8026                 }
8027             }
8028
8029           /* Treat elided base registers as $0.  */
8030           if (strcmp (args, "(b)") == 0)
8031             args += 3;
8032
8033           if (args[0] == '+')
8034             switch (args[1])
8035               {
8036               case 'K':
8037               case 'N':
8038                 /* The register suffix is optional. */
8039                 args += 2;
8040                 break;
8041               }
8042
8043           /* Fail the match if there were too few operands.  */
8044           if (*args)
8045             return FALSE;
8046
8047           /* Successful match.  */
8048           if (!complete_p)
8049             return TRUE;
8050           clear_insn_error ();
8051           if (arg.dest_regno == arg.last_regno
8052               && strncmp (insn->insn_mo->name, "jalr", 4) == 0)
8053             {
8054               if (arg.opnum == 2)
8055                 set_insn_error
8056                   (0, _("source and destination must be different"));
8057               else if (arg.last_regno == 31)
8058                 set_insn_error
8059                   (0, _("a destination register must be supplied"));
8060             }
8061           else if (arg.last_regno == 31
8062                    && (strncmp (insn->insn_mo->name, "bltzal", 6) == 0
8063                        || strncmp (insn->insn_mo->name, "bgezal", 6) == 0))
8064             set_insn_error (0, _("the source register must not be $31"));
8065           check_completed_insn (&arg);
8066           return TRUE;
8067         }
8068
8069       /* Fail the match if the line has too many operands.   */
8070       if (*args == 0)
8071         return FALSE;
8072
8073       /* Handle characters that need to match exactly.  */
8074       if (*args == '(' || *args == ')' || *args == ',')
8075         {
8076           if (match_char (&arg, *args))
8077             continue;
8078           return FALSE;
8079         }
8080       if (*args == '#')
8081         {
8082           ++args;
8083           if (arg.token->type == OT_DOUBLE_CHAR
8084               && arg.token->u.ch == *args)
8085             {
8086               ++arg.token;
8087               continue;
8088             }
8089           return FALSE;
8090         }
8091
8092       /* Handle special macro operands.  Work out the properties of
8093          other operands.  */
8094       arg.opnum += 1;
8095       switch (*args)
8096         {
8097         case '-':
8098           switch (args[1])
8099             {
8100             case 'A':
8101               *offset_reloc = BFD_RELOC_MIPS_19_PCREL_S2;
8102               break;
8103
8104             case 'B':
8105               *offset_reloc = BFD_RELOC_MIPS_18_PCREL_S3;
8106               break;
8107             }
8108           break;
8109
8110         case '+':
8111           switch (args[1])
8112             {
8113             case 'i':
8114               *offset_reloc = BFD_RELOC_MIPS_JMP;
8115               break;
8116
8117             case '\'':
8118               *offset_reloc = BFD_RELOC_MIPS_26_PCREL_S2;
8119               break;
8120
8121             case '\"':
8122               *offset_reloc = BFD_RELOC_MIPS_21_PCREL_S2;
8123               break;
8124             }
8125           break;
8126
8127         case 'I':
8128           if (!match_const_int (&arg, &imm_expr.X_add_number))
8129             return FALSE;
8130           imm_expr.X_op = O_constant;
8131           if (GPR_SIZE == 32)
8132             normalize_constant_expr (&imm_expr);
8133           continue;
8134
8135         case 'A':
8136           if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
8137             {
8138               /* Assume that the offset has been elided and that what
8139                  we saw was a base register.  The match will fail later
8140                  if that assumption turns out to be wrong.  */
8141               offset_expr.X_op = O_constant;
8142               offset_expr.X_add_number = 0;
8143             }
8144           else
8145             {
8146               if (!match_expression (&arg, &offset_expr, offset_reloc))
8147                 return FALSE;
8148               normalize_address_expr (&offset_expr);
8149             }
8150           continue;
8151
8152         case 'F':
8153           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8154                                      8, TRUE))
8155             return FALSE;
8156           continue;
8157
8158         case 'L':
8159           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8160                                      8, FALSE))
8161             return FALSE;
8162           continue;
8163
8164         case 'f':
8165           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8166                                      4, TRUE))
8167             return FALSE;
8168           continue;
8169
8170         case 'l':
8171           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
8172                                      4, FALSE))
8173             return FALSE;
8174           continue;
8175
8176         case 'p':
8177           *offset_reloc = BFD_RELOC_16_PCREL_S2;
8178           break;
8179
8180         case 'a':
8181           *offset_reloc = BFD_RELOC_MIPS_JMP;
8182           break;
8183
8184         case 'm':
8185           gas_assert (mips_opts.micromips);
8186           c = args[1];
8187           switch (c)
8188             {
8189             case 'D':
8190             case 'E':
8191               if (!forced_insn_length)
8192                 *offset_reloc = (int) BFD_RELOC_UNUSED + c;
8193               else if (c == 'D')
8194                 *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
8195               else
8196                 *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
8197               break;
8198             }
8199           break;
8200         }
8201
8202       operand = (mips_opts.micromips
8203                  ? decode_micromips_operand (args)
8204                  : decode_mips_operand (args));
8205       if (!operand)
8206         abort ();
8207
8208       /* Skip prefixes.  */
8209       if (*args == '+' || *args == 'm' || *args == '-')
8210         args++;
8211
8212       if (mips_optional_operand_p (operand)
8213           && args[1] == ','
8214           && (arg.token[0].type != OT_REG
8215               || arg.token[1].type == OT_END))
8216         {
8217           /* Assume that the register has been elided and is the
8218              same as the first operand.  */
8219           arg.token = tokens;
8220           arg.argnum = 1;
8221         }
8222
8223       if (!match_operand (&arg, operand))
8224         return FALSE;
8225     }
8226 }
8227
8228 /* Like match_insn, but for MIPS16.  */
8229
8230 static bfd_boolean
8231 match_mips16_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
8232                    struct mips_operand_token *tokens)
8233 {
8234   const char *args;
8235   const struct mips_operand *operand;
8236   const struct mips_operand *ext_operand;
8237   bfd_boolean pcrel = FALSE;
8238   int required_insn_length;
8239   struct mips_arg_info arg;
8240   int relax_char;
8241
8242   if (forced_insn_length)
8243     required_insn_length = forced_insn_length;
8244   else if (mips_opts.noautoextend && !mips_opcode_32bit_p (opcode))
8245     required_insn_length = 2;
8246   else
8247     required_insn_length = 0;
8248
8249   create_insn (insn, opcode);
8250   imm_expr.X_op = O_absent;
8251   offset_expr.X_op = O_absent;
8252   offset_reloc[0] = BFD_RELOC_UNUSED;
8253   offset_reloc[1] = BFD_RELOC_UNUSED;
8254   offset_reloc[2] = BFD_RELOC_UNUSED;
8255   relax_char = 0;
8256
8257   memset (&arg, 0, sizeof (arg));
8258   arg.insn = insn;
8259   arg.token = tokens;
8260   arg.argnum = 1;
8261   arg.last_regno = ILLEGAL_REG;
8262   arg.dest_regno = ILLEGAL_REG;
8263   relax_char = 0;
8264   for (args = opcode->args;; ++args)
8265     {
8266       int c;
8267
8268       if (arg.token->type == OT_END)
8269         {
8270           offsetT value;
8271
8272           /* Handle unary instructions in which only one operand is given.
8273              The source is then the same as the destination.  */
8274           if (arg.opnum == 1 && *args == ',')
8275             {
8276               operand = decode_mips16_operand (args[1], FALSE);
8277               if (operand && mips_optional_operand_p (operand))
8278                 {
8279                   arg.token = tokens;
8280                   arg.argnum = 1;
8281                   continue;
8282                 }
8283             }
8284
8285           /* Fail the match if there were too few operands.  */
8286           if (*args)
8287             return FALSE;
8288
8289           /* Successful match.  Stuff the immediate value in now, if
8290              we can.  */
8291           clear_insn_error ();
8292           if (opcode->pinfo == INSN_MACRO)
8293             {
8294               gas_assert (relax_char == 0 || relax_char == 'p');
8295               gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
8296             }
8297           else if (relax_char
8298                    && offset_expr.X_op == O_constant
8299                    && !pcrel
8300                    && calculate_reloc (*offset_reloc,
8301                                        offset_expr.X_add_number,
8302                                        &value))
8303             {
8304               mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
8305                             required_insn_length, &insn->insn_opcode);
8306               offset_expr.X_op = O_absent;
8307               *offset_reloc = BFD_RELOC_UNUSED;
8308             }
8309           else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
8310             {
8311               if (required_insn_length == 2)
8312                 set_insn_error (0, _("invalid unextended operand value"));
8313               else if (!mips_opcode_32bit_p (opcode))
8314                 {
8315                   forced_insn_length = 4;
8316                   insn->insn_opcode |= MIPS16_EXTEND;
8317                 }
8318             }
8319           else if (relax_char)
8320             *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
8321
8322           check_completed_insn (&arg);
8323           return TRUE;
8324         }
8325
8326       /* Fail the match if the line has too many operands.   */
8327       if (*args == 0)
8328         return FALSE;
8329
8330       /* Handle characters that need to match exactly.  */
8331       if (*args == '(' || *args == ')' || *args == ',')
8332         {
8333           if (match_char (&arg, *args))
8334             continue;
8335           return FALSE;
8336         }
8337
8338       arg.opnum += 1;
8339       c = *args;
8340       switch (c)
8341         {
8342         case 'p':
8343         case 'q':
8344         case 'A':
8345         case 'B':
8346         case 'E':
8347         case 'V':
8348         case 'u':
8349           relax_char = c;
8350           break;
8351
8352         case 'I':
8353           if (!match_const_int (&arg, &imm_expr.X_add_number))
8354             return FALSE;
8355           imm_expr.X_op = O_constant;
8356           if (GPR_SIZE == 32)
8357             normalize_constant_expr (&imm_expr);
8358           continue;
8359
8360         case 'a':
8361         case 'i':
8362           *offset_reloc = BFD_RELOC_MIPS16_JMP;
8363           break;
8364         }
8365
8366       operand = decode_mips16_operand (c, mips_opcode_32bit_p (opcode));
8367       if (!operand)
8368         abort ();
8369
8370       if (operand->type == OP_PCREL)
8371         pcrel = TRUE;
8372       else
8373         {
8374           ext_operand = decode_mips16_operand (c, TRUE);
8375           if (operand != ext_operand)
8376             {
8377               if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
8378                 {
8379                   offset_expr.X_op = O_constant;
8380                   offset_expr.X_add_number = 0;
8381                   relax_char = c;
8382                   continue;
8383                 }
8384
8385               if (!match_expression (&arg, &offset_expr, offset_reloc))
8386                 return FALSE;
8387
8388               /* '8' is used for SLTI(U) and has traditionally not
8389                  been allowed to take relocation operators.  */
8390               if (offset_reloc[0] != BFD_RELOC_UNUSED
8391                   && (ext_operand->size != 16 || c == '8'))
8392                 {
8393                   match_not_constant (&arg);
8394                   return FALSE;
8395                 }
8396
8397               if (offset_expr.X_op == O_big)
8398                 {
8399                   match_out_of_range (&arg);
8400                   return FALSE;
8401                 }
8402
8403               relax_char = c;
8404               continue;
8405             }
8406         }
8407
8408       if (mips_optional_operand_p (operand)
8409           && args[1] == ','
8410           && (arg.token[0].type != OT_REG
8411               || arg.token[1].type == OT_END))
8412         {
8413           /* Assume that the register has been elided and is the
8414              same as the first operand.  */
8415           arg.token = tokens;
8416           arg.argnum = 1;
8417         }
8418
8419       if (!match_operand (&arg, operand))
8420         return FALSE;
8421     }
8422 }
8423
8424 /* Record that the current instruction is invalid for the current ISA.  */
8425
8426 static void
8427 match_invalid_for_isa (void)
8428 {
8429   set_insn_error_ss
8430     (0, _("opcode not supported on this processor: %s (%s)"),
8431      mips_cpu_info_from_arch (mips_opts.arch)->name,
8432      mips_cpu_info_from_isa (mips_opts.isa)->name);
8433 }
8434
8435 /* Try to match TOKENS against a series of opcode entries, starting at FIRST.
8436    Return true if a definite match or failure was found, storing any match
8437    in INSN.  OPCODE_EXTRA is a value that should be ORed into the opcode
8438    (to handle things like VU0 suffixes).  LAX_MATCH is true if we have already
8439    tried and failed to match under normal conditions and now want to try a
8440    more relaxed match.  */
8441
8442 static bfd_boolean
8443 match_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
8444              const struct mips_opcode *past, struct mips_operand_token *tokens,
8445              int opcode_extra, bfd_boolean lax_match)
8446 {
8447   const struct mips_opcode *opcode;
8448   const struct mips_opcode *invalid_delay_slot;
8449   bfd_boolean seen_valid_for_isa, seen_valid_for_size;
8450
8451   /* Search for a match, ignoring alternatives that don't satisfy the
8452      current ISA or forced_length.  */
8453   invalid_delay_slot = 0;
8454   seen_valid_for_isa = FALSE;
8455   seen_valid_for_size = FALSE;
8456   opcode = first;
8457   do
8458     {
8459       gas_assert (strcmp (opcode->name, first->name) == 0);
8460       if (is_opcode_valid (opcode))
8461         {
8462           seen_valid_for_isa = TRUE;
8463           if (is_size_valid (opcode))
8464             {
8465               bfd_boolean delay_slot_ok;
8466
8467               seen_valid_for_size = TRUE;
8468               delay_slot_ok = is_delay_slot_valid (opcode);
8469               if (match_insn (insn, opcode, tokens, opcode_extra,
8470                               lax_match, delay_slot_ok))
8471                 {
8472                   if (!delay_slot_ok)
8473                     {
8474                       if (!invalid_delay_slot)
8475                         invalid_delay_slot = opcode;
8476                     }
8477                   else
8478                     return TRUE;
8479                 }
8480             }
8481         }
8482       ++opcode;
8483     }
8484   while (opcode < past && strcmp (opcode->name, first->name) == 0);
8485
8486   /* If the only matches we found had the wrong length for the delay slot,
8487      pick the first such match.  We'll issue an appropriate warning later.  */
8488   if (invalid_delay_slot)
8489     {
8490       if (match_insn (insn, invalid_delay_slot, tokens, opcode_extra,
8491                       lax_match, TRUE))
8492         return TRUE;
8493       abort ();
8494     }
8495
8496   /* Handle the case where we didn't try to match an instruction because
8497      all the alternatives were incompatible with the current ISA.  */
8498   if (!seen_valid_for_isa)
8499     {
8500       match_invalid_for_isa ();
8501       return TRUE;
8502     }
8503
8504   /* Handle the case where we didn't try to match an instruction because
8505      all the alternatives were of the wrong size.  */
8506   if (!seen_valid_for_size)
8507     {
8508       if (mips_opts.insn32)
8509         set_insn_error (0, _("opcode not supported in the `insn32' mode"));
8510       else
8511         set_insn_error_i
8512           (0, _("unrecognized %d-bit version of microMIPS opcode"),
8513            8 * forced_insn_length);
8514       return TRUE;
8515     }
8516
8517   return FALSE;
8518 }
8519
8520 /* Like match_insns, but for MIPS16.  */
8521
8522 static bfd_boolean
8523 match_mips16_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
8524                     struct mips_operand_token *tokens)
8525 {
8526   const struct mips_opcode *opcode;
8527   bfd_boolean seen_valid_for_isa;
8528   bfd_boolean seen_valid_for_size;
8529
8530   /* Search for a match, ignoring alternatives that don't satisfy the
8531      current ISA.  There are no separate entries for extended forms so
8532      we deal with forced_length later.  */
8533   seen_valid_for_isa = FALSE;
8534   seen_valid_for_size = FALSE;
8535   opcode = first;
8536   do
8537     {
8538       gas_assert (strcmp (opcode->name, first->name) == 0);
8539       if (is_opcode_valid_16 (opcode))
8540         {
8541           seen_valid_for_isa = TRUE;
8542           if (is_size_valid_16 (opcode))
8543             {
8544               seen_valid_for_size = TRUE;
8545               if (match_mips16_insn (insn, opcode, tokens))
8546                 return TRUE;
8547             }
8548         }
8549       ++opcode;
8550     }
8551   while (opcode < &mips16_opcodes[bfd_mips16_num_opcodes]
8552          && strcmp (opcode->name, first->name) == 0);
8553
8554   /* Handle the case where we didn't try to match an instruction because
8555      all the alternatives were incompatible with the current ISA.  */
8556   if (!seen_valid_for_isa)
8557     {
8558       match_invalid_for_isa ();
8559       return TRUE;
8560     }
8561
8562   /* Handle the case where we didn't try to match an instruction because
8563      all the alternatives were of the wrong size.  */
8564   if (!seen_valid_for_size)
8565     {
8566       if (forced_insn_length == 2)
8567         set_insn_error
8568           (0, _("unrecognized unextended version of MIPS16 opcode"));
8569       else
8570         set_insn_error
8571           (0, _("unrecognized extended version of MIPS16 opcode"));
8572       return TRUE;
8573     }
8574
8575   return FALSE;
8576 }
8577
8578 /* Set up global variables for the start of a new macro.  */
8579
8580 static void
8581 macro_start (void)
8582 {
8583   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
8584   memset (&mips_macro_warning.first_insn_sizes, 0,
8585           sizeof (mips_macro_warning.first_insn_sizes));
8586   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
8587   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
8588                                      && delayed_branch_p (&history[0]));
8589   if (history[0].frag
8590       && history[0].frag->fr_type == rs_machine_dependent
8591       && RELAX_MICROMIPS_P (history[0].frag->fr_subtype)
8592       && RELAX_MICROMIPS_NODS (history[0].frag->fr_subtype))
8593     mips_macro_warning.delay_slot_length = 0;
8594   else
8595     switch (history[0].insn_mo->pinfo2
8596             & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
8597       {
8598       case INSN2_BRANCH_DELAY_32BIT:
8599         mips_macro_warning.delay_slot_length = 4;
8600         break;
8601       case INSN2_BRANCH_DELAY_16BIT:
8602         mips_macro_warning.delay_slot_length = 2;
8603         break;
8604       default:
8605         mips_macro_warning.delay_slot_length = 0;
8606         break;
8607       }
8608   mips_macro_warning.first_frag = NULL;
8609 }
8610
8611 /* Given that a macro is longer than one instruction or of the wrong size,
8612    return the appropriate warning for it.  Return null if no warning is
8613    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
8614    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
8615    and RELAX_NOMACRO.  */
8616
8617 static const char *
8618 macro_warning (relax_substateT subtype)
8619 {
8620   if (subtype & RELAX_DELAY_SLOT)
8621     return _("macro instruction expanded into multiple instructions"
8622              " in a branch delay slot");
8623   else if (subtype & RELAX_NOMACRO)
8624     return _("macro instruction expanded into multiple instructions");
8625   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
8626                       | RELAX_DELAY_SLOT_SIZE_SECOND))
8627     return ((subtype & RELAX_DELAY_SLOT_16BIT)
8628             ? _("macro instruction expanded into a wrong size instruction"
8629                 " in a 16-bit branch delay slot")
8630             : _("macro instruction expanded into a wrong size instruction"
8631                 " in a 32-bit branch delay slot"));
8632   else
8633     return 0;
8634 }
8635
8636 /* Finish up a macro.  Emit warnings as appropriate.  */
8637
8638 static void
8639 macro_end (void)
8640 {
8641   /* Relaxation warning flags.  */
8642   relax_substateT subtype = 0;
8643
8644   /* Check delay slot size requirements.  */
8645   if (mips_macro_warning.delay_slot_length == 2)
8646     subtype |= RELAX_DELAY_SLOT_16BIT;
8647   if (mips_macro_warning.delay_slot_length != 0)
8648     {
8649       if (mips_macro_warning.delay_slot_length
8650           != mips_macro_warning.first_insn_sizes[0])
8651         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
8652       if (mips_macro_warning.delay_slot_length
8653           != mips_macro_warning.first_insn_sizes[1])
8654         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
8655     }
8656
8657   /* Check instruction count requirements.  */
8658   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
8659     {
8660       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
8661         subtype |= RELAX_SECOND_LONGER;
8662       if (mips_opts.warn_about_macros)
8663         subtype |= RELAX_NOMACRO;
8664       if (mips_macro_warning.delay_slot_p)
8665         subtype |= RELAX_DELAY_SLOT;
8666     }
8667
8668   /* If both alternatives fail to fill a delay slot correctly,
8669      emit the warning now.  */
8670   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
8671       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
8672     {
8673       relax_substateT s;
8674       const char *msg;
8675
8676       s = subtype & (RELAX_DELAY_SLOT_16BIT
8677                      | RELAX_DELAY_SLOT_SIZE_FIRST
8678                      | RELAX_DELAY_SLOT_SIZE_SECOND);
8679       msg = macro_warning (s);
8680       if (msg != NULL)
8681         as_warn ("%s", msg);
8682       subtype &= ~s;
8683     }
8684
8685   /* If both implementations are longer than 1 instruction, then emit the
8686      warning now.  */
8687   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
8688     {
8689       relax_substateT s;
8690       const char *msg;
8691
8692       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
8693       msg = macro_warning (s);
8694       if (msg != NULL)
8695         as_warn ("%s", msg);
8696       subtype &= ~s;
8697     }
8698
8699   /* If any flags still set, then one implementation might need a warning
8700      and the other either will need one of a different kind or none at all.
8701      Pass any remaining flags over to relaxation.  */
8702   if (mips_macro_warning.first_frag != NULL)
8703     mips_macro_warning.first_frag->fr_subtype |= subtype;
8704 }
8705
8706 /* Instruction operand formats used in macros that vary between
8707    standard MIPS and microMIPS code.  */
8708
8709 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
8710 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
8711 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
8712 static const char * const lui_fmt[2] = { "t,u", "s,u" };
8713 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
8714 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
8715 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
8716 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
8717
8718 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
8719 #define COP12_FMT (ISA_IS_R6 (mips_opts.isa) ? "E,+:(d)" \
8720                                              : cop12_fmt[mips_opts.micromips])
8721 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
8722 #define LUI_FMT (lui_fmt[mips_opts.micromips])
8723 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
8724 #define LL_SC_FMT (ISA_IS_R6 (mips_opts.isa) ? "t,+j(b)" \
8725                                              : mem12_fmt[mips_opts.micromips])
8726 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
8727 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
8728 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
8729
8730 /* Read a macro's relocation codes from *ARGS and store them in *R.
8731    The first argument in *ARGS will be either the code for a single
8732    relocation or -1 followed by the three codes that make up a
8733    composite relocation.  */
8734
8735 static void
8736 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
8737 {
8738   int i, next;
8739
8740   next = va_arg (*args, int);
8741   if (next >= 0)
8742     r[0] = (bfd_reloc_code_real_type) next;
8743   else
8744     {
8745       for (i = 0; i < 3; i++)
8746         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
8747       /* This function is only used for 16-bit relocation fields.
8748          To make the macro code simpler, treat an unrelocated value
8749          in the same way as BFD_RELOC_LO16.  */
8750       if (r[0] == BFD_RELOC_UNUSED)
8751         r[0] = BFD_RELOC_LO16;
8752     }
8753 }
8754
8755 /* Build an instruction created by a macro expansion.  This is passed
8756    a pointer to the count of instructions created so far, an
8757    expression, the name of the instruction to build, an operand format
8758    string, and corresponding arguments.  */
8759
8760 static void
8761 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
8762 {
8763   const struct mips_opcode *mo = NULL;
8764   bfd_reloc_code_real_type r[3];
8765   const struct mips_opcode *amo;
8766   const struct mips_operand *operand;
8767   struct hash_control *hash;
8768   struct mips_cl_insn insn;
8769   va_list args;
8770   unsigned int uval;
8771
8772   va_start (args, fmt);
8773
8774   if (mips_opts.mips16)
8775     {
8776       mips16_macro_build (ep, name, fmt, &args);
8777       va_end (args);
8778       return;
8779     }
8780
8781   r[0] = BFD_RELOC_UNUSED;
8782   r[1] = BFD_RELOC_UNUSED;
8783   r[2] = BFD_RELOC_UNUSED;
8784   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
8785   amo = (struct mips_opcode *) hash_find (hash, name);
8786   gas_assert (amo);
8787   gas_assert (strcmp (name, amo->name) == 0);
8788
8789   do
8790     {
8791       /* Search until we get a match for NAME.  It is assumed here that
8792          macros will never generate MDMX, MIPS-3D, or MT instructions.
8793          We try to match an instruction that fulfills the branch delay
8794          slot instruction length requirement (if any) of the previous
8795          instruction.  While doing this we record the first instruction
8796          seen that matches all the other conditions and use it anyway
8797          if the requirement cannot be met; we will issue an appropriate
8798          warning later on.  */
8799       if (strcmp (fmt, amo->args) == 0
8800           && amo->pinfo != INSN_MACRO
8801           && is_opcode_valid (amo)
8802           && is_size_valid (amo))
8803         {
8804           if (is_delay_slot_valid (amo))
8805             {
8806               mo = amo;
8807               break;
8808             }
8809           else if (!mo)
8810             mo = amo;
8811         }
8812
8813       ++amo;
8814       gas_assert (amo->name);
8815     }
8816   while (strcmp (name, amo->name) == 0);
8817
8818   gas_assert (mo);
8819   create_insn (&insn, mo);
8820   for (; *fmt; ++fmt)
8821     {
8822       switch (*fmt)
8823         {
8824         case ',':
8825         case '(':
8826         case ')':
8827         case 'z':
8828           break;
8829
8830         case 'i':
8831         case 'j':
8832           macro_read_relocs (&args, r);
8833           gas_assert (*r == BFD_RELOC_GPREL16
8834                       || *r == BFD_RELOC_MIPS_HIGHER
8835                       || *r == BFD_RELOC_HI16_S
8836                       || *r == BFD_RELOC_LO16
8837                       || *r == BFD_RELOC_MIPS_GOT_OFST);
8838           break;
8839
8840         case 'o':
8841           macro_read_relocs (&args, r);
8842           break;
8843
8844         case 'u':
8845           macro_read_relocs (&args, r);
8846           gas_assert (ep != NULL
8847                       && (ep->X_op == O_constant
8848                           || (ep->X_op == O_symbol
8849                               && (*r == BFD_RELOC_MIPS_HIGHEST
8850                                   || *r == BFD_RELOC_HI16_S
8851                                   || *r == BFD_RELOC_HI16
8852                                   || *r == BFD_RELOC_GPREL16
8853                                   || *r == BFD_RELOC_MIPS_GOT_HI16
8854                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
8855           break;
8856
8857         case 'p':
8858           gas_assert (ep != NULL);
8859
8860           /*
8861            * This allows macro() to pass an immediate expression for
8862            * creating short branches without creating a symbol.
8863            *
8864            * We don't allow branch relaxation for these branches, as
8865            * they should only appear in ".set nomacro" anyway.
8866            */
8867           if (ep->X_op == O_constant)
8868             {
8869               /* For microMIPS we always use relocations for branches.
8870                  So we should not resolve immediate values.  */
8871               gas_assert (!mips_opts.micromips);
8872
8873               if ((ep->X_add_number & 3) != 0)
8874                 as_bad (_("branch to misaligned address (0x%lx)"),
8875                         (unsigned long) ep->X_add_number);
8876               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
8877                 as_bad (_("branch address range overflow (0x%lx)"),
8878                         (unsigned long) ep->X_add_number);
8879               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
8880               ep = NULL;
8881             }
8882           else
8883             *r = BFD_RELOC_16_PCREL_S2;
8884           break;
8885
8886         case 'a':
8887           gas_assert (ep != NULL);
8888           *r = BFD_RELOC_MIPS_JMP;
8889           break;
8890
8891         default:
8892           operand = (mips_opts.micromips
8893                      ? decode_micromips_operand (fmt)
8894                      : decode_mips_operand (fmt));
8895           if (!operand)
8896             abort ();
8897
8898           uval = va_arg (args, int);
8899           if (operand->type == OP_CLO_CLZ_DEST)
8900             uval |= (uval << 5);
8901           insn_insert_operand (&insn, operand, uval);
8902
8903           if (*fmt == '+' || *fmt == 'm' || *fmt == '-')
8904             ++fmt;
8905           break;
8906         }
8907     }
8908   va_end (args);
8909   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
8910
8911   append_insn (&insn, ep, r, TRUE);
8912 }
8913
8914 static void
8915 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
8916                     va_list *args)
8917 {
8918   struct mips_opcode *mo;
8919   struct mips_cl_insn insn;
8920   const struct mips_operand *operand;
8921   bfd_reloc_code_real_type r[3]
8922     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
8923
8924   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
8925   gas_assert (mo);
8926   gas_assert (strcmp (name, mo->name) == 0);
8927
8928   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
8929     {
8930       ++mo;
8931       gas_assert (mo->name);
8932       gas_assert (strcmp (name, mo->name) == 0);
8933     }
8934
8935   create_insn (&insn, mo);
8936   for (; *fmt; ++fmt)
8937     {
8938       int c;
8939
8940       c = *fmt;
8941       switch (c)
8942         {
8943         case ',':
8944         case '(':
8945         case ')':
8946           break;
8947
8948         case '.':
8949         case 'S':
8950         case 'P':
8951         case 'R':
8952           break;
8953
8954         case '<':
8955         case '5':
8956         case 'F':
8957         case 'H':
8958         case 'W':
8959         case 'D':
8960         case 'j':
8961         case '8':
8962         case 'V':
8963         case 'C':
8964         case 'U':
8965         case 'k':
8966         case 'K':
8967         case 'p':
8968         case 'q':
8969           {
8970             offsetT value;
8971
8972             gas_assert (ep != NULL);
8973
8974             if (ep->X_op != O_constant)
8975               *r = (int) BFD_RELOC_UNUSED + c;
8976             else if (calculate_reloc (*r, ep->X_add_number, &value))
8977               {
8978                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
8979                 ep = NULL;
8980                 *r = BFD_RELOC_UNUSED;
8981               }
8982           }
8983           break;
8984
8985         default:
8986           operand = decode_mips16_operand (c, FALSE);
8987           if (!operand)
8988             abort ();
8989
8990           insn_insert_operand (&insn, operand, va_arg (*args, int));
8991           break;
8992         }
8993     }
8994
8995   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
8996
8997   append_insn (&insn, ep, r, TRUE);
8998 }
8999
9000 /*
9001  * Generate a "jalr" instruction with a relocation hint to the called
9002  * function.  This occurs in NewABI PIC code.
9003  */
9004 static void
9005 macro_build_jalr (expressionS *ep, int cprestore)
9006 {
9007   static const bfd_reloc_code_real_type jalr_relocs[2]
9008     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
9009   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
9010   const char *jalr;
9011   char *f = NULL;
9012
9013   if (MIPS_JALR_HINT_P (ep))
9014     {
9015       frag_grow (8);
9016       f = frag_more (0);
9017     }
9018   if (mips_opts.micromips)
9019     {
9020       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
9021               ? "jalr" : "jalrs");
9022       if (MIPS_JALR_HINT_P (ep)
9023           || mips_opts.insn32
9024           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
9025         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
9026       else
9027         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
9028     }
9029   else
9030     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
9031   if (MIPS_JALR_HINT_P (ep))
9032     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
9033 }
9034
9035 /*
9036  * Generate a "lui" instruction.
9037  */
9038 static void
9039 macro_build_lui (expressionS *ep, int regnum)
9040 {
9041   gas_assert (! mips_opts.mips16);
9042
9043   if (ep->X_op != O_constant)
9044     {
9045       gas_assert (ep->X_op == O_symbol);
9046       /* _gp_disp is a special case, used from s_cpload.
9047          __gnu_local_gp is used if mips_no_shared.  */
9048       gas_assert (mips_pic == NO_PIC
9049               || (! HAVE_NEWABI
9050                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
9051               || (! mips_in_shared
9052                   && strcmp (S_GET_NAME (ep->X_add_symbol),
9053                              "__gnu_local_gp") == 0));
9054     }
9055
9056   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
9057 }
9058
9059 /* Generate a sequence of instructions to do a load or store from a constant
9060    offset off of a base register (breg) into/from a target register (treg),
9061    using AT if necessary.  */
9062 static void
9063 macro_build_ldst_constoffset (expressionS *ep, const char *op,
9064                               int treg, int breg, int dbl)
9065 {
9066   gas_assert (ep->X_op == O_constant);
9067
9068   /* Sign-extending 32-bit constants makes their handling easier.  */
9069   if (!dbl)
9070     normalize_constant_expr (ep);
9071
9072   /* Right now, this routine can only handle signed 32-bit constants.  */
9073   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
9074     as_warn (_("operand overflow"));
9075
9076   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
9077     {
9078       /* Signed 16-bit offset will fit in the op.  Easy!  */
9079       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
9080     }
9081   else
9082     {
9083       /* 32-bit offset, need multiple instructions and AT, like:
9084            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
9085            addu     $tempreg,$tempreg,$breg
9086            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
9087          to handle the complete offset.  */
9088       macro_build_lui (ep, AT);
9089       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
9090       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
9091
9092       if (!mips_opts.at)
9093         as_bad (_("macro used $at after \".set noat\""));
9094     }
9095 }
9096
9097 /*                      set_at()
9098  * Generates code to set the $at register to true (one)
9099  * if reg is less than the immediate expression.
9100  */
9101 static void
9102 set_at (int reg, int unsignedp)
9103 {
9104   if (imm_expr.X_add_number >= -0x8000
9105       && imm_expr.X_add_number < 0x8000)
9106     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
9107                  AT, reg, BFD_RELOC_LO16);
9108   else
9109     {
9110       load_register (AT, &imm_expr, GPR_SIZE == 64);
9111       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
9112     }
9113 }
9114
9115 /* Count the leading zeroes by performing a binary chop. This is a
9116    bulky bit of source, but performance is a LOT better for the
9117    majority of values than a simple loop to count the bits:
9118        for (lcnt = 0; (lcnt < 32); lcnt++)
9119          if ((v) & (1 << (31 - lcnt)))
9120            break;
9121   However it is not code size friendly, and the gain will drop a bit
9122   on certain cached systems.
9123 */
9124 #define COUNT_TOP_ZEROES(v)             \
9125   (((v) & ~0xffff) == 0                 \
9126    ? ((v) & ~0xff) == 0                 \
9127      ? ((v) & ~0xf) == 0                \
9128        ? ((v) & ~0x3) == 0              \
9129          ? ((v) & ~0x1) == 0            \
9130            ? !(v)                       \
9131              ? 32                       \
9132              : 31                       \
9133            : 30                         \
9134          : ((v) & ~0x7) == 0            \
9135            ? 29                         \
9136            : 28                         \
9137        : ((v) & ~0x3f) == 0             \
9138          ? ((v) & ~0x1f) == 0           \
9139            ? 27                         \
9140            : 26                         \
9141          : ((v) & ~0x7f) == 0           \
9142            ? 25                         \
9143            : 24                         \
9144      : ((v) & ~0xfff) == 0              \
9145        ? ((v) & ~0x3ff) == 0            \
9146          ? ((v) & ~0x1ff) == 0          \
9147            ? 23                         \
9148            : 22                         \
9149          : ((v) & ~0x7ff) == 0          \
9150            ? 21                         \
9151            : 20                         \
9152        : ((v) & ~0x3fff) == 0           \
9153          ? ((v) & ~0x1fff) == 0         \
9154            ? 19                         \
9155            : 18                         \
9156          : ((v) & ~0x7fff) == 0         \
9157            ? 17                         \
9158            : 16                         \
9159    : ((v) & ~0xffffff) == 0             \
9160      ? ((v) & ~0xfffff) == 0            \
9161        ? ((v) & ~0x3ffff) == 0          \
9162          ? ((v) & ~0x1ffff) == 0        \
9163            ? 15                         \
9164            : 14                         \
9165          : ((v) & ~0x7ffff) == 0        \
9166            ? 13                         \
9167            : 12                         \
9168        : ((v) & ~0x3fffff) == 0         \
9169          ? ((v) & ~0x1fffff) == 0       \
9170            ? 11                         \
9171            : 10                         \
9172          : ((v) & ~0x7fffff) == 0       \
9173            ? 9                          \
9174            : 8                          \
9175      : ((v) & ~0xfffffff) == 0          \
9176        ? ((v) & ~0x3ffffff) == 0        \
9177          ? ((v) & ~0x1ffffff) == 0      \
9178            ? 7                          \
9179            : 6                          \
9180          : ((v) & ~0x7ffffff) == 0      \
9181            ? 5                          \
9182            : 4                          \
9183        : ((v) & ~0x3fffffff) == 0       \
9184          ? ((v) & ~0x1fffffff) == 0     \
9185            ? 3                          \
9186            : 2                          \
9187          : ((v) & ~0x7fffffff) == 0     \
9188            ? 1                          \
9189            : 0)
9190
9191 /*                      load_register()
9192  *  This routine generates the least number of instructions necessary to load
9193  *  an absolute expression value into a register.
9194  */
9195 static void
9196 load_register (int reg, expressionS *ep, int dbl)
9197 {
9198   int freg;
9199   expressionS hi32, lo32;
9200
9201   if (ep->X_op != O_big)
9202     {
9203       gas_assert (ep->X_op == O_constant);
9204
9205       /* Sign-extending 32-bit constants makes their handling easier.  */
9206       if (!dbl)
9207         normalize_constant_expr (ep);
9208
9209       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
9210         {
9211           /* We can handle 16 bit signed values with an addiu to
9212              $zero.  No need to ever use daddiu here, since $zero and
9213              the result are always correct in 32 bit mode.  */
9214           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9215           return;
9216         }
9217       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
9218         {
9219           /* We can handle 16 bit unsigned values with an ori to
9220              $zero.  */
9221           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
9222           return;
9223         }
9224       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
9225         {
9226           /* 32 bit values require an lui.  */
9227           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
9228           if ((ep->X_add_number & 0xffff) != 0)
9229             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
9230           return;
9231         }
9232     }
9233
9234   /* The value is larger than 32 bits.  */
9235
9236   if (!dbl || GPR_SIZE == 32)
9237     {
9238       char value[32];
9239
9240       sprintf_vma (value, ep->X_add_number);
9241       as_bad (_("number (0x%s) larger than 32 bits"), value);
9242       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9243       return;
9244     }
9245
9246   if (ep->X_op != O_big)
9247     {
9248       hi32 = *ep;
9249       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
9250       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
9251       hi32.X_add_number &= 0xffffffff;
9252       lo32 = *ep;
9253       lo32.X_add_number &= 0xffffffff;
9254     }
9255   else
9256     {
9257       gas_assert (ep->X_add_number > 2);
9258       if (ep->X_add_number == 3)
9259         generic_bignum[3] = 0;
9260       else if (ep->X_add_number > 4)
9261         as_bad (_("number larger than 64 bits"));
9262       lo32.X_op = O_constant;
9263       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
9264       hi32.X_op = O_constant;
9265       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
9266     }
9267
9268   if (hi32.X_add_number == 0)
9269     freg = 0;
9270   else
9271     {
9272       int shift, bit;
9273       unsigned long hi, lo;
9274
9275       if (hi32.X_add_number == (offsetT) 0xffffffff)
9276         {
9277           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
9278             {
9279               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9280               return;
9281             }
9282           if (lo32.X_add_number & 0x80000000)
9283             {
9284               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
9285               if (lo32.X_add_number & 0xffff)
9286                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
9287               return;
9288             }
9289         }
9290
9291       /* Check for 16bit shifted constant.  We know that hi32 is
9292          non-zero, so start the mask on the first bit of the hi32
9293          value.  */
9294       shift = 17;
9295       do
9296         {
9297           unsigned long himask, lomask;
9298
9299           if (shift < 32)
9300             {
9301               himask = 0xffff >> (32 - shift);
9302               lomask = (0xffff << shift) & 0xffffffff;
9303             }
9304           else
9305             {
9306               himask = 0xffff << (shift - 32);
9307               lomask = 0;
9308             }
9309           if ((hi32.X_add_number & ~(offsetT) himask) == 0
9310               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
9311             {
9312               expressionS tmp;
9313
9314               tmp.X_op = O_constant;
9315               if (shift < 32)
9316                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
9317                                     | (lo32.X_add_number >> shift));
9318               else
9319                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
9320               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
9321               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
9322                            reg, reg, (shift >= 32) ? shift - 32 : shift);
9323               return;
9324             }
9325           ++shift;
9326         }
9327       while (shift <= (64 - 16));
9328
9329       /* Find the bit number of the lowest one bit, and store the
9330          shifted value in hi/lo.  */
9331       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
9332       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
9333       if (lo != 0)
9334         {
9335           bit = 0;
9336           while ((lo & 1) == 0)
9337             {
9338               lo >>= 1;
9339               ++bit;
9340             }
9341           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
9342           hi >>= bit;
9343         }
9344       else
9345         {
9346           bit = 32;
9347           while ((hi & 1) == 0)
9348             {
9349               hi >>= 1;
9350               ++bit;
9351             }
9352           lo = hi;
9353           hi = 0;
9354         }
9355
9356       /* Optimize if the shifted value is a (power of 2) - 1.  */
9357       if ((hi == 0 && ((lo + 1) & lo) == 0)
9358           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
9359         {
9360           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
9361           if (shift != 0)
9362             {
9363               expressionS tmp;
9364
9365               /* This instruction will set the register to be all
9366                  ones.  */
9367               tmp.X_op = O_constant;
9368               tmp.X_add_number = (offsetT) -1;
9369               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9370               if (bit != 0)
9371                 {
9372                   bit += shift;
9373                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
9374                                reg, reg, (bit >= 32) ? bit - 32 : bit);
9375                 }
9376               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
9377                            reg, reg, (shift >= 32) ? shift - 32 : shift);
9378               return;
9379             }
9380         }
9381
9382       /* Sign extend hi32 before calling load_register, because we can
9383          generally get better code when we load a sign extended value.  */
9384       if ((hi32.X_add_number & 0x80000000) != 0)
9385         hi32.X_add_number |= ~(offsetT) 0xffffffff;
9386       load_register (reg, &hi32, 0);
9387       freg = reg;
9388     }
9389   if ((lo32.X_add_number & 0xffff0000) == 0)
9390     {
9391       if (freg != 0)
9392         {
9393           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
9394           freg = reg;
9395         }
9396     }
9397   else
9398     {
9399       expressionS mid16;
9400
9401       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
9402         {
9403           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
9404           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
9405           return;
9406         }
9407
9408       if (freg != 0)
9409         {
9410           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
9411           freg = reg;
9412         }
9413       mid16 = lo32;
9414       mid16.X_add_number >>= 16;
9415       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
9416       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9417       freg = reg;
9418     }
9419   if ((lo32.X_add_number & 0xffff) != 0)
9420     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
9421 }
9422
9423 static inline void
9424 load_delay_nop (void)
9425 {
9426   if (!gpr_interlocks)
9427     macro_build (NULL, "nop", "");
9428 }
9429
9430 /* Load an address into a register.  */
9431
9432 static void
9433 load_address (int reg, expressionS *ep, int *used_at)
9434 {
9435   if (ep->X_op != O_constant
9436       && ep->X_op != O_symbol)
9437     {
9438       as_bad (_("expression too complex"));
9439       ep->X_op = O_constant;
9440     }
9441
9442   if (ep->X_op == O_constant)
9443     {
9444       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
9445       return;
9446     }
9447
9448   if (mips_pic == NO_PIC)
9449     {
9450       /* If this is a reference to a GP relative symbol, we want
9451            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
9452          Otherwise we want
9453            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
9454            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
9455          If we have an addend, we always use the latter form.
9456
9457          With 64bit address space and a usable $at we want
9458            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
9459            lui          $at,<sym>               (BFD_RELOC_HI16_S)
9460            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
9461            daddiu       $at,<sym>               (BFD_RELOC_LO16)
9462            dsll32       $reg,0
9463            daddu        $reg,$reg,$at
9464
9465          If $at is already in use, we use a path which is suboptimal
9466          on superscalar processors.
9467            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
9468            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
9469            dsll         $reg,16
9470            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
9471            dsll         $reg,16
9472            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
9473
9474          For GP relative symbols in 64bit address space we can use
9475          the same sequence as in 32bit address space.  */
9476       if (HAVE_64BIT_SYMBOLS)
9477         {
9478           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
9479               && !nopic_need_relax (ep->X_add_symbol, 1))
9480             {
9481               relax_start (ep->X_add_symbol);
9482               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
9483                            mips_gp_register, BFD_RELOC_GPREL16);
9484               relax_switch ();
9485             }
9486
9487           if (*used_at == 0 && mips_opts.at)
9488             {
9489               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
9490               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
9491               macro_build (ep, "daddiu", "t,r,j", reg, reg,
9492                            BFD_RELOC_MIPS_HIGHER);
9493               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
9494               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
9495               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
9496               *used_at = 1;
9497             }
9498           else
9499             {
9500               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
9501               macro_build (ep, "daddiu", "t,r,j", reg, reg,
9502                            BFD_RELOC_MIPS_HIGHER);
9503               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9504               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
9505               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9506               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
9507             }
9508
9509           if (mips_relax.sequence)
9510             relax_end ();
9511         }
9512       else
9513         {
9514           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
9515               && !nopic_need_relax (ep->X_add_symbol, 1))
9516             {
9517               relax_start (ep->X_add_symbol);
9518               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
9519                            mips_gp_register, BFD_RELOC_GPREL16);
9520               relax_switch ();
9521             }
9522           macro_build_lui (ep, reg);
9523           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
9524                        reg, reg, BFD_RELOC_LO16);
9525           if (mips_relax.sequence)
9526             relax_end ();
9527         }
9528     }
9529   else if (!mips_big_got)
9530     {
9531       expressionS ex;
9532
9533       /* If this is a reference to an external symbol, we want
9534            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
9535          Otherwise we want
9536            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
9537            nop
9538            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
9539          If there is a constant, it must be added in after.
9540
9541          If we have NewABI, we want
9542            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
9543          unless we're referencing a global symbol with a non-zero
9544          offset, in which case cst must be added separately.  */
9545       if (HAVE_NEWABI)
9546         {
9547           if (ep->X_add_number)
9548             {
9549               ex.X_add_number = ep->X_add_number;
9550               ep->X_add_number = 0;
9551               relax_start (ep->X_add_symbol);
9552               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9553                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9554               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9555                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9556               ex.X_op = O_constant;
9557               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
9558                            reg, reg, BFD_RELOC_LO16);
9559               ep->X_add_number = ex.X_add_number;
9560               relax_switch ();
9561             }
9562           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9563                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9564           if (mips_relax.sequence)
9565             relax_end ();
9566         }
9567       else
9568         {
9569           ex.X_add_number = ep->X_add_number;
9570           ep->X_add_number = 0;
9571           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9572                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9573           load_delay_nop ();
9574           relax_start (ep->X_add_symbol);
9575           relax_switch ();
9576           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9577                        BFD_RELOC_LO16);
9578           relax_end ();
9579
9580           if (ex.X_add_number != 0)
9581             {
9582               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9583                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9584               ex.X_op = O_constant;
9585               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
9586                            reg, reg, BFD_RELOC_LO16);
9587             }
9588         }
9589     }
9590   else if (mips_big_got)
9591     {
9592       expressionS ex;
9593
9594       /* This is the large GOT case.  If this is a reference to an
9595          external symbol, we want
9596            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
9597            addu         $reg,$reg,$gp
9598            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
9599
9600          Otherwise, for a reference to a local symbol in old ABI, we want
9601            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
9602            nop
9603            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
9604          If there is a constant, it must be added in after.
9605
9606          In the NewABI, for local symbols, with or without offsets, we want:
9607            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
9608            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
9609       */
9610       if (HAVE_NEWABI)
9611         {
9612           ex.X_add_number = ep->X_add_number;
9613           ep->X_add_number = 0;
9614           relax_start (ep->X_add_symbol);
9615           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
9616           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9617                        reg, reg, mips_gp_register);
9618           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
9619                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
9620           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9621             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9622           else if (ex.X_add_number)
9623             {
9624               ex.X_op = O_constant;
9625               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9626                            BFD_RELOC_LO16);
9627             }
9628
9629           ep->X_add_number = ex.X_add_number;
9630           relax_switch ();
9631           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9632                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9633           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9634                        BFD_RELOC_MIPS_GOT_OFST);
9635           relax_end ();
9636         }
9637       else
9638         {
9639           ex.X_add_number = ep->X_add_number;
9640           ep->X_add_number = 0;
9641           relax_start (ep->X_add_symbol);
9642           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
9643           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9644                        reg, reg, mips_gp_register);
9645           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
9646                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
9647           relax_switch ();
9648           if (reg_needs_delay (mips_gp_register))
9649             {
9650               /* We need a nop before loading from $gp.  This special
9651                  check is required because the lui which starts the main
9652                  instruction stream does not refer to $gp, and so will not
9653                  insert the nop which may be required.  */
9654               macro_build (NULL, "nop", "");
9655             }
9656           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9657                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9658           load_delay_nop ();
9659           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9660                        BFD_RELOC_LO16);
9661           relax_end ();
9662
9663           if (ex.X_add_number != 0)
9664             {
9665               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9666                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9667               ex.X_op = O_constant;
9668               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9669                            BFD_RELOC_LO16);
9670             }
9671         }
9672     }
9673   else
9674     abort ();
9675
9676   if (!mips_opts.at && *used_at == 1)
9677     as_bad (_("macro used $at after \".set noat\""));
9678 }
9679
9680 /* Move the contents of register SOURCE into register DEST.  */
9681
9682 static void
9683 move_register (int dest, int source)
9684 {
9685   /* Prefer to use a 16-bit microMIPS instruction unless the previous
9686      instruction specifically requires a 32-bit one.  */
9687   if (mips_opts.micromips
9688       && !mips_opts.insn32
9689       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
9690     macro_build (NULL, "move", "mp,mj", dest, source);
9691   else
9692     macro_build (NULL, "or", "d,v,t", dest, source, 0);
9693 }
9694
9695 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
9696    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
9697    The two alternatives are:
9698
9699    Global symbol                Local symbol
9700    -------------                ------------
9701    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
9702    ...                          ...
9703    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
9704
9705    load_got_offset emits the first instruction and add_got_offset
9706    emits the second for a 16-bit offset or add_got_offset_hilo emits
9707    a sequence to add a 32-bit offset using a scratch register.  */
9708
9709 static void
9710 load_got_offset (int dest, expressionS *local)
9711 {
9712   expressionS global;
9713
9714   global = *local;
9715   global.X_add_number = 0;
9716
9717   relax_start (local->X_add_symbol);
9718   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
9719                BFD_RELOC_MIPS_GOT16, mips_gp_register);
9720   relax_switch ();
9721   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
9722                BFD_RELOC_MIPS_GOT16, mips_gp_register);
9723   relax_end ();
9724 }
9725
9726 static void
9727 add_got_offset (int dest, expressionS *local)
9728 {
9729   expressionS global;
9730
9731   global.X_op = O_constant;
9732   global.X_op_symbol = NULL;
9733   global.X_add_symbol = NULL;
9734   global.X_add_number = local->X_add_number;
9735
9736   relax_start (local->X_add_symbol);
9737   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
9738                dest, dest, BFD_RELOC_LO16);
9739   relax_switch ();
9740   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
9741   relax_end ();
9742 }
9743
9744 static void
9745 add_got_offset_hilo (int dest, expressionS *local, int tmp)
9746 {
9747   expressionS global;
9748   int hold_mips_optimize;
9749
9750   global.X_op = O_constant;
9751   global.X_op_symbol = NULL;
9752   global.X_add_symbol = NULL;
9753   global.X_add_number = local->X_add_number;
9754
9755   relax_start (local->X_add_symbol);
9756   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
9757   relax_switch ();
9758   /* Set mips_optimize around the lui instruction to avoid
9759      inserting an unnecessary nop after the lw.  */
9760   hold_mips_optimize = mips_optimize;
9761   mips_optimize = 2;
9762   macro_build_lui (&global, tmp);
9763   mips_optimize = hold_mips_optimize;
9764   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
9765   relax_end ();
9766
9767   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
9768 }
9769
9770 /* Emit a sequence of instructions to emulate a branch likely operation.
9771    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
9772    is its complementing branch with the original condition negated.
9773    CALL is set if the original branch specified the link operation.
9774    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
9775
9776    Code like this is produced in the noreorder mode:
9777
9778         BRNEG   <args>, 1f
9779          nop
9780         b       <sym>
9781          delay slot (executed only if branch taken)
9782     1:
9783
9784    or, if CALL is set:
9785
9786         BRNEG   <args>, 1f
9787          nop
9788         bal     <sym>
9789          delay slot (executed only if branch taken)
9790     1:
9791
9792    In the reorder mode the delay slot would be filled with a nop anyway,
9793    so code produced is simply:
9794
9795         BR      <args>, <sym>
9796          nop
9797
9798    This function is used when producing code for the microMIPS ASE that
9799    does not implement branch likely instructions in hardware.  */
9800
9801 static void
9802 macro_build_branch_likely (const char *br, const char *brneg,
9803                            int call, expressionS *ep, const char *fmt,
9804                            unsigned int sreg, unsigned int treg)
9805 {
9806   int noreorder = mips_opts.noreorder;
9807   expressionS expr1;
9808
9809   gas_assert (mips_opts.micromips);
9810   start_noreorder ();
9811   if (noreorder)
9812     {
9813       micromips_label_expr (&expr1);
9814       macro_build (&expr1, brneg, fmt, sreg, treg);
9815       macro_build (NULL, "nop", "");
9816       macro_build (ep, call ? "bal" : "b", "p");
9817
9818       /* Set to true so that append_insn adds a label.  */
9819       emit_branch_likely_macro = TRUE;
9820     }
9821   else
9822     {
9823       macro_build (ep, br, fmt, sreg, treg);
9824       macro_build (NULL, "nop", "");
9825     }
9826   end_noreorder ();
9827 }
9828
9829 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
9830    the condition code tested.  EP specifies the branch target.  */
9831
9832 static void
9833 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
9834 {
9835   const int call = 0;
9836   const char *brneg;
9837   const char *br;
9838
9839   switch (type)
9840     {
9841     case M_BC1FL:
9842       br = "bc1f";
9843       brneg = "bc1t";
9844       break;
9845     case M_BC1TL:
9846       br = "bc1t";
9847       brneg = "bc1f";
9848       break;
9849     case M_BC2FL:
9850       br = "bc2f";
9851       brneg = "bc2t";
9852       break;
9853     case M_BC2TL:
9854       br = "bc2t";
9855       brneg = "bc2f";
9856       break;
9857     default:
9858       abort ();
9859     }
9860   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
9861 }
9862
9863 /* Emit a two-argument branch macro specified by TYPE, using SREG as
9864    the register tested.  EP specifies the branch target.  */
9865
9866 static void
9867 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
9868 {
9869   const char *brneg = NULL;
9870   const char *br;
9871   int call = 0;
9872
9873   switch (type)
9874     {
9875     case M_BGEZ:
9876       br = "bgez";
9877       break;
9878     case M_BGEZL:
9879       br = mips_opts.micromips ? "bgez" : "bgezl";
9880       brneg = "bltz";
9881       break;
9882     case M_BGEZALL:
9883       gas_assert (mips_opts.micromips);
9884       br = mips_opts.insn32 ? "bgezal" : "bgezals";
9885       brneg = "bltz";
9886       call = 1;
9887       break;
9888     case M_BGTZ:
9889       br = "bgtz";
9890       break;
9891     case M_BGTZL:
9892       br = mips_opts.micromips ? "bgtz" : "bgtzl";
9893       brneg = "blez";
9894       break;
9895     case M_BLEZ:
9896       br = "blez";
9897       break;
9898     case M_BLEZL:
9899       br = mips_opts.micromips ? "blez" : "blezl";
9900       brneg = "bgtz";
9901       break;
9902     case M_BLTZ:
9903       br = "bltz";
9904       break;
9905     case M_BLTZL:
9906       br = mips_opts.micromips ? "bltz" : "bltzl";
9907       brneg = "bgez";
9908       break;
9909     case M_BLTZALL:
9910       gas_assert (mips_opts.micromips);
9911       br = mips_opts.insn32 ? "bltzal" : "bltzals";
9912       brneg = "bgez";
9913       call = 1;
9914       break;
9915     default:
9916       abort ();
9917     }
9918   if (mips_opts.micromips && brneg)
9919     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
9920   else
9921     macro_build (ep, br, "s,p", sreg);
9922 }
9923
9924 /* Emit a three-argument branch macro specified by TYPE, using SREG and
9925    TREG as the registers tested.  EP specifies the branch target.  */
9926
9927 static void
9928 macro_build_branch_rsrt (int type, expressionS *ep,
9929                          unsigned int sreg, unsigned int treg)
9930 {
9931   const char *brneg = NULL;
9932   const int call = 0;
9933   const char *br;
9934
9935   switch (type)
9936     {
9937     case M_BEQ:
9938     case M_BEQ_I:
9939       br = "beq";
9940       break;
9941     case M_BEQL:
9942     case M_BEQL_I:
9943       br = mips_opts.micromips ? "beq" : "beql";
9944       brneg = "bne";
9945       break;
9946     case M_BNE:
9947     case M_BNE_I:
9948       br = "bne";
9949       break;
9950     case M_BNEL:
9951     case M_BNEL_I:
9952       br = mips_opts.micromips ? "bne" : "bnel";
9953       brneg = "beq";
9954       break;
9955     default:
9956       abort ();
9957     }
9958   if (mips_opts.micromips && brneg)
9959     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
9960   else
9961     macro_build (ep, br, "s,t,p", sreg, treg);
9962 }
9963
9964 /* Return the high part that should be loaded in order to make the low
9965    part of VALUE accessible using an offset of OFFBITS bits.  */
9966
9967 static offsetT
9968 offset_high_part (offsetT value, unsigned int offbits)
9969 {
9970   offsetT bias;
9971   addressT low_mask;
9972
9973   if (offbits == 0)
9974     return value;
9975   bias = 1 << (offbits - 1);
9976   low_mask = bias * 2 - 1;
9977   return (value + bias) & ~low_mask;
9978 }
9979
9980 /* Return true if the value stored in offset_expr and offset_reloc
9981    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
9982    amount that the caller wants to add without inducing overflow
9983    and ALIGN is the known alignment of the value in bytes.  */
9984
9985 static bfd_boolean
9986 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
9987 {
9988   if (offbits == 16)
9989     {
9990       /* Accept any relocation operator if overflow isn't a concern.  */
9991       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
9992         return TRUE;
9993
9994       /* These relocations are guaranteed not to overflow in correct links.  */
9995       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
9996           || gprel16_reloc_p (*offset_reloc))
9997         return TRUE;
9998     }
9999   if (offset_expr.X_op == O_constant
10000       && offset_high_part (offset_expr.X_add_number, offbits) == 0
10001       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
10002     return TRUE;
10003   return FALSE;
10004 }
10005
10006 /*
10007  *                      Build macros
10008  *   This routine implements the seemingly endless macro or synthesized
10009  * instructions and addressing modes in the mips assembly language. Many
10010  * of these macros are simple and are similar to each other. These could
10011  * probably be handled by some kind of table or grammar approach instead of
10012  * this verbose method. Others are not simple macros but are more like
10013  * optimizing code generation.
10014  *   One interesting optimization is when several store macros appear
10015  * consecutively that would load AT with the upper half of the same address.
10016  * The ensuing load upper instructions are omitted. This implies some kind
10017  * of global optimization. We currently only optimize within a single macro.
10018  *   For many of the load and store macros if the address is specified as a
10019  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
10020  * first load register 'at' with zero and use it as the base register. The
10021  * mips assembler simply uses register $zero. Just one tiny optimization
10022  * we're missing.
10023  */
10024 static void
10025 macro (struct mips_cl_insn *ip, char *str)
10026 {
10027   const struct mips_operand_array *operands;
10028   unsigned int breg, i;
10029   unsigned int tempreg;
10030   int mask;
10031   int used_at = 0;
10032   expressionS label_expr;
10033   expressionS expr1;
10034   expressionS *ep;
10035   const char *s;
10036   const char *s2;
10037   const char *fmt;
10038   int likely = 0;
10039   int coproc = 0;
10040   int offbits = 16;
10041   int call = 0;
10042   int jals = 0;
10043   int dbl = 0;
10044   int imm = 0;
10045   int ust = 0;
10046   int lp = 0;
10047   bfd_boolean large_offset;
10048   int off;
10049   int hold_mips_optimize;
10050   unsigned int align;
10051   unsigned int op[MAX_OPERANDS];
10052
10053   gas_assert (! mips_opts.mips16);
10054
10055   operands = insn_operands (ip);
10056   for (i = 0; i < MAX_OPERANDS; i++)
10057     if (operands->operand[i])
10058       op[i] = insn_extract_operand (ip, operands->operand[i]);
10059     else
10060       op[i] = -1;
10061
10062   mask = ip->insn_mo->mask;
10063
10064   label_expr.X_op = O_constant;
10065   label_expr.X_op_symbol = NULL;
10066   label_expr.X_add_symbol = NULL;
10067   label_expr.X_add_number = 0;
10068
10069   expr1.X_op = O_constant;
10070   expr1.X_op_symbol = NULL;
10071   expr1.X_add_symbol = NULL;
10072   expr1.X_add_number = 1;
10073   align = 1;
10074
10075   switch (mask)
10076     {
10077     case M_DABS:
10078       dbl = 1;
10079       /* Fall through.  */
10080     case M_ABS:
10081       /*    bgez    $a0,1f
10082             move    v0,$a0
10083             sub     v0,$zero,$a0
10084          1:
10085        */
10086
10087       start_noreorder ();
10088
10089       if (mips_opts.micromips)
10090         micromips_label_expr (&label_expr);
10091       else
10092         label_expr.X_add_number = 8;
10093       macro_build (&label_expr, "bgez", "s,p", op[1]);
10094       if (op[0] == op[1])
10095         macro_build (NULL, "nop", "");
10096       else
10097         move_register (op[0], op[1]);
10098       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", op[0], 0, op[1]);
10099       if (mips_opts.micromips)
10100         micromips_add_label ();
10101
10102       end_noreorder ();
10103       break;
10104
10105     case M_ADD_I:
10106       s = "addi";
10107       s2 = "add";
10108       goto do_addi;
10109     case M_ADDU_I:
10110       s = "addiu";
10111       s2 = "addu";
10112       goto do_addi;
10113     case M_DADD_I:
10114       dbl = 1;
10115       s = "daddi";
10116       s2 = "dadd";
10117       if (!mips_opts.micromips)
10118         goto do_addi;
10119       if (imm_expr.X_add_number >= -0x200
10120           && imm_expr.X_add_number < 0x200)
10121         {
10122           macro_build (NULL, s, "t,r,.", op[0], op[1],
10123                        (int) imm_expr.X_add_number);
10124           break;
10125         }
10126       goto do_addi_i;
10127     case M_DADDU_I:
10128       dbl = 1;
10129       s = "daddiu";
10130       s2 = "daddu";
10131     do_addi:
10132       if (imm_expr.X_add_number >= -0x8000
10133           && imm_expr.X_add_number < 0x8000)
10134         {
10135           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
10136           break;
10137         }
10138     do_addi_i:
10139       used_at = 1;
10140       load_register (AT, &imm_expr, dbl);
10141       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
10142       break;
10143
10144     case M_AND_I:
10145       s = "andi";
10146       s2 = "and";
10147       goto do_bit;
10148     case M_OR_I:
10149       s = "ori";
10150       s2 = "or";
10151       goto do_bit;
10152     case M_NOR_I:
10153       s = "";
10154       s2 = "nor";
10155       goto do_bit;
10156     case M_XOR_I:
10157       s = "xori";
10158       s2 = "xor";
10159     do_bit:
10160       if (imm_expr.X_add_number >= 0
10161           && imm_expr.X_add_number < 0x10000)
10162         {
10163           if (mask != M_NOR_I)
10164             macro_build (&imm_expr, s, "t,r,i", op[0], op[1], BFD_RELOC_LO16);
10165           else
10166             {
10167               macro_build (&imm_expr, "ori", "t,r,i",
10168                            op[0], op[1], BFD_RELOC_LO16);
10169               macro_build (NULL, "nor", "d,v,t", op[0], op[0], 0);
10170             }
10171           break;
10172         }
10173
10174       used_at = 1;
10175       load_register (AT, &imm_expr, GPR_SIZE == 64);
10176       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
10177       break;
10178
10179     case M_BALIGN:
10180       switch (imm_expr.X_add_number)
10181         {
10182         case 0:
10183           macro_build (NULL, "nop", "");
10184           break;
10185         case 2:
10186           macro_build (NULL, "packrl.ph", "d,s,t", op[0], op[0], op[1]);
10187           break;
10188         case 1:
10189         case 3:
10190           macro_build (NULL, "balign", "t,s,2", op[0], op[1],
10191                        (int) imm_expr.X_add_number);
10192           break;
10193         default:
10194           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
10195                   (unsigned long) imm_expr.X_add_number);
10196           break;
10197         }
10198       break;
10199
10200     case M_BC1FL:
10201     case M_BC1TL:
10202     case M_BC2FL:
10203     case M_BC2TL:
10204       gas_assert (mips_opts.micromips);
10205       macro_build_branch_ccl (mask, &offset_expr,
10206                               EXTRACT_OPERAND (1, BCC, *ip));
10207       break;
10208
10209     case M_BEQ_I:
10210     case M_BEQL_I:
10211     case M_BNE_I:
10212     case M_BNEL_I:
10213       if (imm_expr.X_add_number == 0)
10214         op[1] = 0;
10215       else
10216         {
10217           op[1] = AT;
10218           used_at = 1;
10219           load_register (op[1], &imm_expr, GPR_SIZE == 64);
10220         }
10221       /* Fall through.  */
10222     case M_BEQL:
10223     case M_BNEL:
10224       macro_build_branch_rsrt (mask, &offset_expr, op[0], op[1]);
10225       break;
10226
10227     case M_BGEL:
10228       likely = 1;
10229       /* Fall through.  */
10230     case M_BGE:
10231       if (op[1] == 0)
10232         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[0]);
10233       else if (op[0] == 0)
10234         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[1]);
10235       else
10236         {
10237           used_at = 1;
10238           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
10239           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10240                                    &offset_expr, AT, ZERO);
10241         }
10242       break;
10243
10244     case M_BGEZL:
10245     case M_BGEZALL:
10246     case M_BGTZL:
10247     case M_BLEZL:
10248     case M_BLTZL:
10249     case M_BLTZALL:
10250       macro_build_branch_rs (mask, &offset_expr, op[0]);
10251       break;
10252
10253     case M_BGTL_I:
10254       likely = 1;
10255       /* Fall through.  */
10256     case M_BGT_I:
10257       /* Check for > max integer.  */
10258       if (imm_expr.X_add_number >= GPR_SMAX)
10259         {
10260         do_false:
10261           /* Result is always false.  */
10262           if (! likely)
10263             macro_build (NULL, "nop", "");
10264           else
10265             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
10266           break;
10267         }
10268       ++imm_expr.X_add_number;
10269       /* FALLTHROUGH */
10270     case M_BGE_I:
10271     case M_BGEL_I:
10272       if (mask == M_BGEL_I)
10273         likely = 1;
10274       if (imm_expr.X_add_number == 0)
10275         {
10276           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
10277                                  &offset_expr, op[0]);
10278           break;
10279         }
10280       if (imm_expr.X_add_number == 1)
10281         {
10282           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
10283                                  &offset_expr, op[0]);
10284           break;
10285         }
10286       if (imm_expr.X_add_number <= GPR_SMIN)
10287         {
10288         do_true:
10289           /* result is always true */
10290           as_warn (_("branch %s is always true"), ip->insn_mo->name);
10291           macro_build (&offset_expr, "b", "p");
10292           break;
10293         }
10294       used_at = 1;
10295       set_at (op[0], 0);
10296       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10297                                &offset_expr, AT, ZERO);
10298       break;
10299
10300     case M_BGEUL:
10301       likely = 1;
10302       /* Fall through.  */
10303     case M_BGEU:
10304       if (op[1] == 0)
10305         goto do_true;
10306       else if (op[0] == 0)
10307         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10308                                  &offset_expr, ZERO, op[1]);
10309       else
10310         {
10311           used_at = 1;
10312           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
10313           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10314                                    &offset_expr, AT, ZERO);
10315         }
10316       break;
10317
10318     case M_BGTUL_I:
10319       likely = 1;
10320       /* Fall through.  */
10321     case M_BGTU_I:
10322       if (op[0] == 0
10323           || (GPR_SIZE == 32
10324               && imm_expr.X_add_number == -1))
10325         goto do_false;
10326       ++imm_expr.X_add_number;
10327       /* FALLTHROUGH */
10328     case M_BGEU_I:
10329     case M_BGEUL_I:
10330       if (mask == M_BGEUL_I)
10331         likely = 1;
10332       if (imm_expr.X_add_number == 0)
10333         goto do_true;
10334       else if (imm_expr.X_add_number == 1)
10335         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10336                                  &offset_expr, op[0], ZERO);
10337       else
10338         {
10339           used_at = 1;
10340           set_at (op[0], 1);
10341           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10342                                    &offset_expr, AT, ZERO);
10343         }
10344       break;
10345
10346     case M_BGTL:
10347       likely = 1;
10348       /* Fall through.  */
10349     case M_BGT:
10350       if (op[1] == 0)
10351         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[0]);
10352       else if (op[0] == 0)
10353         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[1]);
10354       else
10355         {
10356           used_at = 1;
10357           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
10358           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10359                                    &offset_expr, AT, ZERO);
10360         }
10361       break;
10362
10363     case M_BGTUL:
10364       likely = 1;
10365       /* Fall through.  */
10366     case M_BGTU:
10367       if (op[1] == 0)
10368         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10369                                  &offset_expr, op[0], ZERO);
10370       else if (op[0] == 0)
10371         goto do_false;
10372       else
10373         {
10374           used_at = 1;
10375           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
10376           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10377                                    &offset_expr, AT, ZERO);
10378         }
10379       break;
10380
10381     case M_BLEL:
10382       likely = 1;
10383       /* Fall through.  */
10384     case M_BLE:
10385       if (op[1] == 0)
10386         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
10387       else if (op[0] == 0)
10388         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[1]);
10389       else
10390         {
10391           used_at = 1;
10392           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
10393           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10394                                    &offset_expr, AT, ZERO);
10395         }
10396       break;
10397
10398     case M_BLEL_I:
10399       likely = 1;
10400       /* Fall through.  */
10401     case M_BLE_I:
10402       if (imm_expr.X_add_number >= GPR_SMAX)
10403         goto do_true;
10404       ++imm_expr.X_add_number;
10405       /* FALLTHROUGH */
10406     case M_BLT_I:
10407     case M_BLTL_I:
10408       if (mask == M_BLTL_I)
10409         likely = 1;
10410       if (imm_expr.X_add_number == 0)
10411         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
10412       else if (imm_expr.X_add_number == 1)
10413         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
10414       else
10415         {
10416           used_at = 1;
10417           set_at (op[0], 0);
10418           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10419                                    &offset_expr, AT, ZERO);
10420         }
10421       break;
10422
10423     case M_BLEUL:
10424       likely = 1;
10425       /* Fall through.  */
10426     case M_BLEU:
10427       if (op[1] == 0)
10428         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10429                                  &offset_expr, op[0], ZERO);
10430       else if (op[0] == 0)
10431         goto do_true;
10432       else
10433         {
10434           used_at = 1;
10435           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
10436           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10437                                    &offset_expr, AT, ZERO);
10438         }
10439       break;
10440
10441     case M_BLEUL_I:
10442       likely = 1;
10443       /* Fall through.  */
10444     case M_BLEU_I:
10445       if (op[0] == 0
10446           || (GPR_SIZE == 32
10447               && imm_expr.X_add_number == -1))
10448         goto do_true;
10449       ++imm_expr.X_add_number;
10450       /* FALLTHROUGH */
10451     case M_BLTU_I:
10452     case M_BLTUL_I:
10453       if (mask == M_BLTUL_I)
10454         likely = 1;
10455       if (imm_expr.X_add_number == 0)
10456         goto do_false;
10457       else if (imm_expr.X_add_number == 1)
10458         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10459                                  &offset_expr, op[0], ZERO);
10460       else
10461         {
10462           used_at = 1;
10463           set_at (op[0], 1);
10464           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10465                                    &offset_expr, AT, ZERO);
10466         }
10467       break;
10468
10469     case M_BLTL:
10470       likely = 1;
10471       /* Fall through.  */
10472     case M_BLT:
10473       if (op[1] == 0)
10474         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
10475       else if (op[0] == 0)
10476         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[1]);
10477       else
10478         {
10479           used_at = 1;
10480           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
10481           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10482                                    &offset_expr, AT, ZERO);
10483         }
10484       break;
10485
10486     case M_BLTUL:
10487       likely = 1;
10488       /* Fall through.  */
10489     case M_BLTU:
10490       if (op[1] == 0)
10491         goto do_false;
10492       else if (op[0] == 0)
10493         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10494                                  &offset_expr, ZERO, op[1]);
10495       else
10496         {
10497           used_at = 1;
10498           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
10499           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10500                                    &offset_expr, AT, ZERO);
10501         }
10502       break;
10503
10504     case M_DDIV_3:
10505       dbl = 1;
10506       /* Fall through.  */
10507     case M_DIV_3:
10508       s = "mflo";
10509       goto do_div3;
10510     case M_DREM_3:
10511       dbl = 1;
10512       /* Fall through.  */
10513     case M_REM_3:
10514       s = "mfhi";
10515     do_div3:
10516       if (op[2] == 0)
10517         {
10518           as_warn (_("divide by zero"));
10519           if (mips_trap)
10520             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
10521           else
10522             macro_build (NULL, "break", BRK_FMT, 7);
10523           break;
10524         }
10525
10526       start_noreorder ();
10527       if (mips_trap)
10528         {
10529           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
10530           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
10531         }
10532       else
10533         {
10534           if (mips_opts.micromips)
10535             micromips_label_expr (&label_expr);
10536           else
10537             label_expr.X_add_number = 8;
10538           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
10539           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
10540           macro_build (NULL, "break", BRK_FMT, 7);
10541           if (mips_opts.micromips)
10542             micromips_add_label ();
10543         }
10544       expr1.X_add_number = -1;
10545       used_at = 1;
10546       load_register (AT, &expr1, dbl);
10547       if (mips_opts.micromips)
10548         micromips_label_expr (&label_expr);
10549       else
10550         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
10551       macro_build (&label_expr, "bne", "s,t,p", op[2], AT);
10552       if (dbl)
10553         {
10554           expr1.X_add_number = 1;
10555           load_register (AT, &expr1, dbl);
10556           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
10557         }
10558       else
10559         {
10560           expr1.X_add_number = 0x80000000;
10561           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
10562         }
10563       if (mips_trap)
10564         {
10565           macro_build (NULL, "teq", TRAP_FMT, op[1], AT, 6);
10566           /* We want to close the noreorder block as soon as possible, so
10567              that later insns are available for delay slot filling.  */
10568           end_noreorder ();
10569         }
10570       else
10571         {
10572           if (mips_opts.micromips)
10573             micromips_label_expr (&label_expr);
10574           else
10575             label_expr.X_add_number = 8;
10576           macro_build (&label_expr, "bne", "s,t,p", op[1], AT);
10577           macro_build (NULL, "nop", "");
10578
10579           /* We want to close the noreorder block as soon as possible, so
10580              that later insns are available for delay slot filling.  */
10581           end_noreorder ();
10582
10583           macro_build (NULL, "break", BRK_FMT, 6);
10584         }
10585       if (mips_opts.micromips)
10586         micromips_add_label ();
10587       macro_build (NULL, s, MFHL_FMT, op[0]);
10588       break;
10589
10590     case M_DIV_3I:
10591       s = "div";
10592       s2 = "mflo";
10593       goto do_divi;
10594     case M_DIVU_3I:
10595       s = "divu";
10596       s2 = "mflo";
10597       goto do_divi;
10598     case M_REM_3I:
10599       s = "div";
10600       s2 = "mfhi";
10601       goto do_divi;
10602     case M_REMU_3I:
10603       s = "divu";
10604       s2 = "mfhi";
10605       goto do_divi;
10606     case M_DDIV_3I:
10607       dbl = 1;
10608       s = "ddiv";
10609       s2 = "mflo";
10610       goto do_divi;
10611     case M_DDIVU_3I:
10612       dbl = 1;
10613       s = "ddivu";
10614       s2 = "mflo";
10615       goto do_divi;
10616     case M_DREM_3I:
10617       dbl = 1;
10618       s = "ddiv";
10619       s2 = "mfhi";
10620       goto do_divi;
10621     case M_DREMU_3I:
10622       dbl = 1;
10623       s = "ddivu";
10624       s2 = "mfhi";
10625     do_divi:
10626       if (imm_expr.X_add_number == 0)
10627         {
10628           as_warn (_("divide by zero"));
10629           if (mips_trap)
10630             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
10631           else
10632             macro_build (NULL, "break", BRK_FMT, 7);
10633           break;
10634         }
10635       if (imm_expr.X_add_number == 1)
10636         {
10637           if (strcmp (s2, "mflo") == 0)
10638             move_register (op[0], op[1]);
10639           else
10640             move_register (op[0], ZERO);
10641           break;
10642         }
10643       if (imm_expr.X_add_number == -1 && s[strlen (s) - 1] != 'u')
10644         {
10645           if (strcmp (s2, "mflo") == 0)
10646             macro_build (NULL, dbl ? "dneg" : "neg", "d,w", op[0], op[1]);
10647           else
10648             move_register (op[0], ZERO);
10649           break;
10650         }
10651
10652       used_at = 1;
10653       load_register (AT, &imm_expr, dbl);
10654       macro_build (NULL, s, "z,s,t", op[1], AT);
10655       macro_build (NULL, s2, MFHL_FMT, op[0]);
10656       break;
10657
10658     case M_DIVU_3:
10659       s = "divu";
10660       s2 = "mflo";
10661       goto do_divu3;
10662     case M_REMU_3:
10663       s = "divu";
10664       s2 = "mfhi";
10665       goto do_divu3;
10666     case M_DDIVU_3:
10667       s = "ddivu";
10668       s2 = "mflo";
10669       goto do_divu3;
10670     case M_DREMU_3:
10671       s = "ddivu";
10672       s2 = "mfhi";
10673     do_divu3:
10674       start_noreorder ();
10675       if (mips_trap)
10676         {
10677           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
10678           macro_build (NULL, s, "z,s,t", op[1], op[2]);
10679           /* We want to close the noreorder block as soon as possible, so
10680              that later insns are available for delay slot filling.  */
10681           end_noreorder ();
10682         }
10683       else
10684         {
10685           if (mips_opts.micromips)
10686             micromips_label_expr (&label_expr);
10687           else
10688             label_expr.X_add_number = 8;
10689           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
10690           macro_build (NULL, s, "z,s,t", op[1], op[2]);
10691
10692           /* We want to close the noreorder block as soon as possible, so
10693              that later insns are available for delay slot filling.  */
10694           end_noreorder ();
10695           macro_build (NULL, "break", BRK_FMT, 7);
10696           if (mips_opts.micromips)
10697             micromips_add_label ();
10698         }
10699       macro_build (NULL, s2, MFHL_FMT, op[0]);
10700       break;
10701
10702     case M_DLCA_AB:
10703       dbl = 1;
10704       /* Fall through.  */
10705     case M_LCA_AB:
10706       call = 1;
10707       goto do_la;
10708     case M_DLA_AB:
10709       dbl = 1;
10710       /* Fall through.  */
10711     case M_LA_AB:
10712     do_la:
10713       /* Load the address of a symbol into a register.  If breg is not
10714          zero, we then add a base register to it.  */
10715
10716       breg = op[2];
10717       if (dbl && GPR_SIZE == 32)
10718         as_warn (_("dla used to load 32-bit register; recommend using la "
10719                    "instead"));
10720
10721       if (!dbl && HAVE_64BIT_OBJECTS)
10722         as_warn (_("la used to load 64-bit address; recommend using dla "
10723                    "instead"));
10724
10725       if (small_offset_p (0, align, 16))
10726         {
10727           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", op[0], breg,
10728                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
10729           break;
10730         }
10731
10732       if (mips_opts.at && (op[0] == breg))
10733         {
10734           tempreg = AT;
10735           used_at = 1;
10736         }
10737       else
10738         tempreg = op[0];
10739
10740       if (offset_expr.X_op != O_symbol
10741           && offset_expr.X_op != O_constant)
10742         {
10743           as_bad (_("expression too complex"));
10744           offset_expr.X_op = O_constant;
10745         }
10746
10747       if (offset_expr.X_op == O_constant)
10748         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
10749       else if (mips_pic == NO_PIC)
10750         {
10751           /* If this is a reference to a GP relative symbol, we want
10752                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
10753              Otherwise we want
10754                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
10755                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10756              If we have a constant, we need two instructions anyhow,
10757              so we may as well always use the latter form.
10758
10759              With 64bit address space and a usable $at we want
10760                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
10761                lui      $at,<sym>               (BFD_RELOC_HI16_S)
10762                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
10763                daddiu   $at,<sym>               (BFD_RELOC_LO16)
10764                dsll32   $tempreg,0
10765                daddu    $tempreg,$tempreg,$at
10766
10767              If $at is already in use, we use a path which is suboptimal
10768              on superscalar processors.
10769                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
10770                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
10771                dsll     $tempreg,16
10772                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
10773                dsll     $tempreg,16
10774                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
10775
10776              For GP relative symbols in 64bit address space we can use
10777              the same sequence as in 32bit address space.  */
10778           if (HAVE_64BIT_SYMBOLS)
10779             {
10780               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10781                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10782                 {
10783                   relax_start (offset_expr.X_add_symbol);
10784                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10785                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
10786                   relax_switch ();
10787                 }
10788
10789               if (used_at == 0 && mips_opts.at)
10790                 {
10791                   macro_build (&offset_expr, "lui", LUI_FMT,
10792                                tempreg, BFD_RELOC_MIPS_HIGHEST);
10793                   macro_build (&offset_expr, "lui", LUI_FMT,
10794                                AT, BFD_RELOC_HI16_S);
10795                   macro_build (&offset_expr, "daddiu", "t,r,j",
10796                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
10797                   macro_build (&offset_expr, "daddiu", "t,r,j",
10798                                AT, AT, BFD_RELOC_LO16);
10799                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
10800                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
10801                   used_at = 1;
10802                 }
10803               else
10804                 {
10805                   macro_build (&offset_expr, "lui", LUI_FMT,
10806                                tempreg, BFD_RELOC_MIPS_HIGHEST);
10807                   macro_build (&offset_expr, "daddiu", "t,r,j",
10808                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
10809                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
10810                   macro_build (&offset_expr, "daddiu", "t,r,j",
10811                                tempreg, tempreg, BFD_RELOC_HI16_S);
10812                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
10813                   macro_build (&offset_expr, "daddiu", "t,r,j",
10814                                tempreg, tempreg, BFD_RELOC_LO16);
10815                 }
10816
10817               if (mips_relax.sequence)
10818                 relax_end ();
10819             }
10820           else
10821             {
10822               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10823                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10824                 {
10825                   relax_start (offset_expr.X_add_symbol);
10826                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10827                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
10828                   relax_switch ();
10829                 }
10830               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
10831                 as_bad (_("offset too large"));
10832               macro_build_lui (&offset_expr, tempreg);
10833               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10834                            tempreg, tempreg, BFD_RELOC_LO16);
10835               if (mips_relax.sequence)
10836                 relax_end ();
10837             }
10838         }
10839       else if (!mips_big_got && !HAVE_NEWABI)
10840         {
10841           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10842
10843           /* If this is a reference to an external symbol, and there
10844              is no constant, we want
10845                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10846              or for lca or if tempreg is PIC_CALL_REG
10847                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
10848              For a local symbol, we want
10849                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10850                nop
10851                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10852
10853              If we have a small constant, and this is a reference to
10854              an external symbol, we want
10855                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10856                nop
10857                addiu    $tempreg,$tempreg,<constant>
10858              For a local symbol, we want the same instruction
10859              sequence, but we output a BFD_RELOC_LO16 reloc on the
10860              addiu instruction.
10861
10862              If we have a large constant, and this is a reference to
10863              an external symbol, we want
10864                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10865                lui      $at,<hiconstant>
10866                addiu    $at,$at,<loconstant>
10867                addu     $tempreg,$tempreg,$at
10868              For a local symbol, we want the same instruction
10869              sequence, but we output a BFD_RELOC_LO16 reloc on the
10870              addiu instruction.
10871            */
10872
10873           if (offset_expr.X_add_number == 0)
10874             {
10875               if (mips_pic == SVR4_PIC
10876                   && breg == 0
10877                   && (call || tempreg == PIC_CALL_REG))
10878                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
10879
10880               relax_start (offset_expr.X_add_symbol);
10881               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10882                            lw_reloc_type, mips_gp_register);
10883               if (breg != 0)
10884                 {
10885                   /* We're going to put in an addu instruction using
10886                      tempreg, so we may as well insert the nop right
10887                      now.  */
10888                   load_delay_nop ();
10889                 }
10890               relax_switch ();
10891               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10892                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
10893               load_delay_nop ();
10894               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10895                            tempreg, tempreg, BFD_RELOC_LO16);
10896               relax_end ();
10897               /* FIXME: If breg == 0, and the next instruction uses
10898                  $tempreg, then if this variant case is used an extra
10899                  nop will be generated.  */
10900             }
10901           else if (offset_expr.X_add_number >= -0x8000
10902                    && offset_expr.X_add_number < 0x8000)
10903             {
10904               load_got_offset (tempreg, &offset_expr);
10905               load_delay_nop ();
10906               add_got_offset (tempreg, &offset_expr);
10907             }
10908           else
10909             {
10910               expr1.X_add_number = offset_expr.X_add_number;
10911               offset_expr.X_add_number =
10912                 SEXT_16BIT (offset_expr.X_add_number);
10913               load_got_offset (tempreg, &offset_expr);
10914               offset_expr.X_add_number = expr1.X_add_number;
10915               /* If we are going to add in a base register, and the
10916                  target register and the base register are the same,
10917                  then we are using AT as a temporary register.  Since
10918                  we want to load the constant into AT, we add our
10919                  current AT (from the global offset table) and the
10920                  register into the register now, and pretend we were
10921                  not using a base register.  */
10922               if (breg == op[0])
10923                 {
10924                   load_delay_nop ();
10925                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10926                                op[0], AT, breg);
10927                   breg = 0;
10928                   tempreg = op[0];
10929                 }
10930               add_got_offset_hilo (tempreg, &offset_expr, AT);
10931               used_at = 1;
10932             }
10933         }
10934       else if (!mips_big_got && HAVE_NEWABI)
10935         {
10936           int add_breg_early = 0;
10937
10938           /* If this is a reference to an external, and there is no
10939              constant, or local symbol (*), with or without a
10940              constant, we want
10941                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10942              or for lca or if tempreg is PIC_CALL_REG
10943                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
10944
10945              If we have a small constant, and this is a reference to
10946              an external symbol, we want
10947                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10948                addiu    $tempreg,$tempreg,<constant>
10949
10950              If we have a large constant, and this is a reference to
10951              an external symbol, we want
10952                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10953                lui      $at,<hiconstant>
10954                addiu    $at,$at,<loconstant>
10955                addu     $tempreg,$tempreg,$at
10956
10957              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
10958              local symbols, even though it introduces an additional
10959              instruction.  */
10960
10961           if (offset_expr.X_add_number)
10962             {
10963               expr1.X_add_number = offset_expr.X_add_number;
10964               offset_expr.X_add_number = 0;
10965
10966               relax_start (offset_expr.X_add_symbol);
10967               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10968                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10969
10970               if (expr1.X_add_number >= -0x8000
10971                   && expr1.X_add_number < 0x8000)
10972                 {
10973                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10974                                tempreg, tempreg, BFD_RELOC_LO16);
10975                 }
10976               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
10977                 {
10978                   unsigned int dreg;
10979
10980                   /* If we are going to add in a base register, and the
10981                      target register and the base register are the same,
10982                      then we are using AT as a temporary register.  Since
10983                      we want to load the constant into AT, we add our
10984                      current AT (from the global offset table) and the
10985                      register into the register now, and pretend we were
10986                      not using a base register.  */
10987                   if (breg != op[0])
10988                     dreg = tempreg;
10989                   else
10990                     {
10991                       gas_assert (tempreg == AT);
10992                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10993                                    op[0], AT, breg);
10994                       dreg = op[0];
10995                       add_breg_early = 1;
10996                     }
10997
10998                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10999                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11000                                dreg, dreg, AT);
11001
11002                   used_at = 1;
11003                 }
11004               else
11005                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
11006
11007               relax_switch ();
11008               offset_expr.X_add_number = expr1.X_add_number;
11009
11010               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11011                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
11012               if (add_breg_early)
11013                 {
11014                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11015                                op[0], tempreg, breg);
11016                   breg = 0;
11017                   tempreg = op[0];
11018                 }
11019               relax_end ();
11020             }
11021           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
11022             {
11023               relax_start (offset_expr.X_add_symbol);
11024               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11025                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
11026               relax_switch ();
11027               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11028                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
11029               relax_end ();
11030             }
11031           else
11032             {
11033               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11034                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
11035             }
11036         }
11037       else if (mips_big_got && !HAVE_NEWABI)
11038         {
11039           int gpdelay;
11040           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
11041           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
11042           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
11043
11044           /* This is the large GOT case.  If this is a reference to an
11045              external symbol, and there is no constant, we want
11046                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11047                addu     $tempreg,$tempreg,$gp
11048                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11049              or for lca or if tempreg is PIC_CALL_REG
11050                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
11051                addu     $tempreg,$tempreg,$gp
11052                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
11053              For a local symbol, we want
11054                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11055                nop
11056                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11057
11058              If we have a small constant, and this is a reference to
11059              an external symbol, we want
11060                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11061                addu     $tempreg,$tempreg,$gp
11062                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11063                nop
11064                addiu    $tempreg,$tempreg,<constant>
11065              For a local symbol, we want
11066                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11067                nop
11068                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
11069
11070              If we have a large constant, and this is a reference to
11071              an external symbol, we want
11072                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11073                addu     $tempreg,$tempreg,$gp
11074                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11075                lui      $at,<hiconstant>
11076                addiu    $at,$at,<loconstant>
11077                addu     $tempreg,$tempreg,$at
11078              For a local symbol, we want
11079                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11080                lui      $at,<hiconstant>
11081                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
11082                addu     $tempreg,$tempreg,$at
11083           */
11084
11085           expr1.X_add_number = offset_expr.X_add_number;
11086           offset_expr.X_add_number = 0;
11087           relax_start (offset_expr.X_add_symbol);
11088           gpdelay = reg_needs_delay (mips_gp_register);
11089           if (expr1.X_add_number == 0 && breg == 0
11090               && (call || tempreg == PIC_CALL_REG))
11091             {
11092               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
11093               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
11094             }
11095           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
11096           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11097                        tempreg, tempreg, mips_gp_register);
11098           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11099                        tempreg, lw_reloc_type, tempreg);
11100           if (expr1.X_add_number == 0)
11101             {
11102               if (breg != 0)
11103                 {
11104                   /* We're going to put in an addu instruction using
11105                      tempreg, so we may as well insert the nop right
11106                      now.  */
11107                   load_delay_nop ();
11108                 }
11109             }
11110           else if (expr1.X_add_number >= -0x8000
11111                    && expr1.X_add_number < 0x8000)
11112             {
11113               load_delay_nop ();
11114               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
11115                            tempreg, tempreg, BFD_RELOC_LO16);
11116             }
11117           else
11118             {
11119               unsigned int dreg;
11120
11121               /* If we are going to add in a base register, and the
11122                  target register and the base register are the same,
11123                  then we are using AT as a temporary register.  Since
11124                  we want to load the constant into AT, we add our
11125                  current AT (from the global offset table) and the
11126                  register into the register now, and pretend we were
11127                  not using a base register.  */
11128               if (breg != op[0])
11129                 dreg = tempreg;
11130               else
11131                 {
11132                   gas_assert (tempreg == AT);
11133                   load_delay_nop ();
11134                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11135                                op[0], AT, breg);
11136                   dreg = op[0];
11137                 }
11138
11139               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
11140               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
11141
11142               used_at = 1;
11143             }
11144           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
11145           relax_switch ();
11146
11147           if (gpdelay)
11148             {
11149               /* This is needed because this instruction uses $gp, but
11150                  the first instruction on the main stream does not.  */
11151               macro_build (NULL, "nop", "");
11152             }
11153
11154           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11155                        local_reloc_type, mips_gp_register);
11156           if (expr1.X_add_number >= -0x8000
11157               && expr1.X_add_number < 0x8000)
11158             {
11159               load_delay_nop ();
11160               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11161                            tempreg, tempreg, BFD_RELOC_LO16);
11162               /* FIXME: If add_number is 0, and there was no base
11163                  register, the external symbol case ended with a load,
11164                  so if the symbol turns out to not be external, and
11165                  the next instruction uses tempreg, an unnecessary nop
11166                  will be inserted.  */
11167             }
11168           else
11169             {
11170               if (breg == op[0])
11171                 {
11172                   /* We must add in the base register now, as in the
11173                      external symbol case.  */
11174                   gas_assert (tempreg == AT);
11175                   load_delay_nop ();
11176                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11177                                op[0], AT, breg);
11178                   tempreg = op[0];
11179                   /* We set breg to 0 because we have arranged to add
11180                      it in in both cases.  */
11181                   breg = 0;
11182                 }
11183
11184               macro_build_lui (&expr1, AT);
11185               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11186                            AT, AT, BFD_RELOC_LO16);
11187               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11188                            tempreg, tempreg, AT);
11189               used_at = 1;
11190             }
11191           relax_end ();
11192         }
11193       else if (mips_big_got && HAVE_NEWABI)
11194         {
11195           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
11196           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
11197           int add_breg_early = 0;
11198
11199           /* This is the large GOT case.  If this is a reference to an
11200              external symbol, and there is no constant, we want
11201                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11202                add      $tempreg,$tempreg,$gp
11203                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11204              or for lca or if tempreg is PIC_CALL_REG
11205                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
11206                add      $tempreg,$tempreg,$gp
11207                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
11208
11209              If we have a small constant, and this is a reference to
11210              an external symbol, we want
11211                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11212                add      $tempreg,$tempreg,$gp
11213                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11214                addi     $tempreg,$tempreg,<constant>
11215
11216              If we have a large constant, and this is a reference to
11217              an external symbol, we want
11218                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11219                addu     $tempreg,$tempreg,$gp
11220                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11221                lui      $at,<hiconstant>
11222                addi     $at,$at,<loconstant>
11223                add      $tempreg,$tempreg,$at
11224
11225              If we have NewABI, and we know it's a local symbol, we want
11226                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
11227                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
11228              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
11229
11230           relax_start (offset_expr.X_add_symbol);
11231
11232           expr1.X_add_number = offset_expr.X_add_number;
11233           offset_expr.X_add_number = 0;
11234
11235           if (expr1.X_add_number == 0 && breg == 0
11236               && (call || tempreg == PIC_CALL_REG))
11237             {
11238               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
11239               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
11240             }
11241           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
11242           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11243                        tempreg, tempreg, mips_gp_register);
11244           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11245                        tempreg, lw_reloc_type, tempreg);
11246
11247           if (expr1.X_add_number == 0)
11248             ;
11249           else if (expr1.X_add_number >= -0x8000
11250                    && expr1.X_add_number < 0x8000)
11251             {
11252               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
11253                            tempreg, tempreg, BFD_RELOC_LO16);
11254             }
11255           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
11256             {
11257               unsigned int dreg;
11258
11259               /* If we are going to add in a base register, and the
11260                  target register and the base register are the same,
11261                  then we are using AT as a temporary register.  Since
11262                  we want to load the constant into AT, we add our
11263                  current AT (from the global offset table) and the
11264                  register into the register now, and pretend we were
11265                  not using a base register.  */
11266               if (breg != op[0])
11267                 dreg = tempreg;
11268               else
11269                 {
11270                   gas_assert (tempreg == AT);
11271                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11272                                op[0], AT, breg);
11273                   dreg = op[0];
11274                   add_breg_early = 1;
11275                 }
11276
11277               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
11278               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
11279
11280               used_at = 1;
11281             }
11282           else
11283             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
11284
11285           relax_switch ();
11286           offset_expr.X_add_number = expr1.X_add_number;
11287           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11288                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11289           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11290                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
11291           if (add_breg_early)
11292             {
11293               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11294                            op[0], tempreg, breg);
11295               breg = 0;
11296               tempreg = op[0];
11297             }
11298           relax_end ();
11299         }
11300       else
11301         abort ();
11302
11303       if (breg != 0)
11304         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", op[0], tempreg, breg);
11305       break;
11306
11307     case M_MSGSND:
11308       gas_assert (!mips_opts.micromips);
11309       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x01);
11310       break;
11311
11312     case M_MSGLD:
11313       gas_assert (!mips_opts.micromips);
11314       macro_build (NULL, "c2", "C", 0x02);
11315       break;
11316
11317     case M_MSGLD_T:
11318       gas_assert (!mips_opts.micromips);
11319       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x02);
11320       break;
11321
11322     case M_MSGWAIT:
11323       gas_assert (!mips_opts.micromips);
11324       macro_build (NULL, "c2", "C", 3);
11325       break;
11326
11327     case M_MSGWAIT_T:
11328       gas_assert (!mips_opts.micromips);
11329       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x03);
11330       break;
11331
11332     case M_J_A:
11333       /* The j instruction may not be used in PIC code, since it
11334          requires an absolute address.  We convert it to a b
11335          instruction.  */
11336       if (mips_pic == NO_PIC)
11337         macro_build (&offset_expr, "j", "a");
11338       else
11339         macro_build (&offset_expr, "b", "p");
11340       break;
11341
11342       /* The jal instructions must be handled as macros because when
11343          generating PIC code they expand to multi-instruction
11344          sequences.  Normally they are simple instructions.  */
11345     case M_JALS_1:
11346       op[1] = op[0];
11347       op[0] = RA;
11348       /* Fall through.  */
11349     case M_JALS_2:
11350       gas_assert (mips_opts.micromips);
11351       if (mips_opts.insn32)
11352         {
11353           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
11354           break;
11355         }
11356       jals = 1;
11357       goto jal;
11358     case M_JAL_1:
11359       op[1] = op[0];
11360       op[0] = RA;
11361       /* Fall through.  */
11362     case M_JAL_2:
11363     jal:
11364       if (mips_pic == NO_PIC)
11365         {
11366           s = jals ? "jalrs" : "jalr";
11367           if (mips_opts.micromips
11368               && !mips_opts.insn32
11369               && op[0] == RA
11370               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
11371             macro_build (NULL, s, "mj", op[1]);
11372           else
11373             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
11374         }
11375       else
11376         {
11377           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
11378                            && mips_cprestore_offset >= 0);
11379
11380           if (op[1] != PIC_CALL_REG)
11381             as_warn (_("MIPS PIC call to register other than $25"));
11382
11383           s = ((mips_opts.micromips
11384                 && !mips_opts.insn32
11385                 && (!mips_opts.noreorder || cprestore))
11386                ? "jalrs" : "jalr");
11387           if (mips_opts.micromips
11388               && !mips_opts.insn32
11389               && op[0] == RA
11390               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
11391             macro_build (NULL, s, "mj", op[1]);
11392           else
11393             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
11394           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
11395             {
11396               if (mips_cprestore_offset < 0)
11397                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
11398               else
11399                 {
11400                   if (!mips_frame_reg_valid)
11401                     {
11402                       as_warn (_("no .frame pseudo-op used in PIC code"));
11403                       /* Quiet this warning.  */
11404                       mips_frame_reg_valid = 1;
11405                     }
11406                   if (!mips_cprestore_valid)
11407                     {
11408                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
11409                       /* Quiet this warning.  */
11410                       mips_cprestore_valid = 1;
11411                     }
11412                   if (mips_opts.noreorder)
11413                     macro_build (NULL, "nop", "");
11414                   expr1.X_add_number = mips_cprestore_offset;
11415                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
11416                                                 mips_gp_register,
11417                                                 mips_frame_reg,
11418                                                 HAVE_64BIT_ADDRESSES);
11419                 }
11420             }
11421         }
11422
11423       break;
11424
11425     case M_JALS_A:
11426       gas_assert (mips_opts.micromips);
11427       if (mips_opts.insn32)
11428         {
11429           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
11430           break;
11431         }
11432       jals = 1;
11433       /* Fall through.  */
11434     case M_JAL_A:
11435       if (mips_pic == NO_PIC)
11436         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
11437       else if (mips_pic == SVR4_PIC)
11438         {
11439           /* If this is a reference to an external symbol, and we are
11440              using a small GOT, we want
11441                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
11442                nop
11443                jalr     $ra,$25
11444                nop
11445                lw       $gp,cprestore($sp)
11446              The cprestore value is set using the .cprestore
11447              pseudo-op.  If we are using a big GOT, we want
11448                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
11449                addu     $25,$25,$gp
11450                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
11451                nop
11452                jalr     $ra,$25
11453                nop
11454                lw       $gp,cprestore($sp)
11455              If the symbol is not external, we want
11456                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11457                nop
11458                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
11459                jalr     $ra,$25
11460                nop
11461                lw $gp,cprestore($sp)
11462
11463              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
11464              sequences above, minus nops, unless the symbol is local,
11465              which enables us to use GOT_PAGE/GOT_OFST (big got) or
11466              GOT_DISP.  */
11467           if (HAVE_NEWABI)
11468             {
11469               if (!mips_big_got)
11470                 {
11471                   relax_start (offset_expr.X_add_symbol);
11472                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11473                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
11474                                mips_gp_register);
11475                   relax_switch ();
11476                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11477                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
11478                                mips_gp_register);
11479                   relax_end ();
11480                 }
11481               else
11482                 {
11483                   relax_start (offset_expr.X_add_symbol);
11484                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
11485                                BFD_RELOC_MIPS_CALL_HI16);
11486                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
11487                                PIC_CALL_REG, mips_gp_register);
11488                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11489                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
11490                                PIC_CALL_REG);
11491                   relax_switch ();
11492                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11493                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
11494                                mips_gp_register);
11495                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11496                                PIC_CALL_REG, PIC_CALL_REG,
11497                                BFD_RELOC_MIPS_GOT_OFST);
11498                   relax_end ();
11499                 }
11500
11501               macro_build_jalr (&offset_expr, 0);
11502             }
11503           else
11504             {
11505               relax_start (offset_expr.X_add_symbol);
11506               if (!mips_big_got)
11507                 {
11508                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11509                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
11510                                mips_gp_register);
11511                   load_delay_nop ();
11512                   relax_switch ();
11513                 }
11514               else
11515                 {
11516                   int gpdelay;
11517
11518                   gpdelay = reg_needs_delay (mips_gp_register);
11519                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
11520                                BFD_RELOC_MIPS_CALL_HI16);
11521                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
11522                                PIC_CALL_REG, mips_gp_register);
11523                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11524                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
11525                                PIC_CALL_REG);
11526                   load_delay_nop ();
11527                   relax_switch ();
11528                   if (gpdelay)
11529                     macro_build (NULL, "nop", "");
11530                 }
11531               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11532                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
11533                            mips_gp_register);
11534               load_delay_nop ();
11535               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11536                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
11537               relax_end ();
11538               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
11539
11540               if (mips_cprestore_offset < 0)
11541                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
11542               else
11543                 {
11544                   if (!mips_frame_reg_valid)
11545                     {
11546                       as_warn (_("no .frame pseudo-op used in PIC code"));
11547                       /* Quiet this warning.  */
11548                       mips_frame_reg_valid = 1;
11549                     }
11550                   if (!mips_cprestore_valid)
11551                     {
11552                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
11553                       /* Quiet this warning.  */
11554                       mips_cprestore_valid = 1;
11555                     }
11556                   if (mips_opts.noreorder)
11557                     macro_build (NULL, "nop", "");
11558                   expr1.X_add_number = mips_cprestore_offset;
11559                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
11560                                                 mips_gp_register,
11561                                                 mips_frame_reg,
11562                                                 HAVE_64BIT_ADDRESSES);
11563                 }
11564             }
11565         }
11566       else if (mips_pic == VXWORKS_PIC)
11567         as_bad (_("non-PIC jump used in PIC library"));
11568       else
11569         abort ();
11570
11571       break;
11572
11573     case M_LBUE_AB:
11574       s = "lbue";
11575       fmt = "t,+j(b)";
11576       offbits = 9;
11577       goto ld_st;
11578     case M_LHUE_AB:
11579       s = "lhue";
11580       fmt = "t,+j(b)";
11581       offbits = 9;
11582       goto ld_st;
11583     case M_LBE_AB:
11584       s = "lbe";
11585       fmt = "t,+j(b)";
11586       offbits = 9;
11587       goto ld_st;
11588     case M_LHE_AB:
11589       s = "lhe";
11590       fmt = "t,+j(b)";
11591       offbits = 9;
11592       goto ld_st;
11593     case M_LLE_AB:
11594       s = "lle";
11595       fmt = "t,+j(b)";
11596       offbits = 9;
11597       goto ld_st;
11598     case M_LWE_AB:
11599       s = "lwe";
11600       fmt = "t,+j(b)";
11601       offbits = 9;
11602       goto ld_st;
11603     case M_LWLE_AB:
11604       s = "lwle";
11605       fmt = "t,+j(b)";
11606       offbits = 9;
11607       goto ld_st;
11608     case M_LWRE_AB:
11609       s = "lwre";
11610       fmt = "t,+j(b)";
11611       offbits = 9;
11612       goto ld_st;
11613     case M_SBE_AB:
11614       s = "sbe";
11615       fmt = "t,+j(b)";
11616       offbits = 9;
11617       goto ld_st;
11618     case M_SCE_AB:
11619       s = "sce";
11620       fmt = "t,+j(b)";
11621       offbits = 9;
11622       goto ld_st;
11623     case M_SHE_AB:
11624       s = "she";
11625       fmt = "t,+j(b)";
11626       offbits = 9;
11627       goto ld_st;
11628     case M_SWE_AB:
11629       s = "swe";
11630       fmt = "t,+j(b)";
11631       offbits = 9;
11632       goto ld_st;
11633     case M_SWLE_AB:
11634       s = "swle";
11635       fmt = "t,+j(b)";
11636       offbits = 9;
11637       goto ld_st;
11638     case M_SWRE_AB:
11639       s = "swre";
11640       fmt = "t,+j(b)";
11641       offbits = 9;
11642       goto ld_st;
11643     case M_ACLR_AB:
11644       s = "aclr";
11645       fmt = "\\,~(b)";
11646       offbits = 12;
11647       goto ld_st;
11648     case M_ASET_AB:
11649       s = "aset";
11650       fmt = "\\,~(b)";
11651       offbits = 12;
11652       goto ld_st;
11653     case M_LB_AB:
11654       s = "lb";
11655       fmt = "t,o(b)";
11656       goto ld;
11657     case M_LBU_AB:
11658       s = "lbu";
11659       fmt = "t,o(b)";
11660       goto ld;
11661     case M_LH_AB:
11662       s = "lh";
11663       fmt = "t,o(b)";
11664       goto ld;
11665     case M_LHU_AB:
11666       s = "lhu";
11667       fmt = "t,o(b)";
11668       goto ld;
11669     case M_LW_AB:
11670       s = "lw";
11671       fmt = "t,o(b)";
11672       goto ld;
11673     case M_LWC0_AB:
11674       gas_assert (!mips_opts.micromips);
11675       s = "lwc0";
11676       fmt = "E,o(b)";
11677       /* Itbl support may require additional care here.  */
11678       coproc = 1;
11679       goto ld_st;
11680     case M_LWC1_AB:
11681       s = "lwc1";
11682       fmt = "T,o(b)";
11683       /* Itbl support may require additional care here.  */
11684       coproc = 1;
11685       goto ld_st;
11686     case M_LWC2_AB:
11687       s = "lwc2";
11688       fmt = COP12_FMT;
11689       offbits = (mips_opts.micromips ? 12
11690                  : ISA_IS_R6 (mips_opts.isa) ? 11
11691                  : 16);
11692       /* Itbl support may require additional care here.  */
11693       coproc = 1;
11694       goto ld_st;
11695     case M_LWC3_AB:
11696       gas_assert (!mips_opts.micromips);
11697       s = "lwc3";
11698       fmt = "E,o(b)";
11699       /* Itbl support may require additional care here.  */
11700       coproc = 1;
11701       goto ld_st;
11702     case M_LWL_AB:
11703       s = "lwl";
11704       fmt = MEM12_FMT;
11705       offbits = (mips_opts.micromips ? 12 : 16);
11706       goto ld_st;
11707     case M_LWR_AB:
11708       s = "lwr";
11709       fmt = MEM12_FMT;
11710       offbits = (mips_opts.micromips ? 12 : 16);
11711       goto ld_st;
11712     case M_LDC1_AB:
11713       s = "ldc1";
11714       fmt = "T,o(b)";
11715       /* Itbl support may require additional care here.  */
11716       coproc = 1;
11717       goto ld_st;
11718     case M_LDC2_AB:
11719       s = "ldc2";
11720       fmt = COP12_FMT;
11721       offbits = (mips_opts.micromips ? 12
11722                  : ISA_IS_R6 (mips_opts.isa) ? 11
11723                  : 16);
11724       /* Itbl support may require additional care here.  */
11725       coproc = 1;
11726       goto ld_st;
11727     case M_LQC2_AB:
11728       s = "lqc2";
11729       fmt = "+7,o(b)";
11730       /* Itbl support may require additional care here.  */
11731       coproc = 1;
11732       goto ld_st;
11733     case M_LDC3_AB:
11734       s = "ldc3";
11735       fmt = "E,o(b)";
11736       /* Itbl support may require additional care here.  */
11737       coproc = 1;
11738       goto ld_st;
11739     case M_LDL_AB:
11740       s = "ldl";
11741       fmt = MEM12_FMT;
11742       offbits = (mips_opts.micromips ? 12 : 16);
11743       goto ld_st;
11744     case M_LDR_AB:
11745       s = "ldr";
11746       fmt = MEM12_FMT;
11747       offbits = (mips_opts.micromips ? 12 : 16);
11748       goto ld_st;
11749     case M_LL_AB:
11750       s = "ll";
11751       fmt = LL_SC_FMT;
11752       offbits = (mips_opts.micromips ? 12
11753                  : ISA_IS_R6 (mips_opts.isa) ? 9
11754                  : 16);
11755       goto ld;
11756     case M_LLD_AB:
11757       s = "lld";
11758       fmt = LL_SC_FMT;
11759       offbits = (mips_opts.micromips ? 12
11760                  : ISA_IS_R6 (mips_opts.isa) ? 9
11761                  : 16);
11762       goto ld;
11763     case M_LWU_AB:
11764       s = "lwu";
11765       fmt = MEM12_FMT;
11766       offbits = (mips_opts.micromips ? 12 : 16);
11767       goto ld;
11768     case M_LWP_AB:
11769       gas_assert (mips_opts.micromips);
11770       s = "lwp";
11771       fmt = "t,~(b)";
11772       offbits = 12;
11773       lp = 1;
11774       goto ld;
11775     case M_LDP_AB:
11776       gas_assert (mips_opts.micromips);
11777       s = "ldp";
11778       fmt = "t,~(b)";
11779       offbits = 12;
11780       lp = 1;
11781       goto ld;
11782     case M_LWM_AB:
11783       gas_assert (mips_opts.micromips);
11784       s = "lwm";
11785       fmt = "n,~(b)";
11786       offbits = 12;
11787       goto ld_st;
11788     case M_LDM_AB:
11789       gas_assert (mips_opts.micromips);
11790       s = "ldm";
11791       fmt = "n,~(b)";
11792       offbits = 12;
11793       goto ld_st;
11794
11795     ld:
11796       /* We don't want to use $0 as tempreg.  */
11797       if (op[2] == op[0] + lp || op[0] + lp == ZERO)
11798         goto ld_st;
11799       else
11800         tempreg = op[0] + lp;
11801       goto ld_noat;
11802
11803     case M_SB_AB:
11804       s = "sb";
11805       fmt = "t,o(b)";
11806       goto ld_st;
11807     case M_SH_AB:
11808       s = "sh";
11809       fmt = "t,o(b)";
11810       goto ld_st;
11811     case M_SW_AB:
11812       s = "sw";
11813       fmt = "t,o(b)";
11814       goto ld_st;
11815     case M_SWC0_AB:
11816       gas_assert (!mips_opts.micromips);
11817       s = "swc0";
11818       fmt = "E,o(b)";
11819       /* Itbl support may require additional care here.  */
11820       coproc = 1;
11821       goto ld_st;
11822     case M_SWC1_AB:
11823       s = "swc1";
11824       fmt = "T,o(b)";
11825       /* Itbl support may require additional care here.  */
11826       coproc = 1;
11827       goto ld_st;
11828     case M_SWC2_AB:
11829       s = "swc2";
11830       fmt = COP12_FMT;
11831       offbits = (mips_opts.micromips ? 12
11832                  : ISA_IS_R6 (mips_opts.isa) ? 11
11833                  : 16);
11834       /* Itbl support may require additional care here.  */
11835       coproc = 1;
11836       goto ld_st;
11837     case M_SWC3_AB:
11838       gas_assert (!mips_opts.micromips);
11839       s = "swc3";
11840       fmt = "E,o(b)";
11841       /* Itbl support may require additional care here.  */
11842       coproc = 1;
11843       goto ld_st;
11844     case M_SWL_AB:
11845       s = "swl";
11846       fmt = MEM12_FMT;
11847       offbits = (mips_opts.micromips ? 12 : 16);
11848       goto ld_st;
11849     case M_SWR_AB:
11850       s = "swr";
11851       fmt = MEM12_FMT;
11852       offbits = (mips_opts.micromips ? 12 : 16);
11853       goto ld_st;
11854     case M_SC_AB:
11855       s = "sc";
11856       fmt = LL_SC_FMT;
11857       offbits = (mips_opts.micromips ? 12
11858                  : ISA_IS_R6 (mips_opts.isa) ? 9
11859                  : 16);
11860       goto ld_st;
11861     case M_SCD_AB:
11862       s = "scd";
11863       fmt = LL_SC_FMT;
11864       offbits = (mips_opts.micromips ? 12
11865                  : ISA_IS_R6 (mips_opts.isa) ? 9
11866                  : 16);
11867       goto ld_st;
11868     case M_CACHE_AB:
11869       s = "cache";
11870       fmt = (mips_opts.micromips ? "k,~(b)"
11871              : ISA_IS_R6 (mips_opts.isa) ? "k,+j(b)"
11872              : "k,o(b)");
11873       offbits = (mips_opts.micromips ? 12
11874                  : ISA_IS_R6 (mips_opts.isa) ? 9
11875                  : 16);
11876       goto ld_st;
11877     case M_CACHEE_AB:
11878       s = "cachee";
11879       fmt = "k,+j(b)";
11880       offbits = 9;
11881       goto ld_st;
11882     case M_PREF_AB:
11883       s = "pref";
11884       fmt = (mips_opts.micromips ? "k,~(b)"
11885              : ISA_IS_R6 (mips_opts.isa) ? "k,+j(b)"
11886              : "k,o(b)");
11887       offbits = (mips_opts.micromips ? 12
11888                  : ISA_IS_R6 (mips_opts.isa) ? 9
11889                  : 16);
11890       goto ld_st;
11891     case M_PREFE_AB:
11892       s = "prefe";
11893       fmt = "k,+j(b)";
11894       offbits = 9;
11895       goto ld_st;
11896     case M_SDC1_AB:
11897       s = "sdc1";
11898       fmt = "T,o(b)";
11899       coproc = 1;
11900       /* Itbl support may require additional care here.  */
11901       goto ld_st;
11902     case M_SDC2_AB:
11903       s = "sdc2";
11904       fmt = COP12_FMT;
11905       offbits = (mips_opts.micromips ? 12
11906                  : ISA_IS_R6 (mips_opts.isa) ? 11
11907                  : 16);
11908       /* Itbl support may require additional care here.  */
11909       coproc = 1;
11910       goto ld_st;
11911     case M_SQC2_AB:
11912       s = "sqc2";
11913       fmt = "+7,o(b)";
11914       /* Itbl support may require additional care here.  */
11915       coproc = 1;
11916       goto ld_st;
11917     case M_SDC3_AB:
11918       gas_assert (!mips_opts.micromips);
11919       s = "sdc3";
11920       fmt = "E,o(b)";
11921       /* Itbl support may require additional care here.  */
11922       coproc = 1;
11923       goto ld_st;
11924     case M_SDL_AB:
11925       s = "sdl";
11926       fmt = MEM12_FMT;
11927       offbits = (mips_opts.micromips ? 12 : 16);
11928       goto ld_st;
11929     case M_SDR_AB:
11930       s = "sdr";
11931       fmt = MEM12_FMT;
11932       offbits = (mips_opts.micromips ? 12 : 16);
11933       goto ld_st;
11934     case M_SWP_AB:
11935       gas_assert (mips_opts.micromips);
11936       s = "swp";
11937       fmt = "t,~(b)";
11938       offbits = 12;
11939       goto ld_st;
11940     case M_SDP_AB:
11941       gas_assert (mips_opts.micromips);
11942       s = "sdp";
11943       fmt = "t,~(b)";
11944       offbits = 12;
11945       goto ld_st;
11946     case M_SWM_AB:
11947       gas_assert (mips_opts.micromips);
11948       s = "swm";
11949       fmt = "n,~(b)";
11950       offbits = 12;
11951       goto ld_st;
11952     case M_SDM_AB:
11953       gas_assert (mips_opts.micromips);
11954       s = "sdm";
11955       fmt = "n,~(b)";
11956       offbits = 12;
11957
11958     ld_st:
11959       tempreg = AT;
11960     ld_noat:
11961       breg = op[2];
11962       if (small_offset_p (0, align, 16))
11963         {
11964           /* The first case exists for M_LD_AB and M_SD_AB, which are
11965              macros for o32 but which should act like normal instructions
11966              otherwise.  */
11967           if (offbits == 16)
11968             macro_build (&offset_expr, s, fmt, op[0], -1, offset_reloc[0],
11969                          offset_reloc[1], offset_reloc[2], breg);
11970           else if (small_offset_p (0, align, offbits))
11971             {
11972               if (offbits == 0)
11973                 macro_build (NULL, s, fmt, op[0], breg);
11974               else
11975                 macro_build (NULL, s, fmt, op[0],
11976                              (int) offset_expr.X_add_number, breg);
11977             }
11978           else
11979             {
11980               if (tempreg == AT)
11981                 used_at = 1;
11982               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11983                            tempreg, breg, -1, offset_reloc[0],
11984                            offset_reloc[1], offset_reloc[2]);
11985               if (offbits == 0)
11986                 macro_build (NULL, s, fmt, op[0], tempreg);
11987               else
11988                 macro_build (NULL, s, fmt, op[0], 0, tempreg);
11989             }
11990           break;
11991         }
11992
11993       if (tempreg == AT)
11994         used_at = 1;
11995
11996       if (offset_expr.X_op != O_constant
11997           && offset_expr.X_op != O_symbol)
11998         {
11999           as_bad (_("expression too complex"));
12000           offset_expr.X_op = O_constant;
12001         }
12002
12003       if (HAVE_32BIT_ADDRESSES
12004           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
12005         {
12006           char value [32];
12007
12008           sprintf_vma (value, offset_expr.X_add_number);
12009           as_bad (_("number (0x%s) larger than 32 bits"), value);
12010         }
12011
12012       /* A constant expression in PIC code can be handled just as it
12013          is in non PIC code.  */
12014       if (offset_expr.X_op == O_constant)
12015         {
12016           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
12017                                                  offbits == 0 ? 16 : offbits);
12018           offset_expr.X_add_number -= expr1.X_add_number;
12019
12020           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
12021           if (breg != 0)
12022             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12023                          tempreg, tempreg, breg);
12024           if (offbits == 0)
12025             {
12026               if (offset_expr.X_add_number != 0)
12027                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
12028                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
12029               macro_build (NULL, s, fmt, op[0], tempreg);
12030             }
12031           else if (offbits == 16)
12032             macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12033           else
12034             macro_build (NULL, s, fmt, op[0],
12035                          (int) offset_expr.X_add_number, tempreg);
12036         }
12037       else if (offbits != 16)
12038         {
12039           /* The offset field is too narrow to be used for a low-part
12040              relocation, so load the whole address into the auxiliary
12041              register.  */
12042           load_address (tempreg, &offset_expr, &used_at);
12043           if (breg != 0)
12044             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12045                          tempreg, tempreg, breg);
12046           if (offbits == 0)
12047             macro_build (NULL, s, fmt, op[0], tempreg);
12048           else
12049             macro_build (NULL, s, fmt, op[0], 0, tempreg);
12050         }
12051       else if (mips_pic == NO_PIC)
12052         {
12053           /* If this is a reference to a GP relative symbol, and there
12054              is no base register, we want
12055                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
12056              Otherwise, if there is no base register, we want
12057                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
12058                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
12059              If we have a constant, we need two instructions anyhow,
12060              so we always use the latter form.
12061
12062              If we have a base register, and this is a reference to a
12063              GP relative symbol, we want
12064                addu     $tempreg,$breg,$gp
12065                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_GPREL16)
12066              Otherwise we want
12067                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
12068                addu     $tempreg,$tempreg,$breg
12069                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
12070              With a constant we always use the latter case.
12071
12072              With 64bit address space and no base register and $at usable,
12073              we want
12074                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
12075                lui      $at,<sym>               (BFD_RELOC_HI16_S)
12076                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
12077                dsll32   $tempreg,0
12078                daddu    $tempreg,$at
12079                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
12080              If we have a base register, we want
12081                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
12082                lui      $at,<sym>               (BFD_RELOC_HI16_S)
12083                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
12084                daddu    $at,$breg
12085                dsll32   $tempreg,0
12086                daddu    $tempreg,$at
12087                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
12088
12089              Without $at we can't generate the optimal path for superscalar
12090              processors here since this would require two temporary registers.
12091                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
12092                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
12093                dsll     $tempreg,16
12094                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
12095                dsll     $tempreg,16
12096                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
12097              If we have a base register, we want
12098                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
12099                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
12100                dsll     $tempreg,16
12101                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
12102                dsll     $tempreg,16
12103                daddu    $tempreg,$tempreg,$breg
12104                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
12105
12106              For GP relative symbols in 64bit address space we can use
12107              the same sequence as in 32bit address space.  */
12108           if (HAVE_64BIT_SYMBOLS)
12109             {
12110               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12111                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12112                 {
12113                   relax_start (offset_expr.X_add_symbol);
12114                   if (breg == 0)
12115                     {
12116                       macro_build (&offset_expr, s, fmt, op[0],
12117                                    BFD_RELOC_GPREL16, mips_gp_register);
12118                     }
12119                   else
12120                     {
12121                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12122                                    tempreg, breg, mips_gp_register);
12123                       macro_build (&offset_expr, s, fmt, op[0],
12124                                    BFD_RELOC_GPREL16, tempreg);
12125                     }
12126                   relax_switch ();
12127                 }
12128
12129               if (used_at == 0 && mips_opts.at)
12130                 {
12131                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12132                                BFD_RELOC_MIPS_HIGHEST);
12133                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
12134                                BFD_RELOC_HI16_S);
12135                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
12136                                tempreg, BFD_RELOC_MIPS_HIGHER);
12137                   if (breg != 0)
12138                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
12139                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
12140                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
12141                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16,
12142                                tempreg);
12143                   used_at = 1;
12144                 }
12145               else
12146                 {
12147                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12148                                BFD_RELOC_MIPS_HIGHEST);
12149                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
12150                                tempreg, BFD_RELOC_MIPS_HIGHER);
12151                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
12152                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
12153                                tempreg, BFD_RELOC_HI16_S);
12154                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
12155                   if (breg != 0)
12156                     macro_build (NULL, "daddu", "d,v,t",
12157                                  tempreg, tempreg, breg);
12158                   macro_build (&offset_expr, s, fmt, op[0],
12159                                BFD_RELOC_LO16, tempreg);
12160                 }
12161
12162               if (mips_relax.sequence)
12163                 relax_end ();
12164               break;
12165             }
12166
12167           if (breg == 0)
12168             {
12169               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12170                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12171                 {
12172                   relax_start (offset_expr.X_add_symbol);
12173                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_GPREL16,
12174                                mips_gp_register);
12175                   relax_switch ();
12176                 }
12177               macro_build_lui (&offset_expr, tempreg);
12178               macro_build (&offset_expr, s, fmt, op[0],
12179                            BFD_RELOC_LO16, tempreg);
12180               if (mips_relax.sequence)
12181                 relax_end ();
12182             }
12183           else
12184             {
12185               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12186                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12187                 {
12188                   relax_start (offset_expr.X_add_symbol);
12189                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12190                                tempreg, breg, mips_gp_register);
12191                   macro_build (&offset_expr, s, fmt, op[0],
12192                                BFD_RELOC_GPREL16, tempreg);
12193                   relax_switch ();
12194                 }
12195               macro_build_lui (&offset_expr, tempreg);
12196               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12197                            tempreg, tempreg, breg);
12198               macro_build (&offset_expr, s, fmt, op[0],
12199                            BFD_RELOC_LO16, tempreg);
12200               if (mips_relax.sequence)
12201                 relax_end ();
12202             }
12203         }
12204       else if (!mips_big_got)
12205         {
12206           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
12207
12208           /* If this is a reference to an external symbol, we want
12209                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
12210                nop
12211                <op>     op[0],0($tempreg)
12212              Otherwise we want
12213                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
12214                nop
12215                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
12216                <op>     op[0],0($tempreg)
12217
12218              For NewABI, we want
12219                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
12220                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
12221
12222              If there is a base register, we add it to $tempreg before
12223              the <op>.  If there is a constant, we stick it in the
12224              <op> instruction.  We don't handle constants larger than
12225              16 bits, because we have no way to load the upper 16 bits
12226              (actually, we could handle them for the subset of cases
12227              in which we are not using $at).  */
12228           gas_assert (offset_expr.X_op == O_symbol);
12229           if (HAVE_NEWABI)
12230             {
12231               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12232                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
12233               if (breg != 0)
12234                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12235                              tempreg, tempreg, breg);
12236               macro_build (&offset_expr, s, fmt, op[0],
12237                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
12238               break;
12239             }
12240           expr1.X_add_number = offset_expr.X_add_number;
12241           offset_expr.X_add_number = 0;
12242           if (expr1.X_add_number < -0x8000
12243               || expr1.X_add_number >= 0x8000)
12244             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12245           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12246                        lw_reloc_type, mips_gp_register);
12247           load_delay_nop ();
12248           relax_start (offset_expr.X_add_symbol);
12249           relax_switch ();
12250           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
12251                        tempreg, BFD_RELOC_LO16);
12252           relax_end ();
12253           if (breg != 0)
12254             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12255                          tempreg, tempreg, breg);
12256           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12257         }
12258       else if (mips_big_got && !HAVE_NEWABI)
12259         {
12260           int gpdelay;
12261
12262           /* If this is a reference to an external symbol, we want
12263                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
12264                addu     $tempreg,$tempreg,$gp
12265                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
12266                <op>     op[0],0($tempreg)
12267              Otherwise we want
12268                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
12269                nop
12270                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
12271                <op>     op[0],0($tempreg)
12272              If there is a base register, we add it to $tempreg before
12273              the <op>.  If there is a constant, we stick it in the
12274              <op> instruction.  We don't handle constants larger than
12275              16 bits, because we have no way to load the upper 16 bits
12276              (actually, we could handle them for the subset of cases
12277              in which we are not using $at).  */
12278           gas_assert (offset_expr.X_op == O_symbol);
12279           expr1.X_add_number = offset_expr.X_add_number;
12280           offset_expr.X_add_number = 0;
12281           if (expr1.X_add_number < -0x8000
12282               || expr1.X_add_number >= 0x8000)
12283             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12284           gpdelay = reg_needs_delay (mips_gp_register);
12285           relax_start (offset_expr.X_add_symbol);
12286           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12287                        BFD_RELOC_MIPS_GOT_HI16);
12288           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
12289                        mips_gp_register);
12290           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12291                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
12292           relax_switch ();
12293           if (gpdelay)
12294             macro_build (NULL, "nop", "");
12295           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12296                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
12297           load_delay_nop ();
12298           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
12299                        tempreg, BFD_RELOC_LO16);
12300           relax_end ();
12301
12302           if (breg != 0)
12303             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12304                          tempreg, tempreg, breg);
12305           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12306         }
12307       else if (mips_big_got && HAVE_NEWABI)
12308         {
12309           /* If this is a reference to an external symbol, we want
12310                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
12311                add      $tempreg,$tempreg,$gp
12312                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
12313                <op>     op[0],<ofst>($tempreg)
12314              Otherwise, for local symbols, we want:
12315                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
12316                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
12317           gas_assert (offset_expr.X_op == O_symbol);
12318           expr1.X_add_number = offset_expr.X_add_number;
12319           offset_expr.X_add_number = 0;
12320           if (expr1.X_add_number < -0x8000
12321               || expr1.X_add_number >= 0x8000)
12322             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12323           relax_start (offset_expr.X_add_symbol);
12324           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
12325                        BFD_RELOC_MIPS_GOT_HI16);
12326           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
12327                        mips_gp_register);
12328           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12329                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
12330           if (breg != 0)
12331             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12332                          tempreg, tempreg, breg);
12333           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
12334
12335           relax_switch ();
12336           offset_expr.X_add_number = expr1.X_add_number;
12337           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
12338                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
12339           if (breg != 0)
12340             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12341                          tempreg, tempreg, breg);
12342           macro_build (&offset_expr, s, fmt, op[0],
12343                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
12344           relax_end ();
12345         }
12346       else
12347         abort ();
12348
12349       break;
12350
12351     case M_JRADDIUSP:
12352       gas_assert (mips_opts.micromips);
12353       gas_assert (mips_opts.insn32);
12354       start_noreorder ();
12355       macro_build (NULL, "jr", "s", RA);
12356       expr1.X_add_number = op[0] << 2;
12357       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
12358       end_noreorder ();
12359       break;
12360
12361     case M_JRC:
12362       gas_assert (mips_opts.micromips);
12363       gas_assert (mips_opts.insn32);
12364       macro_build (NULL, "jr", "s", op[0]);
12365       if (mips_opts.noreorder)
12366         macro_build (NULL, "nop", "");
12367       break;
12368
12369     case M_LI:
12370     case M_LI_S:
12371       load_register (op[0], &imm_expr, 0);
12372       break;
12373
12374     case M_DLI:
12375       load_register (op[0], &imm_expr, 1);
12376       break;
12377
12378     case M_LI_SS:
12379       if (imm_expr.X_op == O_constant)
12380         {
12381           used_at = 1;
12382           load_register (AT, &imm_expr, 0);
12383           macro_build (NULL, "mtc1", "t,G", AT, op[0]);
12384           break;
12385         }
12386       else
12387         {
12388           gas_assert (imm_expr.X_op == O_absent
12389                       && offset_expr.X_op == O_symbol
12390                       && strcmp (segment_name (S_GET_SEGMENT
12391                                                (offset_expr.X_add_symbol)),
12392                                  ".lit4") == 0
12393                       && offset_expr.X_add_number == 0);
12394           macro_build (&offset_expr, "lwc1", "T,o(b)", op[0],
12395                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
12396           break;
12397         }
12398
12399     case M_LI_D:
12400       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
12401          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
12402          order 32 bits of the value and the low order 32 bits are either
12403          zero or in OFFSET_EXPR.  */
12404       if (imm_expr.X_op == O_constant)
12405         {
12406           if (GPR_SIZE == 64)
12407             load_register (op[0], &imm_expr, 1);
12408           else
12409             {
12410               int hreg, lreg;
12411
12412               if (target_big_endian)
12413                 {
12414                   hreg = op[0];
12415                   lreg = op[0] + 1;
12416                 }
12417               else
12418                 {
12419                   hreg = op[0] + 1;
12420                   lreg = op[0];
12421                 }
12422
12423               if (hreg <= 31)
12424                 load_register (hreg, &imm_expr, 0);
12425               if (lreg <= 31)
12426                 {
12427                   if (offset_expr.X_op == O_absent)
12428                     move_register (lreg, 0);
12429                   else
12430                     {
12431                       gas_assert (offset_expr.X_op == O_constant);
12432                       load_register (lreg, &offset_expr, 0);
12433                     }
12434                 }
12435             }
12436           break;
12437         }
12438       gas_assert (imm_expr.X_op == O_absent);
12439
12440       /* We know that sym is in the .rdata section.  First we get the
12441          upper 16 bits of the address.  */
12442       if (mips_pic == NO_PIC)
12443         {
12444           macro_build_lui (&offset_expr, AT);
12445           used_at = 1;
12446         }
12447       else
12448         {
12449           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12450                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
12451           used_at = 1;
12452         }
12453
12454       /* Now we load the register(s).  */
12455       if (GPR_SIZE == 64)
12456         {
12457           used_at = 1;
12458           macro_build (&offset_expr, "ld", "t,o(b)", op[0],
12459                        BFD_RELOC_LO16, AT);
12460         }
12461       else
12462         {
12463           used_at = 1;
12464           macro_build (&offset_expr, "lw", "t,o(b)", op[0],
12465                        BFD_RELOC_LO16, AT);
12466           if (op[0] != RA)
12467             {
12468               /* FIXME: How in the world do we deal with the possible
12469                  overflow here?  */
12470               offset_expr.X_add_number += 4;
12471               macro_build (&offset_expr, "lw", "t,o(b)",
12472                            op[0] + 1, BFD_RELOC_LO16, AT);
12473             }
12474         }
12475       break;
12476
12477     case M_LI_DD:
12478       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
12479          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
12480          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
12481          the value and the low order 32 bits are either zero or in
12482          OFFSET_EXPR.  */
12483       if (imm_expr.X_op == O_constant)
12484         {
12485           used_at = 1;
12486           load_register (AT, &imm_expr, FPR_SIZE == 64);
12487           if (FPR_SIZE == 64 && GPR_SIZE == 64)
12488             macro_build (NULL, "dmtc1", "t,S", AT, op[0]);
12489           else
12490             {
12491               if (ISA_HAS_MXHC1 (mips_opts.isa))
12492                 macro_build (NULL, "mthc1", "t,G", AT, op[0]);
12493               else if (FPR_SIZE != 32)
12494                 as_bad (_("Unable to generate `%s' compliant code "
12495                           "without mthc1"),
12496                         (FPR_SIZE == 64) ? "fp64" : "fpxx");
12497               else
12498                 macro_build (NULL, "mtc1", "t,G", AT, op[0] + 1);
12499               if (offset_expr.X_op == O_absent)
12500                 macro_build (NULL, "mtc1", "t,G", 0, op[0]);
12501               else
12502                 {
12503                   gas_assert (offset_expr.X_op == O_constant);
12504                   load_register (AT, &offset_expr, 0);
12505                   macro_build (NULL, "mtc1", "t,G", AT, op[0]);
12506                 }
12507             }
12508           break;
12509         }
12510
12511       gas_assert (imm_expr.X_op == O_absent
12512                   && offset_expr.X_op == O_symbol
12513                   && offset_expr.X_add_number == 0);
12514       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
12515       if (strcmp (s, ".lit8") == 0)
12516         {
12517           op[2] = mips_gp_register;
12518           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
12519           offset_reloc[1] = BFD_RELOC_UNUSED;
12520           offset_reloc[2] = BFD_RELOC_UNUSED;
12521         }
12522       else
12523         {
12524           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
12525           used_at = 1;
12526           if (mips_pic != NO_PIC)
12527             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12528                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
12529           else
12530             {
12531               /* FIXME: This won't work for a 64 bit address.  */
12532               macro_build_lui (&offset_expr, AT);
12533             }
12534
12535           op[2] = AT;
12536           offset_reloc[0] = BFD_RELOC_LO16;
12537           offset_reloc[1] = BFD_RELOC_UNUSED;
12538           offset_reloc[2] = BFD_RELOC_UNUSED;
12539         }
12540       align = 8;
12541       /* Fall through */
12542
12543     case M_L_DAB:
12544       /*
12545        * The MIPS assembler seems to check for X_add_number not
12546        * being double aligned and generating:
12547        *        lui     at,%hi(foo+1)
12548        *        addu    at,at,v1
12549        *        addiu   at,at,%lo(foo+1)
12550        *        lwc1    f2,0(at)
12551        *        lwc1    f3,4(at)
12552        * But, the resulting address is the same after relocation so why
12553        * generate the extra instruction?
12554        */
12555       /* Itbl support may require additional care here.  */
12556       coproc = 1;
12557       fmt = "T,o(b)";
12558       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
12559         {
12560           s = "ldc1";
12561           goto ld_st;
12562         }
12563       s = "lwc1";
12564       goto ldd_std;
12565
12566     case M_S_DAB:
12567       gas_assert (!mips_opts.micromips);
12568       /* Itbl support may require additional care here.  */
12569       coproc = 1;
12570       fmt = "T,o(b)";
12571       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
12572         {
12573           s = "sdc1";
12574           goto ld_st;
12575         }
12576       s = "swc1";
12577       goto ldd_std;
12578
12579     case M_LQ_AB:
12580       fmt = "t,o(b)";
12581       s = "lq";
12582       goto ld;
12583
12584     case M_SQ_AB:
12585       fmt = "t,o(b)";
12586       s = "sq";
12587       goto ld_st;
12588
12589     case M_LD_AB:
12590       fmt = "t,o(b)";
12591       if (GPR_SIZE == 64)
12592         {
12593           s = "ld";
12594           goto ld;
12595         }
12596       s = "lw";
12597       goto ldd_std;
12598
12599     case M_SD_AB:
12600       fmt = "t,o(b)";
12601       if (GPR_SIZE == 64)
12602         {
12603           s = "sd";
12604           goto ld_st;
12605         }
12606       s = "sw";
12607
12608     ldd_std:
12609       /* Even on a big endian machine $fn comes before $fn+1.  We have
12610          to adjust when loading from memory.  We set coproc if we must
12611          load $fn+1 first.  */
12612       /* Itbl support may require additional care here.  */
12613       if (!target_big_endian)
12614         coproc = 0;
12615
12616       breg = op[2];
12617       if (small_offset_p (0, align, 16))
12618         {
12619           ep = &offset_expr;
12620           if (!small_offset_p (4, align, 16))
12621             {
12622               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
12623                            -1, offset_reloc[0], offset_reloc[1],
12624                            offset_reloc[2]);
12625               expr1.X_add_number = 0;
12626               ep = &expr1;
12627               breg = AT;
12628               used_at = 1;
12629               offset_reloc[0] = BFD_RELOC_LO16;
12630               offset_reloc[1] = BFD_RELOC_UNUSED;
12631               offset_reloc[2] = BFD_RELOC_UNUSED;
12632             }
12633           if (strcmp (s, "lw") == 0 && op[0] == breg)
12634             {
12635               ep->X_add_number += 4;
12636               macro_build (ep, s, fmt, op[0] + 1, -1, offset_reloc[0],
12637                            offset_reloc[1], offset_reloc[2], breg);
12638               ep->X_add_number -= 4;
12639               macro_build (ep, s, fmt, op[0], -1, offset_reloc[0],
12640                            offset_reloc[1], offset_reloc[2], breg);
12641             }
12642           else
12643             {
12644               macro_build (ep, s, fmt, coproc ? op[0] + 1 : op[0], -1,
12645                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
12646                            breg);
12647               ep->X_add_number += 4;
12648               macro_build (ep, s, fmt, coproc ? op[0] : op[0] + 1, -1,
12649                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
12650                            breg);
12651             }
12652           break;
12653         }
12654
12655       if (offset_expr.X_op != O_symbol
12656           && offset_expr.X_op != O_constant)
12657         {
12658           as_bad (_("expression too complex"));
12659           offset_expr.X_op = O_constant;
12660         }
12661
12662       if (HAVE_32BIT_ADDRESSES
12663           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
12664         {
12665           char value [32];
12666
12667           sprintf_vma (value, offset_expr.X_add_number);
12668           as_bad (_("number (0x%s) larger than 32 bits"), value);
12669         }
12670
12671       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
12672         {
12673           /* If this is a reference to a GP relative symbol, we want
12674                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
12675                <op>     op[0]+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
12676              If we have a base register, we use this
12677                addu     $at,$breg,$gp
12678                <op>     op[0],<sym>($at)        (BFD_RELOC_GPREL16)
12679                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
12680              If this is not a GP relative symbol, we want
12681                lui      $at,<sym>               (BFD_RELOC_HI16_S)
12682                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12683                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12684              If there is a base register, we add it to $at after the
12685              lui instruction.  If there is a constant, we always use
12686              the last case.  */
12687           if (offset_expr.X_op == O_symbol
12688               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12689               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12690             {
12691               relax_start (offset_expr.X_add_symbol);
12692               if (breg == 0)
12693                 {
12694                   tempreg = mips_gp_register;
12695                 }
12696               else
12697                 {
12698                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12699                                AT, breg, mips_gp_register);
12700                   tempreg = AT;
12701                   used_at = 1;
12702                 }
12703
12704               /* Itbl support may require additional care here.  */
12705               macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12706                            BFD_RELOC_GPREL16, tempreg);
12707               offset_expr.X_add_number += 4;
12708
12709               /* Set mips_optimize to 2 to avoid inserting an
12710                  undesired nop.  */
12711               hold_mips_optimize = mips_optimize;
12712               mips_optimize = 2;
12713               /* Itbl support may require additional care here.  */
12714               macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12715                            BFD_RELOC_GPREL16, tempreg);
12716               mips_optimize = hold_mips_optimize;
12717
12718               relax_switch ();
12719
12720               offset_expr.X_add_number -= 4;
12721             }
12722           used_at = 1;
12723           if (offset_high_part (offset_expr.X_add_number, 16)
12724               != offset_high_part (offset_expr.X_add_number + 4, 16))
12725             {
12726               load_address (AT, &offset_expr, &used_at);
12727               offset_expr.X_op = O_constant;
12728               offset_expr.X_add_number = 0;
12729             }
12730           else
12731             macro_build_lui (&offset_expr, AT);
12732           if (breg != 0)
12733             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12734           /* Itbl support may require additional care here.  */
12735           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12736                        BFD_RELOC_LO16, AT);
12737           /* FIXME: How do we handle overflow here?  */
12738           offset_expr.X_add_number += 4;
12739           /* Itbl support may require additional care here.  */
12740           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12741                        BFD_RELOC_LO16, AT);
12742           if (mips_relax.sequence)
12743             relax_end ();
12744         }
12745       else if (!mips_big_got)
12746         {
12747           /* If this is a reference to an external symbol, we want
12748                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12749                nop
12750                <op>     op[0],0($at)
12751                <op>     op[0]+1,4($at)
12752              Otherwise we want
12753                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12754                nop
12755                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12756                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12757              If there is a base register we add it to $at before the
12758              lwc1 instructions.  If there is a constant we include it
12759              in the lwc1 instructions.  */
12760           used_at = 1;
12761           expr1.X_add_number = offset_expr.X_add_number;
12762           if (expr1.X_add_number < -0x8000
12763               || expr1.X_add_number >= 0x8000 - 4)
12764             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12765           load_got_offset (AT, &offset_expr);
12766           load_delay_nop ();
12767           if (breg != 0)
12768             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12769
12770           /* Set mips_optimize to 2 to avoid inserting an undesired
12771              nop.  */
12772           hold_mips_optimize = mips_optimize;
12773           mips_optimize = 2;
12774
12775           /* Itbl support may require additional care here.  */
12776           relax_start (offset_expr.X_add_symbol);
12777           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
12778                        BFD_RELOC_LO16, AT);
12779           expr1.X_add_number += 4;
12780           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
12781                        BFD_RELOC_LO16, AT);
12782           relax_switch ();
12783           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12784                        BFD_RELOC_LO16, AT);
12785           offset_expr.X_add_number += 4;
12786           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12787                        BFD_RELOC_LO16, AT);
12788           relax_end ();
12789
12790           mips_optimize = hold_mips_optimize;
12791         }
12792       else if (mips_big_got)
12793         {
12794           int gpdelay;
12795
12796           /* If this is a reference to an external symbol, we want
12797                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
12798                addu     $at,$at,$gp
12799                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
12800                nop
12801                <op>     op[0],0($at)
12802                <op>     op[0]+1,4($at)
12803              Otherwise we want
12804                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12805                nop
12806                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12807                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12808              If there is a base register we add it to $at before the
12809              lwc1 instructions.  If there is a constant we include it
12810              in the lwc1 instructions.  */
12811           used_at = 1;
12812           expr1.X_add_number = offset_expr.X_add_number;
12813           offset_expr.X_add_number = 0;
12814           if (expr1.X_add_number < -0x8000
12815               || expr1.X_add_number >= 0x8000 - 4)
12816             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12817           gpdelay = reg_needs_delay (mips_gp_register);
12818           relax_start (offset_expr.X_add_symbol);
12819           macro_build (&offset_expr, "lui", LUI_FMT,
12820                        AT, BFD_RELOC_MIPS_GOT_HI16);
12821           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12822                        AT, AT, mips_gp_register);
12823           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
12824                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
12825           load_delay_nop ();
12826           if (breg != 0)
12827             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12828           /* Itbl support may require additional care here.  */
12829           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
12830                        BFD_RELOC_LO16, AT);
12831           expr1.X_add_number += 4;
12832
12833           /* Set mips_optimize to 2 to avoid inserting an undesired
12834              nop.  */
12835           hold_mips_optimize = mips_optimize;
12836           mips_optimize = 2;
12837           /* Itbl support may require additional care here.  */
12838           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
12839                        BFD_RELOC_LO16, AT);
12840           mips_optimize = hold_mips_optimize;
12841           expr1.X_add_number -= 4;
12842
12843           relax_switch ();
12844           offset_expr.X_add_number = expr1.X_add_number;
12845           if (gpdelay)
12846             macro_build (NULL, "nop", "");
12847           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12848                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
12849           load_delay_nop ();
12850           if (breg != 0)
12851             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12852           /* Itbl support may require additional care here.  */
12853           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12854                        BFD_RELOC_LO16, AT);
12855           offset_expr.X_add_number += 4;
12856
12857           /* Set mips_optimize to 2 to avoid inserting an undesired
12858              nop.  */
12859           hold_mips_optimize = mips_optimize;
12860           mips_optimize = 2;
12861           /* Itbl support may require additional care here.  */
12862           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12863                        BFD_RELOC_LO16, AT);
12864           mips_optimize = hold_mips_optimize;
12865           relax_end ();
12866         }
12867       else
12868         abort ();
12869
12870       break;
12871
12872     case M_SAA_AB:
12873       s = "saa";
12874       goto saa_saad;
12875     case M_SAAD_AB:
12876       s = "saad";
12877     saa_saad:
12878       gas_assert (!mips_opts.micromips);
12879       offbits = 0;
12880       fmt = "t,(b)";
12881       goto ld_st;
12882
12883    /* New code added to support COPZ instructions.
12884       This code builds table entries out of the macros in mip_opcodes.
12885       R4000 uses interlocks to handle coproc delays.
12886       Other chips (like the R3000) require nops to be inserted for delays.
12887
12888       FIXME: Currently, we require that the user handle delays.
12889       In order to fill delay slots for non-interlocked chips,
12890       we must have a way to specify delays based on the coprocessor.
12891       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
12892       What are the side-effects of the cop instruction?
12893       What cache support might we have and what are its effects?
12894       Both coprocessor & memory require delays. how long???
12895       What registers are read/set/modified?
12896
12897       If an itbl is provided to interpret cop instructions,
12898       this knowledge can be encoded in the itbl spec.  */
12899
12900     case M_COP0:
12901       s = "c0";
12902       goto copz;
12903     case M_COP1:
12904       s = "c1";
12905       goto copz;
12906     case M_COP2:
12907       s = "c2";
12908       goto copz;
12909     case M_COP3:
12910       s = "c3";
12911     copz:
12912       gas_assert (!mips_opts.micromips);
12913       /* For now we just do C (same as Cz).  The parameter will be
12914          stored in insn_opcode by mips_ip.  */
12915       macro_build (NULL, s, "C", (int) ip->insn_opcode);
12916       break;
12917
12918     case M_MOVE:
12919       move_register (op[0], op[1]);
12920       break;
12921
12922     case M_MOVEP:
12923       gas_assert (mips_opts.micromips);
12924       gas_assert (mips_opts.insn32);
12925       move_register (micromips_to_32_reg_h_map1[op[0]],
12926                      micromips_to_32_reg_m_map[op[1]]);
12927       move_register (micromips_to_32_reg_h_map2[op[0]],
12928                      micromips_to_32_reg_n_map[op[2]]);
12929       break;
12930
12931     case M_DMUL:
12932       dbl = 1;
12933       /* Fall through.  */
12934     case M_MUL:
12935       if (mips_opts.arch == CPU_R5900)
12936         macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", op[0], op[1],
12937                      op[2]);
12938       else
12939         {
12940           macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", op[1], op[2]);
12941           macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12942         }
12943       break;
12944
12945     case M_DMUL_I:
12946       dbl = 1;
12947       /* Fall through.  */
12948     case M_MUL_I:
12949       /* The MIPS assembler some times generates shifts and adds.  I'm
12950          not trying to be that fancy. GCC should do this for us
12951          anyway.  */
12952       used_at = 1;
12953       load_register (AT, &imm_expr, dbl);
12954       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", op[1], AT);
12955       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12956       break;
12957
12958     case M_DMULO_I:
12959       dbl = 1;
12960       /* Fall through.  */
12961     case M_MULO_I:
12962       imm = 1;
12963       goto do_mulo;
12964
12965     case M_DMULO:
12966       dbl = 1;
12967       /* Fall through.  */
12968     case M_MULO:
12969     do_mulo:
12970       start_noreorder ();
12971       used_at = 1;
12972       if (imm)
12973         load_register (AT, &imm_expr, dbl);
12974       macro_build (NULL, dbl ? "dmult" : "mult", "s,t",
12975                    op[1], imm ? AT : op[2]);
12976       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12977       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, op[0], op[0], 31);
12978       macro_build (NULL, "mfhi", MFHL_FMT, AT);
12979       if (mips_trap)
12980         macro_build (NULL, "tne", TRAP_FMT, op[0], AT, 6);
12981       else
12982         {
12983           if (mips_opts.micromips)
12984             micromips_label_expr (&label_expr);
12985           else
12986             label_expr.X_add_number = 8;
12987           macro_build (&label_expr, "beq", "s,t,p", op[0], AT);
12988           macro_build (NULL, "nop", "");
12989           macro_build (NULL, "break", BRK_FMT, 6);
12990           if (mips_opts.micromips)
12991             micromips_add_label ();
12992         }
12993       end_noreorder ();
12994       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12995       break;
12996
12997     case M_DMULOU_I:
12998       dbl = 1;
12999       /* Fall through.  */
13000     case M_MULOU_I:
13001       imm = 1;
13002       goto do_mulou;
13003
13004     case M_DMULOU:
13005       dbl = 1;
13006       /* Fall through.  */
13007     case M_MULOU:
13008     do_mulou:
13009       start_noreorder ();
13010       used_at = 1;
13011       if (imm)
13012         load_register (AT, &imm_expr, dbl);
13013       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
13014                    op[1], imm ? AT : op[2]);
13015       macro_build (NULL, "mfhi", MFHL_FMT, AT);
13016       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
13017       if (mips_trap)
13018         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
13019       else
13020         {
13021           if (mips_opts.micromips)
13022             micromips_label_expr (&label_expr);
13023           else
13024             label_expr.X_add_number = 8;
13025           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
13026           macro_build (NULL, "nop", "");
13027           macro_build (NULL, "break", BRK_FMT, 6);
13028           if (mips_opts.micromips)
13029             micromips_add_label ();
13030         }
13031       end_noreorder ();
13032       break;
13033
13034     case M_DROL:
13035       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
13036         {
13037           if (op[0] == op[1])
13038             {
13039               tempreg = AT;
13040               used_at = 1;
13041             }
13042           else
13043             tempreg = op[0];
13044           macro_build (NULL, "dnegu", "d,w", tempreg, op[2]);
13045           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], tempreg);
13046           break;
13047         }
13048       used_at = 1;
13049       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
13050       macro_build (NULL, "dsrlv", "d,t,s", AT, op[1], AT);
13051       macro_build (NULL, "dsllv", "d,t,s", op[0], op[1], op[2]);
13052       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13053       break;
13054
13055     case M_ROL:
13056       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
13057         {
13058           if (op[0] == op[1])
13059             {
13060               tempreg = AT;
13061               used_at = 1;
13062             }
13063           else
13064             tempreg = op[0];
13065           macro_build (NULL, "negu", "d,w", tempreg, op[2]);
13066           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], tempreg);
13067           break;
13068         }
13069       used_at = 1;
13070       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
13071       macro_build (NULL, "srlv", "d,t,s", AT, op[1], AT);
13072       macro_build (NULL, "sllv", "d,t,s", op[0], op[1], op[2]);
13073       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13074       break;
13075
13076     case M_DROL_I:
13077       {
13078         unsigned int rot;
13079         const char *l;
13080         const char *rr;
13081
13082         rot = imm_expr.X_add_number & 0x3f;
13083         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
13084           {
13085             rot = (64 - rot) & 0x3f;
13086             if (rot >= 32)
13087               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
13088             else
13089               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
13090             break;
13091           }
13092         if (rot == 0)
13093           {
13094             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
13095             break;
13096           }
13097         l = (rot < 0x20) ? "dsll" : "dsll32";
13098         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
13099         rot &= 0x1f;
13100         used_at = 1;
13101         macro_build (NULL, l, SHFT_FMT, AT, op[1], rot);
13102         macro_build (NULL, rr, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13103         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13104       }
13105       break;
13106
13107     case M_ROL_I:
13108       {
13109         unsigned int rot;
13110
13111         rot = imm_expr.X_add_number & 0x1f;
13112         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
13113           {
13114             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1],
13115                          (32 - rot) & 0x1f);
13116             break;
13117           }
13118         if (rot == 0)
13119           {
13120             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
13121             break;
13122           }
13123         used_at = 1;
13124         macro_build (NULL, "sll", SHFT_FMT, AT, op[1], rot);
13125         macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13126         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13127       }
13128       break;
13129
13130     case M_DROR:
13131       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
13132         {
13133           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], op[2]);
13134           break;
13135         }
13136       used_at = 1;
13137       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
13138       macro_build (NULL, "dsllv", "d,t,s", AT, op[1], AT);
13139       macro_build (NULL, "dsrlv", "d,t,s", op[0], op[1], op[2]);
13140       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13141       break;
13142
13143     case M_ROR:
13144       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
13145         {
13146           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], op[2]);
13147           break;
13148         }
13149       used_at = 1;
13150       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
13151       macro_build (NULL, "sllv", "d,t,s", AT, op[1], AT);
13152       macro_build (NULL, "srlv", "d,t,s", op[0], op[1], op[2]);
13153       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13154       break;
13155
13156     case M_DROR_I:
13157       {
13158         unsigned int rot;
13159         const char *l;
13160         const char *rr;
13161
13162         rot = imm_expr.X_add_number & 0x3f;
13163         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
13164           {
13165             if (rot >= 32)
13166               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
13167             else
13168               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
13169             break;
13170           }
13171         if (rot == 0)
13172           {
13173             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
13174             break;
13175           }
13176         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
13177         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
13178         rot &= 0x1f;
13179         used_at = 1;
13180         macro_build (NULL, rr, SHFT_FMT, AT, op[1], rot);
13181         macro_build (NULL, l, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13182         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13183       }
13184       break;
13185
13186     case M_ROR_I:
13187       {
13188         unsigned int rot;
13189
13190         rot = imm_expr.X_add_number & 0x1f;
13191         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
13192           {
13193             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1], rot);
13194             break;
13195           }
13196         if (rot == 0)
13197           {
13198             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
13199             break;
13200           }
13201         used_at = 1;
13202         macro_build (NULL, "srl", SHFT_FMT, AT, op[1], rot);
13203         macro_build (NULL, "sll", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
13204         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13205       }
13206       break;
13207
13208     case M_SEQ:
13209       if (op[1] == 0)
13210         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[2], BFD_RELOC_LO16);
13211       else if (op[2] == 0)
13212         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13213       else
13214         {
13215           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
13216           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
13217         }
13218       break;
13219
13220     case M_SEQ_I:
13221       if (imm_expr.X_add_number == 0)
13222         {
13223           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13224           break;
13225         }
13226       if (op[1] == 0)
13227         {
13228           as_warn (_("instruction %s: result is always false"),
13229                    ip->insn_mo->name);
13230           move_register (op[0], 0);
13231           break;
13232         }
13233       if (CPU_HAS_SEQ (mips_opts.arch)
13234           && -512 <= imm_expr.X_add_number
13235           && imm_expr.X_add_number < 512)
13236         {
13237           macro_build (NULL, "seqi", "t,r,+Q", op[0], op[1],
13238                        (int) imm_expr.X_add_number);
13239           break;
13240         }
13241       if (imm_expr.X_add_number >= 0
13242           && imm_expr.X_add_number < 0x10000)
13243         macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1], BFD_RELOC_LO16);
13244       else if (imm_expr.X_add_number > -0x8000
13245                && imm_expr.X_add_number < 0)
13246         {
13247           imm_expr.X_add_number = -imm_expr.X_add_number;
13248           macro_build (&imm_expr, GPR_SIZE == 32 ? "addiu" : "daddiu",
13249                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13250         }
13251       else if (CPU_HAS_SEQ (mips_opts.arch))
13252         {
13253           used_at = 1;
13254           load_register (AT, &imm_expr, GPR_SIZE == 64);
13255           macro_build (NULL, "seq", "d,v,t", op[0], op[1], AT);
13256           break;
13257         }
13258       else
13259         {
13260           load_register (AT, &imm_expr, GPR_SIZE == 64);
13261           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
13262           used_at = 1;
13263         }
13264       macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
13265       break;
13266
13267     case M_SGE:         /* X >= Y  <==>  not (X < Y) */
13268       s = "slt";
13269       goto sge;
13270     case M_SGEU:
13271       s = "sltu";
13272     sge:
13273       macro_build (NULL, s, "d,v,t", op[0], op[1], op[2]);
13274       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13275       break;
13276
13277     case M_SGE_I:       /* X >= I  <==>  not (X < I) */
13278     case M_SGEU_I:
13279       if (imm_expr.X_add_number >= -0x8000
13280           && imm_expr.X_add_number < 0x8000)
13281         macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
13282                      op[0], op[1], BFD_RELOC_LO16);
13283       else
13284         {
13285           load_register (AT, &imm_expr, GPR_SIZE == 64);
13286           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
13287                        op[0], op[1], AT);
13288           used_at = 1;
13289         }
13290       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13291       break;
13292
13293     case M_SGT:         /* X > Y  <==>  Y < X */
13294       s = "slt";
13295       goto sgt;
13296     case M_SGTU:
13297       s = "sltu";
13298     sgt:
13299       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
13300       break;
13301
13302     case M_SGT_I:       /* X > I  <==>  I < X */
13303       s = "slt";
13304       goto sgti;
13305     case M_SGTU_I:
13306       s = "sltu";
13307     sgti:
13308       used_at = 1;
13309       load_register (AT, &imm_expr, GPR_SIZE == 64);
13310       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
13311       break;
13312
13313     case M_SLE:         /* X <= Y  <==>  Y >= X  <==>  not (Y < X) */
13314       s = "slt";
13315       goto sle;
13316     case M_SLEU:
13317       s = "sltu";
13318     sle:
13319       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
13320       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13321       break;
13322
13323     case M_SLE_I:       /* X <= I  <==>  I >= X  <==>  not (I < X) */
13324       s = "slt";
13325       goto slei;
13326     case M_SLEU_I:
13327       s = "sltu";
13328     slei:
13329       used_at = 1;
13330       load_register (AT, &imm_expr, GPR_SIZE == 64);
13331       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
13332       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
13333       break;
13334
13335     case M_SLT_I:
13336       if (imm_expr.X_add_number >= -0x8000
13337           && imm_expr.X_add_number < 0x8000)
13338         {
13339           macro_build (&imm_expr, "slti", "t,r,j", op[0], op[1],
13340                        BFD_RELOC_LO16);
13341           break;
13342         }
13343       used_at = 1;
13344       load_register (AT, &imm_expr, GPR_SIZE == 64);
13345       macro_build (NULL, "slt", "d,v,t", op[0], op[1], AT);
13346       break;
13347
13348     case M_SLTU_I:
13349       if (imm_expr.X_add_number >= -0x8000
13350           && imm_expr.X_add_number < 0x8000)
13351         {
13352           macro_build (&imm_expr, "sltiu", "t,r,j", op[0], op[1],
13353                        BFD_RELOC_LO16);
13354           break;
13355         }
13356       used_at = 1;
13357       load_register (AT, &imm_expr, GPR_SIZE == 64);
13358       macro_build (NULL, "sltu", "d,v,t", op[0], op[1], AT);
13359       break;
13360
13361     case M_SNE:
13362       if (op[1] == 0)
13363         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[2]);
13364       else if (op[2] == 0)
13365         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
13366       else
13367         {
13368           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
13369           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
13370         }
13371       break;
13372
13373     case M_SNE_I:
13374       if (imm_expr.X_add_number == 0)
13375         {
13376           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
13377           break;
13378         }
13379       if (op[1] == 0)
13380         {
13381           as_warn (_("instruction %s: result is always true"),
13382                    ip->insn_mo->name);
13383           macro_build (&expr1, GPR_SIZE == 32 ? "addiu" : "daddiu", "t,r,j",
13384                        op[0], 0, BFD_RELOC_LO16);
13385           break;
13386         }
13387       if (CPU_HAS_SEQ (mips_opts.arch)
13388           && -512 <= imm_expr.X_add_number
13389           && imm_expr.X_add_number < 512)
13390         {
13391           macro_build (NULL, "snei", "t,r,+Q", op[0], op[1],
13392                        (int) imm_expr.X_add_number);
13393           break;
13394         }
13395       if (imm_expr.X_add_number >= 0
13396           && imm_expr.X_add_number < 0x10000)
13397         {
13398           macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1],
13399                        BFD_RELOC_LO16);
13400         }
13401       else if (imm_expr.X_add_number > -0x8000
13402                && imm_expr.X_add_number < 0)
13403         {
13404           imm_expr.X_add_number = -imm_expr.X_add_number;
13405           macro_build (&imm_expr, GPR_SIZE == 32 ? "addiu" : "daddiu",
13406                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13407         }
13408       else if (CPU_HAS_SEQ (mips_opts.arch))
13409         {
13410           used_at = 1;
13411           load_register (AT, &imm_expr, GPR_SIZE == 64);
13412           macro_build (NULL, "sne", "d,v,t", op[0], op[1], AT);
13413           break;
13414         }
13415       else
13416         {
13417           load_register (AT, &imm_expr, GPR_SIZE == 64);
13418           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
13419           used_at = 1;
13420         }
13421       macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
13422       break;
13423
13424     case M_SUB_I:
13425       s = "addi";
13426       s2 = "sub";
13427       goto do_subi;
13428     case M_SUBU_I:
13429       s = "addiu";
13430       s2 = "subu";
13431       goto do_subi;
13432     case M_DSUB_I:
13433       dbl = 1;
13434       s = "daddi";
13435       s2 = "dsub";
13436       if (!mips_opts.micromips)
13437         goto do_subi;
13438       if (imm_expr.X_add_number > -0x200
13439           && imm_expr.X_add_number <= 0x200)
13440         {
13441           macro_build (NULL, s, "t,r,.", op[0], op[1],
13442                        (int) -imm_expr.X_add_number);
13443           break;
13444         }
13445       goto do_subi_i;
13446     case M_DSUBU_I:
13447       dbl = 1;
13448       s = "daddiu";
13449       s2 = "dsubu";
13450     do_subi:
13451       if (imm_expr.X_add_number > -0x8000
13452           && imm_expr.X_add_number <= 0x8000)
13453         {
13454           imm_expr.X_add_number = -imm_expr.X_add_number;
13455           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13456           break;
13457         }
13458     do_subi_i:
13459       used_at = 1;
13460       load_register (AT, &imm_expr, dbl);
13461       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
13462       break;
13463
13464     case M_TEQ_I:
13465       s = "teq";
13466       goto trap;
13467     case M_TGE_I:
13468       s = "tge";
13469       goto trap;
13470     case M_TGEU_I:
13471       s = "tgeu";
13472       goto trap;
13473     case M_TLT_I:
13474       s = "tlt";
13475       goto trap;
13476     case M_TLTU_I:
13477       s = "tltu";
13478       goto trap;
13479     case M_TNE_I:
13480       s = "tne";
13481     trap:
13482       used_at = 1;
13483       load_register (AT, &imm_expr, GPR_SIZE == 64);
13484       macro_build (NULL, s, "s,t", op[0], AT);
13485       break;
13486
13487     case M_TRUNCWS:
13488     case M_TRUNCWD:
13489       gas_assert (!mips_opts.micromips);
13490       gas_assert (mips_opts.isa == ISA_MIPS1);
13491       used_at = 1;
13492
13493       /*
13494        * Is the double cfc1 instruction a bug in the mips assembler;
13495        * or is there a reason for it?
13496        */
13497       start_noreorder ();
13498       macro_build (NULL, "cfc1", "t,G", op[2], RA);
13499       macro_build (NULL, "cfc1", "t,G", op[2], RA);
13500       macro_build (NULL, "nop", "");
13501       expr1.X_add_number = 3;
13502       macro_build (&expr1, "ori", "t,r,i", AT, op[2], BFD_RELOC_LO16);
13503       expr1.X_add_number = 2;
13504       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
13505       macro_build (NULL, "ctc1", "t,G", AT, RA);
13506       macro_build (NULL, "nop", "");
13507       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
13508                    op[0], op[1]);
13509       macro_build (NULL, "ctc1", "t,G", op[2], RA);
13510       macro_build (NULL, "nop", "");
13511       end_noreorder ();
13512       break;
13513
13514     case M_ULH_AB:
13515       s = "lb";
13516       s2 = "lbu";
13517       off = 1;
13518       goto uld_st;
13519     case M_ULHU_AB:
13520       s = "lbu";
13521       s2 = "lbu";
13522       off = 1;
13523       goto uld_st;
13524     case M_ULW_AB:
13525       s = "lwl";
13526       s2 = "lwr";
13527       offbits = (mips_opts.micromips ? 12 : 16);
13528       off = 3;
13529       goto uld_st;
13530     case M_ULD_AB:
13531       s = "ldl";
13532       s2 = "ldr";
13533       offbits = (mips_opts.micromips ? 12 : 16);
13534       off = 7;
13535       goto uld_st;
13536     case M_USH_AB:
13537       s = "sb";
13538       s2 = "sb";
13539       off = 1;
13540       ust = 1;
13541       goto uld_st;
13542     case M_USW_AB:
13543       s = "swl";
13544       s2 = "swr";
13545       offbits = (mips_opts.micromips ? 12 : 16);
13546       off = 3;
13547       ust = 1;
13548       goto uld_st;
13549     case M_USD_AB:
13550       s = "sdl";
13551       s2 = "sdr";
13552       offbits = (mips_opts.micromips ? 12 : 16);
13553       off = 7;
13554       ust = 1;
13555
13556     uld_st:
13557       breg = op[2];
13558       large_offset = !small_offset_p (off, align, offbits);
13559       ep = &offset_expr;
13560       expr1.X_add_number = 0;
13561       if (large_offset)
13562         {
13563           used_at = 1;
13564           tempreg = AT;
13565           if (small_offset_p (0, align, 16))
13566             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
13567                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
13568           else
13569             {
13570               load_address (tempreg, ep, &used_at);
13571               if (breg != 0)
13572                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
13573                              tempreg, tempreg, breg);
13574             }
13575           offset_reloc[0] = BFD_RELOC_LO16;
13576           offset_reloc[1] = BFD_RELOC_UNUSED;
13577           offset_reloc[2] = BFD_RELOC_UNUSED;
13578           breg = tempreg;
13579           tempreg = op[0];
13580           ep = &expr1;
13581         }
13582       else if (!ust && op[0] == breg)
13583         {
13584           used_at = 1;
13585           tempreg = AT;
13586         }
13587       else
13588         tempreg = op[0];
13589
13590       if (off == 1)
13591         goto ulh_sh;
13592
13593       if (!target_big_endian)
13594         ep->X_add_number += off;
13595       if (offbits == 12)
13596         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
13597       else
13598         macro_build (ep, s, "t,o(b)", tempreg, -1,
13599                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13600
13601       if (!target_big_endian)
13602         ep->X_add_number -= off;
13603       else
13604         ep->X_add_number += off;
13605       if (offbits == 12)
13606         macro_build (NULL, s2, "t,~(b)",
13607                      tempreg, (int) ep->X_add_number, breg);
13608       else
13609         macro_build (ep, s2, "t,o(b)", tempreg, -1,
13610                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13611
13612       /* If necessary, move the result in tempreg to the final destination.  */
13613       if (!ust && op[0] != tempreg)
13614         {
13615           /* Protect second load's delay slot.  */
13616           load_delay_nop ();
13617           move_register (op[0], tempreg);
13618         }
13619       break;
13620
13621     ulh_sh:
13622       used_at = 1;
13623       if (target_big_endian == ust)
13624         ep->X_add_number += off;
13625       tempreg = ust || large_offset ? op[0] : AT;
13626       macro_build (ep, s, "t,o(b)", tempreg, -1,
13627                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13628
13629       /* For halfword transfers we need a temporary register to shuffle
13630          bytes.  Unfortunately for M_USH_A we have none available before
13631          the next store as AT holds the base address.  We deal with this
13632          case by clobbering TREG and then restoring it as with ULH.  */
13633       tempreg = ust == large_offset ? op[0] : AT;
13634       if (ust)
13635         macro_build (NULL, "srl", SHFT_FMT, tempreg, op[0], 8);
13636
13637       if (target_big_endian == ust)
13638         ep->X_add_number -= off;
13639       else
13640         ep->X_add_number += off;
13641       macro_build (ep, s2, "t,o(b)", tempreg, -1,
13642                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13643
13644       /* For M_USH_A re-retrieve the LSB.  */
13645       if (ust && large_offset)
13646         {
13647           if (target_big_endian)
13648             ep->X_add_number += off;
13649           else
13650             ep->X_add_number -= off;
13651           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
13652                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
13653         }
13654       /* For ULH and M_USH_A OR the LSB in.  */
13655       if (!ust || large_offset)
13656         {
13657           tempreg = !large_offset ? AT : op[0];
13658           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
13659           macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13660         }
13661       break;
13662
13663     default:
13664       /* FIXME: Check if this is one of the itbl macros, since they
13665          are added dynamically.  */
13666       as_bad (_("macro %s not implemented yet"), ip->insn_mo->name);
13667       break;
13668     }
13669   if (!mips_opts.at && used_at)
13670     as_bad (_("macro used $at after \".set noat\""));
13671 }
13672
13673 /* Implement macros in mips16 mode.  */
13674
13675 static void
13676 mips16_macro (struct mips_cl_insn *ip)
13677 {
13678   const struct mips_operand_array *operands;
13679   int mask;
13680   int tmp;
13681   expressionS expr1;
13682   int dbl;
13683   const char *s, *s2, *s3;
13684   unsigned int op[MAX_OPERANDS];
13685   unsigned int i;
13686
13687   mask = ip->insn_mo->mask;
13688
13689   operands = insn_operands (ip);
13690   for (i = 0; i < MAX_OPERANDS; i++)
13691     if (operands->operand[i])
13692       op[i] = insn_extract_operand (ip, operands->operand[i]);
13693     else
13694       op[i] = -1;
13695
13696   expr1.X_op = O_constant;
13697   expr1.X_op_symbol = NULL;
13698   expr1.X_add_symbol = NULL;
13699   expr1.X_add_number = 1;
13700
13701   dbl = 0;
13702
13703   switch (mask)
13704     {
13705     default:
13706       abort ();
13707
13708     case M_DDIV_3:
13709       dbl = 1;
13710       /* Fall through.  */
13711     case M_DIV_3:
13712       s = "mflo";
13713       goto do_div3;
13714     case M_DREM_3:
13715       dbl = 1;
13716       /* Fall through.  */
13717     case M_REM_3:
13718       s = "mfhi";
13719     do_div3:
13720       start_noreorder ();
13721       macro_build (NULL, dbl ? "ddiv" : "div", ".,x,y", op[1], op[2]);
13722       expr1.X_add_number = 2;
13723       macro_build (&expr1, "bnez", "x,p", op[2]);
13724       macro_build (NULL, "break", "6", 7);
13725
13726       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
13727          since that causes an overflow.  We should do that as well,
13728          but I don't see how to do the comparisons without a temporary
13729          register.  */
13730       end_noreorder ();
13731       macro_build (NULL, s, "x", op[0]);
13732       break;
13733
13734     case M_DIVU_3:
13735       s = "divu";
13736       s2 = "mflo";
13737       goto do_divu3;
13738     case M_REMU_3:
13739       s = "divu";
13740       s2 = "mfhi";
13741       goto do_divu3;
13742     case M_DDIVU_3:
13743       s = "ddivu";
13744       s2 = "mflo";
13745       goto do_divu3;
13746     case M_DREMU_3:
13747       s = "ddivu";
13748       s2 = "mfhi";
13749     do_divu3:
13750       start_noreorder ();
13751       macro_build (NULL, s, ".,x,y", op[1], op[2]);
13752       expr1.X_add_number = 2;
13753       macro_build (&expr1, "bnez", "x,p", op[2]);
13754       macro_build (NULL, "break", "6", 7);
13755       end_noreorder ();
13756       macro_build (NULL, s2, "x", op[0]);
13757       break;
13758
13759     case M_DMUL:
13760       dbl = 1;
13761       /* Fall through.  */
13762     case M_MUL:
13763       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", op[1], op[2]);
13764       macro_build (NULL, "mflo", "x", op[0]);
13765       break;
13766
13767     case M_DSUBU_I:
13768       dbl = 1;
13769       goto do_subu;
13770     case M_SUBU_I:
13771     do_subu:
13772       imm_expr.X_add_number = -imm_expr.X_add_number;
13773       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,F", op[0], op[1]);
13774       break;
13775
13776     case M_SUBU_I_2:
13777       imm_expr.X_add_number = -imm_expr.X_add_number;
13778       macro_build (&imm_expr, "addiu", "x,k", op[0]);
13779       break;
13780
13781     case M_DSUBU_I_2:
13782       imm_expr.X_add_number = -imm_expr.X_add_number;
13783       macro_build (&imm_expr, "daddiu", "y,j", op[0]);
13784       break;
13785
13786     case M_BEQ:
13787       s = "cmp";
13788       s2 = "bteqz";
13789       goto do_branch;
13790     case M_BNE:
13791       s = "cmp";
13792       s2 = "btnez";
13793       goto do_branch;
13794     case M_BLT:
13795       s = "slt";
13796       s2 = "btnez";
13797       goto do_branch;
13798     case M_BLTU:
13799       s = "sltu";
13800       s2 = "btnez";
13801       goto do_branch;
13802     case M_BLE:
13803       s = "slt";
13804       s2 = "bteqz";
13805       goto do_reverse_branch;
13806     case M_BLEU:
13807       s = "sltu";
13808       s2 = "bteqz";
13809       goto do_reverse_branch;
13810     case M_BGE:
13811       s = "slt";
13812       s2 = "bteqz";
13813       goto do_branch;
13814     case M_BGEU:
13815       s = "sltu";
13816       s2 = "bteqz";
13817       goto do_branch;
13818     case M_BGT:
13819       s = "slt";
13820       s2 = "btnez";
13821       goto do_reverse_branch;
13822     case M_BGTU:
13823       s = "sltu";
13824       s2 = "btnez";
13825
13826     do_reverse_branch:
13827       tmp = op[1];
13828       op[1] = op[0];
13829       op[0] = tmp;
13830
13831     do_branch:
13832       macro_build (NULL, s, "x,y", op[0], op[1]);
13833       macro_build (&offset_expr, s2, "p");
13834       break;
13835
13836     case M_BEQ_I:
13837       s = "cmpi";
13838       s2 = "bteqz";
13839       s3 = "x,U";
13840       goto do_branch_i;
13841     case M_BNE_I:
13842       s = "cmpi";
13843       s2 = "btnez";
13844       s3 = "x,U";
13845       goto do_branch_i;
13846     case M_BLT_I:
13847       s = "slti";
13848       s2 = "btnez";
13849       s3 = "x,8";
13850       goto do_branch_i;
13851     case M_BLTU_I:
13852       s = "sltiu";
13853       s2 = "btnez";
13854       s3 = "x,8";
13855       goto do_branch_i;
13856     case M_BLE_I:
13857       s = "slti";
13858       s2 = "btnez";
13859       s3 = "x,8";
13860       goto do_addone_branch_i;
13861     case M_BLEU_I:
13862       s = "sltiu";
13863       s2 = "btnez";
13864       s3 = "x,8";
13865       goto do_addone_branch_i;
13866     case M_BGE_I:
13867       s = "slti";
13868       s2 = "bteqz";
13869       s3 = "x,8";
13870       goto do_branch_i;
13871     case M_BGEU_I:
13872       s = "sltiu";
13873       s2 = "bteqz";
13874       s3 = "x,8";
13875       goto do_branch_i;
13876     case M_BGT_I:
13877       s = "slti";
13878       s2 = "bteqz";
13879       s3 = "x,8";
13880       goto do_addone_branch_i;
13881     case M_BGTU_I:
13882       s = "sltiu";
13883       s2 = "bteqz";
13884       s3 = "x,8";
13885
13886     do_addone_branch_i:
13887       ++imm_expr.X_add_number;
13888
13889     do_branch_i:
13890       macro_build (&imm_expr, s, s3, op[0]);
13891       macro_build (&offset_expr, s2, "p");
13892       break;
13893
13894     case M_ABS:
13895       expr1.X_add_number = 0;
13896       macro_build (&expr1, "slti", "x,8", op[1]);
13897       if (op[0] != op[1])
13898         macro_build (NULL, "move", "y,X", op[0], mips16_to_32_reg_map[op[1]]);
13899       expr1.X_add_number = 2;
13900       macro_build (&expr1, "bteqz", "p");
13901       macro_build (NULL, "neg", "x,w", op[0], op[0]);
13902       break;
13903     }
13904 }
13905
13906 /* Look up instruction [START, START + LENGTH) in HASH.  Record any extra
13907    opcode bits in *OPCODE_EXTRA.  */
13908
13909 static struct mips_opcode *
13910 mips_lookup_insn (struct hash_control *hash, const char *start,
13911                   ssize_t length, unsigned int *opcode_extra)
13912 {
13913   char *name, *dot, *p;
13914   unsigned int mask, suffix;
13915   ssize_t opend;
13916   struct mips_opcode *insn;
13917
13918   /* Make a copy of the instruction so that we can fiddle with it.  */
13919   name = xstrndup (start, length);
13920
13921   /* Look up the instruction as-is.  */
13922   insn = (struct mips_opcode *) hash_find (hash, name);
13923   if (insn)
13924     goto end;
13925
13926   dot = strchr (name, '.');
13927   if (dot && dot[1])
13928     {
13929       /* Try to interpret the text after the dot as a VU0 channel suffix.  */
13930       p = mips_parse_vu0_channels (dot + 1, &mask);
13931       if (*p == 0 && mask != 0)
13932         {
13933           *dot = 0;
13934           insn = (struct mips_opcode *) hash_find (hash, name);
13935           *dot = '.';
13936           if (insn && (insn->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0)
13937             {
13938               *opcode_extra |= mask << mips_vu0_channel_mask.lsb;
13939               goto end;
13940             }
13941         }
13942     }
13943
13944   if (mips_opts.micromips)
13945     {
13946       /* See if there's an instruction size override suffix,
13947          either `16' or `32', at the end of the mnemonic proper,
13948          that defines the operation, i.e. before the first `.'
13949          character if any.  Strip it and retry.  */
13950       opend = dot != NULL ? dot - name : length;
13951       if (opend >= 3 && name[opend - 2] == '1' && name[opend - 1] == '6')
13952         suffix = 2;
13953       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
13954         suffix = 4;
13955       else
13956         suffix = 0;
13957       if (suffix)
13958         {
13959           memcpy (name + opend - 2, name + opend, length - opend + 1);
13960           insn = (struct mips_opcode *) hash_find (hash, name);
13961           if (insn)
13962             {
13963               forced_insn_length = suffix;
13964               goto end;
13965             }
13966         }
13967     }
13968
13969   insn = NULL;
13970  end:
13971   free (name);
13972   return insn;
13973 }
13974
13975 /* Assemble an instruction into its binary format.  If the instruction
13976    is a macro, set imm_expr and offset_expr to the values associated
13977    with "I" and "A" operands respectively.  Otherwise store the value
13978    of the relocatable field (if any) in offset_expr.  In both cases
13979    set offset_reloc to the relocation operators applied to offset_expr.  */
13980
13981 static void
13982 mips_ip (char *str, struct mips_cl_insn *insn)
13983 {
13984   const struct mips_opcode *first, *past;
13985   struct hash_control *hash;
13986   char format;
13987   size_t end;
13988   struct mips_operand_token *tokens;
13989   unsigned int opcode_extra;
13990
13991   if (mips_opts.micromips)
13992     {
13993       hash = micromips_op_hash;
13994       past = &micromips_opcodes[bfd_micromips_num_opcodes];
13995     }
13996   else
13997     {
13998       hash = op_hash;
13999       past = &mips_opcodes[NUMOPCODES];
14000     }
14001   forced_insn_length = 0;
14002   opcode_extra = 0;
14003
14004   /* We first try to match an instruction up to a space or to the end.  */
14005   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
14006     continue;
14007
14008   first = mips_lookup_insn (hash, str, end, &opcode_extra);
14009   if (first == NULL)
14010     {
14011       set_insn_error (0, _("unrecognized opcode"));
14012       return;
14013     }
14014
14015   if (strcmp (first->name, "li.s") == 0)
14016     format = 'f';
14017   else if (strcmp (first->name, "li.d") == 0)
14018     format = 'd';
14019   else
14020     format = 0;
14021   tokens = mips_parse_arguments (str + end, format);
14022   if (!tokens)
14023     return;
14024
14025   if (!match_insns (insn, first, past, tokens, opcode_extra, FALSE)
14026       && !match_insns (insn, first, past, tokens, opcode_extra, TRUE))
14027     set_insn_error (0, _("invalid operands"));
14028
14029   obstack_free (&mips_operand_tokens, tokens);
14030 }
14031
14032 /* As for mips_ip, but used when assembling MIPS16 code.
14033    Also set forced_insn_length to the resulting instruction size in
14034    bytes if the user explicitly requested a small or extended instruction.  */
14035
14036 static void
14037 mips16_ip (char *str, struct mips_cl_insn *insn)
14038 {
14039   char *end, *s, c;
14040   struct mips_opcode *first;
14041   struct mips_operand_token *tokens;
14042   unsigned int l;
14043
14044   for (s = str; *s != '\0' && *s != '.' && *s != ' '; ++s)
14045     ;
14046   end = s;
14047   c = *end;
14048
14049   l = 0;
14050   switch (c)
14051     {
14052     case '\0':
14053       break;
14054
14055     case ' ':
14056       s++;
14057       break;
14058
14059     case '.':
14060       s++;
14061       if (*s == 't')
14062         {
14063           l = 2;
14064           s++;
14065         }
14066       else if (*s == 'e')
14067         {
14068           l = 4;
14069           s++;
14070         }
14071       if (*s == '\0')
14072         break;
14073       else if (*s++ == ' ')
14074         break;
14075       set_insn_error (0, _("unrecognized opcode"));
14076       return;
14077     }
14078   forced_insn_length = l;
14079
14080   *end = 0;
14081   first = (struct mips_opcode *) hash_find (mips16_op_hash, str);
14082   *end = c;
14083
14084   if (!first)
14085     {
14086       set_insn_error (0, _("unrecognized opcode"));
14087       return;
14088     }
14089
14090   tokens = mips_parse_arguments (s, 0);
14091   if (!tokens)
14092     return;
14093
14094   if (!match_mips16_insns (insn, first, tokens))
14095     set_insn_error (0, _("invalid operands"));
14096
14097   obstack_free (&mips_operand_tokens, tokens);
14098 }
14099
14100 /* Marshal immediate value VAL for an extended MIPS16 instruction.
14101    NBITS is the number of significant bits in VAL.  */
14102
14103 static unsigned long
14104 mips16_immed_extend (offsetT val, unsigned int nbits)
14105 {
14106   int extval;
14107
14108   extval = 0;
14109   val &= (1U << nbits) - 1;
14110   if (nbits == 16 || nbits == 9)
14111     {
14112       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
14113       val &= 0x1f;
14114     }
14115   else if (nbits == 15)
14116     {
14117       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
14118       val &= 0xf;
14119     }
14120   else if (nbits == 6)
14121     {
14122       extval = ((val & 0x1f) << 6) | (val & 0x20);
14123       val = 0;
14124     }
14125   return (extval << 16) | val;
14126 }
14127
14128 /* Like decode_mips16_operand, but require the operand to be defined and
14129    require it to be an integer.  */
14130
14131 static const struct mips_int_operand *
14132 mips16_immed_operand (int type, bfd_boolean extended_p)
14133 {
14134   const struct mips_operand *operand;
14135
14136   operand = decode_mips16_operand (type, extended_p);
14137   if (!operand || (operand->type != OP_INT && operand->type != OP_PCREL))
14138     abort ();
14139   return (const struct mips_int_operand *) operand;
14140 }
14141
14142 /* Return true if SVAL fits OPERAND.  RELOC is as for mips16_immed.  */
14143
14144 static bfd_boolean
14145 mips16_immed_in_range_p (const struct mips_int_operand *operand,
14146                          bfd_reloc_code_real_type reloc, offsetT sval)
14147 {
14148   int min_val, max_val;
14149
14150   min_val = mips_int_operand_min (operand);
14151   max_val = mips_int_operand_max (operand);
14152   if (reloc != BFD_RELOC_UNUSED)
14153     {
14154       if (min_val < 0)
14155         sval = SEXT_16BIT (sval);
14156       else
14157         sval &= 0xffff;
14158     }
14159
14160   return (sval >= min_val
14161           && sval <= max_val
14162           && (sval & ((1 << operand->shift) - 1)) == 0);
14163 }
14164
14165 /* Install immediate value VAL into MIPS16 instruction *INSN,
14166    extending it if necessary.  The instruction in *INSN may
14167    already be extended.
14168
14169    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
14170    if none.  In the former case, VAL is a 16-bit number with no
14171    defined signedness.
14172
14173    TYPE is the type of the immediate field.  USER_INSN_LENGTH
14174    is the length that the user requested, or 0 if none.  */
14175
14176 static void
14177 mips16_immed (const char *file, unsigned int line, int type,
14178               bfd_reloc_code_real_type reloc, offsetT val,
14179               unsigned int user_insn_length, unsigned long *insn)
14180 {
14181   const struct mips_int_operand *operand;
14182   unsigned int uval, length;
14183
14184   operand = mips16_immed_operand (type, FALSE);
14185   if (!mips16_immed_in_range_p (operand, reloc, val))
14186     {
14187       /* We need an extended instruction.  */
14188       if (user_insn_length == 2)
14189         as_bad_where (file, line, _("invalid unextended operand value"));
14190       else
14191         *insn |= MIPS16_EXTEND;
14192     }
14193   else if (user_insn_length == 4)
14194     {
14195       /* The operand doesn't force an unextended instruction to be extended.
14196          Warn if the user wanted an extended instruction anyway.  */
14197       *insn |= MIPS16_EXTEND;
14198       as_warn_where (file, line,
14199                      _("extended operand requested but not required"));
14200     }
14201
14202   length = mips16_opcode_length (*insn);
14203   if (length == 4)
14204     {
14205       operand = mips16_immed_operand (type, TRUE);
14206       if (!mips16_immed_in_range_p (operand, reloc, val))
14207         as_bad_where (file, line,
14208                       _("operand value out of range for instruction"));
14209     }
14210   uval = ((unsigned int) val >> operand->shift) - operand->bias;
14211   if (length == 2 || operand->root.lsb != 0)
14212     *insn = mips_insert_operand (&operand->root, *insn, uval);
14213   else
14214     *insn |= mips16_immed_extend (uval, operand->root.size);
14215 }
14216 \f
14217 struct percent_op_match
14218 {
14219   const char *str;
14220   bfd_reloc_code_real_type reloc;
14221 };
14222
14223 static const struct percent_op_match mips_percent_op[] =
14224 {
14225   {"%lo", BFD_RELOC_LO16},
14226   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
14227   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
14228   {"%call16", BFD_RELOC_MIPS_CALL16},
14229   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
14230   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
14231   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
14232   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
14233   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
14234   {"%got", BFD_RELOC_MIPS_GOT16},
14235   {"%gp_rel", BFD_RELOC_GPREL16},
14236   {"%gprel", BFD_RELOC_GPREL16},
14237   {"%half", BFD_RELOC_16},
14238   {"%highest", BFD_RELOC_MIPS_HIGHEST},
14239   {"%higher", BFD_RELOC_MIPS_HIGHER},
14240   {"%neg", BFD_RELOC_MIPS_SUB},
14241   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
14242   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
14243   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
14244   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
14245   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
14246   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
14247   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
14248   {"%hi", BFD_RELOC_HI16_S},
14249   {"%pcrel_hi", BFD_RELOC_HI16_S_PCREL},
14250   {"%pcrel_lo", BFD_RELOC_LO16_PCREL}
14251 };
14252
14253 static const struct percent_op_match mips16_percent_op[] =
14254 {
14255   {"%lo", BFD_RELOC_MIPS16_LO16},
14256   {"%gp_rel", BFD_RELOC_MIPS16_GPREL},
14257   {"%gprel", BFD_RELOC_MIPS16_GPREL},
14258   {"%got", BFD_RELOC_MIPS16_GOT16},
14259   {"%call16", BFD_RELOC_MIPS16_CALL16},
14260   {"%hi", BFD_RELOC_MIPS16_HI16_S},
14261   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
14262   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
14263   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
14264   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
14265   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
14266   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
14267   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
14268 };
14269
14270
14271 /* Return true if *STR points to a relocation operator.  When returning true,
14272    move *STR over the operator and store its relocation code in *RELOC.
14273    Leave both *STR and *RELOC alone when returning false.  */
14274
14275 static bfd_boolean
14276 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
14277 {
14278   const struct percent_op_match *percent_op;
14279   size_t limit, i;
14280
14281   if (mips_opts.mips16)
14282     {
14283       percent_op = mips16_percent_op;
14284       limit = ARRAY_SIZE (mips16_percent_op);
14285     }
14286   else
14287     {
14288       percent_op = mips_percent_op;
14289       limit = ARRAY_SIZE (mips_percent_op);
14290     }
14291
14292   for (i = 0; i < limit; i++)
14293     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
14294       {
14295         int len = strlen (percent_op[i].str);
14296
14297         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
14298           continue;
14299
14300         *str += strlen (percent_op[i].str);
14301         *reloc = percent_op[i].reloc;
14302
14303         /* Check whether the output BFD supports this relocation.
14304            If not, issue an error and fall back on something safe.  */
14305         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
14306           {
14307             as_bad (_("relocation %s isn't supported by the current ABI"),
14308                     percent_op[i].str);
14309             *reloc = BFD_RELOC_UNUSED;
14310           }
14311         return TRUE;
14312       }
14313   return FALSE;
14314 }
14315
14316
14317 /* Parse string STR as a 16-bit relocatable operand.  Store the
14318    expression in *EP and the relocations in the array starting
14319    at RELOC.  Return the number of relocation operators used.
14320
14321    On exit, EXPR_END points to the first character after the expression.  */
14322
14323 static size_t
14324 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
14325                        char *str)
14326 {
14327   bfd_reloc_code_real_type reversed_reloc[3];
14328   size_t reloc_index, i;
14329   int crux_depth, str_depth;
14330   char *crux;
14331
14332   /* Search for the start of the main expression, recoding relocations
14333      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
14334      of the main expression and with CRUX_DEPTH containing the number
14335      of open brackets at that point.  */
14336   reloc_index = -1;
14337   str_depth = 0;
14338   do
14339     {
14340       reloc_index++;
14341       crux = str;
14342       crux_depth = str_depth;
14343
14344       /* Skip over whitespace and brackets, keeping count of the number
14345          of brackets.  */
14346       while (*str == ' ' || *str == '\t' || *str == '(')
14347         if (*str++ == '(')
14348           str_depth++;
14349     }
14350   while (*str == '%'
14351          && reloc_index < (HAVE_NEWABI ? 3 : 1)
14352          && parse_relocation (&str, &reversed_reloc[reloc_index]));
14353
14354   my_getExpression (ep, crux);
14355   str = expr_end;
14356
14357   /* Match every open bracket.  */
14358   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
14359     if (*str++ == ')')
14360       crux_depth--;
14361
14362   if (crux_depth > 0)
14363     as_bad (_("unclosed '('"));
14364
14365   expr_end = str;
14366
14367   if (reloc_index != 0)
14368     {
14369       prev_reloc_op_frag = frag_now;
14370       for (i = 0; i < reloc_index; i++)
14371         reloc[i] = reversed_reloc[reloc_index - 1 - i];
14372     }
14373
14374   return reloc_index;
14375 }
14376
14377 static void
14378 my_getExpression (expressionS *ep, char *str)
14379 {
14380   char *save_in;
14381
14382   save_in = input_line_pointer;
14383   input_line_pointer = str;
14384   expression (ep);
14385   expr_end = input_line_pointer;
14386   input_line_pointer = save_in;
14387 }
14388
14389 const char *
14390 md_atof (int type, char *litP, int *sizeP)
14391 {
14392   return ieee_md_atof (type, litP, sizeP, target_big_endian);
14393 }
14394
14395 void
14396 md_number_to_chars (char *buf, valueT val, int n)
14397 {
14398   if (target_big_endian)
14399     number_to_chars_bigendian (buf, val, n);
14400   else
14401     number_to_chars_littleendian (buf, val, n);
14402 }
14403 \f
14404 static int support_64bit_objects(void)
14405 {
14406   const char **list, **l;
14407   int yes;
14408
14409   list = bfd_target_list ();
14410   for (l = list; *l != NULL; l++)
14411     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
14412         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
14413       break;
14414   yes = (*l != NULL);
14415   free (list);
14416   return yes;
14417 }
14418
14419 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
14420    NEW_VALUE.  Warn if another value was already specified.  Note:
14421    we have to defer parsing the -march and -mtune arguments in order
14422    to handle 'from-abi' correctly, since the ABI might be specified
14423    in a later argument.  */
14424
14425 static void
14426 mips_set_option_string (const char **string_ptr, const char *new_value)
14427 {
14428   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
14429     as_warn (_("a different %s was already specified, is now %s"),
14430              string_ptr == &mips_arch_string ? "-march" : "-mtune",
14431              new_value);
14432
14433   *string_ptr = new_value;
14434 }
14435
14436 int
14437 md_parse_option (int c, const char *arg)
14438 {
14439   unsigned int i;
14440
14441   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
14442     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
14443       {
14444         file_ase_explicit |= mips_set_ase (&mips_ases[i], &file_mips_opts,
14445                                            c == mips_ases[i].option_on);
14446         return 1;
14447       }
14448
14449   switch (c)
14450     {
14451     case OPTION_CONSTRUCT_FLOATS:
14452       mips_disable_float_construction = 0;
14453       break;
14454
14455     case OPTION_NO_CONSTRUCT_FLOATS:
14456       mips_disable_float_construction = 1;
14457       break;
14458
14459     case OPTION_TRAP:
14460       mips_trap = 1;
14461       break;
14462
14463     case OPTION_BREAK:
14464       mips_trap = 0;
14465       break;
14466
14467     case OPTION_EB:
14468       target_big_endian = 1;
14469       break;
14470
14471     case OPTION_EL:
14472       target_big_endian = 0;
14473       break;
14474
14475     case 'O':
14476       if (arg == NULL)
14477         mips_optimize = 1;
14478       else if (arg[0] == '0')
14479         mips_optimize = 0;
14480       else if (arg[0] == '1')
14481         mips_optimize = 1;
14482       else
14483         mips_optimize = 2;
14484       break;
14485
14486     case 'g':
14487       if (arg == NULL)
14488         mips_debug = 2;
14489       else
14490         mips_debug = atoi (arg);
14491       break;
14492
14493     case OPTION_MIPS1:
14494       file_mips_opts.isa = ISA_MIPS1;
14495       break;
14496
14497     case OPTION_MIPS2:
14498       file_mips_opts.isa = ISA_MIPS2;
14499       break;
14500
14501     case OPTION_MIPS3:
14502       file_mips_opts.isa = ISA_MIPS3;
14503       break;
14504
14505     case OPTION_MIPS4:
14506       file_mips_opts.isa = ISA_MIPS4;
14507       break;
14508
14509     case OPTION_MIPS5:
14510       file_mips_opts.isa = ISA_MIPS5;
14511       break;
14512
14513     case OPTION_MIPS32:
14514       file_mips_opts.isa = ISA_MIPS32;
14515       break;
14516
14517     case OPTION_MIPS32R2:
14518       file_mips_opts.isa = ISA_MIPS32R2;
14519       break;
14520
14521     case OPTION_MIPS32R3:
14522       file_mips_opts.isa = ISA_MIPS32R3;
14523       break;
14524
14525     case OPTION_MIPS32R5:
14526       file_mips_opts.isa = ISA_MIPS32R5;
14527       break;
14528
14529     case OPTION_MIPS32R6:
14530       file_mips_opts.isa = ISA_MIPS32R6;
14531       break;
14532
14533     case OPTION_MIPS64R2:
14534       file_mips_opts.isa = ISA_MIPS64R2;
14535       break;
14536
14537     case OPTION_MIPS64R3:
14538       file_mips_opts.isa = ISA_MIPS64R3;
14539       break;
14540
14541     case OPTION_MIPS64R5:
14542       file_mips_opts.isa = ISA_MIPS64R5;
14543       break;
14544
14545     case OPTION_MIPS64R6:
14546       file_mips_opts.isa = ISA_MIPS64R6;
14547       break;
14548
14549     case OPTION_MIPS64:
14550       file_mips_opts.isa = ISA_MIPS64;
14551       break;
14552
14553     case OPTION_MTUNE:
14554       mips_set_option_string (&mips_tune_string, arg);
14555       break;
14556
14557     case OPTION_MARCH:
14558       mips_set_option_string (&mips_arch_string, arg);
14559       break;
14560
14561     case OPTION_M4650:
14562       mips_set_option_string (&mips_arch_string, "4650");
14563       mips_set_option_string (&mips_tune_string, "4650");
14564       break;
14565
14566     case OPTION_NO_M4650:
14567       break;
14568
14569     case OPTION_M4010:
14570       mips_set_option_string (&mips_arch_string, "4010");
14571       mips_set_option_string (&mips_tune_string, "4010");
14572       break;
14573
14574     case OPTION_NO_M4010:
14575       break;
14576
14577     case OPTION_M4100:
14578       mips_set_option_string (&mips_arch_string, "4100");
14579       mips_set_option_string (&mips_tune_string, "4100");
14580       break;
14581
14582     case OPTION_NO_M4100:
14583       break;
14584
14585     case OPTION_M3900:
14586       mips_set_option_string (&mips_arch_string, "3900");
14587       mips_set_option_string (&mips_tune_string, "3900");
14588       break;
14589
14590     case OPTION_NO_M3900:
14591       break;
14592
14593     case OPTION_MICROMIPS:
14594       if (file_mips_opts.mips16 == 1)
14595         {
14596           as_bad (_("-mmicromips cannot be used with -mips16"));
14597           return 0;
14598         }
14599       file_mips_opts.micromips = 1;
14600       mips_no_prev_insn ();
14601       break;
14602
14603     case OPTION_NO_MICROMIPS:
14604       file_mips_opts.micromips = 0;
14605       mips_no_prev_insn ();
14606       break;
14607
14608     case OPTION_MIPS16:
14609       if (file_mips_opts.micromips == 1)
14610         {
14611           as_bad (_("-mips16 cannot be used with -micromips"));
14612           return 0;
14613         }
14614       file_mips_opts.mips16 = 1;
14615       mips_no_prev_insn ();
14616       break;
14617
14618     case OPTION_NO_MIPS16:
14619       file_mips_opts.mips16 = 0;
14620       mips_no_prev_insn ();
14621       break;
14622
14623     case OPTION_FIX_24K:
14624       mips_fix_24k = 1;
14625       break;
14626
14627     case OPTION_NO_FIX_24K:
14628       mips_fix_24k = 0;
14629       break;
14630
14631     case OPTION_FIX_RM7000:
14632       mips_fix_rm7000 = 1;
14633       break;
14634
14635     case OPTION_NO_FIX_RM7000:
14636       mips_fix_rm7000 = 0;
14637       break;
14638
14639     case OPTION_FIX_LOONGSON2F_JUMP:
14640       mips_fix_loongson2f_jump = TRUE;
14641       break;
14642
14643     case OPTION_NO_FIX_LOONGSON2F_JUMP:
14644       mips_fix_loongson2f_jump = FALSE;
14645       break;
14646
14647     case OPTION_FIX_LOONGSON2F_NOP:
14648       mips_fix_loongson2f_nop = TRUE;
14649       break;
14650
14651     case OPTION_NO_FIX_LOONGSON2F_NOP:
14652       mips_fix_loongson2f_nop = FALSE;
14653       break;
14654
14655     case OPTION_FIX_VR4120:
14656       mips_fix_vr4120 = 1;
14657       break;
14658
14659     case OPTION_NO_FIX_VR4120:
14660       mips_fix_vr4120 = 0;
14661       break;
14662
14663     case OPTION_FIX_VR4130:
14664       mips_fix_vr4130 = 1;
14665       break;
14666
14667     case OPTION_NO_FIX_VR4130:
14668       mips_fix_vr4130 = 0;
14669       break;
14670
14671     case OPTION_FIX_CN63XXP1:
14672       mips_fix_cn63xxp1 = TRUE;
14673       break;
14674
14675     case OPTION_NO_FIX_CN63XXP1:
14676       mips_fix_cn63xxp1 = FALSE;
14677       break;
14678
14679     case OPTION_RELAX_BRANCH:
14680       mips_relax_branch = 1;
14681       break;
14682
14683     case OPTION_NO_RELAX_BRANCH:
14684       mips_relax_branch = 0;
14685       break;
14686
14687     case OPTION_IGNORE_BRANCH_ISA:
14688       mips_ignore_branch_isa = TRUE;
14689       break;
14690
14691     case OPTION_NO_IGNORE_BRANCH_ISA:
14692       mips_ignore_branch_isa = FALSE;
14693       break;
14694
14695     case OPTION_INSN32:
14696       file_mips_opts.insn32 = TRUE;
14697       break;
14698
14699     case OPTION_NO_INSN32:
14700       file_mips_opts.insn32 = FALSE;
14701       break;
14702
14703     case OPTION_MSHARED:
14704       mips_in_shared = TRUE;
14705       break;
14706
14707     case OPTION_MNO_SHARED:
14708       mips_in_shared = FALSE;
14709       break;
14710
14711     case OPTION_MSYM32:
14712       file_mips_opts.sym32 = TRUE;
14713       break;
14714
14715     case OPTION_MNO_SYM32:
14716       file_mips_opts.sym32 = FALSE;
14717       break;
14718
14719       /* When generating ELF code, we permit -KPIC and -call_shared to
14720          select SVR4_PIC, and -non_shared to select no PIC.  This is
14721          intended to be compatible with Irix 5.  */
14722     case OPTION_CALL_SHARED:
14723       mips_pic = SVR4_PIC;
14724       mips_abicalls = TRUE;
14725       break;
14726
14727     case OPTION_CALL_NONPIC:
14728       mips_pic = NO_PIC;
14729       mips_abicalls = TRUE;
14730       break;
14731
14732     case OPTION_NON_SHARED:
14733       mips_pic = NO_PIC;
14734       mips_abicalls = FALSE;
14735       break;
14736
14737       /* The -xgot option tells the assembler to use 32 bit offsets
14738          when accessing the got in SVR4_PIC mode.  It is for Irix
14739          compatibility.  */
14740     case OPTION_XGOT:
14741       mips_big_got = 1;
14742       break;
14743
14744     case 'G':
14745       g_switch_value = atoi (arg);
14746       g_switch_seen = 1;
14747       break;
14748
14749       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
14750          and -mabi=64.  */
14751     case OPTION_32:
14752       mips_abi = O32_ABI;
14753       break;
14754
14755     case OPTION_N32:
14756       mips_abi = N32_ABI;
14757       break;
14758
14759     case OPTION_64:
14760       mips_abi = N64_ABI;
14761       if (!support_64bit_objects())
14762         as_fatal (_("no compiled in support for 64 bit object file format"));
14763       break;
14764
14765     case OPTION_GP32:
14766       file_mips_opts.gp = 32;
14767       break;
14768
14769     case OPTION_GP64:
14770       file_mips_opts.gp = 64;
14771       break;
14772
14773     case OPTION_FP32:
14774       file_mips_opts.fp = 32;
14775       break;
14776
14777     case OPTION_FPXX:
14778       file_mips_opts.fp = 0;
14779       break;
14780
14781     case OPTION_FP64:
14782       file_mips_opts.fp = 64;
14783       break;
14784
14785     case OPTION_ODD_SPREG:
14786       file_mips_opts.oddspreg = 1;
14787       break;
14788
14789     case OPTION_NO_ODD_SPREG:
14790       file_mips_opts.oddspreg = 0;
14791       break;
14792
14793     case OPTION_SINGLE_FLOAT:
14794       file_mips_opts.single_float = 1;
14795       break;
14796
14797     case OPTION_DOUBLE_FLOAT:
14798       file_mips_opts.single_float = 0;
14799       break;
14800
14801     case OPTION_SOFT_FLOAT:
14802       file_mips_opts.soft_float = 1;
14803       break;
14804
14805     case OPTION_HARD_FLOAT:
14806       file_mips_opts.soft_float = 0;
14807       break;
14808
14809     case OPTION_MABI:
14810       if (strcmp (arg, "32") == 0)
14811         mips_abi = O32_ABI;
14812       else if (strcmp (arg, "o64") == 0)
14813         mips_abi = O64_ABI;
14814       else if (strcmp (arg, "n32") == 0)
14815         mips_abi = N32_ABI;
14816       else if (strcmp (arg, "64") == 0)
14817         {
14818           mips_abi = N64_ABI;
14819           if (! support_64bit_objects())
14820             as_fatal (_("no compiled in support for 64 bit object file "
14821                         "format"));
14822         }
14823       else if (strcmp (arg, "eabi") == 0)
14824         mips_abi = EABI_ABI;
14825       else
14826         {
14827           as_fatal (_("invalid abi -mabi=%s"), arg);
14828           return 0;
14829         }
14830       break;
14831
14832     case OPTION_M7000_HILO_FIX:
14833       mips_7000_hilo_fix = TRUE;
14834       break;
14835
14836     case OPTION_MNO_7000_HILO_FIX:
14837       mips_7000_hilo_fix = FALSE;
14838       break;
14839
14840     case OPTION_MDEBUG:
14841       mips_flag_mdebug = TRUE;
14842       break;
14843
14844     case OPTION_NO_MDEBUG:
14845       mips_flag_mdebug = FALSE;
14846       break;
14847
14848     case OPTION_PDR:
14849       mips_flag_pdr = TRUE;
14850       break;
14851
14852     case OPTION_NO_PDR:
14853       mips_flag_pdr = FALSE;
14854       break;
14855
14856     case OPTION_MVXWORKS_PIC:
14857       mips_pic = VXWORKS_PIC;
14858       break;
14859
14860     case OPTION_NAN:
14861       if (strcmp (arg, "2008") == 0)
14862         mips_nan2008 = 1;
14863       else if (strcmp (arg, "legacy") == 0)
14864         mips_nan2008 = 0;
14865       else
14866         {
14867           as_fatal (_("invalid NaN setting -mnan=%s"), arg);
14868           return 0;
14869         }
14870       break;
14871
14872     default:
14873       return 0;
14874     }
14875
14876     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
14877
14878   return 1;
14879 }
14880 \f
14881 /* Set up globals to tune for the ISA or processor described by INFO.  */
14882
14883 static void
14884 mips_set_tune (const struct mips_cpu_info *info)
14885 {
14886   if (info != 0)
14887     mips_tune = info->cpu;
14888 }
14889
14890
14891 void
14892 mips_after_parse_args (void)
14893 {
14894   const struct mips_cpu_info *arch_info = 0;
14895   const struct mips_cpu_info *tune_info = 0;
14896
14897   /* GP relative stuff not working for PE */
14898   if (strncmp (TARGET_OS, "pe", 2) == 0)
14899     {
14900       if (g_switch_seen && g_switch_value != 0)
14901         as_bad (_("-G not supported in this configuration"));
14902       g_switch_value = 0;
14903     }
14904
14905   if (mips_abi == NO_ABI)
14906     mips_abi = MIPS_DEFAULT_ABI;
14907
14908   /* The following code determines the architecture.
14909      Similar code was added to GCC 3.3 (see override_options() in
14910      config/mips/mips.c).  The GAS and GCC code should be kept in sync
14911      as much as possible.  */
14912
14913   if (mips_arch_string != 0)
14914     arch_info = mips_parse_cpu ("-march", mips_arch_string);
14915
14916   if (file_mips_opts.isa != ISA_UNKNOWN)
14917     {
14918       /* Handle -mipsN.  At this point, file_mips_opts.isa contains the
14919          ISA level specified by -mipsN, while arch_info->isa contains
14920          the -march selection (if any).  */
14921       if (arch_info != 0)
14922         {
14923           /* -march takes precedence over -mipsN, since it is more descriptive.
14924              There's no harm in specifying both as long as the ISA levels
14925              are the same.  */
14926           if (file_mips_opts.isa != arch_info->isa)
14927             as_bad (_("-%s conflicts with the other architecture options,"
14928                       " which imply -%s"),
14929                     mips_cpu_info_from_isa (file_mips_opts.isa)->name,
14930                     mips_cpu_info_from_isa (arch_info->isa)->name);
14931         }
14932       else
14933         arch_info = mips_cpu_info_from_isa (file_mips_opts.isa);
14934     }
14935
14936   if (arch_info == 0)
14937     {
14938       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
14939       gas_assert (arch_info);
14940     }
14941
14942   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
14943     as_bad (_("-march=%s is not compatible with the selected ABI"),
14944             arch_info->name);
14945
14946   file_mips_opts.arch = arch_info->cpu;
14947   file_mips_opts.isa = arch_info->isa;
14948
14949   /* Set up initial mips_opts state.  */
14950   mips_opts = file_mips_opts;
14951
14952   /* The register size inference code is now placed in
14953      file_mips_check_options.  */
14954
14955   /* Optimize for file_mips_opts.arch, unless -mtune selects a different
14956      processor.  */
14957   if (mips_tune_string != 0)
14958     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
14959
14960   if (tune_info == 0)
14961     mips_set_tune (arch_info);
14962   else
14963     mips_set_tune (tune_info);
14964
14965   if (mips_flag_mdebug < 0)
14966     mips_flag_mdebug = 0;
14967 }
14968 \f
14969 void
14970 mips_init_after_args (void)
14971 {
14972   /* initialize opcodes */
14973   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
14974   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
14975 }
14976
14977 long
14978 md_pcrel_from (fixS *fixP)
14979 {
14980   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
14981   switch (fixP->fx_r_type)
14982     {
14983     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14984     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14985       /* Return the address of the delay slot.  */
14986       return addr + 2;
14987
14988     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14989     case BFD_RELOC_MICROMIPS_JMP:
14990     case BFD_RELOC_MIPS16_16_PCREL_S1:
14991     case BFD_RELOC_16_PCREL_S2:
14992     case BFD_RELOC_MIPS_21_PCREL_S2:
14993     case BFD_RELOC_MIPS_26_PCREL_S2:
14994     case BFD_RELOC_MIPS_JMP:
14995       /* Return the address of the delay slot.  */
14996       return addr + 4;
14997
14998     case BFD_RELOC_MIPS_18_PCREL_S3:
14999       /* Return the aligned address of the doubleword containing
15000          the instruction.  */
15001       return addr & ~7;
15002
15003     default:
15004       return addr;
15005     }
15006 }
15007
15008 /* This is called before the symbol table is processed.  In order to
15009    work with gcc when using mips-tfile, we must keep all local labels.
15010    However, in other cases, we want to discard them.  If we were
15011    called with -g, but we didn't see any debugging information, it may
15012    mean that gcc is smuggling debugging information through to
15013    mips-tfile, in which case we must generate all local labels.  */
15014
15015 void
15016 mips_frob_file_before_adjust (void)
15017 {
15018 #ifndef NO_ECOFF_DEBUGGING
15019   if (ECOFF_DEBUGGING
15020       && mips_debug != 0
15021       && ! ecoff_debugging_seen)
15022     flag_keep_locals = 1;
15023 #endif
15024 }
15025
15026 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
15027    the corresponding LO16 reloc.  This is called before md_apply_fix and
15028    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
15029    relocation operators.
15030
15031    For our purposes, a %lo() expression matches a %got() or %hi()
15032    expression if:
15033
15034       (a) it refers to the same symbol; and
15035       (b) the offset applied in the %lo() expression is no lower than
15036           the offset applied in the %got() or %hi().
15037
15038    (b) allows us to cope with code like:
15039
15040         lui     $4,%hi(foo)
15041         lh      $4,%lo(foo+2)($4)
15042
15043    ...which is legal on RELA targets, and has a well-defined behaviour
15044    if the user knows that adding 2 to "foo" will not induce a carry to
15045    the high 16 bits.
15046
15047    When several %lo()s match a particular %got() or %hi(), we use the
15048    following rules to distinguish them:
15049
15050      (1) %lo()s with smaller offsets are a better match than %lo()s with
15051          higher offsets.
15052
15053      (2) %lo()s with no matching %got() or %hi() are better than those
15054          that already have a matching %got() or %hi().
15055
15056      (3) later %lo()s are better than earlier %lo()s.
15057
15058    These rules are applied in order.
15059
15060    (1) means, among other things, that %lo()s with identical offsets are
15061    chosen if they exist.
15062
15063    (2) means that we won't associate several high-part relocations with
15064    the same low-part relocation unless there's no alternative.  Having
15065    several high parts for the same low part is a GNU extension; this rule
15066    allows careful users to avoid it.
15067
15068    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
15069    with the last high-part relocation being at the front of the list.
15070    It therefore makes sense to choose the last matching low-part
15071    relocation, all other things being equal.  It's also easier
15072    to code that way.  */
15073
15074 void
15075 mips_frob_file (void)
15076 {
15077   struct mips_hi_fixup *l;
15078   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
15079
15080   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
15081     {
15082       segment_info_type *seginfo;
15083       bfd_boolean matched_lo_p;
15084       fixS **hi_pos, **lo_pos, **pos;
15085
15086       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
15087
15088       /* If a GOT16 relocation turns out to be against a global symbol,
15089          there isn't supposed to be a matching LO.  Ignore %gots against
15090          constants; we'll report an error for those later.  */
15091       if (got16_reloc_p (l->fixp->fx_r_type)
15092           && !(l->fixp->fx_addsy
15093                && pic_need_relax (l->fixp->fx_addsy)))
15094         continue;
15095
15096       /* Check quickly whether the next fixup happens to be a matching %lo.  */
15097       if (fixup_has_matching_lo_p (l->fixp))
15098         continue;
15099
15100       seginfo = seg_info (l->seg);
15101
15102       /* Set HI_POS to the position of this relocation in the chain.
15103          Set LO_POS to the position of the chosen low-part relocation.
15104          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
15105          relocation that matches an immediately-preceding high-part
15106          relocation.  */
15107       hi_pos = NULL;
15108       lo_pos = NULL;
15109       matched_lo_p = FALSE;
15110       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
15111
15112       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
15113         {
15114           if (*pos == l->fixp)
15115             hi_pos = pos;
15116
15117           if ((*pos)->fx_r_type == looking_for_rtype
15118               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
15119               && (*pos)->fx_offset >= l->fixp->fx_offset
15120               && (lo_pos == NULL
15121                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
15122                   || (!matched_lo_p
15123                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
15124             lo_pos = pos;
15125
15126           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
15127                           && fixup_has_matching_lo_p (*pos));
15128         }
15129
15130       /* If we found a match, remove the high-part relocation from its
15131          current position and insert it before the low-part relocation.
15132          Make the offsets match so that fixup_has_matching_lo_p()
15133          will return true.
15134
15135          We don't warn about unmatched high-part relocations since some
15136          versions of gcc have been known to emit dead "lui ...%hi(...)"
15137          instructions.  */
15138       if (lo_pos != NULL)
15139         {
15140           l->fixp->fx_offset = (*lo_pos)->fx_offset;
15141           if (l->fixp->fx_next != *lo_pos)
15142             {
15143               *hi_pos = l->fixp->fx_next;
15144               l->fixp->fx_next = *lo_pos;
15145               *lo_pos = l->fixp;
15146             }
15147         }
15148     }
15149 }
15150
15151 int
15152 mips_force_relocation (fixS *fixp)
15153 {
15154   if (generic_force_reloc (fixp))
15155     return 1;
15156
15157   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
15158      so that the linker relaxation can update targets.  */
15159   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
15160       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
15161       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
15162     return 1;
15163
15164   /* We want to keep BFD_RELOC_16_PCREL_S2 BFD_RELOC_MIPS_21_PCREL_S2
15165      and BFD_RELOC_MIPS_26_PCREL_S2 relocations against MIPS16 and
15166      microMIPS symbols so that we can do cross-mode branch diagnostics
15167      and BAL to JALX conversion by the linker.  */
15168   if ((fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
15169        || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
15170        || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2)
15171       && fixp->fx_addsy
15172       && ELF_ST_IS_COMPRESSED (S_GET_OTHER (fixp->fx_addsy)))
15173     return 1;
15174
15175   /* We want all PC-relative relocations to be kept for R6 relaxation.  */
15176   if (ISA_IS_R6 (file_mips_opts.isa)
15177       && (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
15178           || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
15179           || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2
15180           || fixp->fx_r_type == BFD_RELOC_MIPS_18_PCREL_S3
15181           || fixp->fx_r_type == BFD_RELOC_MIPS_19_PCREL_S2
15182           || fixp->fx_r_type == BFD_RELOC_HI16_S_PCREL
15183           || fixp->fx_r_type == BFD_RELOC_LO16_PCREL))
15184     return 1;
15185
15186   return 0;
15187 }
15188
15189 /* Implement TC_FORCE_RELOCATION_ABS.  */
15190
15191 bfd_boolean
15192 mips_force_relocation_abs (fixS *fixp)
15193 {
15194   if (generic_force_reloc (fixp))
15195     return TRUE;
15196
15197   /* These relocations do not have enough bits in the in-place addend
15198      to hold an arbitrary absolute section's offset.  */
15199   if (HAVE_IN_PLACE_ADDENDS && limited_pcrel_reloc_p (fixp->fx_r_type))
15200     return TRUE;
15201
15202   return FALSE;
15203 }
15204
15205 /* Read the instruction associated with RELOC from BUF.  */
15206
15207 static unsigned int
15208 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
15209 {
15210   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
15211     return read_compressed_insn (buf, 4);
15212   else
15213     return read_insn (buf);
15214 }
15215
15216 /* Write instruction INSN to BUF, given that it has been relocated
15217    by RELOC.  */
15218
15219 static void
15220 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
15221                   unsigned long insn)
15222 {
15223   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
15224     write_compressed_insn (buf, insn, 4);
15225   else
15226     write_insn (buf, insn);
15227 }
15228
15229 /* Return TRUE if the instruction pointed to by FIXP is an invalid jump
15230    to a symbol in another ISA mode, which cannot be converted to JALX.  */
15231
15232 static bfd_boolean
15233 fix_bad_cross_mode_jump_p (fixS *fixP)
15234 {
15235   unsigned long opcode;
15236   int other;
15237   char *buf;
15238
15239   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15240     return FALSE;
15241
15242   other = S_GET_OTHER (fixP->fx_addsy);
15243   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15244   opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 26;
15245   switch (fixP->fx_r_type)
15246     {
15247     case BFD_RELOC_MIPS_JMP:
15248       return opcode != 0x1d && opcode != 0x03 && ELF_ST_IS_COMPRESSED (other);
15249     case BFD_RELOC_MICROMIPS_JMP:
15250       return opcode != 0x3c && opcode != 0x3d && !ELF_ST_IS_MICROMIPS (other);
15251     default:
15252       return FALSE;
15253     }
15254 }
15255
15256 /* Return TRUE if the instruction pointed to by FIXP is an invalid JALX
15257    jump to a symbol in the same ISA mode.  */
15258
15259 static bfd_boolean
15260 fix_bad_same_mode_jalx_p (fixS *fixP)
15261 {
15262   unsigned long opcode;
15263   int other;
15264   char *buf;
15265
15266   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15267     return FALSE;
15268
15269   other = S_GET_OTHER (fixP->fx_addsy);
15270   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15271   opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 26;
15272   switch (fixP->fx_r_type)
15273     {
15274     case BFD_RELOC_MIPS_JMP:
15275       return opcode == 0x1d && !ELF_ST_IS_COMPRESSED (other);
15276     case BFD_RELOC_MIPS16_JMP:
15277       return opcode == 0x07 && ELF_ST_IS_COMPRESSED (other);
15278     case BFD_RELOC_MICROMIPS_JMP:
15279       return opcode == 0x3c && ELF_ST_IS_COMPRESSED (other);
15280     default:
15281       return FALSE;
15282     }
15283 }
15284
15285 /* Return TRUE if the instruction pointed to by FIXP is an invalid jump
15286    to a symbol whose value plus addend is not aligned according to the
15287    ultimate (after linker relaxation) jump instruction's immediate field
15288    requirement, either to (1 << SHIFT), or, for jumps from microMIPS to
15289    regular MIPS code, to (1 << 2).  */
15290
15291 static bfd_boolean
15292 fix_bad_misaligned_jump_p (fixS *fixP, int shift)
15293 {
15294   bfd_boolean micro_to_mips_p;
15295   valueT val;
15296   int other;
15297
15298   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15299     return FALSE;
15300
15301   other = S_GET_OTHER (fixP->fx_addsy);
15302   val = S_GET_VALUE (fixP->fx_addsy) | ELF_ST_IS_COMPRESSED (other);
15303   val += fixP->fx_offset;
15304   micro_to_mips_p = (fixP->fx_r_type == BFD_RELOC_MICROMIPS_JMP
15305                      && !ELF_ST_IS_MICROMIPS (other));
15306   return ((val & ((1 << (micro_to_mips_p ? 2 : shift)) - 1))
15307           != ELF_ST_IS_COMPRESSED (other));
15308 }
15309
15310 /* Return TRUE if the instruction pointed to by FIXP is an invalid branch
15311    to a symbol whose annotation indicates another ISA mode.  For absolute
15312    symbols check the ISA bit instead.
15313
15314    We accept BFD_RELOC_16_PCREL_S2 relocations against MIPS16 and microMIPS
15315    symbols or BFD_RELOC_MICROMIPS_16_PCREL_S1 relocations against regular
15316    MIPS symbols and associated with BAL instructions as these instructions
15317    may be be converted to JALX by the linker.  */
15318
15319 static bfd_boolean
15320 fix_bad_cross_mode_branch_p (fixS *fixP)
15321 {
15322   bfd_boolean absolute_p;
15323   unsigned long opcode;
15324   asection *symsec;
15325   valueT val;
15326   int other;
15327   char *buf;
15328
15329   if (mips_ignore_branch_isa)
15330     return FALSE;
15331
15332   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15333     return FALSE;
15334
15335   symsec = S_GET_SEGMENT (fixP->fx_addsy);
15336   absolute_p = bfd_is_abs_section (symsec);
15337
15338   val = S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset;
15339   other = S_GET_OTHER (fixP->fx_addsy);
15340
15341   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15342   opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 16;
15343   switch (fixP->fx_r_type)
15344     {
15345     case BFD_RELOC_16_PCREL_S2:
15346       return ((absolute_p ? val & 1 : ELF_ST_IS_COMPRESSED (other))
15347               && opcode != 0x0411);
15348     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15349       return ((absolute_p ? !(val & 1) : !ELF_ST_IS_MICROMIPS (other))
15350               && opcode != 0x4060);
15351     case BFD_RELOC_MIPS_21_PCREL_S2:
15352     case BFD_RELOC_MIPS_26_PCREL_S2:
15353       return absolute_p ? val & 1 : ELF_ST_IS_COMPRESSED (other);
15354     case BFD_RELOC_MIPS16_16_PCREL_S1:
15355       return absolute_p ? !(val & 1) : !ELF_ST_IS_MIPS16 (other);
15356     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15357     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15358       return absolute_p ? !(val & 1) : !ELF_ST_IS_MICROMIPS (other);
15359     default:
15360       abort ();
15361     }
15362 }
15363
15364 /* Return TRUE if the symbol plus addend associated with a regular MIPS
15365    branch instruction pointed to by FIXP is not aligned according to the
15366    branch instruction's immediate field requirement.  We need the addend
15367    to preserve the ISA bit and also the sum must not have bit 2 set.  We
15368    must explicitly OR in the ISA bit from symbol annotation as the bit
15369    won't be set in the symbol's value then.  */
15370
15371 static bfd_boolean
15372 fix_bad_misaligned_branch_p (fixS *fixP)
15373 {
15374   bfd_boolean absolute_p;
15375   asection *symsec;
15376   valueT isa_bit;
15377   valueT val;
15378   valueT off;
15379   int other;
15380
15381   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15382     return FALSE;
15383
15384   symsec = S_GET_SEGMENT (fixP->fx_addsy);
15385   absolute_p = bfd_is_abs_section (symsec);
15386
15387   val = S_GET_VALUE (fixP->fx_addsy);
15388   other = S_GET_OTHER (fixP->fx_addsy);
15389   off = fixP->fx_offset;
15390
15391   isa_bit = absolute_p ? (val + off) & 1 : ELF_ST_IS_COMPRESSED (other);
15392   val |= ELF_ST_IS_COMPRESSED (other);
15393   val += off;
15394   return (val & 0x3) != isa_bit;
15395 }
15396
15397 /* Make the necessary checks on a regular MIPS branch pointed to by FIXP
15398    and its calculated value VAL.  */
15399
15400 static void
15401 fix_validate_branch (fixS *fixP, valueT val)
15402 {
15403   if (fixP->fx_done && (val & 0x3) != 0)
15404     as_bad_where (fixP->fx_file, fixP->fx_line,
15405                   _("branch to misaligned address (0x%lx)"),
15406                   (long) (val + md_pcrel_from (fixP)));
15407   else if (fix_bad_cross_mode_branch_p (fixP))
15408     as_bad_where (fixP->fx_file, fixP->fx_line,
15409                   _("branch to a symbol in another ISA mode"));
15410   else if (fix_bad_misaligned_branch_p (fixP))
15411     as_bad_where (fixP->fx_file, fixP->fx_line,
15412                   _("branch to misaligned address (0x%lx)"),
15413                   (long) (S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset));
15414   else if (HAVE_IN_PLACE_ADDENDS && (fixP->fx_offset & 0x3) != 0)
15415     as_bad_where (fixP->fx_file, fixP->fx_line,
15416                   _("cannot encode misaligned addend "
15417                     "in the relocatable field (0x%lx)"),
15418                   (long) fixP->fx_offset);
15419 }
15420
15421 /* Apply a fixup to the object file.  */
15422
15423 void
15424 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
15425 {
15426   char *buf;
15427   unsigned long insn;
15428   reloc_howto_type *howto;
15429
15430   if (fixP->fx_pcrel)
15431     switch (fixP->fx_r_type)
15432       {
15433       case BFD_RELOC_16_PCREL_S2:
15434       case BFD_RELOC_MIPS16_16_PCREL_S1:
15435       case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15436       case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15437       case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15438       case BFD_RELOC_32_PCREL:
15439       case BFD_RELOC_MIPS_21_PCREL_S2:
15440       case BFD_RELOC_MIPS_26_PCREL_S2:
15441       case BFD_RELOC_MIPS_18_PCREL_S3:
15442       case BFD_RELOC_MIPS_19_PCREL_S2:
15443       case BFD_RELOC_HI16_S_PCREL:
15444       case BFD_RELOC_LO16_PCREL:
15445         break;
15446
15447       case BFD_RELOC_32:
15448         fixP->fx_r_type = BFD_RELOC_32_PCREL;
15449         break;
15450
15451       default:
15452         as_bad_where (fixP->fx_file, fixP->fx_line,
15453                       _("PC-relative reference to a different section"));
15454         break;
15455       }
15456
15457   /* Handle BFD_RELOC_8, since it's easy.  Punt on other bfd relocations
15458      that have no MIPS ELF equivalent.  */
15459   if (fixP->fx_r_type != BFD_RELOC_8)
15460     {
15461       howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
15462       if (!howto)
15463         return;
15464     }
15465
15466   gas_assert (fixP->fx_size == 2
15467               || fixP->fx_size == 4
15468               || fixP->fx_r_type == BFD_RELOC_8
15469               || fixP->fx_r_type == BFD_RELOC_16
15470               || fixP->fx_r_type == BFD_RELOC_64
15471               || fixP->fx_r_type == BFD_RELOC_CTOR
15472               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
15473               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
15474               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
15475               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
15476               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64
15477               || fixP->fx_r_type == BFD_RELOC_NONE);
15478
15479   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15480
15481   /* Don't treat parts of a composite relocation as done.  There are two
15482      reasons for this:
15483
15484      (1) The second and third parts will be against 0 (RSS_UNDEF) but
15485          should nevertheless be emitted if the first part is.
15486
15487      (2) In normal usage, composite relocations are never assembly-time
15488          constants.  The easiest way of dealing with the pathological
15489          exceptions is to generate a relocation against STN_UNDEF and
15490          leave everything up to the linker.  */
15491   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
15492     fixP->fx_done = 1;
15493
15494   switch (fixP->fx_r_type)
15495     {
15496     case BFD_RELOC_MIPS_TLS_GD:
15497     case BFD_RELOC_MIPS_TLS_LDM:
15498     case BFD_RELOC_MIPS_TLS_DTPREL32:
15499     case BFD_RELOC_MIPS_TLS_DTPREL64:
15500     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
15501     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
15502     case BFD_RELOC_MIPS_TLS_GOTTPREL:
15503     case BFD_RELOC_MIPS_TLS_TPREL32:
15504     case BFD_RELOC_MIPS_TLS_TPREL64:
15505     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
15506     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
15507     case BFD_RELOC_MICROMIPS_TLS_GD:
15508     case BFD_RELOC_MICROMIPS_TLS_LDM:
15509     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
15510     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
15511     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
15512     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
15513     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
15514     case BFD_RELOC_MIPS16_TLS_GD:
15515     case BFD_RELOC_MIPS16_TLS_LDM:
15516     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
15517     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
15518     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
15519     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
15520     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
15521       if (fixP->fx_addsy)
15522         S_SET_THREAD_LOCAL (fixP->fx_addsy);
15523       else
15524         as_bad_where (fixP->fx_file, fixP->fx_line,
15525                       _("TLS relocation against a constant"));
15526       break;
15527
15528     case BFD_RELOC_MIPS_JMP:
15529     case BFD_RELOC_MIPS16_JMP:
15530     case BFD_RELOC_MICROMIPS_JMP:
15531       {
15532         int shift;
15533
15534         gas_assert (!fixP->fx_done);
15535
15536         /* Shift is 2, unusually, for microMIPS JALX.  */
15537         if (fixP->fx_r_type == BFD_RELOC_MICROMIPS_JMP
15538             && (read_compressed_insn (buf, 4) >> 26) != 0x3c)
15539           shift = 1;
15540         else
15541           shift = 2;
15542
15543         if (fix_bad_cross_mode_jump_p (fixP))
15544           as_bad_where (fixP->fx_file, fixP->fx_line,
15545                         _("jump to a symbol in another ISA mode"));
15546         else if (fix_bad_same_mode_jalx_p (fixP))
15547           as_bad_where (fixP->fx_file, fixP->fx_line,
15548                         _("JALX to a symbol in the same ISA mode"));
15549         else if (fix_bad_misaligned_jump_p (fixP, shift))
15550           as_bad_where (fixP->fx_file, fixP->fx_line,
15551                         _("jump to misaligned address (0x%lx)"),
15552                         (long) (S_GET_VALUE (fixP->fx_addsy)
15553                                 + fixP->fx_offset));
15554         else if (HAVE_IN_PLACE_ADDENDS
15555                  && (fixP->fx_offset & ((1 << shift) - 1)) != 0)
15556           as_bad_where (fixP->fx_file, fixP->fx_line,
15557                         _("cannot encode misaligned addend "
15558                           "in the relocatable field (0x%lx)"),
15559                         (long) fixP->fx_offset);
15560       }
15561       /* Fall through.  */
15562
15563     case BFD_RELOC_MIPS_SHIFT5:
15564     case BFD_RELOC_MIPS_SHIFT6:
15565     case BFD_RELOC_MIPS_GOT_DISP:
15566     case BFD_RELOC_MIPS_GOT_PAGE:
15567     case BFD_RELOC_MIPS_GOT_OFST:
15568     case BFD_RELOC_MIPS_SUB:
15569     case BFD_RELOC_MIPS_INSERT_A:
15570     case BFD_RELOC_MIPS_INSERT_B:
15571     case BFD_RELOC_MIPS_DELETE:
15572     case BFD_RELOC_MIPS_HIGHEST:
15573     case BFD_RELOC_MIPS_HIGHER:
15574     case BFD_RELOC_MIPS_SCN_DISP:
15575     case BFD_RELOC_MIPS_REL16:
15576     case BFD_RELOC_MIPS_RELGOT:
15577     case BFD_RELOC_MIPS_JALR:
15578     case BFD_RELOC_HI16:
15579     case BFD_RELOC_HI16_S:
15580     case BFD_RELOC_LO16:
15581     case BFD_RELOC_GPREL16:
15582     case BFD_RELOC_MIPS_LITERAL:
15583     case BFD_RELOC_MIPS_CALL16:
15584     case BFD_RELOC_MIPS_GOT16:
15585     case BFD_RELOC_GPREL32:
15586     case BFD_RELOC_MIPS_GOT_HI16:
15587     case BFD_RELOC_MIPS_GOT_LO16:
15588     case BFD_RELOC_MIPS_CALL_HI16:
15589     case BFD_RELOC_MIPS_CALL_LO16:
15590     case BFD_RELOC_HI16_S_PCREL:
15591     case BFD_RELOC_LO16_PCREL:
15592     case BFD_RELOC_MIPS16_GPREL:
15593     case BFD_RELOC_MIPS16_GOT16:
15594     case BFD_RELOC_MIPS16_CALL16:
15595     case BFD_RELOC_MIPS16_HI16:
15596     case BFD_RELOC_MIPS16_HI16_S:
15597     case BFD_RELOC_MIPS16_LO16:
15598     case BFD_RELOC_MICROMIPS_GOT_DISP:
15599     case BFD_RELOC_MICROMIPS_GOT_PAGE:
15600     case BFD_RELOC_MICROMIPS_GOT_OFST:
15601     case BFD_RELOC_MICROMIPS_SUB:
15602     case BFD_RELOC_MICROMIPS_HIGHEST:
15603     case BFD_RELOC_MICROMIPS_HIGHER:
15604     case BFD_RELOC_MICROMIPS_SCN_DISP:
15605     case BFD_RELOC_MICROMIPS_JALR:
15606     case BFD_RELOC_MICROMIPS_HI16:
15607     case BFD_RELOC_MICROMIPS_HI16_S:
15608     case BFD_RELOC_MICROMIPS_LO16:
15609     case BFD_RELOC_MICROMIPS_GPREL16:
15610     case BFD_RELOC_MICROMIPS_LITERAL:
15611     case BFD_RELOC_MICROMIPS_CALL16:
15612     case BFD_RELOC_MICROMIPS_GOT16:
15613     case BFD_RELOC_MICROMIPS_GOT_HI16:
15614     case BFD_RELOC_MICROMIPS_GOT_LO16:
15615     case BFD_RELOC_MICROMIPS_CALL_HI16:
15616     case BFD_RELOC_MICROMIPS_CALL_LO16:
15617     case BFD_RELOC_MIPS_EH:
15618       if (fixP->fx_done)
15619         {
15620           offsetT value;
15621
15622           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
15623             {
15624               insn = read_reloc_insn (buf, fixP->fx_r_type);
15625               if (mips16_reloc_p (fixP->fx_r_type))
15626                 insn |= mips16_immed_extend (value, 16);
15627               else
15628                 insn |= (value & 0xffff);
15629               write_reloc_insn (buf, fixP->fx_r_type, insn);
15630             }
15631           else
15632             as_bad_where (fixP->fx_file, fixP->fx_line,
15633                           _("unsupported constant in relocation"));
15634         }
15635       break;
15636
15637     case BFD_RELOC_64:
15638       /* This is handled like BFD_RELOC_32, but we output a sign
15639          extended value if we are only 32 bits.  */
15640       if (fixP->fx_done)
15641         {
15642           if (8 <= sizeof (valueT))
15643             md_number_to_chars (buf, *valP, 8);
15644           else
15645             {
15646               valueT hiv;
15647
15648               if ((*valP & 0x80000000) != 0)
15649                 hiv = 0xffffffff;
15650               else
15651                 hiv = 0;
15652               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
15653               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
15654             }
15655         }
15656       break;
15657
15658     case BFD_RELOC_RVA:
15659     case BFD_RELOC_32:
15660     case BFD_RELOC_32_PCREL:
15661     case BFD_RELOC_16:
15662     case BFD_RELOC_8:
15663       /* If we are deleting this reloc entry, we must fill in the
15664          value now.  This can happen if we have a .word which is not
15665          resolved when it appears but is later defined.  */
15666       if (fixP->fx_done)
15667         md_number_to_chars (buf, *valP, fixP->fx_size);
15668       break;
15669
15670     case BFD_RELOC_MIPS_21_PCREL_S2:
15671       fix_validate_branch (fixP, *valP);
15672       if (!fixP->fx_done)
15673         break;
15674
15675       if (*valP + 0x400000 <= 0x7fffff)
15676         {
15677           insn = read_insn (buf);
15678           insn |= (*valP >> 2) & 0x1fffff;
15679           write_insn (buf, insn);
15680         }
15681       else
15682         as_bad_where (fixP->fx_file, fixP->fx_line,
15683                       _("branch out of range"));
15684       break;
15685
15686     case BFD_RELOC_MIPS_26_PCREL_S2:
15687       fix_validate_branch (fixP, *valP);
15688       if (!fixP->fx_done)
15689         break;
15690
15691       if (*valP + 0x8000000 <= 0xfffffff)
15692         {
15693           insn = read_insn (buf);
15694           insn |= (*valP >> 2) & 0x3ffffff;
15695           write_insn (buf, insn);
15696         }
15697       else
15698         as_bad_where (fixP->fx_file, fixP->fx_line,
15699                       _("branch out of range"));
15700       break;
15701
15702     case BFD_RELOC_MIPS_18_PCREL_S3:
15703       if (fixP->fx_addsy && (S_GET_VALUE (fixP->fx_addsy) & 0x7) != 0)
15704         as_bad_where (fixP->fx_file, fixP->fx_line,
15705                       _("PC-relative access using misaligned symbol (%lx)"),
15706                       (long) S_GET_VALUE (fixP->fx_addsy));
15707       if ((fixP->fx_offset & 0x7) != 0)
15708         as_bad_where (fixP->fx_file, fixP->fx_line,
15709                       _("PC-relative access using misaligned offset (%lx)"),
15710                       (long) fixP->fx_offset);
15711       if (!fixP->fx_done)
15712         break;
15713
15714       if (*valP + 0x100000 <= 0x1fffff)
15715         {
15716           insn = read_insn (buf);
15717           insn |= (*valP >> 3) & 0x3ffff;
15718           write_insn (buf, insn);
15719         }
15720       else
15721         as_bad_where (fixP->fx_file, fixP->fx_line,
15722                       _("PC-relative access out of range"));
15723       break;
15724
15725     case BFD_RELOC_MIPS_19_PCREL_S2:
15726       if ((*valP & 0x3) != 0)
15727         as_bad_where (fixP->fx_file, fixP->fx_line,
15728                       _("PC-relative access to misaligned address (%lx)"),
15729                       (long) *valP);
15730       if (!fixP->fx_done)
15731         break;
15732
15733       if (*valP + 0x100000 <= 0x1fffff)
15734         {
15735           insn = read_insn (buf);
15736           insn |= (*valP >> 2) & 0x7ffff;
15737           write_insn (buf, insn);
15738         }
15739       else
15740         as_bad_where (fixP->fx_file, fixP->fx_line,
15741                       _("PC-relative access out of range"));
15742       break;
15743
15744     case BFD_RELOC_16_PCREL_S2:
15745       fix_validate_branch (fixP, *valP);
15746
15747       /* We need to save the bits in the instruction since fixup_segment()
15748          might be deleting the relocation entry (i.e., a branch within
15749          the current segment).  */
15750       if (! fixP->fx_done)
15751         break;
15752
15753       /* Update old instruction data.  */
15754       insn = read_insn (buf);
15755
15756       if (*valP + 0x20000 <= 0x3ffff)
15757         {
15758           insn |= (*valP >> 2) & 0xffff;
15759           write_insn (buf, insn);
15760         }
15761       else if (fixP->fx_tcbit2
15762                && fixP->fx_done
15763                && fixP->fx_frag->fr_address >= text_section->vma
15764                && (fixP->fx_frag->fr_address
15765                    < text_section->vma + bfd_get_section_size (text_section))
15766                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
15767                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
15768                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
15769         {
15770           /* The branch offset is too large.  If this is an
15771              unconditional branch, and we are not generating PIC code,
15772              we can convert it to an absolute jump instruction.  */
15773           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
15774             insn = 0x0c000000;  /* jal */
15775           else
15776             insn = 0x08000000;  /* j */
15777           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
15778           fixP->fx_done = 0;
15779           fixP->fx_addsy = section_symbol (text_section);
15780           *valP += md_pcrel_from (fixP);
15781           write_insn (buf, insn);
15782         }
15783       else
15784         {
15785           /* If we got here, we have branch-relaxation disabled,
15786              and there's nothing we can do to fix this instruction
15787              without turning it into a longer sequence.  */
15788           as_bad_where (fixP->fx_file, fixP->fx_line,
15789                         _("branch out of range"));
15790         }
15791       break;
15792
15793     case BFD_RELOC_MIPS16_16_PCREL_S1:
15794     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15795     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15796     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15797       gas_assert (!fixP->fx_done);
15798       if (fix_bad_cross_mode_branch_p (fixP))
15799         as_bad_where (fixP->fx_file, fixP->fx_line,
15800                       _("branch to a symbol in another ISA mode"));
15801       else if (fixP->fx_addsy
15802                && !S_FORCE_RELOC (fixP->fx_addsy, TRUE)
15803                && !bfd_is_abs_section (S_GET_SEGMENT (fixP->fx_addsy))
15804                && (fixP->fx_offset & 0x1) != 0)
15805         as_bad_where (fixP->fx_file, fixP->fx_line,
15806                       _("branch to misaligned address (0x%lx)"),
15807                       (long) (S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset));
15808       else if (HAVE_IN_PLACE_ADDENDS && (fixP->fx_offset & 0x1) != 0)
15809         as_bad_where (fixP->fx_file, fixP->fx_line,
15810                       _("cannot encode misaligned addend "
15811                         "in the relocatable field (0x%lx)"),
15812                       (long) fixP->fx_offset);
15813       break;
15814
15815     case BFD_RELOC_VTABLE_INHERIT:
15816       fixP->fx_done = 0;
15817       if (fixP->fx_addsy
15818           && !S_IS_DEFINED (fixP->fx_addsy)
15819           && !S_IS_WEAK (fixP->fx_addsy))
15820         S_SET_WEAK (fixP->fx_addsy);
15821       break;
15822
15823     case BFD_RELOC_NONE:
15824     case BFD_RELOC_VTABLE_ENTRY:
15825       fixP->fx_done = 0;
15826       break;
15827
15828     default:
15829       abort ();
15830     }
15831
15832   /* Remember value for tc_gen_reloc.  */
15833   fixP->fx_addnumber = *valP;
15834 }
15835
15836 static symbolS *
15837 get_symbol (void)
15838 {
15839   int c;
15840   char *name;
15841   symbolS *p;
15842
15843   c = get_symbol_name (&name);
15844   p = (symbolS *) symbol_find_or_make (name);
15845   (void) restore_line_pointer (c);
15846   return p;
15847 }
15848
15849 /* Align the current frag to a given power of two.  If a particular
15850    fill byte should be used, FILL points to an integer that contains
15851    that byte, otherwise FILL is null.
15852
15853    This function used to have the comment:
15854
15855       The MIPS assembler also automatically adjusts any preceding label.
15856
15857    The implementation therefore applied the adjustment to a maximum of
15858    one label.  However, other label adjustments are applied to batches
15859    of labels, and adjusting just one caused problems when new labels
15860    were added for the sake of debugging or unwind information.
15861    We therefore adjust all preceding labels (given as LABELS) instead.  */
15862
15863 static void
15864 mips_align (int to, int *fill, struct insn_label_list *labels)
15865 {
15866   mips_emit_delays ();
15867   mips_record_compressed_mode ();
15868   if (fill == NULL && subseg_text_p (now_seg))
15869     frag_align_code (to, 0);
15870   else
15871     frag_align (to, fill ? *fill : 0, 0);
15872   record_alignment (now_seg, to);
15873   mips_move_labels (labels, FALSE);
15874 }
15875
15876 /* Align to a given power of two.  .align 0 turns off the automatic
15877    alignment used by the data creating pseudo-ops.  */
15878
15879 static void
15880 s_align (int x ATTRIBUTE_UNUSED)
15881 {
15882   int temp, fill_value, *fill_ptr;
15883   long max_alignment = 28;
15884
15885   /* o Note that the assembler pulls down any immediately preceding label
15886        to the aligned address.
15887      o It's not documented but auto alignment is reinstated by
15888        a .align pseudo instruction.
15889      o Note also that after auto alignment is turned off the mips assembler
15890        issues an error on attempt to assemble an improperly aligned data item.
15891        We don't.  */
15892
15893   temp = get_absolute_expression ();
15894   if (temp > max_alignment)
15895     as_bad (_("alignment too large, %d assumed"), temp = max_alignment);
15896   else if (temp < 0)
15897     {
15898       as_warn (_("alignment negative, 0 assumed"));
15899       temp = 0;
15900     }
15901   if (*input_line_pointer == ',')
15902     {
15903       ++input_line_pointer;
15904       fill_value = get_absolute_expression ();
15905       fill_ptr = &fill_value;
15906     }
15907   else
15908     fill_ptr = 0;
15909   if (temp)
15910     {
15911       segment_info_type *si = seg_info (now_seg);
15912       struct insn_label_list *l = si->label_list;
15913       /* Auto alignment should be switched on by next section change.  */
15914       auto_align = 1;
15915       mips_align (temp, fill_ptr, l);
15916     }
15917   else
15918     {
15919       auto_align = 0;
15920     }
15921
15922   demand_empty_rest_of_line ();
15923 }
15924
15925 static void
15926 s_change_sec (int sec)
15927 {
15928   segT seg;
15929
15930   /* The ELF backend needs to know that we are changing sections, so
15931      that .previous works correctly.  We could do something like check
15932      for an obj_section_change_hook macro, but that might be confusing
15933      as it would not be appropriate to use it in the section changing
15934      functions in read.c, since obj-elf.c intercepts those.  FIXME:
15935      This should be cleaner, somehow.  */
15936   obj_elf_section_change_hook ();
15937
15938   mips_emit_delays ();
15939
15940   switch (sec)
15941     {
15942     case 't':
15943       s_text (0);
15944       break;
15945     case 'd':
15946       s_data (0);
15947       break;
15948     case 'b':
15949       subseg_set (bss_section, (subsegT) get_absolute_expression ());
15950       demand_empty_rest_of_line ();
15951       break;
15952
15953     case 'r':
15954       seg = subseg_new (RDATA_SECTION_NAME,
15955                         (subsegT) get_absolute_expression ());
15956       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
15957                                               | SEC_READONLY | SEC_RELOC
15958                                               | SEC_DATA));
15959       if (strncmp (TARGET_OS, "elf", 3) != 0)
15960         record_alignment (seg, 4);
15961       demand_empty_rest_of_line ();
15962       break;
15963
15964     case 's':
15965       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
15966       bfd_set_section_flags (stdoutput, seg,
15967                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
15968       if (strncmp (TARGET_OS, "elf", 3) != 0)
15969         record_alignment (seg, 4);
15970       demand_empty_rest_of_line ();
15971       break;
15972
15973     case 'B':
15974       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
15975       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
15976       if (strncmp (TARGET_OS, "elf", 3) != 0)
15977         record_alignment (seg, 4);
15978       demand_empty_rest_of_line ();
15979       break;
15980     }
15981
15982   auto_align = 1;
15983 }
15984
15985 void
15986 s_change_section (int ignore ATTRIBUTE_UNUSED)
15987 {
15988   char *saved_ilp;
15989   char *section_name;
15990   char c, endc;
15991   char next_c = 0;
15992   int section_type;
15993   int section_flag;
15994   int section_entry_size;
15995   int section_alignment;
15996
15997   saved_ilp = input_line_pointer;
15998   endc = get_symbol_name (&section_name);
15999   c = (endc == '"' ? input_line_pointer[1] : endc);
16000   if (c)
16001     next_c = input_line_pointer [(endc == '"' ? 2 : 1)];
16002
16003   /* Do we have .section Name<,"flags">?  */
16004   if (c != ',' || (c == ',' && next_c == '"'))
16005     {
16006       /* Just after name is now '\0'.  */
16007       (void) restore_line_pointer (endc);
16008       input_line_pointer = saved_ilp;
16009       obj_elf_section (ignore);
16010       return;
16011     }
16012
16013   section_name = xstrdup (section_name);
16014   c = restore_line_pointer (endc);
16015
16016   input_line_pointer++;
16017
16018   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
16019   if (c == ',')
16020     section_type = get_absolute_expression ();
16021   else
16022     section_type = 0;
16023
16024   if (*input_line_pointer++ == ',')
16025     section_flag = get_absolute_expression ();
16026   else
16027     section_flag = 0;
16028
16029   if (*input_line_pointer++ == ',')
16030     section_entry_size = get_absolute_expression ();
16031   else
16032     section_entry_size = 0;
16033
16034   if (*input_line_pointer++ == ',')
16035     section_alignment = get_absolute_expression ();
16036   else
16037     section_alignment = 0;
16038
16039   /* FIXME: really ignore?  */
16040   (void) section_alignment;
16041
16042   /* When using the generic form of .section (as implemented by obj-elf.c),
16043      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
16044      traditionally had to fall back on the more common @progbits instead.
16045
16046      There's nothing really harmful in this, since bfd will correct
16047      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
16048      means that, for backwards compatibility, the special_section entries
16049      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
16050
16051      Even so, we shouldn't force users of the MIPS .section syntax to
16052      incorrectly label the sections as SHT_PROGBITS.  The best compromise
16053      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
16054      generic type-checking code.  */
16055   if (section_type == SHT_MIPS_DWARF)
16056     section_type = SHT_PROGBITS;
16057
16058   obj_elf_change_section (section_name, section_type, 0, section_flag,
16059                           section_entry_size, 0, 0, 0);
16060
16061   if (now_seg->name != section_name)
16062     free (section_name);
16063 }
16064
16065 void
16066 mips_enable_auto_align (void)
16067 {
16068   auto_align = 1;
16069 }
16070
16071 static void
16072 s_cons (int log_size)
16073 {
16074   segment_info_type *si = seg_info (now_seg);
16075   struct insn_label_list *l = si->label_list;
16076
16077   mips_emit_delays ();
16078   if (log_size > 0 && auto_align)
16079     mips_align (log_size, 0, l);
16080   cons (1 << log_size);
16081   mips_clear_insn_labels ();
16082 }
16083
16084 static void
16085 s_float_cons (int type)
16086 {
16087   segment_info_type *si = seg_info (now_seg);
16088   struct insn_label_list *l = si->label_list;
16089
16090   mips_emit_delays ();
16091
16092   if (auto_align)
16093     {
16094       if (type == 'd')
16095         mips_align (3, 0, l);
16096       else
16097         mips_align (2, 0, l);
16098     }
16099
16100   float_cons (type);
16101   mips_clear_insn_labels ();
16102 }
16103
16104 /* Handle .globl.  We need to override it because on Irix 5 you are
16105    permitted to say
16106        .globl foo .text
16107    where foo is an undefined symbol, to mean that foo should be
16108    considered to be the address of a function.  */
16109
16110 static void
16111 s_mips_globl (int x ATTRIBUTE_UNUSED)
16112 {
16113   char *name;
16114   int c;
16115   symbolS *symbolP;
16116   flagword flag;
16117
16118   do
16119     {
16120       c = get_symbol_name (&name);
16121       symbolP = symbol_find_or_make (name);
16122       S_SET_EXTERNAL (symbolP);
16123
16124       *input_line_pointer = c;
16125       SKIP_WHITESPACE_AFTER_NAME ();
16126
16127       /* On Irix 5, every global symbol that is not explicitly labelled as
16128          being a function is apparently labelled as being an object.  */
16129       flag = BSF_OBJECT;
16130
16131       if (!is_end_of_line[(unsigned char) *input_line_pointer]
16132           && (*input_line_pointer != ','))
16133         {
16134           char *secname;
16135           asection *sec;
16136
16137           c = get_symbol_name (&secname);
16138           sec = bfd_get_section_by_name (stdoutput, secname);
16139           if (sec == NULL)
16140             as_bad (_("%s: no such section"), secname);
16141           (void) restore_line_pointer (c);
16142
16143           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
16144             flag = BSF_FUNCTION;
16145         }
16146
16147       symbol_get_bfdsym (symbolP)->flags |= flag;
16148
16149       c = *input_line_pointer;
16150       if (c == ',')
16151         {
16152           input_line_pointer++;
16153           SKIP_WHITESPACE ();
16154           if (is_end_of_line[(unsigned char) *input_line_pointer])
16155             c = '\n';
16156         }
16157     }
16158   while (c == ',');
16159
16160   demand_empty_rest_of_line ();
16161 }
16162
16163 static void
16164 s_option (int x ATTRIBUTE_UNUSED)
16165 {
16166   char *opt;
16167   char c;
16168
16169   c = get_symbol_name (&opt);
16170
16171   if (*opt == 'O')
16172     {
16173       /* FIXME: What does this mean?  */
16174     }
16175   else if (strncmp (opt, "pic", 3) == 0 && ISDIGIT (opt[3]) && opt[4] == '\0')
16176     {
16177       int i;
16178
16179       i = atoi (opt + 3);
16180       if (i != 0 && i != 2)
16181         as_bad (_(".option pic%d not supported"), i);
16182       else if (mips_pic == VXWORKS_PIC)
16183         as_bad (_(".option pic%d not supported in VxWorks PIC mode"), i);
16184       else if (i == 0)
16185         mips_pic = NO_PIC;
16186       else if (i == 2)
16187         {
16188           mips_pic = SVR4_PIC;
16189           mips_abicalls = TRUE;
16190         }
16191
16192       if (mips_pic == SVR4_PIC)
16193         {
16194           if (g_switch_seen && g_switch_value != 0)
16195             as_warn (_("-G may not be used with SVR4 PIC code"));
16196           g_switch_value = 0;
16197           bfd_set_gp_size (stdoutput, 0);
16198         }
16199     }
16200   else
16201     as_warn (_("unrecognized option \"%s\""), opt);
16202
16203   (void) restore_line_pointer (c);
16204   demand_empty_rest_of_line ();
16205 }
16206
16207 /* This structure is used to hold a stack of .set values.  */
16208
16209 struct mips_option_stack
16210 {
16211   struct mips_option_stack *next;
16212   struct mips_set_options options;
16213 };
16214
16215 static struct mips_option_stack *mips_opts_stack;
16216
16217 /* Return status for .set/.module option handling.  */
16218
16219 enum code_option_type
16220 {
16221   /* Unrecognized option.  */
16222   OPTION_TYPE_BAD = -1,
16223
16224   /* Ordinary option.  */
16225   OPTION_TYPE_NORMAL,
16226
16227   /* ISA changing option.  */
16228   OPTION_TYPE_ISA
16229 };
16230
16231 /* Handle common .set/.module options.  Return status indicating option
16232    type.  */
16233
16234 static enum code_option_type
16235 parse_code_option (char * name)
16236 {
16237   bfd_boolean isa_set = FALSE;
16238   const struct mips_ase *ase;
16239
16240   if (strncmp (name, "at=", 3) == 0)
16241     {
16242       char *s = name + 3;
16243
16244       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
16245         as_bad (_("unrecognized register name `%s'"), s);
16246     }
16247   else if (strcmp (name, "at") == 0)
16248     mips_opts.at = ATREG;
16249   else if (strcmp (name, "noat") == 0)
16250     mips_opts.at = ZERO;
16251   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
16252     mips_opts.nomove = 0;
16253   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
16254     mips_opts.nomove = 1;
16255   else if (strcmp (name, "bopt") == 0)
16256     mips_opts.nobopt = 0;
16257   else if (strcmp (name, "nobopt") == 0)
16258     mips_opts.nobopt = 1;
16259   else if (strcmp (name, "gp=32") == 0)
16260     mips_opts.gp = 32;
16261   else if (strcmp (name, "gp=64") == 0)
16262     mips_opts.gp = 64;
16263   else if (strcmp (name, "fp=32") == 0)
16264     mips_opts.fp = 32;
16265   else if (strcmp (name, "fp=xx") == 0)
16266     mips_opts.fp = 0;
16267   else if (strcmp (name, "fp=64") == 0)
16268     mips_opts.fp = 64;
16269   else if (strcmp (name, "softfloat") == 0)
16270     mips_opts.soft_float = 1;
16271   else if (strcmp (name, "hardfloat") == 0)
16272     mips_opts.soft_float = 0;
16273   else if (strcmp (name, "singlefloat") == 0)
16274     mips_opts.single_float = 1;
16275   else if (strcmp (name, "doublefloat") == 0)
16276     mips_opts.single_float = 0;
16277   else if (strcmp (name, "nooddspreg") == 0)
16278     mips_opts.oddspreg = 0;
16279   else if (strcmp (name, "oddspreg") == 0)
16280     mips_opts.oddspreg = 1;
16281   else if (strcmp (name, "mips16") == 0
16282            || strcmp (name, "MIPS-16") == 0)
16283     mips_opts.mips16 = 1;
16284   else if (strcmp (name, "nomips16") == 0
16285            || strcmp (name, "noMIPS-16") == 0)
16286     mips_opts.mips16 = 0;
16287   else if (strcmp (name, "micromips") == 0)
16288     mips_opts.micromips = 1;
16289   else if (strcmp (name, "nomicromips") == 0)
16290     mips_opts.micromips = 0;
16291   else if (name[0] == 'n'
16292            && name[1] == 'o'
16293            && (ase = mips_lookup_ase (name + 2)))
16294     mips_set_ase (ase, &mips_opts, FALSE);
16295   else if ((ase = mips_lookup_ase (name)))
16296     mips_set_ase (ase, &mips_opts, TRUE);
16297   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
16298     {
16299       /* Permit the user to change the ISA and architecture on the fly.
16300          Needless to say, misuse can cause serious problems.  */
16301       if (strncmp (name, "arch=", 5) == 0)
16302         {
16303           const struct mips_cpu_info *p;
16304
16305           p = mips_parse_cpu ("internal use", name + 5);
16306           if (!p)
16307             as_bad (_("unknown architecture %s"), name + 5);
16308           else
16309             {
16310               mips_opts.arch = p->cpu;
16311               mips_opts.isa = p->isa;
16312               isa_set = TRUE;
16313             }
16314         }
16315       else if (strncmp (name, "mips", 4) == 0)
16316         {
16317           const struct mips_cpu_info *p;
16318
16319           p = mips_parse_cpu ("internal use", name);
16320           if (!p)
16321             as_bad (_("unknown ISA level %s"), name + 4);
16322           else
16323             {
16324               mips_opts.arch = p->cpu;
16325               mips_opts.isa = p->isa;
16326               isa_set = TRUE;
16327             }
16328         }
16329       else
16330         as_bad (_("unknown ISA or architecture %s"), name);
16331     }
16332   else if (strcmp (name, "autoextend") == 0)
16333     mips_opts.noautoextend = 0;
16334   else if (strcmp (name, "noautoextend") == 0)
16335     mips_opts.noautoextend = 1;
16336   else if (strcmp (name, "insn32") == 0)
16337     mips_opts.insn32 = TRUE;
16338   else if (strcmp (name, "noinsn32") == 0)
16339     mips_opts.insn32 = FALSE;
16340   else if (strcmp (name, "sym32") == 0)
16341     mips_opts.sym32 = TRUE;
16342   else if (strcmp (name, "nosym32") == 0)
16343     mips_opts.sym32 = FALSE;
16344   else
16345     return OPTION_TYPE_BAD;
16346
16347   return isa_set ? OPTION_TYPE_ISA : OPTION_TYPE_NORMAL;
16348 }
16349
16350 /* Handle the .set pseudo-op.  */
16351
16352 static void
16353 s_mipsset (int x ATTRIBUTE_UNUSED)
16354 {
16355   enum code_option_type type = OPTION_TYPE_NORMAL;
16356   char *name = input_line_pointer, ch;
16357
16358   file_mips_check_options ();
16359
16360   while (!is_end_of_line[(unsigned char) *input_line_pointer])
16361     ++input_line_pointer;
16362   ch = *input_line_pointer;
16363   *input_line_pointer = '\0';
16364
16365   if (strchr (name, ','))
16366     {
16367       /* Generic ".set" directive; use the generic handler.  */
16368       *input_line_pointer = ch;
16369       input_line_pointer = name;
16370       s_set (0);
16371       return;
16372     }
16373
16374   if (strcmp (name, "reorder") == 0)
16375     {
16376       if (mips_opts.noreorder)
16377         end_noreorder ();
16378     }
16379   else if (strcmp (name, "noreorder") == 0)
16380     {
16381       if (!mips_opts.noreorder)
16382         start_noreorder ();
16383     }
16384   else if (strcmp (name, "macro") == 0)
16385     mips_opts.warn_about_macros = 0;
16386   else if (strcmp (name, "nomacro") == 0)
16387     {
16388       if (mips_opts.noreorder == 0)
16389         as_bad (_("`noreorder' must be set before `nomacro'"));
16390       mips_opts.warn_about_macros = 1;
16391     }
16392   else if (strcmp (name, "gp=default") == 0)
16393     mips_opts.gp = file_mips_opts.gp;
16394   else if (strcmp (name, "fp=default") == 0)
16395     mips_opts.fp = file_mips_opts.fp;
16396   else if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
16397     {
16398       mips_opts.isa = file_mips_opts.isa;
16399       mips_opts.arch = file_mips_opts.arch;
16400       mips_opts.gp = file_mips_opts.gp;
16401       mips_opts.fp = file_mips_opts.fp;
16402     }
16403   else if (strcmp (name, "push") == 0)
16404     {
16405       struct mips_option_stack *s;
16406
16407       s = XNEW (struct mips_option_stack);
16408       s->next = mips_opts_stack;
16409       s->options = mips_opts;
16410       mips_opts_stack = s;
16411     }
16412   else if (strcmp (name, "pop") == 0)
16413     {
16414       struct mips_option_stack *s;
16415
16416       s = mips_opts_stack;
16417       if (s == NULL)
16418         as_bad (_(".set pop with no .set push"));
16419       else
16420         {
16421           /* If we're changing the reorder mode we need to handle
16422              delay slots correctly.  */
16423           if (s->options.noreorder && ! mips_opts.noreorder)
16424             start_noreorder ();
16425           else if (! s->options.noreorder && mips_opts.noreorder)
16426             end_noreorder ();
16427
16428           mips_opts = s->options;
16429           mips_opts_stack = s->next;
16430           free (s);
16431         }
16432     }
16433   else
16434     {
16435       type = parse_code_option (name);
16436       if (type == OPTION_TYPE_BAD)
16437         as_warn (_("tried to set unrecognized symbol: %s\n"), name);
16438     }
16439
16440   /* The use of .set [arch|cpu]= historically 'fixes' the width of gp and fp
16441      registers based on what is supported by the arch/cpu.  */
16442   if (type == OPTION_TYPE_ISA)
16443     {
16444       switch (mips_opts.isa)
16445         {
16446         case 0:
16447           break;
16448         case ISA_MIPS1:
16449           /* MIPS I cannot support FPXX.  */
16450           mips_opts.fp = 32;
16451           /* fall-through.  */
16452         case ISA_MIPS2:
16453         case ISA_MIPS32:
16454         case ISA_MIPS32R2:
16455         case ISA_MIPS32R3:
16456         case ISA_MIPS32R5:
16457           mips_opts.gp = 32;
16458           if (mips_opts.fp != 0)
16459             mips_opts.fp = 32;
16460           break;
16461         case ISA_MIPS32R6:
16462           mips_opts.gp = 32;
16463           mips_opts.fp = 64;
16464           break;
16465         case ISA_MIPS3:
16466         case ISA_MIPS4:
16467         case ISA_MIPS5:
16468         case ISA_MIPS64:
16469         case ISA_MIPS64R2:
16470         case ISA_MIPS64R3:
16471         case ISA_MIPS64R5:
16472         case ISA_MIPS64R6:
16473           mips_opts.gp = 64;
16474           if (mips_opts.fp != 0)
16475             {
16476               if (mips_opts.arch == CPU_R5900)
16477                 mips_opts.fp = 32;
16478               else
16479                 mips_opts.fp = 64;
16480             }
16481           break;
16482         default:
16483           as_bad (_("unknown ISA level %s"), name + 4);
16484           break;
16485         }
16486     }
16487
16488   mips_check_options (&mips_opts, FALSE);
16489
16490   mips_check_isa_supports_ases ();
16491   *input_line_pointer = ch;
16492   demand_empty_rest_of_line ();
16493 }
16494
16495 /* Handle the .module pseudo-op.  */
16496
16497 static void
16498 s_module (int ignore ATTRIBUTE_UNUSED)
16499 {
16500   char *name = input_line_pointer, ch;
16501
16502   while (!is_end_of_line[(unsigned char) *input_line_pointer])
16503     ++input_line_pointer;
16504   ch = *input_line_pointer;
16505   *input_line_pointer = '\0';
16506
16507   if (!file_mips_opts_checked)
16508     {
16509       if (parse_code_option (name) == OPTION_TYPE_BAD)
16510         as_bad (_(".module used with unrecognized symbol: %s\n"), name);
16511
16512       /* Update module level settings from mips_opts.  */
16513       file_mips_opts = mips_opts;
16514     }
16515   else
16516     as_bad (_(".module is not permitted after generating code"));
16517
16518   *input_line_pointer = ch;
16519   demand_empty_rest_of_line ();
16520 }
16521
16522 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
16523    .option pic2.  It means to generate SVR4 PIC calls.  */
16524
16525 static void
16526 s_abicalls (int ignore ATTRIBUTE_UNUSED)
16527 {
16528   mips_pic = SVR4_PIC;
16529   mips_abicalls = TRUE;
16530
16531   if (g_switch_seen && g_switch_value != 0)
16532     as_warn (_("-G may not be used with SVR4 PIC code"));
16533   g_switch_value = 0;
16534
16535   bfd_set_gp_size (stdoutput, 0);
16536   demand_empty_rest_of_line ();
16537 }
16538
16539 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
16540    PIC code.  It sets the $gp register for the function based on the
16541    function address, which is in the register named in the argument.
16542    This uses a relocation against _gp_disp, which is handled specially
16543    by the linker.  The result is:
16544         lui     $gp,%hi(_gp_disp)
16545         addiu   $gp,$gp,%lo(_gp_disp)
16546         addu    $gp,$gp,.cpload argument
16547    The .cpload argument is normally $25 == $t9.
16548
16549    The -mno-shared option changes this to:
16550         lui     $gp,%hi(__gnu_local_gp)
16551         addiu   $gp,$gp,%lo(__gnu_local_gp)
16552    and the argument is ignored.  This saves an instruction, but the
16553    resulting code is not position independent; it uses an absolute
16554    address for __gnu_local_gp.  Thus code assembled with -mno-shared
16555    can go into an ordinary executable, but not into a shared library.  */
16556
16557 static void
16558 s_cpload (int ignore ATTRIBUTE_UNUSED)
16559 {
16560   expressionS ex;
16561   int reg;
16562   int in_shared;
16563
16564   file_mips_check_options ();
16565
16566   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16567      .cpload is ignored.  */
16568   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16569     {
16570       s_ignore (0);
16571       return;
16572     }
16573
16574   if (mips_opts.mips16)
16575     {
16576       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
16577       ignore_rest_of_line ();
16578       return;
16579     }
16580
16581   /* .cpload should be in a .set noreorder section.  */
16582   if (mips_opts.noreorder == 0)
16583     as_warn (_(".cpload not in noreorder section"));
16584
16585   reg = tc_get_register (0);
16586
16587   /* If we need to produce a 64-bit address, we are better off using
16588      the default instruction sequence.  */
16589   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
16590
16591   ex.X_op = O_symbol;
16592   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
16593                                          "__gnu_local_gp");
16594   ex.X_op_symbol = NULL;
16595   ex.X_add_number = 0;
16596
16597   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16598   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16599
16600   mips_mark_labels ();
16601   mips_assembling_insn = TRUE;
16602
16603   macro_start ();
16604   macro_build_lui (&ex, mips_gp_register);
16605   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16606                mips_gp_register, BFD_RELOC_LO16);
16607   if (in_shared)
16608     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
16609                  mips_gp_register, reg);
16610   macro_end ();
16611
16612   mips_assembling_insn = FALSE;
16613   demand_empty_rest_of_line ();
16614 }
16615
16616 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
16617      .cpsetup $reg1, offset|$reg2, label
16618
16619    If offset is given, this results in:
16620      sd         $gp, offset($sp)
16621      lui        $gp, %hi(%neg(%gp_rel(label)))
16622      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16623      daddu      $gp, $gp, $reg1
16624
16625    If $reg2 is given, this results in:
16626      or         $reg2, $gp, $0
16627      lui        $gp, %hi(%neg(%gp_rel(label)))
16628      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16629      daddu      $gp, $gp, $reg1
16630    $reg1 is normally $25 == $t9.
16631
16632    The -mno-shared option replaces the last three instructions with
16633         lui     $gp,%hi(_gp)
16634         addiu   $gp,$gp,%lo(_gp)  */
16635
16636 static void
16637 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
16638 {
16639   expressionS ex_off;
16640   expressionS ex_sym;
16641   int reg1;
16642
16643   file_mips_check_options ();
16644
16645   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
16646      We also need NewABI support.  */
16647   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16648     {
16649       s_ignore (0);
16650       return;
16651     }
16652
16653   if (mips_opts.mips16)
16654     {
16655       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
16656       ignore_rest_of_line ();
16657       return;
16658     }
16659
16660   reg1 = tc_get_register (0);
16661   SKIP_WHITESPACE ();
16662   if (*input_line_pointer != ',')
16663     {
16664       as_bad (_("missing argument separator ',' for .cpsetup"));
16665       return;
16666     }
16667   else
16668     ++input_line_pointer;
16669   SKIP_WHITESPACE ();
16670   if (*input_line_pointer == '$')
16671     {
16672       mips_cpreturn_register = tc_get_register (0);
16673       mips_cpreturn_offset = -1;
16674     }
16675   else
16676     {
16677       mips_cpreturn_offset = get_absolute_expression ();
16678       mips_cpreturn_register = -1;
16679     }
16680   SKIP_WHITESPACE ();
16681   if (*input_line_pointer != ',')
16682     {
16683       as_bad (_("missing argument separator ',' for .cpsetup"));
16684       return;
16685     }
16686   else
16687     ++input_line_pointer;
16688   SKIP_WHITESPACE ();
16689   expression (&ex_sym);
16690
16691   mips_mark_labels ();
16692   mips_assembling_insn = TRUE;
16693
16694   macro_start ();
16695   if (mips_cpreturn_register == -1)
16696     {
16697       ex_off.X_op = O_constant;
16698       ex_off.X_add_symbol = NULL;
16699       ex_off.X_op_symbol = NULL;
16700       ex_off.X_add_number = mips_cpreturn_offset;
16701
16702       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
16703                    BFD_RELOC_LO16, SP);
16704     }
16705   else
16706     move_register (mips_cpreturn_register, mips_gp_register);
16707
16708   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
16709     {
16710       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
16711                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
16712                    BFD_RELOC_HI16_S);
16713
16714       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
16715                    mips_gp_register, -1, BFD_RELOC_GPREL16,
16716                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
16717
16718       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
16719                    mips_gp_register, reg1);
16720     }
16721   else
16722     {
16723       expressionS ex;
16724
16725       ex.X_op = O_symbol;
16726       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
16727       ex.X_op_symbol = NULL;
16728       ex.X_add_number = 0;
16729
16730       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16731       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16732
16733       macro_build_lui (&ex, mips_gp_register);
16734       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16735                    mips_gp_register, BFD_RELOC_LO16);
16736     }
16737
16738   macro_end ();
16739
16740   mips_assembling_insn = FALSE;
16741   demand_empty_rest_of_line ();
16742 }
16743
16744 static void
16745 s_cplocal (int ignore ATTRIBUTE_UNUSED)
16746 {
16747   file_mips_check_options ();
16748
16749   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
16750      .cplocal is ignored.  */
16751   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16752     {
16753       s_ignore (0);
16754       return;
16755     }
16756
16757   if (mips_opts.mips16)
16758     {
16759       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
16760       ignore_rest_of_line ();
16761       return;
16762     }
16763
16764   mips_gp_register = tc_get_register (0);
16765   demand_empty_rest_of_line ();
16766 }
16767
16768 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
16769    offset from $sp.  The offset is remembered, and after making a PIC
16770    call $gp is restored from that location.  */
16771
16772 static void
16773 s_cprestore (int ignore ATTRIBUTE_UNUSED)
16774 {
16775   expressionS ex;
16776
16777   file_mips_check_options ();
16778
16779   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16780      .cprestore is ignored.  */
16781   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16782     {
16783       s_ignore (0);
16784       return;
16785     }
16786
16787   if (mips_opts.mips16)
16788     {
16789       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
16790       ignore_rest_of_line ();
16791       return;
16792     }
16793
16794   mips_cprestore_offset = get_absolute_expression ();
16795   mips_cprestore_valid = 1;
16796
16797   ex.X_op = O_constant;
16798   ex.X_add_symbol = NULL;
16799   ex.X_op_symbol = NULL;
16800   ex.X_add_number = mips_cprestore_offset;
16801
16802   mips_mark_labels ();
16803   mips_assembling_insn = TRUE;
16804
16805   macro_start ();
16806   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
16807                                 SP, HAVE_64BIT_ADDRESSES);
16808   macro_end ();
16809
16810   mips_assembling_insn = FALSE;
16811   demand_empty_rest_of_line ();
16812 }
16813
16814 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
16815    was given in the preceding .cpsetup, it results in:
16816      ld         $gp, offset($sp)
16817
16818    If a register $reg2 was given there, it results in:
16819      or         $gp, $reg2, $0  */
16820
16821 static void
16822 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
16823 {
16824   expressionS ex;
16825
16826   file_mips_check_options ();
16827
16828   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
16829      We also need NewABI support.  */
16830   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16831     {
16832       s_ignore (0);
16833       return;
16834     }
16835
16836   if (mips_opts.mips16)
16837     {
16838       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
16839       ignore_rest_of_line ();
16840       return;
16841     }
16842
16843   mips_mark_labels ();
16844   mips_assembling_insn = TRUE;
16845
16846   macro_start ();
16847   if (mips_cpreturn_register == -1)
16848     {
16849       ex.X_op = O_constant;
16850       ex.X_add_symbol = NULL;
16851       ex.X_op_symbol = NULL;
16852       ex.X_add_number = mips_cpreturn_offset;
16853
16854       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
16855     }
16856   else
16857     move_register (mips_gp_register, mips_cpreturn_register);
16858
16859   macro_end ();
16860
16861   mips_assembling_insn = FALSE;
16862   demand_empty_rest_of_line ();
16863 }
16864
16865 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
16866    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
16867    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
16868    debug information or MIPS16 TLS.  */
16869
16870 static void
16871 s_tls_rel_directive (const size_t bytes, const char *dirstr,
16872                      bfd_reloc_code_real_type rtype)
16873 {
16874   expressionS ex;
16875   char *p;
16876
16877   expression (&ex);
16878
16879   if (ex.X_op != O_symbol)
16880     {
16881       as_bad (_("unsupported use of %s"), dirstr);
16882       ignore_rest_of_line ();
16883     }
16884
16885   p = frag_more (bytes);
16886   md_number_to_chars (p, 0, bytes);
16887   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
16888   demand_empty_rest_of_line ();
16889   mips_clear_insn_labels ();
16890 }
16891
16892 /* Handle .dtprelword.  */
16893
16894 static void
16895 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
16896 {
16897   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
16898 }
16899
16900 /* Handle .dtpreldword.  */
16901
16902 static void
16903 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
16904 {
16905   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
16906 }
16907
16908 /* Handle .tprelword.  */
16909
16910 static void
16911 s_tprelword (int ignore ATTRIBUTE_UNUSED)
16912 {
16913   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
16914 }
16915
16916 /* Handle .tpreldword.  */
16917
16918 static void
16919 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
16920 {
16921   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
16922 }
16923
16924 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
16925    code.  It sets the offset to use in gp_rel relocations.  */
16926
16927 static void
16928 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
16929 {
16930   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
16931      We also need NewABI support.  */
16932   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16933     {
16934       s_ignore (0);
16935       return;
16936     }
16937
16938   mips_gprel_offset = get_absolute_expression ();
16939
16940   demand_empty_rest_of_line ();
16941 }
16942
16943 /* Handle the .gpword pseudo-op.  This is used when generating PIC
16944    code.  It generates a 32 bit GP relative reloc.  */
16945
16946 static void
16947 s_gpword (int ignore ATTRIBUTE_UNUSED)
16948 {
16949   segment_info_type *si;
16950   struct insn_label_list *l;
16951   expressionS ex;
16952   char *p;
16953
16954   /* When not generating PIC code, this is treated as .word.  */
16955   if (mips_pic != SVR4_PIC)
16956     {
16957       s_cons (2);
16958       return;
16959     }
16960
16961   si = seg_info (now_seg);
16962   l = si->label_list;
16963   mips_emit_delays ();
16964   if (auto_align)
16965     mips_align (2, 0, l);
16966
16967   expression (&ex);
16968   mips_clear_insn_labels ();
16969
16970   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16971     {
16972       as_bad (_("unsupported use of .gpword"));
16973       ignore_rest_of_line ();
16974     }
16975
16976   p = frag_more (4);
16977   md_number_to_chars (p, 0, 4);
16978   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16979                BFD_RELOC_GPREL32);
16980
16981   demand_empty_rest_of_line ();
16982 }
16983
16984 static void
16985 s_gpdword (int ignore ATTRIBUTE_UNUSED)
16986 {
16987   segment_info_type *si;
16988   struct insn_label_list *l;
16989   expressionS ex;
16990   char *p;
16991
16992   /* When not generating PIC code, this is treated as .dword.  */
16993   if (mips_pic != SVR4_PIC)
16994     {
16995       s_cons (3);
16996       return;
16997     }
16998
16999   si = seg_info (now_seg);
17000   l = si->label_list;
17001   mips_emit_delays ();
17002   if (auto_align)
17003     mips_align (3, 0, l);
17004
17005   expression (&ex);
17006   mips_clear_insn_labels ();
17007
17008   if (ex.X_op != O_symbol || ex.X_add_number != 0)
17009     {
17010       as_bad (_("unsupported use of .gpdword"));
17011       ignore_rest_of_line ();
17012     }
17013
17014   p = frag_more (8);
17015   md_number_to_chars (p, 0, 8);
17016   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
17017                BFD_RELOC_GPREL32)->fx_tcbit = 1;
17018
17019   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
17020   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
17021            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
17022
17023   demand_empty_rest_of_line ();
17024 }
17025
17026 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
17027    tables.  It generates a R_MIPS_EH reloc.  */
17028
17029 static void
17030 s_ehword (int ignore ATTRIBUTE_UNUSED)
17031 {
17032   expressionS ex;
17033   char *p;
17034
17035   mips_emit_delays ();
17036
17037   expression (&ex);
17038   mips_clear_insn_labels ();
17039
17040   if (ex.X_op != O_symbol || ex.X_add_number != 0)
17041     {
17042       as_bad (_("unsupported use of .ehword"));
17043       ignore_rest_of_line ();
17044     }
17045
17046   p = frag_more (4);
17047   md_number_to_chars (p, 0, 4);
17048   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
17049                BFD_RELOC_32_PCREL);
17050
17051   demand_empty_rest_of_line ();
17052 }
17053
17054 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
17055    tables in SVR4 PIC code.  */
17056
17057 static void
17058 s_cpadd (int ignore ATTRIBUTE_UNUSED)
17059 {
17060   int reg;
17061
17062   file_mips_check_options ();
17063
17064   /* This is ignored when not generating SVR4 PIC code.  */
17065   if (mips_pic != SVR4_PIC)
17066     {
17067       s_ignore (0);
17068       return;
17069     }
17070
17071   mips_mark_labels ();
17072   mips_assembling_insn = TRUE;
17073
17074   /* Add $gp to the register named as an argument.  */
17075   macro_start ();
17076   reg = tc_get_register (0);
17077   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
17078   macro_end ();
17079
17080   mips_assembling_insn = FALSE;
17081   demand_empty_rest_of_line ();
17082 }
17083
17084 /* Handle the .insn pseudo-op.  This marks instruction labels in
17085    mips16/micromips mode.  This permits the linker to handle them specially,
17086    such as generating jalx instructions when needed.  We also make
17087    them odd for the duration of the assembly, in order to generate the
17088    right sort of code.  We will make them even in the adjust_symtab
17089    routine, while leaving them marked.  This is convenient for the
17090    debugger and the disassembler.  The linker knows to make them odd
17091    again.  */
17092
17093 static void
17094 s_insn (int ignore ATTRIBUTE_UNUSED)
17095 {
17096   file_mips_check_options ();
17097   file_ase_mips16 |= mips_opts.mips16;
17098   file_ase_micromips |= mips_opts.micromips;
17099
17100   mips_mark_labels ();
17101
17102   demand_empty_rest_of_line ();
17103 }
17104
17105 /* Handle the .nan pseudo-op.  */
17106
17107 static void
17108 s_nan (int ignore ATTRIBUTE_UNUSED)
17109 {
17110   static const char str_legacy[] = "legacy";
17111   static const char str_2008[] = "2008";
17112   size_t i;
17113
17114   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
17115
17116   if (i == sizeof (str_2008) - 1
17117       && memcmp (input_line_pointer, str_2008, i) == 0)
17118     mips_nan2008 = 1;
17119   else if (i == sizeof (str_legacy) - 1
17120            && memcmp (input_line_pointer, str_legacy, i) == 0)
17121     {
17122       if (ISA_HAS_LEGACY_NAN (file_mips_opts.isa))
17123         mips_nan2008 = 0;
17124       else
17125         as_bad (_("`%s' does not support legacy NaN"),
17126                   mips_cpu_info_from_isa (file_mips_opts.isa)->name);
17127     }
17128   else
17129     as_bad (_("bad .nan directive"));
17130
17131   input_line_pointer += i;
17132   demand_empty_rest_of_line ();
17133 }
17134
17135 /* Handle a .stab[snd] directive.  Ideally these directives would be
17136    implemented in a transparent way, so that removing them would not
17137    have any effect on the generated instructions.  However, s_stab
17138    internally changes the section, so in practice we need to decide
17139    now whether the preceding label marks compressed code.  We do not
17140    support changing the compression mode of a label after a .stab*
17141    directive, such as in:
17142
17143    foo:
17144         .stabs ...
17145         .set mips16
17146
17147    so the current mode wins.  */
17148
17149 static void
17150 s_mips_stab (int type)
17151 {
17152   mips_mark_labels ();
17153   s_stab (type);
17154 }
17155
17156 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
17157
17158 static void
17159 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
17160 {
17161   char *name;
17162   int c;
17163   symbolS *symbolP;
17164   expressionS exp;
17165
17166   c = get_symbol_name (&name);
17167   symbolP = symbol_find_or_make (name);
17168   S_SET_WEAK (symbolP);
17169   *input_line_pointer = c;
17170
17171   SKIP_WHITESPACE_AFTER_NAME ();
17172
17173   if (! is_end_of_line[(unsigned char) *input_line_pointer])
17174     {
17175       if (S_IS_DEFINED (symbolP))
17176         {
17177           as_bad (_("ignoring attempt to redefine symbol %s"),
17178                   S_GET_NAME (symbolP));
17179           ignore_rest_of_line ();
17180           return;
17181         }
17182
17183       if (*input_line_pointer == ',')
17184         {
17185           ++input_line_pointer;
17186           SKIP_WHITESPACE ();
17187         }
17188
17189       expression (&exp);
17190       if (exp.X_op != O_symbol)
17191         {
17192           as_bad (_("bad .weakext directive"));
17193           ignore_rest_of_line ();
17194           return;
17195         }
17196       symbol_set_value_expression (symbolP, &exp);
17197     }
17198
17199   demand_empty_rest_of_line ();
17200 }
17201
17202 /* Parse a register string into a number.  Called from the ECOFF code
17203    to parse .frame.  The argument is non-zero if this is the frame
17204    register, so that we can record it in mips_frame_reg.  */
17205
17206 int
17207 tc_get_register (int frame)
17208 {
17209   unsigned int reg;
17210
17211   SKIP_WHITESPACE ();
17212   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
17213     reg = 0;
17214   if (frame)
17215     {
17216       mips_frame_reg = reg != 0 ? reg : SP;
17217       mips_frame_reg_valid = 1;
17218       mips_cprestore_valid = 0;
17219     }
17220   return reg;
17221 }
17222
17223 valueT
17224 md_section_align (asection *seg, valueT addr)
17225 {
17226   int align = bfd_get_section_alignment (stdoutput, seg);
17227
17228   /* We don't need to align ELF sections to the full alignment.
17229      However, Irix 5 may prefer that we align them at least to a 16
17230      byte boundary.  We don't bother to align the sections if we
17231      are targeted for an embedded system.  */
17232   if (strncmp (TARGET_OS, "elf", 3) == 0)
17233     return addr;
17234   if (align > 4)
17235     align = 4;
17236
17237   return ((addr + (1 << align) - 1) & -(1 << align));
17238 }
17239
17240 /* Utility routine, called from above as well.  If called while the
17241    input file is still being read, it's only an approximation.  (For
17242    example, a symbol may later become defined which appeared to be
17243    undefined earlier.)  */
17244
17245 static int
17246 nopic_need_relax (symbolS *sym, int before_relaxing)
17247 {
17248   if (sym == 0)
17249     return 0;
17250
17251   if (g_switch_value > 0)
17252     {
17253       const char *symname;
17254       int change;
17255
17256       /* Find out whether this symbol can be referenced off the $gp
17257          register.  It can be if it is smaller than the -G size or if
17258          it is in the .sdata or .sbss section.  Certain symbols can
17259          not be referenced off the $gp, although it appears as though
17260          they can.  */
17261       symname = S_GET_NAME (sym);
17262       if (symname != (const char *) NULL
17263           && (strcmp (symname, "eprol") == 0
17264               || strcmp (symname, "etext") == 0
17265               || strcmp (symname, "_gp") == 0
17266               || strcmp (symname, "edata") == 0
17267               || strcmp (symname, "_fbss") == 0
17268               || strcmp (symname, "_fdata") == 0
17269               || strcmp (symname, "_ftext") == 0
17270               || strcmp (symname, "end") == 0
17271               || strcmp (symname, "_gp_disp") == 0))
17272         change = 1;
17273       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
17274                && (0
17275 #ifndef NO_ECOFF_DEBUGGING
17276                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
17277                        && (symbol_get_obj (sym)->ecoff_extern_size
17278                            <= g_switch_value))
17279 #endif
17280                    /* We must defer this decision until after the whole
17281                       file has been read, since there might be a .extern
17282                       after the first use of this symbol.  */
17283                    || (before_relaxing
17284 #ifndef NO_ECOFF_DEBUGGING
17285                        && symbol_get_obj (sym)->ecoff_extern_size == 0
17286 #endif
17287                        && S_GET_VALUE (sym) == 0)
17288                    || (S_GET_VALUE (sym) != 0
17289                        && S_GET_VALUE (sym) <= g_switch_value)))
17290         change = 0;
17291       else
17292         {
17293           const char *segname;
17294
17295           segname = segment_name (S_GET_SEGMENT (sym));
17296           gas_assert (strcmp (segname, ".lit8") != 0
17297                   && strcmp (segname, ".lit4") != 0);
17298           change = (strcmp (segname, ".sdata") != 0
17299                     && strcmp (segname, ".sbss") != 0
17300                     && strncmp (segname, ".sdata.", 7) != 0
17301                     && strncmp (segname, ".sbss.", 6) != 0
17302                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
17303                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
17304         }
17305       return change;
17306     }
17307   else
17308     /* We are not optimizing for the $gp register.  */
17309     return 1;
17310 }
17311
17312
17313 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
17314
17315 static bfd_boolean
17316 pic_need_relax (symbolS *sym)
17317 {
17318   asection *symsec;
17319
17320   /* Handle the case of a symbol equated to another symbol.  */
17321   while (symbol_equated_reloc_p (sym))
17322     {
17323       symbolS *n;
17324
17325       /* It's possible to get a loop here in a badly written program.  */
17326       n = symbol_get_value_expression (sym)->X_add_symbol;
17327       if (n == sym)
17328         break;
17329       sym = n;
17330     }
17331
17332   if (symbol_section_p (sym))
17333     return TRUE;
17334
17335   symsec = S_GET_SEGMENT (sym);
17336
17337   /* This must duplicate the test in adjust_reloc_syms.  */
17338   return (!bfd_is_und_section (symsec)
17339           && !bfd_is_abs_section (symsec)
17340           && !bfd_is_com_section (symsec)
17341           /* A global or weak symbol is treated as external.  */
17342           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
17343 }
17344 \f
17345 /* Given a MIPS16 variant frag FRAGP and PC-relative operand PCREL_OP
17346    convert a section-relative value VAL to the equivalent PC-relative
17347    value.  */
17348
17349 static offsetT
17350 mips16_pcrel_val (fragS *fragp, const struct mips_pcrel_operand *pcrel_op,
17351                   offsetT val, long stretch)
17352 {
17353   fragS *sym_frag;
17354   addressT addr;
17355
17356   gas_assert (pcrel_op->root.root.type == OP_PCREL);
17357
17358   sym_frag = symbol_get_frag (fragp->fr_symbol);
17359
17360   /* If the relax_marker of the symbol fragment differs from the
17361      relax_marker of this fragment, we have not yet adjusted the
17362      symbol fragment fr_address.  We want to add in STRETCH in
17363      order to get a better estimate of the address.  This
17364      particularly matters because of the shift bits.  */
17365   if (stretch != 0 && sym_frag->relax_marker != fragp->relax_marker)
17366     {
17367       fragS *f;
17368
17369       /* Adjust stretch for any alignment frag.  Note that if have
17370          been expanding the earlier code, the symbol may be
17371          defined in what appears to be an earlier frag.  FIXME:
17372          This doesn't handle the fr_subtype field, which specifies
17373          a maximum number of bytes to skip when doing an
17374          alignment.  */
17375       for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
17376         {
17377           if (f->fr_type == rs_align || f->fr_type == rs_align_code)
17378             {
17379               if (stretch < 0)
17380                 stretch = -(-stretch & ~((1 << (int) f->fr_offset) - 1));
17381               else
17382                 stretch &= ~((1 << (int) f->fr_offset) - 1);
17383               if (stretch == 0)
17384                 break;
17385             }
17386         }
17387       if (f != NULL)
17388         val += stretch;
17389     }
17390
17391   addr = fragp->fr_address + fragp->fr_fix;
17392
17393   /* The base address rules are complicated.  The base address of
17394      a branch is the following instruction.  The base address of a
17395      PC relative load or add is the instruction itself, but if it
17396      is in a delay slot (in which case it can not be extended) use
17397      the address of the instruction whose delay slot it is in.  */
17398   if (pcrel_op->include_isa_bit)
17399     {
17400       addr += 2;
17401
17402       /* If we are currently assuming that this frag should be
17403          extended, then the current address is two bytes higher.  */
17404       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17405         addr += 2;
17406
17407       /* Ignore the low bit in the target, since it will be set
17408          for a text label.  */
17409       val &= -2;
17410     }
17411   else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17412     addr -= 4;
17413   else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17414     addr -= 2;
17415
17416   val -= addr & -(1 << pcrel_op->align_log2);
17417
17418   return val;
17419 }
17420
17421 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
17422    extended opcode.  SEC is the section the frag is in.  */
17423
17424 static int
17425 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
17426 {
17427   const struct mips_int_operand *operand;
17428   offsetT val;
17429   segT symsec;
17430   int type;
17431
17432   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
17433     return 0;
17434   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17435     return 1;
17436
17437   symsec = S_GET_SEGMENT (fragp->fr_symbol);
17438   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17439   operand = mips16_immed_operand (type, FALSE);
17440   if (S_FORCE_RELOC (fragp->fr_symbol, TRUE)
17441       || (operand->root.type == OP_PCREL
17442           ? sec != symsec
17443           : !bfd_is_abs_section (symsec)))
17444     return 1;
17445
17446   val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17447
17448   if (operand->root.type == OP_PCREL)
17449     {
17450       const struct mips_pcrel_operand *pcrel_op;
17451       offsetT maxtiny;
17452
17453       if (RELAX_MIPS16_ALWAYS_EXTENDED (fragp->fr_subtype))
17454         return 1;
17455
17456       pcrel_op = (const struct mips_pcrel_operand *) operand;
17457       val = mips16_pcrel_val (fragp, pcrel_op, val, stretch);
17458
17459       /* If any of the shifted bits are set, we must use an extended
17460          opcode.  If the address depends on the size of this
17461          instruction, this can lead to a loop, so we arrange to always
17462          use an extended opcode.  */
17463       if ((val & ((1 << operand->shift) - 1)) != 0)
17464         {
17465           fragp->fr_subtype =
17466             RELAX_MIPS16_MARK_ALWAYS_EXTENDED (fragp->fr_subtype);
17467           return 1;
17468         }
17469
17470       /* If we are about to mark a frag as extended because the value
17471          is precisely the next value above maxtiny, then there is a
17472          chance of an infinite loop as in the following code:
17473              la $4,foo
17474              .skip      1020
17475              .align     2
17476            foo:
17477          In this case when the la is extended, foo is 0x3fc bytes
17478          away, so the la can be shrunk, but then foo is 0x400 away, so
17479          the la must be extended.  To avoid this loop, we mark the
17480          frag as extended if it was small, and is about to become
17481          extended with the next value above maxtiny.  */
17482       maxtiny = mips_int_operand_max (operand);
17483       if (val == maxtiny + (1 << operand->shift)
17484           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17485         {
17486           fragp->fr_subtype =
17487             RELAX_MIPS16_MARK_ALWAYS_EXTENDED (fragp->fr_subtype);
17488           return 1;
17489         }
17490     }
17491
17492   return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
17493 }
17494
17495 /* Given a MIPS16 variant frag FRAGP, return non-zero if it needs
17496    macro expansion.  SEC is the section the frag is in.  We only
17497    support PC-relative instructions (LA, DLA, LW, LD) here, in
17498    non-PIC code using 32-bit addressing.  */
17499
17500 static int
17501 mips16_macro_frag (fragS *fragp, asection *sec, long stretch)
17502 {
17503   const struct mips_pcrel_operand *pcrel_op;
17504   const struct mips_int_operand *operand;
17505   offsetT val;
17506   segT symsec;
17507   int type;
17508
17509   gas_assert (!RELAX_MIPS16_USER_SMALL (fragp->fr_subtype));
17510
17511   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17512     return 0;
17513   if (!RELAX_MIPS16_SYM32 (fragp->fr_subtype))
17514     return 0;
17515
17516   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17517   switch (type)
17518     {
17519     case 'A':
17520     case 'B':
17521     case 'E':
17522       symsec = S_GET_SEGMENT (fragp->fr_symbol);
17523       if (bfd_is_abs_section (symsec))
17524         return 1;
17525       if (RELAX_MIPS16_PIC (fragp->fr_subtype))
17526         return 0;
17527       if (S_FORCE_RELOC (fragp->fr_symbol, TRUE) || sec != symsec)
17528         return 1;
17529
17530       operand = mips16_immed_operand (type, TRUE);
17531       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17532       pcrel_op = (const struct mips_pcrel_operand *) operand;
17533       val = mips16_pcrel_val (fragp, pcrel_op, val, stretch);
17534
17535       return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
17536
17537     default:
17538       return 0;
17539     }
17540 }
17541
17542 /* Compute the length of a branch sequence, and adjust the
17543    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
17544    worst-case length is computed, with UPDATE being used to indicate
17545    whether an unconditional (-1), branch-likely (+1) or regular (0)
17546    branch is to be computed.  */
17547 static int
17548 relaxed_branch_length (fragS *fragp, asection *sec, int update)
17549 {
17550   bfd_boolean toofar;
17551   int length;
17552
17553   if (fragp
17554       && S_IS_DEFINED (fragp->fr_symbol)
17555       && !S_IS_WEAK (fragp->fr_symbol)
17556       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17557     {
17558       addressT addr;
17559       offsetT val;
17560
17561       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17562
17563       addr = fragp->fr_address + fragp->fr_fix + 4;
17564
17565       val -= addr;
17566
17567       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
17568     }
17569   else
17570     /* If the symbol is not defined or it's in a different segment,
17571        we emit the long sequence.  */
17572     toofar = TRUE;
17573
17574   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
17575     fragp->fr_subtype
17576       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
17577                              RELAX_BRANCH_PIC (fragp->fr_subtype),
17578                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
17579                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
17580                              RELAX_BRANCH_LINK (fragp->fr_subtype),
17581                              toofar);
17582
17583   length = 4;
17584   if (toofar)
17585     {
17586       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
17587         length += 8;
17588
17589       if (!fragp || RELAX_BRANCH_PIC (fragp->fr_subtype))
17590         {
17591           /* Additional space for PIC loading of target address.  */
17592           length += 8;
17593           if (mips_opts.isa == ISA_MIPS1)
17594             /* Additional space for $at-stabilizing nop.  */
17595             length += 4;
17596         }
17597
17598       /* If branch is conditional.  */
17599       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
17600         length += 8;
17601     }
17602
17603   return length;
17604 }
17605
17606 /* Get a FRAG's branch instruction delay slot size, either from the
17607    short-delay-slot bit of a branch-and-link instruction if AL is TRUE,
17608    or SHORT_INSN_SIZE otherwise.  */
17609
17610 static int
17611 frag_branch_delay_slot_size (fragS *fragp, bfd_boolean al, int short_insn_size)
17612 {
17613   char *buf = fragp->fr_literal + fragp->fr_fix;
17614
17615   if (al)
17616     return (read_compressed_insn (buf, 4) & 0x02000000) ? 2 : 4;
17617   else
17618     return short_insn_size;
17619 }
17620
17621 /* Compute the length of a branch sequence, and adjust the
17622    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
17623    worst-case length is computed, with UPDATE being used to indicate
17624    whether an unconditional (-1), or regular (0) branch is to be
17625    computed.  */
17626
17627 static int
17628 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
17629 {
17630   bfd_boolean insn32 = TRUE;
17631   bfd_boolean nods = TRUE;
17632   bfd_boolean pic = TRUE;
17633   bfd_boolean al = TRUE;
17634   int short_insn_size;
17635   bfd_boolean toofar;
17636   int length;
17637
17638   if (fragp)
17639     {
17640       insn32 = RELAX_MICROMIPS_INSN32 (fragp->fr_subtype);
17641       nods = RELAX_MICROMIPS_NODS (fragp->fr_subtype);
17642       pic = RELAX_MICROMIPS_PIC (fragp->fr_subtype);
17643       al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
17644     }
17645   short_insn_size = insn32 ? 4 : 2;
17646
17647   if (fragp
17648       && S_IS_DEFINED (fragp->fr_symbol)
17649       && !S_IS_WEAK (fragp->fr_symbol)
17650       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17651     {
17652       addressT addr;
17653       offsetT val;
17654
17655       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17656       /* Ignore the low bit in the target, since it will be set
17657          for a text label.  */
17658       if ((val & 1) != 0)
17659         --val;
17660
17661       addr = fragp->fr_address + fragp->fr_fix + 4;
17662
17663       val -= addr;
17664
17665       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
17666     }
17667   else
17668     /* If the symbol is not defined or it's in a different segment,
17669        we emit the long sequence.  */
17670     toofar = TRUE;
17671
17672   if (fragp && update
17673       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17674     fragp->fr_subtype = (toofar
17675                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
17676                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
17677
17678   length = 4;
17679   if (toofar)
17680     {
17681       bfd_boolean compact_known = fragp != NULL;
17682       bfd_boolean compact = FALSE;
17683       bfd_boolean uncond;
17684
17685       if (fragp)
17686         {
17687           compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
17688           uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
17689         }
17690       else
17691         uncond = update < 0;
17692
17693       /* If label is out of range, we turn branch <br>:
17694
17695                 <br>    label                   # 4 bytes
17696             0:
17697
17698          into:
17699
17700                 j       label                   # 4 bytes
17701                 nop                             # 2/4 bytes if
17702                                                 #  compact && (!PIC || insn32)
17703             0:
17704        */
17705       if ((!pic || insn32) && (!compact_known || compact))
17706         length += short_insn_size;
17707
17708       /* If assembling PIC code, we further turn:
17709
17710                         j       label                   # 4 bytes
17711
17712          into:
17713
17714                         lw/ld   at, %got(label)(gp)     # 4 bytes
17715                         d/addiu at, %lo(label)          # 4 bytes
17716                         jr/c    at                      # 2/4 bytes
17717        */
17718       if (pic)
17719         length += 4 + short_insn_size;
17720
17721       /* Add an extra nop if the jump has no compact form and we need
17722          to fill the delay slot.  */
17723       if ((!pic || al) && nods)
17724         length += (fragp
17725                    ? frag_branch_delay_slot_size (fragp, al, short_insn_size)
17726                    : short_insn_size);
17727
17728       /* If branch <br> is conditional, we prepend negated branch <brneg>:
17729
17730                         <brneg> 0f                      # 4 bytes
17731                         nop                             # 2/4 bytes if !compact
17732        */
17733       if (!uncond)
17734         length += (compact_known && compact) ? 4 : 4 + short_insn_size;
17735     }
17736   else if (nods)
17737     {
17738       /* Add an extra nop to fill the delay slot.  */
17739       gas_assert (fragp);
17740       length += frag_branch_delay_slot_size (fragp, al, short_insn_size);
17741     }
17742
17743   return length;
17744 }
17745
17746 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
17747    bit accordingly.  */
17748
17749 static int
17750 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
17751 {
17752   bfd_boolean toofar;
17753
17754   if (fragp
17755       && S_IS_DEFINED (fragp->fr_symbol)
17756       && !S_IS_WEAK (fragp->fr_symbol)
17757       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17758     {
17759       addressT addr;
17760       offsetT val;
17761       int type;
17762
17763       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17764       /* Ignore the low bit in the target, since it will be set
17765          for a text label.  */
17766       if ((val & 1) != 0)
17767         --val;
17768
17769       /* Assume this is a 2-byte branch.  */
17770       addr = fragp->fr_address + fragp->fr_fix + 2;
17771
17772       /* We try to avoid the infinite loop by not adding 2 more bytes for
17773          long branches.  */
17774
17775       val -= addr;
17776
17777       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
17778       if (type == 'D')
17779         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
17780       else if (type == 'E')
17781         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
17782       else
17783         abort ();
17784     }
17785   else
17786     /* If the symbol is not defined or it's in a different segment,
17787        we emit a normal 32-bit branch.  */
17788     toofar = TRUE;
17789
17790   if (fragp && update
17791       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
17792     fragp->fr_subtype
17793       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
17794                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
17795
17796   if (toofar)
17797     return 4;
17798
17799   return 2;
17800 }
17801
17802 /* Estimate the size of a frag before relaxing.  Unless this is the
17803    mips16, we are not really relaxing here, and the final size is
17804    encoded in the subtype information.  For the mips16, we have to
17805    decide whether we are using an extended opcode or not.  */
17806
17807 int
17808 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
17809 {
17810   int change;
17811
17812   if (RELAX_BRANCH_P (fragp->fr_subtype))
17813     {
17814
17815       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
17816
17817       return fragp->fr_var;
17818     }
17819
17820   if (RELAX_MIPS16_P (fragp->fr_subtype))
17821     {
17822       /* We don't want to modify the EXTENDED bit here; it might get us
17823          into infinite loops.  We change it only in mips_relax_frag().  */
17824       if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
17825         return RELAX_MIPS16_E2 (fragp->fr_subtype) ? 8 : 12;
17826       else
17827         return RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2;
17828     }
17829
17830   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17831     {
17832       int length = 4;
17833
17834       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
17835         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
17836       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
17837         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
17838       fragp->fr_var = length;
17839
17840       return length;
17841     }
17842
17843   if (mips_pic == VXWORKS_PIC)
17844     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
17845     change = 0;
17846   else if (RELAX_PIC (fragp->fr_subtype))
17847     change = pic_need_relax (fragp->fr_symbol);
17848   else
17849     change = nopic_need_relax (fragp->fr_symbol, 0);
17850
17851   if (change)
17852     {
17853       fragp->fr_subtype |= RELAX_USE_SECOND;
17854       return -RELAX_FIRST (fragp->fr_subtype);
17855     }
17856   else
17857     return -RELAX_SECOND (fragp->fr_subtype);
17858 }
17859
17860 /* This is called to see whether a reloc against a defined symbol
17861    should be converted into a reloc against a section.  */
17862
17863 int
17864 mips_fix_adjustable (fixS *fixp)
17865 {
17866   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
17867       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
17868     return 0;
17869
17870   if (fixp->fx_addsy == NULL)
17871     return 1;
17872
17873   /* Allow relocs used for EH tables.  */
17874   if (fixp->fx_r_type == BFD_RELOC_32_PCREL)
17875     return 1;
17876
17877   /* If symbol SYM is in a mergeable section, relocations of the form
17878      SYM + 0 can usually be made section-relative.  The mergeable data
17879      is then identified by the section offset rather than by the symbol.
17880
17881      However, if we're generating REL LO16 relocations, the offset is split
17882      between the LO16 and partnering high part relocation.  The linker will
17883      need to recalculate the complete offset in order to correctly identify
17884      the merge data.
17885
17886      The linker has traditionally not looked for the partnering high part
17887      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
17888      placed anywhere.  Rather than break backwards compatibility by changing
17889      this, it seems better not to force the issue, and instead keep the
17890      original symbol.  This will work with either linker behavior.  */
17891   if ((lo16_reloc_p (fixp->fx_r_type)
17892        || reloc_needs_lo_p (fixp->fx_r_type))
17893       && HAVE_IN_PLACE_ADDENDS
17894       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
17895     return 0;
17896
17897   /* There is no place to store an in-place offset for JALR relocations.  */
17898   if (jalr_reloc_p (fixp->fx_r_type) && HAVE_IN_PLACE_ADDENDS)
17899     return 0;
17900
17901   /* Likewise an in-range offset of limited PC-relative relocations may
17902      overflow the in-place relocatable field if recalculated against the
17903      start address of the symbol's containing section.
17904
17905      Also, PC relative relocations for MIPS R6 need to be symbol rather than
17906      section relative to allow linker relaxations to be performed later on.  */
17907   if (limited_pcrel_reloc_p (fixp->fx_r_type)
17908       && (HAVE_IN_PLACE_ADDENDS || ISA_IS_R6 (file_mips_opts.isa)))
17909     return 0;
17910
17911   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
17912      to a floating-point stub.  The same is true for non-R_MIPS16_26
17913      relocations against MIPS16 functions; in this case, the stub becomes
17914      the function's canonical address.
17915
17916      Floating-point stubs are stored in unique .mips16.call.* or
17917      .mips16.fn.* sections.  If a stub T for function F is in section S,
17918      the first relocation in section S must be against F; this is how the
17919      linker determines the target function.  All relocations that might
17920      resolve to T must also be against F.  We therefore have the following
17921      restrictions, which are given in an intentionally-redundant way:
17922
17923        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
17924           symbols.
17925
17926        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
17927           if that stub might be used.
17928
17929        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
17930           symbols.
17931
17932        4. We cannot reduce a stub's relocations against MIPS16 symbols if
17933           that stub might be used.
17934
17935      There is a further restriction:
17936
17937        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
17938           R_MICROMIPS_26_S1) or branch relocations (R_MIPS_PC26_S2,
17939           R_MIPS_PC21_S2, R_MIPS_PC16, R_MIPS16_PC16_S1,
17940           R_MICROMIPS_PC16_S1, R_MICROMIPS_PC10_S1 or R_MICROMIPS_PC7_S1)
17941           against MIPS16 or microMIPS symbols because we need to keep the
17942           MIPS16 or microMIPS symbol for the purpose of mode mismatch
17943           detection and JAL or BAL to JALX instruction conversion in the
17944           linker.
17945
17946      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
17947      against a MIPS16 symbol.  We deal with (5) by additionally leaving
17948      alone any jump and branch relocations against a microMIPS symbol.
17949
17950      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
17951      relocation against some symbol R, no relocation against R may be
17952      reduced.  (Note that this deals with (2) as well as (1) because
17953      relocations against global symbols will never be reduced on ELF
17954      targets.)  This approach is a little simpler than trying to detect
17955      stub sections, and gives the "all or nothing" per-symbol consistency
17956      that we have for MIPS16 symbols.  */
17957   if (fixp->fx_subsy == NULL
17958       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
17959           || (ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
17960               && (jmp_reloc_p (fixp->fx_r_type)
17961                   || b_reloc_p (fixp->fx_r_type)))
17962           || *symbol_get_tc (fixp->fx_addsy)))
17963     return 0;
17964
17965   return 1;
17966 }
17967
17968 /* Translate internal representation of relocation info to BFD target
17969    format.  */
17970
17971 arelent **
17972 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
17973 {
17974   static arelent *retval[4];
17975   arelent *reloc;
17976   bfd_reloc_code_real_type code;
17977
17978   memset (retval, 0, sizeof(retval));
17979   reloc = retval[0] = XCNEW (arelent);
17980   reloc->sym_ptr_ptr = XNEW (asymbol *);
17981   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
17982   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
17983
17984   if (fixp->fx_pcrel)
17985     {
17986       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
17987                   || fixp->fx_r_type == BFD_RELOC_MIPS16_16_PCREL_S1
17988                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
17989                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
17990                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
17991                   || fixp->fx_r_type == BFD_RELOC_32_PCREL
17992                   || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
17993                   || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2
17994                   || fixp->fx_r_type == BFD_RELOC_MIPS_18_PCREL_S3
17995                   || fixp->fx_r_type == BFD_RELOC_MIPS_19_PCREL_S2
17996                   || fixp->fx_r_type == BFD_RELOC_HI16_S_PCREL
17997                   || fixp->fx_r_type == BFD_RELOC_LO16_PCREL);
17998
17999       /* At this point, fx_addnumber is "symbol offset - pcrel address".
18000          Relocations want only the symbol offset.  */
18001       switch (fixp->fx_r_type)
18002         {
18003         case BFD_RELOC_MIPS_18_PCREL_S3:
18004           reloc->addend = fixp->fx_addnumber + (reloc->address & ~7);
18005           break;
18006         default:
18007           reloc->addend = fixp->fx_addnumber + reloc->address;
18008           break;
18009         }
18010     }
18011   else if (HAVE_IN_PLACE_ADDENDS
18012            && fixp->fx_r_type == BFD_RELOC_MICROMIPS_JMP
18013            && (read_compressed_insn (fixp->fx_frag->fr_literal
18014                                      + fixp->fx_where, 4) >> 26) == 0x3c)
18015     {
18016       /* Shift is 2, unusually, for microMIPS JALX.  Adjust the in-place
18017          addend accordingly.  */
18018       reloc->addend = fixp->fx_addnumber >> 1;
18019     }
18020   else
18021     reloc->addend = fixp->fx_addnumber;
18022
18023   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
18024      entry to be used in the relocation's section offset.  */
18025   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
18026     {
18027       reloc->address = reloc->addend;
18028       reloc->addend = 0;
18029     }
18030
18031   code = fixp->fx_r_type;
18032
18033   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
18034   if (reloc->howto == NULL)
18035     {
18036       as_bad_where (fixp->fx_file, fixp->fx_line,
18037                     _("cannot represent %s relocation in this object file"
18038                       " format"),
18039                     bfd_get_reloc_code_name (code));
18040       retval[0] = NULL;
18041     }
18042
18043   return retval;
18044 }
18045
18046 /* Relax a machine dependent frag.  This returns the amount by which
18047    the current size of the frag should change.  */
18048
18049 int
18050 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
18051 {
18052   if (RELAX_BRANCH_P (fragp->fr_subtype))
18053     {
18054       offsetT old_var = fragp->fr_var;
18055
18056       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
18057
18058       return fragp->fr_var - old_var;
18059     }
18060
18061   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
18062     {
18063       offsetT old_var = fragp->fr_var;
18064       offsetT new_var = 4;
18065
18066       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
18067         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
18068       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
18069         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
18070       fragp->fr_var = new_var;
18071
18072       return new_var - old_var;
18073     }
18074
18075   if (! RELAX_MIPS16_P (fragp->fr_subtype))
18076     return 0;
18077
18078   if (!mips16_extended_frag (fragp, sec, stretch))
18079     {
18080       if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
18081         {
18082           fragp->fr_subtype = RELAX_MIPS16_CLEAR_MACRO (fragp->fr_subtype);
18083           return RELAX_MIPS16_E2 (fragp->fr_subtype) ? -6 : -10;
18084         }
18085       else if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
18086         {
18087           fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
18088           return -2;
18089         }
18090       else
18091         return 0;
18092     }
18093   else if (!mips16_macro_frag (fragp, sec, stretch))
18094     {
18095       if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
18096         {
18097           fragp->fr_subtype = RELAX_MIPS16_CLEAR_MACRO (fragp->fr_subtype);
18098           fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
18099           return RELAX_MIPS16_E2 (fragp->fr_subtype) ? -4 : -8;
18100         }
18101       else if (!RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
18102         {
18103           fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
18104           return 2;
18105         }
18106       else
18107         return 0;
18108     }
18109   else
18110     {
18111       if (RELAX_MIPS16_MACRO (fragp->fr_subtype))
18112         return 0;
18113       else if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
18114         {
18115           fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
18116           fragp->fr_subtype = RELAX_MIPS16_MARK_MACRO (fragp->fr_subtype);
18117           return RELAX_MIPS16_E2 (fragp->fr_subtype) ? 4 : 8;
18118         }
18119       else
18120         {
18121           fragp->fr_subtype = RELAX_MIPS16_MARK_MACRO (fragp->fr_subtype);
18122           return RELAX_MIPS16_E2 (fragp->fr_subtype) ? 6 : 10;
18123         }
18124     }
18125
18126   return 0;
18127 }
18128
18129 /* Convert a machine dependent frag.  */
18130
18131 void
18132 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
18133 {
18134   if (RELAX_BRANCH_P (fragp->fr_subtype))
18135     {
18136       char *buf;
18137       unsigned long insn;
18138       expressionS exp;
18139       fixS *fixp;
18140
18141       buf = fragp->fr_literal + fragp->fr_fix;
18142       insn = read_insn (buf);
18143
18144       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
18145         {
18146           /* We generate a fixup instead of applying it right now
18147              because, if there are linker relaxations, we're going to
18148              need the relocations.  */
18149           exp.X_op = O_symbol;
18150           exp.X_add_symbol = fragp->fr_symbol;
18151           exp.X_add_number = fragp->fr_offset;
18152
18153           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
18154                               BFD_RELOC_16_PCREL_S2);
18155           fixp->fx_file = fragp->fr_file;
18156           fixp->fx_line = fragp->fr_line;
18157
18158           buf = write_insn (buf, insn);
18159         }
18160       else
18161         {
18162           int i;
18163
18164           as_warn_where (fragp->fr_file, fragp->fr_line,
18165                          _("relaxed out-of-range branch into a jump"));
18166
18167           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
18168             goto uncond;
18169
18170           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18171             {
18172               /* Reverse the branch.  */
18173               switch ((insn >> 28) & 0xf)
18174                 {
18175                 case 4:
18176                   if ((insn & 0xff000000) == 0x47000000
18177                       || (insn & 0xff600000) == 0x45600000)
18178                     {
18179                       /* BZ.df/BNZ.df, BZ.V/BNZ.V can have the condition
18180                          reversed by tweaking bit 23.  */
18181                       insn ^= 0x00800000;
18182                     }
18183                   else
18184                     {
18185                       /* bc[0-3][tf]l? instructions can have the condition
18186                          reversed by tweaking a single TF bit, and their
18187                          opcodes all have 0x4???????.  */
18188                       gas_assert ((insn & 0xf3e00000) == 0x41000000);
18189                       insn ^= 0x00010000;
18190                     }
18191                   break;
18192
18193                 case 0:
18194                   /* bltz       0x04000000      bgez    0x04010000
18195                      bltzal     0x04100000      bgezal  0x04110000  */
18196                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
18197                   insn ^= 0x00010000;
18198                   break;
18199
18200                 case 1:
18201                   /* beq        0x10000000      bne     0x14000000
18202                      blez       0x18000000      bgtz    0x1c000000  */
18203                   insn ^= 0x04000000;
18204                   break;
18205
18206                 default:
18207                   abort ();
18208                 }
18209             }
18210
18211           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
18212             {
18213               /* Clear the and-link bit.  */
18214               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
18215
18216               /* bltzal         0x04100000      bgezal  0x04110000
18217                  bltzall        0x04120000      bgezall 0x04130000  */
18218               insn &= ~0x00100000;
18219             }
18220
18221           /* Branch over the branch (if the branch was likely) or the
18222              full jump (not likely case).  Compute the offset from the
18223              current instruction to branch to.  */
18224           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18225             i = 16;
18226           else
18227             {
18228               /* How many bytes in instructions we've already emitted?  */
18229               i = buf - fragp->fr_literal - fragp->fr_fix;
18230               /* How many bytes in instructions from here to the end?  */
18231               i = fragp->fr_var - i;
18232             }
18233           /* Convert to instruction count.  */
18234           i >>= 2;
18235           /* Branch counts from the next instruction.  */
18236           i--;
18237           insn |= i;
18238           /* Branch over the jump.  */
18239           buf = write_insn (buf, insn);
18240
18241           /* nop */
18242           buf = write_insn (buf, 0);
18243
18244           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18245             {
18246               /* beql $0, $0, 2f */
18247               insn = 0x50000000;
18248               /* Compute the PC offset from the current instruction to
18249                  the end of the variable frag.  */
18250               /* How many bytes in instructions we've already emitted?  */
18251               i = buf - fragp->fr_literal - fragp->fr_fix;
18252               /* How many bytes in instructions from here to the end?  */
18253               i = fragp->fr_var - i;
18254               /* Convert to instruction count.  */
18255               i >>= 2;
18256               /* Don't decrement i, because we want to branch over the
18257                  delay slot.  */
18258               insn |= i;
18259
18260               buf = write_insn (buf, insn);
18261               buf = write_insn (buf, 0);
18262             }
18263
18264         uncond:
18265           if (!RELAX_BRANCH_PIC (fragp->fr_subtype))
18266             {
18267               /* j or jal.  */
18268               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
18269                       ? 0x0c000000 : 0x08000000);
18270               exp.X_op = O_symbol;
18271               exp.X_add_symbol = fragp->fr_symbol;
18272               exp.X_add_number = fragp->fr_offset;
18273
18274               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
18275                                   FALSE, BFD_RELOC_MIPS_JMP);
18276               fixp->fx_file = fragp->fr_file;
18277               fixp->fx_line = fragp->fr_line;
18278
18279               buf = write_insn (buf, insn);
18280             }
18281           else
18282             {
18283               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
18284
18285               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
18286               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
18287               insn |= at << OP_SH_RT;
18288               exp.X_op = O_symbol;
18289               exp.X_add_symbol = fragp->fr_symbol;
18290               exp.X_add_number = fragp->fr_offset;
18291
18292               if (fragp->fr_offset)
18293                 {
18294                   exp.X_add_symbol = make_expr_symbol (&exp);
18295                   exp.X_add_number = 0;
18296                 }
18297
18298               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
18299                                   FALSE, BFD_RELOC_MIPS_GOT16);
18300               fixp->fx_file = fragp->fr_file;
18301               fixp->fx_line = fragp->fr_line;
18302
18303               buf = write_insn (buf, insn);
18304
18305               if (mips_opts.isa == ISA_MIPS1)
18306                 /* nop */
18307                 buf = write_insn (buf, 0);
18308
18309               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
18310               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
18311               insn |= at << OP_SH_RS | at << OP_SH_RT;
18312
18313               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
18314                                   FALSE, BFD_RELOC_LO16);
18315               fixp->fx_file = fragp->fr_file;
18316               fixp->fx_line = fragp->fr_line;
18317
18318               buf = write_insn (buf, insn);
18319
18320               /* j(al)r $at.  */
18321               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
18322                 insn = 0x0000f809;
18323               else
18324                 insn = 0x00000008;
18325               insn |= at << OP_SH_RS;
18326
18327               buf = write_insn (buf, insn);
18328             }
18329         }
18330
18331       fragp->fr_fix += fragp->fr_var;
18332       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18333       return;
18334     }
18335
18336   /* Relax microMIPS branches.  */
18337   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
18338     {
18339       char *buf = fragp->fr_literal + fragp->fr_fix;
18340       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
18341       bfd_boolean insn32 = RELAX_MICROMIPS_INSN32 (fragp->fr_subtype);
18342       bfd_boolean nods = RELAX_MICROMIPS_NODS (fragp->fr_subtype);
18343       bfd_boolean pic = RELAX_MICROMIPS_PIC (fragp->fr_subtype);
18344       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
18345       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
18346       bfd_boolean short_ds;
18347       unsigned long insn;
18348       expressionS exp;
18349       fixS *fixp;
18350
18351       exp.X_op = O_symbol;
18352       exp.X_add_symbol = fragp->fr_symbol;
18353       exp.X_add_number = fragp->fr_offset;
18354
18355       fragp->fr_fix += fragp->fr_var;
18356
18357       /* Handle 16-bit branches that fit or are forced to fit.  */
18358       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
18359         {
18360           /* We generate a fixup instead of applying it right now,
18361              because if there is linker relaxation, we're going to
18362              need the relocations.  */
18363           if (type == 'D')
18364             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
18365                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
18366           else if (type == 'E')
18367             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
18368                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
18369           else
18370             abort ();
18371
18372           fixp->fx_file = fragp->fr_file;
18373           fixp->fx_line = fragp->fr_line;
18374
18375           /* These relocations can have an addend that won't fit in
18376              2 octets.  */
18377           fixp->fx_no_overflow = 1;
18378
18379           return;
18380         }
18381
18382       /* Handle 32-bit branches that fit or are forced to fit.  */
18383       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
18384           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18385         {
18386           /* We generate a fixup instead of applying it right now,
18387              because if there is linker relaxation, we're going to
18388              need the relocations.  */
18389           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
18390                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
18391           fixp->fx_file = fragp->fr_file;
18392           fixp->fx_line = fragp->fr_line;
18393
18394           if (type == 0)
18395             {
18396               insn = read_compressed_insn (buf, 4);
18397               buf += 4;
18398
18399               if (nods)
18400                 {
18401                   /* Check the short-delay-slot bit.  */
18402                   if (!al || (insn & 0x02000000) != 0)
18403                     buf = write_compressed_insn (buf, 0x0c00, 2);
18404                   else
18405                     buf = write_compressed_insn (buf, 0x00000000, 4);
18406                 }
18407
18408               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18409               return;
18410             }
18411         }
18412
18413       /* Relax 16-bit branches to 32-bit branches.  */
18414       if (type != 0)
18415         {
18416           insn = read_compressed_insn (buf, 2);
18417
18418           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
18419             insn = 0x94000000;                          /* beq  */
18420           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
18421             {
18422               unsigned long regno;
18423
18424               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
18425               regno = micromips_to_32_reg_d_map [regno];
18426               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
18427               insn |= regno << MICROMIPSOP_SH_RS;
18428             }
18429           else
18430             abort ();
18431
18432           /* Nothing else to do, just write it out.  */
18433           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
18434               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18435             {
18436               buf = write_compressed_insn (buf, insn, 4);
18437               if (nods)
18438                 buf = write_compressed_insn (buf, 0x0c00, 2);
18439               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18440               return;
18441             }
18442         }
18443       else
18444         insn = read_compressed_insn (buf, 4);
18445
18446       /* Relax 32-bit branches to a sequence of instructions.  */
18447       as_warn_where (fragp->fr_file, fragp->fr_line,
18448                      _("relaxed out-of-range branch into a jump"));
18449
18450       /* Set the short-delay-slot bit.  */
18451       short_ds = !al || (insn & 0x02000000) != 0;
18452
18453       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
18454         {
18455           symbolS *l;
18456
18457           /* Reverse the branch.  */
18458           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
18459               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
18460             insn ^= 0x20000000;
18461           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
18462                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
18463                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
18464                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
18465                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
18466                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
18467                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
18468                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
18469                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
18470                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
18471             insn ^= 0x00400000;
18472           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
18473                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
18474                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
18475                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
18476             insn ^= 0x00200000;
18477           else if ((insn & 0xff000000) == 0x83000000            /* BZ.df
18478                                                                    BNZ.df  */
18479                     || (insn & 0xff600000) == 0x81600000)       /* BZ.V
18480                                                                    BNZ.V */
18481             insn ^= 0x00800000;
18482           else
18483             abort ();
18484
18485           if (al)
18486             {
18487               /* Clear the and-link and short-delay-slot bits.  */
18488               gas_assert ((insn & 0xfda00000) == 0x40200000);
18489
18490               /* bltzal  0x40200000     bgezal  0x40600000  */
18491               /* bltzals 0x42200000     bgezals 0x42600000  */
18492               insn &= ~0x02200000;
18493             }
18494
18495           /* Make a label at the end for use with the branch.  */
18496           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
18497           micromips_label_inc ();
18498           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
18499
18500           /* Refer to it.  */
18501           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
18502                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
18503           fixp->fx_file = fragp->fr_file;
18504           fixp->fx_line = fragp->fr_line;
18505
18506           /* Branch over the jump.  */
18507           buf = write_compressed_insn (buf, insn, 4);
18508
18509           if (!compact)
18510             {
18511               /* nop  */
18512               if (insn32)
18513                 buf = write_compressed_insn (buf, 0x00000000, 4);
18514               else
18515                 buf = write_compressed_insn (buf, 0x0c00, 2);
18516             }
18517         }
18518
18519       if (!pic)
18520         {
18521           unsigned long jal = (short_ds || nods
18522                                ? 0x74000000 : 0xf4000000);      /* jal/s  */
18523
18524           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
18525           insn = al ? jal : 0xd4000000;
18526
18527           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18528                               BFD_RELOC_MICROMIPS_JMP);
18529           fixp->fx_file = fragp->fr_file;
18530           fixp->fx_line = fragp->fr_line;
18531
18532           buf = write_compressed_insn (buf, insn, 4);
18533
18534           if (compact || nods)
18535             {
18536               /* nop  */
18537               if (insn32)
18538                 buf = write_compressed_insn (buf, 0x00000000, 4);
18539               else
18540                 buf = write_compressed_insn (buf, 0x0c00, 2);
18541             }
18542         }
18543       else
18544         {
18545           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
18546
18547           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
18548           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
18549           insn |= at << MICROMIPSOP_SH_RT;
18550
18551           if (exp.X_add_number)
18552             {
18553               exp.X_add_symbol = make_expr_symbol (&exp);
18554               exp.X_add_number = 0;
18555             }
18556
18557           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18558                               BFD_RELOC_MICROMIPS_GOT16);
18559           fixp->fx_file = fragp->fr_file;
18560           fixp->fx_line = fragp->fr_line;
18561
18562           buf = write_compressed_insn (buf, insn, 4);
18563
18564           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
18565           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
18566           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
18567
18568           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18569                               BFD_RELOC_MICROMIPS_LO16);
18570           fixp->fx_file = fragp->fr_file;
18571           fixp->fx_line = fragp->fr_line;
18572
18573           buf = write_compressed_insn (buf, insn, 4);
18574
18575           if (insn32)
18576             {
18577               /* jr/jalr $at  */
18578               insn = 0x00000f3c | (al ? RA : ZERO) << MICROMIPSOP_SH_RT;
18579               insn |= at << MICROMIPSOP_SH_RS;
18580
18581               buf = write_compressed_insn (buf, insn, 4);
18582
18583               if (compact || nods)
18584                 /* nop  */
18585                 buf = write_compressed_insn (buf, 0x00000000, 4);
18586             }
18587           else
18588             {
18589               /* jr/jrc/jalr/jalrs $at  */
18590               unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;  /* jalr/s  */
18591               unsigned long jr = compact || nods ? 0x45a0 : 0x4580; /* jr/c  */
18592
18593               insn = al ? jalr : jr;
18594               insn |= at << MICROMIPSOP_SH_MJ;
18595
18596               buf = write_compressed_insn (buf, insn, 2);
18597               if (al && nods)
18598                 {
18599                   /* nop  */
18600                   if (short_ds)
18601                     buf = write_compressed_insn (buf, 0x0c00, 2);
18602                   else
18603                     buf = write_compressed_insn (buf, 0x00000000, 4);
18604                 }
18605             }
18606         }
18607
18608       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18609       return;
18610     }
18611
18612   if (RELAX_MIPS16_P (fragp->fr_subtype))
18613     {
18614       int type;
18615       const struct mips_int_operand *operand;
18616       offsetT val;
18617       char *buf;
18618       unsigned int user_length;
18619       bfd_boolean need_reloc;
18620       unsigned long insn;
18621       bfd_boolean mac;
18622       bfd_boolean ext;
18623       segT symsec;
18624
18625       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
18626       operand = mips16_immed_operand (type, FALSE);
18627
18628       mac = RELAX_MIPS16_MACRO (fragp->fr_subtype);
18629       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
18630       val = resolve_symbol_value (fragp->fr_symbol) + fragp->fr_offset;
18631
18632       symsec = S_GET_SEGMENT (fragp->fr_symbol);
18633       need_reloc = (S_FORCE_RELOC (fragp->fr_symbol, TRUE)
18634                     || (operand->root.type == OP_PCREL && !mac
18635                         ? asec != symsec
18636                         : !bfd_is_abs_section (symsec)));
18637
18638       if (operand->root.type == OP_PCREL && !mac)
18639         {
18640           const struct mips_pcrel_operand *pcrel_op;
18641
18642           pcrel_op = (const struct mips_pcrel_operand *) operand;
18643
18644           if (pcrel_op->include_isa_bit && !need_reloc)
18645             {
18646               if (!ELF_ST_IS_MIPS16 (S_GET_OTHER (fragp->fr_symbol)))
18647                 as_bad_where (fragp->fr_file, fragp->fr_line,
18648                               _("branch to a symbol in another ISA mode"));
18649               else if ((fragp->fr_offset & 0x1) != 0)
18650                 as_bad_where (fragp->fr_file, fragp->fr_line,
18651                               _("branch to misaligned address (0x%lx)"),
18652                               (long) val);
18653             }
18654
18655           val = mips16_pcrel_val (fragp, pcrel_op, val, 0);
18656
18657           /* Make sure the section winds up with the alignment we have
18658              assumed.  */
18659           if (operand->shift > 0)
18660             record_alignment (asec, operand->shift);
18661         }
18662
18663       if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
18664           || RELAX_MIPS16_DSLOT (fragp->fr_subtype))
18665         {
18666           if (mac)
18667             as_warn_where (fragp->fr_file, fragp->fr_line,
18668                            _("macro instruction expanded into multiple "
18669                              "instructions in a branch delay slot"));
18670           else if (ext)
18671             as_warn_where (fragp->fr_file, fragp->fr_line,
18672                            _("extended instruction in a branch delay slot"));
18673         }
18674       else if (RELAX_MIPS16_NOMACRO (fragp->fr_subtype) && mac)
18675         as_warn_where (fragp->fr_file, fragp->fr_line,
18676                        _("macro instruction expanded into multiple "
18677                          "instructions"));
18678
18679       buf = fragp->fr_literal + fragp->fr_fix;
18680
18681       insn = read_compressed_insn (buf, 2);
18682       if (ext)
18683         insn |= MIPS16_EXTEND;
18684
18685       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
18686         user_length = 4;
18687       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
18688         user_length = 2;
18689       else
18690         user_length = 0;
18691
18692       if (mac)
18693         {
18694           unsigned long reg;
18695           unsigned long new;
18696           unsigned long op;
18697           bfd_boolean e2;
18698
18699           gas_assert (type == 'A' || type == 'B' || type == 'E');
18700           gas_assert (RELAX_MIPS16_SYM32 (fragp->fr_subtype));
18701
18702           e2 = RELAX_MIPS16_E2 (fragp->fr_subtype);
18703
18704           if (need_reloc)
18705             {
18706               fixS *fixp;
18707
18708               gas_assert (!RELAX_MIPS16_PIC (fragp->fr_subtype));
18709
18710               fixp = fix_new (fragp, buf - fragp->fr_literal, 4,
18711                               fragp->fr_symbol, fragp->fr_offset,
18712                               FALSE, BFD_RELOC_MIPS16_HI16_S);
18713               fixp->fx_file = fragp->fr_file;
18714               fixp->fx_line = fragp->fr_line;
18715
18716               fixp = fix_new (fragp, buf - fragp->fr_literal + (e2 ? 4 : 8), 4,
18717                               fragp->fr_symbol, fragp->fr_offset,
18718                               FALSE, BFD_RELOC_MIPS16_LO16);
18719               fixp->fx_file = fragp->fr_file;
18720               fixp->fx_line = fragp->fr_line;
18721
18722               val = 0;
18723             }
18724
18725           switch (insn & 0xf800)
18726             {
18727             case 0x0800:                                        /* ADDIU */
18728               reg = (insn >> 8) & 0x7;
18729               op = 0xf0004800 | (reg << 8);
18730               break;
18731             case 0xb000:                                        /* LW */
18732               reg = (insn >> 8) & 0x7;
18733               op = 0xf0009800 | (reg << 8) | (reg << 5);
18734               break;
18735             case 0xf800:                                        /* I64 */
18736               reg = (insn >> 5) & 0x7;
18737               switch (insn & 0x0700)
18738                 {
18739                 case 0x0400:                                    /* LD */
18740                   op = 0xf0003800 | (reg << 8) | (reg << 5);
18741                   break;
18742                 case 0x0600:                                    /* DADDIU */
18743                   op = 0xf000fd00 | (reg << 5);
18744                   break;
18745                 default:
18746                   abort ();
18747                 }
18748               break;
18749             default:
18750               abort ();
18751             }
18752
18753           new = (e2 ? 0xf0006820 : 0xf0006800) | (reg << 8);    /* LUI/LI */
18754           new |= mips16_immed_extend ((val + 0x8000) >> 16, 16);
18755           buf = write_compressed_insn (buf, new, 4);
18756           if (!e2)
18757             {
18758               new = 0xf4003000 | (reg << 8) | (reg << 5);       /* SLL */
18759               buf = write_compressed_insn (buf, new, 4);
18760             }
18761           op |= mips16_immed_extend (val, 16);
18762           buf = write_compressed_insn (buf, op, 4);
18763
18764           fragp->fr_fix += e2 ? 8 : 12;
18765         }
18766       else
18767         {
18768           unsigned int length = ext ? 4 : 2;
18769
18770           if (need_reloc)
18771             {
18772               bfd_reloc_code_real_type reloc = BFD_RELOC_NONE;
18773               expressionS exp;
18774               fixS *fixp;
18775
18776               switch (type)
18777                 {
18778                 case 'p':
18779                 case 'q':
18780                   reloc = BFD_RELOC_MIPS16_16_PCREL_S1;
18781                   break;
18782                 default:
18783                   break;
18784                 }
18785               if (mac || reloc == BFD_RELOC_NONE)
18786                 as_bad_where (fragp->fr_file, fragp->fr_line,
18787                               _("unsupported relocation"));
18788               else if (ext)
18789                 {
18790                   exp.X_op = O_symbol;
18791                   exp.X_add_symbol = fragp->fr_symbol;
18792                   exp.X_add_number = fragp->fr_offset;
18793
18794                   fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
18795                                       TRUE, reloc);
18796
18797                   fixp->fx_file = fragp->fr_file;
18798                   fixp->fx_line = fragp->fr_line;
18799                 }
18800               else
18801                 as_bad_where (fragp->fr_file, fragp->fr_line,
18802                               _("invalid unextended operand value"));
18803             }
18804           else
18805             mips16_immed (fragp->fr_file, fragp->fr_line, type,
18806                           BFD_RELOC_UNUSED, val, user_length, &insn);
18807
18808           gas_assert (mips16_opcode_length (insn) == length);
18809           write_compressed_insn (buf, insn, length);
18810           fragp->fr_fix += length;
18811         }
18812     }
18813   else
18814     {
18815       relax_substateT subtype = fragp->fr_subtype;
18816       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
18817       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
18818       int first, second;
18819       fixS *fixp;
18820
18821       first = RELAX_FIRST (subtype);
18822       second = RELAX_SECOND (subtype);
18823       fixp = (fixS *) fragp->fr_opcode;
18824
18825       /* If the delay slot chosen does not match the size of the instruction,
18826          then emit a warning.  */
18827       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
18828            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
18829         {
18830           relax_substateT s;
18831           const char *msg;
18832
18833           s = subtype & (RELAX_DELAY_SLOT_16BIT
18834                          | RELAX_DELAY_SLOT_SIZE_FIRST
18835                          | RELAX_DELAY_SLOT_SIZE_SECOND);
18836           msg = macro_warning (s);
18837           if (msg != NULL)
18838             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18839           subtype &= ~s;
18840         }
18841
18842       /* Possibly emit a warning if we've chosen the longer option.  */
18843       if (use_second == second_longer)
18844         {
18845           relax_substateT s;
18846           const char *msg;
18847
18848           s = (subtype
18849                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
18850           msg = macro_warning (s);
18851           if (msg != NULL)
18852             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18853           subtype &= ~s;
18854         }
18855
18856       /* Go through all the fixups for the first sequence.  Disable them
18857          (by marking them as done) if we're going to use the second
18858          sequence instead.  */
18859       while (fixp
18860              && fixp->fx_frag == fragp
18861              && fixp->fx_where < fragp->fr_fix - second)
18862         {
18863           if (subtype & RELAX_USE_SECOND)
18864             fixp->fx_done = 1;
18865           fixp = fixp->fx_next;
18866         }
18867
18868       /* Go through the fixups for the second sequence.  Disable them if
18869          we're going to use the first sequence, otherwise adjust their
18870          addresses to account for the relaxation.  */
18871       while (fixp && fixp->fx_frag == fragp)
18872         {
18873           if (subtype & RELAX_USE_SECOND)
18874             fixp->fx_where -= first;
18875           else
18876             fixp->fx_done = 1;
18877           fixp = fixp->fx_next;
18878         }
18879
18880       /* Now modify the frag contents.  */
18881       if (subtype & RELAX_USE_SECOND)
18882         {
18883           char *start;
18884
18885           start = fragp->fr_literal + fragp->fr_fix - first - second;
18886           memmove (start, start + first, second);
18887           fragp->fr_fix -= first;
18888         }
18889       else
18890         fragp->fr_fix -= second;
18891     }
18892 }
18893
18894 /* This function is called after the relocs have been generated.
18895    We've been storing mips16 text labels as odd.  Here we convert them
18896    back to even for the convenience of the debugger.  */
18897
18898 void
18899 mips_frob_file_after_relocs (void)
18900 {
18901   asymbol **syms;
18902   unsigned int count, i;
18903
18904   syms = bfd_get_outsymbols (stdoutput);
18905   count = bfd_get_symcount (stdoutput);
18906   for (i = 0; i < count; i++, syms++)
18907     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
18908         && ((*syms)->value & 1) != 0)
18909       {
18910         (*syms)->value &= ~1;
18911         /* If the symbol has an odd size, it was probably computed
18912            incorrectly, so adjust that as well.  */
18913         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
18914           ++elf_symbol (*syms)->internal_elf_sym.st_size;
18915       }
18916 }
18917
18918 /* This function is called whenever a label is defined, including fake
18919    labels instantiated off the dot special symbol.  It is used when
18920    handling branch delays; if a branch has a label, we assume we cannot
18921    move it.  This also bumps the value of the symbol by 1 in compressed
18922    code.  */
18923
18924 static void
18925 mips_record_label (symbolS *sym)
18926 {
18927   segment_info_type *si = seg_info (now_seg);
18928   struct insn_label_list *l;
18929
18930   if (free_insn_labels == NULL)
18931     l = XNEW (struct insn_label_list);
18932   else
18933     {
18934       l = free_insn_labels;
18935       free_insn_labels = l->next;
18936     }
18937
18938   l->label = sym;
18939   l->next = si->label_list;
18940   si->label_list = l;
18941 }
18942
18943 /* This function is called as tc_frob_label() whenever a label is defined
18944    and adds a DWARF-2 record we only want for true labels.  */
18945
18946 void
18947 mips_define_label (symbolS *sym)
18948 {
18949   mips_record_label (sym);
18950   dwarf2_emit_label (sym);
18951 }
18952
18953 /* This function is called by tc_new_dot_label whenever a new dot symbol
18954    is defined.  */
18955
18956 void
18957 mips_add_dot_label (symbolS *sym)
18958 {
18959   mips_record_label (sym);
18960   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
18961     mips_compressed_mark_label (sym);
18962 }
18963 \f
18964 /* Converting ASE flags from internal to .MIPS.abiflags values.  */
18965 static unsigned int
18966 mips_convert_ase_flags (int ase)
18967 {
18968   unsigned int ext_ases = 0;
18969
18970   if (ase & ASE_DSP)
18971     ext_ases |= AFL_ASE_DSP;
18972   if (ase & ASE_DSPR2)
18973     ext_ases |= AFL_ASE_DSPR2;
18974   if (ase & ASE_DSPR3)
18975     ext_ases |= AFL_ASE_DSPR3;
18976   if (ase & ASE_EVA)
18977     ext_ases |= AFL_ASE_EVA;
18978   if (ase & ASE_MCU)
18979     ext_ases |= AFL_ASE_MCU;
18980   if (ase & ASE_MDMX)
18981     ext_ases |= AFL_ASE_MDMX;
18982   if (ase & ASE_MIPS3D)
18983     ext_ases |= AFL_ASE_MIPS3D;
18984   if (ase & ASE_MT)
18985     ext_ases |= AFL_ASE_MT;
18986   if (ase & ASE_SMARTMIPS)
18987     ext_ases |= AFL_ASE_SMARTMIPS;
18988   if (ase & ASE_VIRT)
18989     ext_ases |= AFL_ASE_VIRT;
18990   if (ase & ASE_MSA)
18991     ext_ases |= AFL_ASE_MSA;
18992   if (ase & ASE_XPA)
18993     ext_ases |= AFL_ASE_XPA;
18994   if (ase & ASE_MIPS16E2)
18995     ext_ases |= file_ase_mips16 ? AFL_ASE_MIPS16E2 : 0;
18996
18997   return ext_ases;
18998 }
18999 /* Some special processing for a MIPS ELF file.  */
19000
19001 void
19002 mips_elf_final_processing (void)
19003 {
19004   int fpabi;
19005   Elf_Internal_ABIFlags_v0 flags;
19006
19007   flags.version = 0;
19008   flags.isa_rev = 0;
19009   switch (file_mips_opts.isa)
19010     {
19011     case INSN_ISA1:
19012       flags.isa_level = 1;
19013       break;
19014     case INSN_ISA2:
19015       flags.isa_level = 2;
19016       break;
19017     case INSN_ISA3:
19018       flags.isa_level = 3;
19019       break;
19020     case INSN_ISA4:
19021       flags.isa_level = 4;
19022       break;
19023     case INSN_ISA5:
19024       flags.isa_level = 5;
19025       break;
19026     case INSN_ISA32:
19027       flags.isa_level = 32;
19028       flags.isa_rev = 1;
19029       break;
19030     case INSN_ISA32R2:
19031       flags.isa_level = 32;
19032       flags.isa_rev = 2;
19033       break;
19034     case INSN_ISA32R3:
19035       flags.isa_level = 32;
19036       flags.isa_rev = 3;
19037       break;
19038     case INSN_ISA32R5:
19039       flags.isa_level = 32;
19040       flags.isa_rev = 5;
19041       break;
19042     case INSN_ISA32R6:
19043       flags.isa_level = 32;
19044       flags.isa_rev = 6;
19045       break;
19046     case INSN_ISA64:
19047       flags.isa_level = 64;
19048       flags.isa_rev = 1;
19049       break;
19050     case INSN_ISA64R2:
19051       flags.isa_level = 64;
19052       flags.isa_rev = 2;
19053       break;
19054     case INSN_ISA64R3:
19055       flags.isa_level = 64;
19056       flags.isa_rev = 3;
19057       break;
19058     case INSN_ISA64R5:
19059       flags.isa_level = 64;
19060       flags.isa_rev = 5;
19061       break;
19062     case INSN_ISA64R6:
19063       flags.isa_level = 64;
19064       flags.isa_rev = 6;
19065       break;
19066     }
19067
19068   flags.gpr_size = file_mips_opts.gp == 32 ? AFL_REG_32 : AFL_REG_64;
19069   flags.cpr1_size = file_mips_opts.soft_float ? AFL_REG_NONE
19070                     : (file_mips_opts.ase & ASE_MSA) ? AFL_REG_128
19071                     : (file_mips_opts.fp == 64) ? AFL_REG_64
19072                     : AFL_REG_32;
19073   flags.cpr2_size = AFL_REG_NONE;
19074   flags.fp_abi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
19075                                            Tag_GNU_MIPS_ABI_FP);
19076   flags.isa_ext = bfd_mips_isa_ext (stdoutput);
19077   flags.ases = mips_convert_ase_flags (file_mips_opts.ase);
19078   if (file_ase_mips16)
19079     flags.ases |= AFL_ASE_MIPS16;
19080   if (file_ase_micromips)
19081     flags.ases |= AFL_ASE_MICROMIPS;
19082   flags.flags1 = 0;
19083   if ((ISA_HAS_ODD_SINGLE_FPR (file_mips_opts.isa, file_mips_opts.arch)
19084        || file_mips_opts.fp == 64)
19085       && file_mips_opts.oddspreg)
19086     flags.flags1 |= AFL_FLAGS1_ODDSPREG;
19087   flags.flags2 = 0;
19088
19089   bfd_mips_elf_swap_abiflags_v0_out (stdoutput, &flags,
19090                                      ((Elf_External_ABIFlags_v0 *)
19091                                      mips_flags_frag));
19092
19093   /* Write out the register information.  */
19094   if (mips_abi != N64_ABI)
19095     {
19096       Elf32_RegInfo s;
19097
19098       s.ri_gprmask = mips_gprmask;
19099       s.ri_cprmask[0] = mips_cprmask[0];
19100       s.ri_cprmask[1] = mips_cprmask[1];
19101       s.ri_cprmask[2] = mips_cprmask[2];
19102       s.ri_cprmask[3] = mips_cprmask[3];
19103       /* The gp_value field is set by the MIPS ELF backend.  */
19104
19105       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
19106                                        ((Elf32_External_RegInfo *)
19107                                         mips_regmask_frag));
19108     }
19109   else
19110     {
19111       Elf64_Internal_RegInfo s;
19112
19113       s.ri_gprmask = mips_gprmask;
19114       s.ri_pad = 0;
19115       s.ri_cprmask[0] = mips_cprmask[0];
19116       s.ri_cprmask[1] = mips_cprmask[1];
19117       s.ri_cprmask[2] = mips_cprmask[2];
19118       s.ri_cprmask[3] = mips_cprmask[3];
19119       /* The gp_value field is set by the MIPS ELF backend.  */
19120
19121       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
19122                                        ((Elf64_External_RegInfo *)
19123                                         mips_regmask_frag));
19124     }
19125
19126   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
19127      sort of BFD interface for this.  */
19128   if (mips_any_noreorder)
19129     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
19130   if (mips_pic != NO_PIC)
19131     {
19132       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
19133       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
19134     }
19135   if (mips_abicalls)
19136     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
19137
19138   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
19139      defined at present; this might need to change in future.  */
19140   if (file_ase_mips16)
19141     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
19142   if (file_ase_micromips)
19143     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
19144   if (file_mips_opts.ase & ASE_MDMX)
19145     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
19146
19147   /* Set the MIPS ELF ABI flags.  */
19148   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
19149     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
19150   else if (mips_abi == O64_ABI)
19151     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
19152   else if (mips_abi == EABI_ABI)
19153     {
19154       if (file_mips_opts.gp == 64)
19155         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
19156       else
19157         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
19158     }
19159   else if (mips_abi == N32_ABI)
19160     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
19161
19162   /* Nothing to do for N64_ABI.  */
19163
19164   if (mips_32bitmode)
19165     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
19166
19167   if (mips_nan2008 == 1)
19168     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
19169
19170   /* 32 bit code with 64 bit FP registers.  */
19171   fpabi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
19172                                     Tag_GNU_MIPS_ABI_FP);
19173   if (fpabi == Val_GNU_MIPS_ABI_FP_OLD_64)
19174     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_FP64;
19175 }
19176 \f
19177 typedef struct proc {
19178   symbolS *func_sym;
19179   symbolS *func_end_sym;
19180   unsigned long reg_mask;
19181   unsigned long reg_offset;
19182   unsigned long fpreg_mask;
19183   unsigned long fpreg_offset;
19184   unsigned long frame_offset;
19185   unsigned long frame_reg;
19186   unsigned long pc_reg;
19187 } procS;
19188
19189 static procS cur_proc;
19190 static procS *cur_proc_ptr;
19191 static int numprocs;
19192
19193 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
19194    as "2", and a normal nop as "0".  */
19195
19196 #define NOP_OPCODE_MIPS         0
19197 #define NOP_OPCODE_MIPS16       1
19198 #define NOP_OPCODE_MICROMIPS    2
19199
19200 char
19201 mips_nop_opcode (void)
19202 {
19203   if (seg_info (now_seg)->tc_segment_info_data.micromips)
19204     return NOP_OPCODE_MICROMIPS;
19205   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
19206     return NOP_OPCODE_MIPS16;
19207   else
19208     return NOP_OPCODE_MIPS;
19209 }
19210
19211 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
19212    32-bit microMIPS NOPs here (if applicable).  */
19213
19214 void
19215 mips_handle_align (fragS *fragp)
19216 {
19217   char nop_opcode;
19218   char *p;
19219   int bytes, size, excess;
19220   valueT opcode;
19221
19222   if (fragp->fr_type != rs_align_code)
19223     return;
19224
19225   p = fragp->fr_literal + fragp->fr_fix;
19226   nop_opcode = *p;
19227   switch (nop_opcode)
19228     {
19229     case NOP_OPCODE_MICROMIPS:
19230       opcode = micromips_nop32_insn.insn_opcode;
19231       size = 4;
19232       break;
19233     case NOP_OPCODE_MIPS16:
19234       opcode = mips16_nop_insn.insn_opcode;
19235       size = 2;
19236       break;
19237     case NOP_OPCODE_MIPS:
19238     default:
19239       opcode = nop_insn.insn_opcode;
19240       size = 4;
19241       break;
19242     }
19243
19244   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
19245   excess = bytes % size;
19246
19247   /* Handle the leading part if we're not inserting a whole number of
19248      instructions, and make it the end of the fixed part of the frag.
19249      Try to fit in a short microMIPS NOP if applicable and possible,
19250      and use zeroes otherwise.  */
19251   gas_assert (excess < 4);
19252   fragp->fr_fix += excess;
19253   switch (excess)
19254     {
19255     case 3:
19256       *p++ = '\0';
19257       /* Fall through.  */
19258     case 2:
19259       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
19260         {
19261           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
19262           break;
19263         }
19264       *p++ = '\0';
19265       /* Fall through.  */
19266     case 1:
19267       *p++ = '\0';
19268       /* Fall through.  */
19269     case 0:
19270       break;
19271     }
19272
19273   md_number_to_chars (p, opcode, size);
19274   fragp->fr_var = size;
19275 }
19276
19277 static long
19278 get_number (void)
19279 {
19280   int negative = 0;
19281   long val = 0;
19282
19283   if (*input_line_pointer == '-')
19284     {
19285       ++input_line_pointer;
19286       negative = 1;
19287     }
19288   if (!ISDIGIT (*input_line_pointer))
19289     as_bad (_("expected simple number"));
19290   if (input_line_pointer[0] == '0')
19291     {
19292       if (input_line_pointer[1] == 'x')
19293         {
19294           input_line_pointer += 2;
19295           while (ISXDIGIT (*input_line_pointer))
19296             {
19297               val <<= 4;
19298               val |= hex_value (*input_line_pointer++);
19299             }
19300           return negative ? -val : val;
19301         }
19302       else
19303         {
19304           ++input_line_pointer;
19305           while (ISDIGIT (*input_line_pointer))
19306             {
19307               val <<= 3;
19308               val |= *input_line_pointer++ - '0';
19309             }
19310           return negative ? -val : val;
19311         }
19312     }
19313   if (!ISDIGIT (*input_line_pointer))
19314     {
19315       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
19316               *input_line_pointer, *input_line_pointer);
19317       as_warn (_("invalid number"));
19318       return -1;
19319     }
19320   while (ISDIGIT (*input_line_pointer))
19321     {
19322       val *= 10;
19323       val += *input_line_pointer++ - '0';
19324     }
19325   return negative ? -val : val;
19326 }
19327
19328 /* The .file directive; just like the usual .file directive, but there
19329    is an initial number which is the ECOFF file index.  In the non-ECOFF
19330    case .file implies DWARF-2.  */
19331
19332 static void
19333 s_mips_file (int x ATTRIBUTE_UNUSED)
19334 {
19335   static int first_file_directive = 0;
19336
19337   if (ECOFF_DEBUGGING)
19338     {
19339       get_number ();
19340       s_app_file (0);
19341     }
19342   else
19343     {
19344       char *filename;
19345
19346       filename = dwarf2_directive_file (0);
19347
19348       /* Versions of GCC up to 3.1 start files with a ".file"
19349          directive even for stabs output.  Make sure that this
19350          ".file" is handled.  Note that you need a version of GCC
19351          after 3.1 in order to support DWARF-2 on MIPS.  */
19352       if (filename != NULL && ! first_file_directive)
19353         {
19354           (void) new_logical_line (filename, -1);
19355           s_app_file_string (filename, 0);
19356         }
19357       first_file_directive = 1;
19358     }
19359 }
19360
19361 /* The .loc directive, implying DWARF-2.  */
19362
19363 static void
19364 s_mips_loc (int x ATTRIBUTE_UNUSED)
19365 {
19366   if (!ECOFF_DEBUGGING)
19367     dwarf2_directive_loc (0);
19368 }
19369
19370 /* The .end directive.  */
19371
19372 static void
19373 s_mips_end (int x ATTRIBUTE_UNUSED)
19374 {
19375   symbolS *p;
19376
19377   /* Following functions need their own .frame and .cprestore directives.  */
19378   mips_frame_reg_valid = 0;
19379   mips_cprestore_valid = 0;
19380
19381   if (!is_end_of_line[(unsigned char) *input_line_pointer])
19382     {
19383       p = get_symbol ();
19384       demand_empty_rest_of_line ();
19385     }
19386   else
19387     p = NULL;
19388
19389   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
19390     as_warn (_(".end not in text section"));
19391
19392   if (!cur_proc_ptr)
19393     {
19394       as_warn (_(".end directive without a preceding .ent directive"));
19395       demand_empty_rest_of_line ();
19396       return;
19397     }
19398
19399   if (p != NULL)
19400     {
19401       gas_assert (S_GET_NAME (p));
19402       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
19403         as_warn (_(".end symbol does not match .ent symbol"));
19404
19405       if (debug_type == DEBUG_STABS)
19406         stabs_generate_asm_endfunc (S_GET_NAME (p),
19407                                     S_GET_NAME (p));
19408     }
19409   else
19410     as_warn (_(".end directive missing or unknown symbol"));
19411
19412   /* Create an expression to calculate the size of the function.  */
19413   if (p && cur_proc_ptr)
19414     {
19415       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
19416       expressionS *exp = XNEW (expressionS);
19417
19418       obj->size = exp;
19419       exp->X_op = O_subtract;
19420       exp->X_add_symbol = symbol_temp_new_now ();
19421       exp->X_op_symbol = p;
19422       exp->X_add_number = 0;
19423
19424       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
19425     }
19426
19427 #ifdef md_flush_pending_output
19428   md_flush_pending_output ();
19429 #endif
19430
19431   /* Generate a .pdr section.  */
19432   if (!ECOFF_DEBUGGING && mips_flag_pdr)
19433     {
19434       segT saved_seg = now_seg;
19435       subsegT saved_subseg = now_subseg;
19436       expressionS exp;
19437       char *fragp;
19438
19439       gas_assert (pdr_seg);
19440       subseg_set (pdr_seg, 0);
19441
19442       /* Write the symbol.  */
19443       exp.X_op = O_symbol;
19444       exp.X_add_symbol = p;
19445       exp.X_add_number = 0;
19446       emit_expr (&exp, 4);
19447
19448       fragp = frag_more (7 * 4);
19449
19450       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
19451       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
19452       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
19453       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
19454       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
19455       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
19456       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
19457
19458       subseg_set (saved_seg, saved_subseg);
19459     }
19460
19461   cur_proc_ptr = NULL;
19462 }
19463
19464 /* The .aent and .ent directives.  */
19465
19466 static void
19467 s_mips_ent (int aent)
19468 {
19469   symbolS *symbolP;
19470
19471   symbolP = get_symbol ();
19472   if (*input_line_pointer == ',')
19473     ++input_line_pointer;
19474   SKIP_WHITESPACE ();
19475   if (ISDIGIT (*input_line_pointer)
19476       || *input_line_pointer == '-')
19477     get_number ();
19478
19479   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
19480     as_warn (_(".ent or .aent not in text section"));
19481
19482   if (!aent && cur_proc_ptr)
19483     as_warn (_("missing .end"));
19484
19485   if (!aent)
19486     {
19487       /* This function needs its own .frame and .cprestore directives.  */
19488       mips_frame_reg_valid = 0;
19489       mips_cprestore_valid = 0;
19490
19491       cur_proc_ptr = &cur_proc;
19492       memset (cur_proc_ptr, '\0', sizeof (procS));
19493
19494       cur_proc_ptr->func_sym = symbolP;
19495
19496       ++numprocs;
19497
19498       if (debug_type == DEBUG_STABS)
19499         stabs_generate_asm_func (S_GET_NAME (symbolP),
19500                                  S_GET_NAME (symbolP));
19501     }
19502
19503   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
19504
19505   demand_empty_rest_of_line ();
19506 }
19507
19508 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
19509    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
19510    s_mips_frame is used so that we can set the PDR information correctly.
19511    We can't use the ecoff routines because they make reference to the ecoff
19512    symbol table (in the mdebug section).  */
19513
19514 static void
19515 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
19516 {
19517   if (ECOFF_DEBUGGING)
19518     s_ignore (ignore);
19519   else
19520     {
19521       long val;
19522
19523       if (cur_proc_ptr == (procS *) NULL)
19524         {
19525           as_warn (_(".frame outside of .ent"));
19526           demand_empty_rest_of_line ();
19527           return;
19528         }
19529
19530       cur_proc_ptr->frame_reg = tc_get_register (1);
19531
19532       SKIP_WHITESPACE ();
19533       if (*input_line_pointer++ != ','
19534           || get_absolute_expression_and_terminator (&val) != ',')
19535         {
19536           as_warn (_("bad .frame directive"));
19537           --input_line_pointer;
19538           demand_empty_rest_of_line ();
19539           return;
19540         }
19541
19542       cur_proc_ptr->frame_offset = val;
19543       cur_proc_ptr->pc_reg = tc_get_register (0);
19544
19545       demand_empty_rest_of_line ();
19546     }
19547 }
19548
19549 /* The .fmask and .mask directives. If the mdebug section is present
19550    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
19551    embedded targets, s_mips_mask is used so that we can set the PDR
19552    information correctly. We can't use the ecoff routines because they
19553    make reference to the ecoff symbol table (in the mdebug section).  */
19554
19555 static void
19556 s_mips_mask (int reg_type)
19557 {
19558   if (ECOFF_DEBUGGING)
19559     s_ignore (reg_type);
19560   else
19561     {
19562       long mask, off;
19563
19564       if (cur_proc_ptr == (procS *) NULL)
19565         {
19566           as_warn (_(".mask/.fmask outside of .ent"));
19567           demand_empty_rest_of_line ();
19568           return;
19569         }
19570
19571       if (get_absolute_expression_and_terminator (&mask) != ',')
19572         {
19573           as_warn (_("bad .mask/.fmask directive"));
19574           --input_line_pointer;
19575           demand_empty_rest_of_line ();
19576           return;
19577         }
19578
19579       off = get_absolute_expression ();
19580
19581       if (reg_type == 'F')
19582         {
19583           cur_proc_ptr->fpreg_mask = mask;
19584           cur_proc_ptr->fpreg_offset = off;
19585         }
19586       else
19587         {
19588           cur_proc_ptr->reg_mask = mask;
19589           cur_proc_ptr->reg_offset = off;
19590         }
19591
19592       demand_empty_rest_of_line ();
19593     }
19594 }
19595
19596 /* A table describing all the processors gas knows about.  Names are
19597    matched in the order listed.
19598
19599    To ease comparison, please keep this table in the same order as
19600    gcc's mips_cpu_info_table[].  */
19601 static const struct mips_cpu_info mips_cpu_info_table[] =
19602 {
19603   /* Entries for generic ISAs */
19604   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
19605   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
19606   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
19607   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
19608   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
19609   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
19610   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
19611   { "mips32r3",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R3, CPU_MIPS32R3 },
19612   { "mips32r5",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R5, CPU_MIPS32R5 },
19613   { "mips32r6",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R6, CPU_MIPS32R6 },
19614   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
19615   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
19616   { "mips64r3",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R3, CPU_MIPS64R3 },
19617   { "mips64r5",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R5, CPU_MIPS64R5 },
19618   { "mips64r6",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R6, CPU_MIPS64R6 },
19619
19620   /* MIPS I */
19621   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
19622   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
19623   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
19624
19625   /* MIPS II */
19626   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
19627
19628   /* MIPS III */
19629   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
19630   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
19631   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
19632   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
19633   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
19634   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
19635   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
19636   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
19637   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
19638   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
19639   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
19640   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
19641   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
19642   /* ST Microelectronics Loongson 2E and 2F cores */
19643   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
19644   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
19645
19646   /* MIPS IV */
19647   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
19648   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
19649   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
19650   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
19651   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
19652   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19653   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
19654   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
19655   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19656   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19657   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19658   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19659   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19660   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
19661   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
19662
19663   /* MIPS 32 */
19664   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19665   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19666   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19667   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
19668
19669   /* MIPS 32 Release 2 */
19670   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19671   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19672   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19673   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
19674   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19675   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19676   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
19677   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
19678   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
19679                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
19680   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
19681                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
19682   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19683   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19684   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19685   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19686   /* Deprecated forms of the above.  */
19687   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19688   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19689   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
19690   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19691   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19692   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19693   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19694   /* Deprecated forms of the above.  */
19695   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19696   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19697   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
19698   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19699   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19700   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19701   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19702   /* Deprecated forms of the above.  */
19703   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19704   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19705   /* 34Kn is a 34kc without DSP.  */
19706   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
19707   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
19708   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19709   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19710   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19711   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19712   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19713   /* Deprecated forms of the above.  */
19714   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19715   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19716   /* 1004K cores are multiprocessor versions of the 34K.  */
19717   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19718   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19719   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19720   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19721   /* interaptiv is the new name for 1004kf */
19722   { "interaptiv",     0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19723   { "interaptiv-mr2", 0,
19724     ASE_DSP | ASE_EVA | ASE_MT | ASE_MIPS16E2 | ASE_MIPS16E2_MT,
19725     ISA_MIPS32R3, CPU_INTERAPTIV_MR2 },
19726   /* M5100 family */
19727   { "m5100",          0, ASE_MCU,               ISA_MIPS32R5, CPU_MIPS32R5 },
19728   { "m5101",          0, ASE_MCU,               ISA_MIPS32R5, CPU_MIPS32R5 },
19729   /* P5600 with EVA and Virtualization ASEs, other ASEs are optional.  */
19730   { "p5600",          0, ASE_VIRT | ASE_EVA | ASE_XPA,  ISA_MIPS32R5, CPU_MIPS32R5 },
19731
19732   /* MIPS 64 */
19733   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
19734   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
19735   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
19736   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
19737
19738   /* Broadcom SB-1 CPU core */
19739   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
19740   /* Broadcom SB-1A CPU core */
19741   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
19742
19743   { "loongson3a",     0, 0,                     ISA_MIPS64R2, CPU_LOONGSON_3A },
19744
19745   /* MIPS 64 Release 2 */
19746
19747   /* Cavium Networks Octeon CPU core */
19748   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
19749   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
19750   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
19751   { "octeon3",        0, ASE_VIRT | ASE_VIRT64, ISA_MIPS64R5, CPU_OCTEON3 },
19752
19753   /* RMI Xlr */
19754   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
19755
19756   /* Broadcom XLP.
19757      XLP is mostly like XLR, with the prominent exception that it is
19758      MIPS64R2 rather than MIPS64.  */
19759   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
19760
19761   /* MIPS 64 Release 6 */
19762   { "i6400",          0, ASE_MSA,               ISA_MIPS64R6, CPU_MIPS64R6},
19763   { "p6600",          0, ASE_VIRT | ASE_MSA,    ISA_MIPS64R6, CPU_MIPS64R6},
19764
19765   /* End marker */
19766   { NULL, 0, 0, 0, 0 }
19767 };
19768
19769
19770 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
19771    with a final "000" replaced by "k".  Ignore case.
19772
19773    Note: this function is shared between GCC and GAS.  */
19774
19775 static bfd_boolean
19776 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
19777 {
19778   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
19779     given++, canonical++;
19780
19781   return ((*given == 0 && *canonical == 0)
19782           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
19783 }
19784
19785
19786 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
19787    CPU name.  We've traditionally allowed a lot of variation here.
19788
19789    Note: this function is shared between GCC and GAS.  */
19790
19791 static bfd_boolean
19792 mips_matching_cpu_name_p (const char *canonical, const char *given)
19793 {
19794   /* First see if the name matches exactly, or with a final "000"
19795      turned into "k".  */
19796   if (mips_strict_matching_cpu_name_p (canonical, given))
19797     return TRUE;
19798
19799   /* If not, try comparing based on numerical designation alone.
19800      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
19801   if (TOLOWER (*given) == 'r')
19802     given++;
19803   if (!ISDIGIT (*given))
19804     return FALSE;
19805
19806   /* Skip over some well-known prefixes in the canonical name,
19807      hoping to find a number there too.  */
19808   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
19809     canonical += 2;
19810   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
19811     canonical += 2;
19812   else if (TOLOWER (canonical[0]) == 'r')
19813     canonical += 1;
19814
19815   return mips_strict_matching_cpu_name_p (canonical, given);
19816 }
19817
19818
19819 /* Parse an option that takes the name of a processor as its argument.
19820    OPTION is the name of the option and CPU_STRING is the argument.
19821    Return the corresponding processor enumeration if the CPU_STRING is
19822    recognized, otherwise report an error and return null.
19823
19824    A similar function exists in GCC.  */
19825
19826 static const struct mips_cpu_info *
19827 mips_parse_cpu (const char *option, const char *cpu_string)
19828 {
19829   const struct mips_cpu_info *p;
19830
19831   /* 'from-abi' selects the most compatible architecture for the given
19832      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
19833      EABIs, we have to decide whether we're using the 32-bit or 64-bit
19834      version.  Look first at the -mgp options, if given, otherwise base
19835      the choice on MIPS_DEFAULT_64BIT.
19836
19837      Treat NO_ABI like the EABIs.  One reason to do this is that the
19838      plain 'mips' and 'mips64' configs have 'from-abi' as their default
19839      architecture.  This code picks MIPS I for 'mips' and MIPS III for
19840      'mips64', just as we did in the days before 'from-abi'.  */
19841   if (strcasecmp (cpu_string, "from-abi") == 0)
19842     {
19843       if (ABI_NEEDS_32BIT_REGS (mips_abi))
19844         return mips_cpu_info_from_isa (ISA_MIPS1);
19845
19846       if (ABI_NEEDS_64BIT_REGS (mips_abi))
19847         return mips_cpu_info_from_isa (ISA_MIPS3);
19848
19849       if (file_mips_opts.gp >= 0)
19850         return mips_cpu_info_from_isa (file_mips_opts.gp == 32
19851                                        ? ISA_MIPS1 : ISA_MIPS3);
19852
19853       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
19854                                      ? ISA_MIPS3
19855                                      : ISA_MIPS1);
19856     }
19857
19858   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
19859   if (strcasecmp (cpu_string, "default") == 0)
19860     return 0;
19861
19862   for (p = mips_cpu_info_table; p->name != 0; p++)
19863     if (mips_matching_cpu_name_p (p->name, cpu_string))
19864       return p;
19865
19866   as_bad (_("bad value (%s) for %s"), cpu_string, option);
19867   return 0;
19868 }
19869
19870 /* Return the canonical processor information for ISA (a member of the
19871    ISA_MIPS* enumeration).  */
19872
19873 static const struct mips_cpu_info *
19874 mips_cpu_info_from_isa (int isa)
19875 {
19876   int i;
19877
19878   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19879     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
19880         && isa == mips_cpu_info_table[i].isa)
19881       return (&mips_cpu_info_table[i]);
19882
19883   return NULL;
19884 }
19885
19886 static const struct mips_cpu_info *
19887 mips_cpu_info_from_arch (int arch)
19888 {
19889   int i;
19890
19891   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19892     if (arch == mips_cpu_info_table[i].cpu)
19893       return (&mips_cpu_info_table[i]);
19894
19895   return NULL;
19896 }
19897 \f
19898 static void
19899 show (FILE *stream, const char *string, int *col_p, int *first_p)
19900 {
19901   if (*first_p)
19902     {
19903       fprintf (stream, "%24s", "");
19904       *col_p = 24;
19905     }
19906   else
19907     {
19908       fprintf (stream, ", ");
19909       *col_p += 2;
19910     }
19911
19912   if (*col_p + strlen (string) > 72)
19913     {
19914       fprintf (stream, "\n%24s", "");
19915       *col_p = 24;
19916     }
19917
19918   fprintf (stream, "%s", string);
19919   *col_p += strlen (string);
19920
19921   *first_p = 0;
19922 }
19923
19924 void
19925 md_show_usage (FILE *stream)
19926 {
19927   int column, first;
19928   size_t i;
19929
19930   fprintf (stream, _("\
19931 MIPS options:\n\
19932 -EB                     generate big endian output\n\
19933 -EL                     generate little endian output\n\
19934 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
19935 -G NUM                  allow referencing objects up to NUM bytes\n\
19936                         implicitly with the gp register [default 8]\n"));
19937   fprintf (stream, _("\
19938 -mips1                  generate MIPS ISA I instructions\n\
19939 -mips2                  generate MIPS ISA II instructions\n\
19940 -mips3                  generate MIPS ISA III instructions\n\
19941 -mips4                  generate MIPS ISA IV instructions\n\
19942 -mips5                  generate MIPS ISA V instructions\n\
19943 -mips32                 generate MIPS32 ISA instructions\n\
19944 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
19945 -mips32r3               generate MIPS32 release 3 ISA instructions\n\
19946 -mips32r5               generate MIPS32 release 5 ISA instructions\n\
19947 -mips32r6               generate MIPS32 release 6 ISA instructions\n\
19948 -mips64                 generate MIPS64 ISA instructions\n\
19949 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
19950 -mips64r3               generate MIPS64 release 3 ISA instructions\n\
19951 -mips64r5               generate MIPS64 release 5 ISA instructions\n\
19952 -mips64r6               generate MIPS64 release 6 ISA instructions\n\
19953 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
19954
19955   first = 1;
19956
19957   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19958     show (stream, mips_cpu_info_table[i].name, &column, &first);
19959   show (stream, "from-abi", &column, &first);
19960   fputc ('\n', stream);
19961
19962   fprintf (stream, _("\
19963 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
19964 -no-mCPU                don't generate code specific to CPU.\n\
19965                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
19966
19967   first = 1;
19968
19969   show (stream, "3900", &column, &first);
19970   show (stream, "4010", &column, &first);
19971   show (stream, "4100", &column, &first);
19972   show (stream, "4650", &column, &first);
19973   fputc ('\n', stream);
19974
19975   fprintf (stream, _("\
19976 -mips16                 generate mips16 instructions\n\
19977 -no-mips16              do not generate mips16 instructions\n"));
19978   fprintf (stream, _("\
19979 -mmicromips             generate microMIPS instructions\n\
19980 -mno-micromips          do not generate microMIPS instructions\n"));
19981   fprintf (stream, _("\
19982 -msmartmips             generate smartmips instructions\n\
19983 -mno-smartmips          do not generate smartmips instructions\n"));
19984   fprintf (stream, _("\
19985 -mdsp                   generate DSP instructions\n\
19986 -mno-dsp                do not generate DSP instructions\n"));
19987   fprintf (stream, _("\
19988 -mdspr2                 generate DSP R2 instructions\n\
19989 -mno-dspr2              do not generate DSP R2 instructions\n"));
19990   fprintf (stream, _("\
19991 -mdspr3                 generate DSP R3 instructions\n\
19992 -mno-dspr3              do not generate DSP R3 instructions\n"));
19993   fprintf (stream, _("\
19994 -mmt                    generate MT instructions\n\
19995 -mno-mt                 do not generate MT instructions\n"));
19996   fprintf (stream, _("\
19997 -mmcu                   generate MCU instructions\n\
19998 -mno-mcu                do not generate MCU instructions\n"));
19999   fprintf (stream, _("\
20000 -mmsa                   generate MSA instructions\n\
20001 -mno-msa                do not generate MSA instructions\n"));
20002   fprintf (stream, _("\
20003 -mxpa                   generate eXtended Physical Address (XPA) instructions\n\
20004 -mno-xpa                do not generate eXtended Physical Address (XPA) instructions\n"));
20005   fprintf (stream, _("\
20006 -mvirt                  generate Virtualization instructions\n\
20007 -mno-virt               do not generate Virtualization instructions\n"));
20008   fprintf (stream, _("\
20009 -minsn32                only generate 32-bit microMIPS instructions\n\
20010 -mno-insn32             generate all microMIPS instructions\n"));
20011   fprintf (stream, _("\
20012 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
20013 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
20014 -mfix-vr4120            work around certain VR4120 errata\n\
20015 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
20016 -mfix-24k               insert a nop after ERET and DERET instructions\n\
20017 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
20018 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
20019 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
20020 -msym32                 assume all symbols have 32-bit values\n\
20021 -O0                     remove unneeded NOPs, do not swap branches\n\
20022 -O                      remove unneeded NOPs and swap branches\n\
20023 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
20024 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
20025   fprintf (stream, _("\
20026 -mhard-float            allow floating-point instructions\n\
20027 -msoft-float            do not allow floating-point instructions\n\
20028 -msingle-float          only allow 32-bit floating-point operations\n\
20029 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
20030 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
20031 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
20032 -mignore-branch-isa     accept invalid branches requiring an ISA mode switch\n\
20033 -mno-ignore-branch-isa  reject invalid branches requiring an ISA mode switch\n\
20034 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
20035
20036   first = 1;
20037
20038   show (stream, "legacy", &column, &first);
20039   show (stream, "2008", &column, &first);
20040
20041   fputc ('\n', stream);
20042
20043   fprintf (stream, _("\
20044 -KPIC, -call_shared     generate SVR4 position independent code\n\
20045 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
20046 -mvxworks-pic           generate VxWorks position independent code\n\
20047 -non_shared             do not generate code that can operate with DSOs\n\
20048 -xgot                   assume a 32 bit GOT\n\
20049 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
20050 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
20051                         position dependent (non shared) code\n\
20052 -mabi=ABI               create ABI conformant object file for:\n"));
20053
20054   first = 1;
20055
20056   show (stream, "32", &column, &first);
20057   show (stream, "o64", &column, &first);
20058   show (stream, "n32", &column, &first);
20059   show (stream, "64", &column, &first);
20060   show (stream, "eabi", &column, &first);
20061
20062   fputc ('\n', stream);
20063
20064   fprintf (stream, _("\
20065 -32                     create o32 ABI object file (default)\n\
20066 -n32                    create n32 ABI object file\n\
20067 -64                     create 64 ABI object file\n"));
20068 }
20069
20070 #ifdef TE_IRIX
20071 enum dwarf2_format
20072 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
20073 {
20074   if (HAVE_64BIT_SYMBOLS)
20075     return dwarf2_format_64bit_irix;
20076   else
20077     return dwarf2_format_32bit;
20078 }
20079 #endif
20080
20081 int
20082 mips_dwarf2_addr_size (void)
20083 {
20084   if (HAVE_64BIT_OBJECTS)
20085     return 8;
20086   else
20087     return 4;
20088 }
20089
20090 /* Standard calling conventions leave the CFA at SP on entry.  */
20091 void
20092 mips_cfi_frame_initial_instructions (void)
20093 {
20094   cfi_add_CFA_def_cfa_register (SP);
20095 }
20096
20097 int
20098 tc_mips_regname_to_dw2regnum (char *regname)
20099 {
20100   unsigned int regnum = -1;
20101   unsigned int reg;
20102
20103   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
20104     regnum = reg;
20105
20106   return regnum;
20107 }
20108
20109 /* Implement CONVERT_SYMBOLIC_ATTRIBUTE.
20110    Given a symbolic attribute NAME, return the proper integer value.
20111    Returns -1 if the attribute is not known.  */
20112
20113 int
20114 mips_convert_symbolic_attribute (const char *name)
20115 {
20116   static const struct
20117   {
20118     const char * name;
20119     const int    tag;
20120   }
20121   attribute_table[] =
20122     {
20123 #define T(tag) {#tag, tag}
20124       T (Tag_GNU_MIPS_ABI_FP),
20125       T (Tag_GNU_MIPS_ABI_MSA),
20126 #undef T
20127     };
20128   unsigned int i;
20129
20130   if (name == NULL)
20131     return -1;
20132
20133   for (i = 0; i < ARRAY_SIZE (attribute_table); i++)
20134     if (streq (name, attribute_table[i].name))
20135       return attribute_table[i].tag;
20136
20137   return -1;
20138 }
20139
20140 void
20141 md_mips_end (void)
20142 {
20143   int fpabi = Val_GNU_MIPS_ABI_FP_ANY;
20144
20145   mips_emit_delays ();
20146   if (cur_proc_ptr)
20147     as_warn (_("missing .end at end of assembly"));
20148
20149   /* Just in case no code was emitted, do the consistency check.  */
20150   file_mips_check_options ();
20151
20152   /* Set a floating-point ABI if the user did not.  */
20153   if (obj_elf_seen_attribute (OBJ_ATTR_GNU, Tag_GNU_MIPS_ABI_FP))
20154     {
20155       /* Perform consistency checks on the floating-point ABI.  */
20156       fpabi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
20157                                         Tag_GNU_MIPS_ABI_FP);
20158       if (fpabi != Val_GNU_MIPS_ABI_FP_ANY)
20159         check_fpabi (fpabi);
20160     }
20161   else
20162     {
20163       /* Soft-float gets precedence over single-float, the two options should
20164          not be used together so this should not matter.  */
20165       if (file_mips_opts.soft_float == 1)
20166         fpabi = Val_GNU_MIPS_ABI_FP_SOFT;
20167       /* Single-float gets precedence over all double_float cases.  */
20168       else if (file_mips_opts.single_float == 1)
20169         fpabi = Val_GNU_MIPS_ABI_FP_SINGLE;
20170       else
20171         {
20172           switch (file_mips_opts.fp)
20173             {
20174             case 32:
20175               if (file_mips_opts.gp == 32)
20176                 fpabi = Val_GNU_MIPS_ABI_FP_DOUBLE;
20177               break;
20178             case 0:
20179               fpabi = Val_GNU_MIPS_ABI_FP_XX;
20180               break;
20181             case 64:
20182               if (file_mips_opts.gp == 32 && !file_mips_opts.oddspreg)
20183                 fpabi = Val_GNU_MIPS_ABI_FP_64A;
20184               else if (file_mips_opts.gp == 32)
20185                 fpabi = Val_GNU_MIPS_ABI_FP_64;
20186               else
20187                 fpabi = Val_GNU_MIPS_ABI_FP_DOUBLE;
20188               break;
20189             }
20190         }
20191
20192       bfd_elf_add_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
20193                                 Tag_GNU_MIPS_ABI_FP, fpabi);
20194     }
20195 }
20196
20197 /*  Returns the relocation type required for a particular CFI encoding.  */
20198
20199 bfd_reloc_code_real_type
20200 mips_cfi_reloc_for_encoding (int encoding)
20201 {
20202   if (encoding == (DW_EH_PE_sdata4 | DW_EH_PE_pcrel))
20203     return BFD_RELOC_32_PCREL;
20204   else return BFD_RELOC_NONE;
20205 }