gas/
[external/binutils.git] / gas / config / tc-mips.c
1 /* tc-mips.c -- assemble code for a MIPS chip.
2    Copyright (C) 1993-2014 Free Software Foundation, Inc.
3    Contributed by the OSF and Ralph Campbell.
4    Written by Keith Knowles and Ralph Campbell, working independently.
5    Modified for ECOFF and R4000 support by Ian Lance Taylor of Cygnus
6    Support.
7
8    This file is part of GAS.
9
10    GAS is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3, or (at your option)
13    any later version.
14
15    GAS is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with GAS; see the file COPYING.  If not, write to the Free
22    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
23    02110-1301, USA.  */
24
25 #include "as.h"
26 #include "config.h"
27 #include "subsegs.h"
28 #include "safe-ctype.h"
29
30 #include "opcode/mips.h"
31 #include "itbl-ops.h"
32 #include "dwarf2dbg.h"
33 #include "dw2gencfi.h"
34
35 /* Check assumptions made in this file.  */
36 typedef char static_assert1[sizeof (offsetT) < 8 ? -1 : 1];
37 typedef char static_assert2[sizeof (valueT) < 8 ? -1 : 1];
38
39 #ifdef DEBUG
40 #define DBG(x) printf x
41 #else
42 #define DBG(x)
43 #endif
44
45 #define SKIP_SPACE_TABS(S) \
46   do { while (*(S) == ' ' || *(S) == '\t') ++(S); } while (0)
47
48 /* Clean up namespace so we can include obj-elf.h too.  */
49 static int mips_output_flavor (void);
50 static int mips_output_flavor (void) { return OUTPUT_FLAVOR; }
51 #undef OBJ_PROCESS_STAB
52 #undef OUTPUT_FLAVOR
53 #undef S_GET_ALIGN
54 #undef S_GET_SIZE
55 #undef S_SET_ALIGN
56 #undef S_SET_SIZE
57 #undef obj_frob_file
58 #undef obj_frob_file_after_relocs
59 #undef obj_frob_symbol
60 #undef obj_pop_insert
61 #undef obj_sec_sym_ok_for_reloc
62 #undef OBJ_COPY_SYMBOL_ATTRIBUTES
63
64 #include "obj-elf.h"
65 /* Fix any of them that we actually care about.  */
66 #undef OUTPUT_FLAVOR
67 #define OUTPUT_FLAVOR mips_output_flavor()
68
69 #include "elf/mips.h"
70
71 #ifndef ECOFF_DEBUGGING
72 #define NO_ECOFF_DEBUGGING
73 #define ECOFF_DEBUGGING 0
74 #endif
75
76 int mips_flag_mdebug = -1;
77
78 /* Control generation of .pdr sections.  Off by default on IRIX: the native
79    linker doesn't know about and discards them, but relocations against them
80    remain, leading to rld crashes.  */
81 #ifdef TE_IRIX
82 int mips_flag_pdr = FALSE;
83 #else
84 int mips_flag_pdr = TRUE;
85 #endif
86
87 #include "ecoff.h"
88
89 static char *mips_regmask_frag;
90
91 #define ZERO 0
92 #define ATREG 1
93 #define S0  16
94 #define S7  23
95 #define TREG 24
96 #define PIC_CALL_REG 25
97 #define KT0 26
98 #define KT1 27
99 #define GP  28
100 #define SP  29
101 #define FP  30
102 #define RA  31
103
104 #define ILLEGAL_REG (32)
105
106 #define AT  mips_opts.at
107
108 extern int target_big_endian;
109
110 /* The name of the readonly data section.  */
111 #define RDATA_SECTION_NAME ".rodata"
112
113 /* Ways in which an instruction can be "appended" to the output.  */
114 enum append_method {
115   /* Just add it normally.  */
116   APPEND_ADD,
117
118   /* Add it normally and then add a nop.  */
119   APPEND_ADD_WITH_NOP,
120
121   /* Turn an instruction with a delay slot into a "compact" version.  */
122   APPEND_ADD_COMPACT,
123
124   /* Insert the instruction before the last one.  */
125   APPEND_SWAP
126 };
127
128 /* Information about an instruction, including its format, operands
129    and fixups.  */
130 struct mips_cl_insn
131 {
132   /* The opcode's entry in mips_opcodes or mips16_opcodes.  */
133   const struct mips_opcode *insn_mo;
134
135   /* The 16-bit or 32-bit bitstring of the instruction itself.  This is
136      a copy of INSN_MO->match with the operands filled in.  If we have
137      decided to use an extended MIPS16 instruction, this includes the
138      extension.  */
139   unsigned long insn_opcode;
140
141   /* The frag that contains the instruction.  */
142   struct frag *frag;
143
144   /* The offset into FRAG of the first instruction byte.  */
145   long where;
146
147   /* The relocs associated with the instruction, if any.  */
148   fixS *fixp[3];
149
150   /* True if this entry cannot be moved from its current position.  */
151   unsigned int fixed_p : 1;
152
153   /* True if this instruction occurred in a .set noreorder block.  */
154   unsigned int noreorder_p : 1;
155
156   /* True for mips16 instructions that jump to an absolute address.  */
157   unsigned int mips16_absolute_jump_p : 1;
158
159   /* True if this instruction is complete.  */
160   unsigned int complete_p : 1;
161
162   /* True if this instruction is cleared from history by unconditional
163      branch.  */
164   unsigned int cleared_p : 1;
165 };
166
167 /* The ABI to use.  */
168 enum mips_abi_level
169 {
170   NO_ABI = 0,
171   O32_ABI,
172   O64_ABI,
173   N32_ABI,
174   N64_ABI,
175   EABI_ABI
176 };
177
178 /* MIPS ABI we are using for this output file.  */
179 static enum mips_abi_level mips_abi = NO_ABI;
180
181 /* Whether or not we have code that can call pic code.  */
182 int mips_abicalls = FALSE;
183
184 /* Whether or not we have code which can be put into a shared
185    library.  */
186 static bfd_boolean mips_in_shared = TRUE;
187
188 /* This is the set of options which may be modified by the .set
189    pseudo-op.  We use a struct so that .set push and .set pop are more
190    reliable.  */
191
192 struct mips_set_options
193 {
194   /* MIPS ISA (Instruction Set Architecture) level.  This is set to -1
195      if it has not been initialized.  Changed by `.set mipsN', and the
196      -mipsN command line option, and the default CPU.  */
197   int isa;
198   /* Enabled Application Specific Extensions (ASEs).  Changed by `.set
199      <asename>', by command line options, and based on the default
200      architecture.  */
201   int ase;
202   /* Whether we are assembling for the mips16 processor.  0 if we are
203      not, 1 if we are, and -1 if the value has not been initialized.
204      Changed by `.set mips16' and `.set nomips16', and the -mips16 and
205      -nomips16 command line options, and the default CPU.  */
206   int mips16;
207   /* Whether we are assembling for the mipsMIPS ASE.  0 if we are not,
208      1 if we are, and -1 if the value has not been initialized.  Changed
209      by `.set micromips' and `.set nomicromips', and the -mmicromips
210      and -mno-micromips command line options, and the default CPU.  */
211   int micromips;
212   /* Non-zero if we should not reorder instructions.  Changed by `.set
213      reorder' and `.set noreorder'.  */
214   int noreorder;
215   /* Non-zero if we should not permit the register designated "assembler
216      temporary" to be used in instructions.  The value is the register
217      number, normally $at ($1).  Changed by `.set at=REG', `.set noat'
218      (same as `.set at=$0') and `.set at' (same as `.set at=$1').  */
219   unsigned int at;
220   /* Non-zero if we should warn when a macro instruction expands into
221      more than one machine instruction.  Changed by `.set nomacro' and
222      `.set macro'.  */
223   int warn_about_macros;
224   /* Non-zero if we should not move instructions.  Changed by `.set
225      move', `.set volatile', `.set nomove', and `.set novolatile'.  */
226   int nomove;
227   /* Non-zero if we should not optimize branches by moving the target
228      of the branch into the delay slot.  Actually, we don't perform
229      this optimization anyhow.  Changed by `.set bopt' and `.set
230      nobopt'.  */
231   int nobopt;
232   /* Non-zero if we should not autoextend mips16 instructions.
233      Changed by `.set autoextend' and `.set noautoextend'.  */
234   int noautoextend;
235   /* True if we should only emit 32-bit microMIPS instructions.
236      Changed by `.set insn32' and `.set noinsn32', and the -minsn32
237      and -mno-insn32 command line options.  */
238   bfd_boolean insn32;
239   /* Restrict general purpose registers and floating point registers
240      to 32 bit.  This is initially determined when -mgp32 or -mfp32
241      is passed but can changed if the assembler code uses .set mipsN.  */
242   int gp32;
243   int fp32;
244   /* MIPS architecture (CPU) type.  Changed by .set arch=FOO, the -march
245      command line option, and the default CPU.  */
246   int arch;
247   /* True if ".set sym32" is in effect.  */
248   bfd_boolean sym32;
249   /* True if floating-point operations are not allowed.  Changed by .set
250      softfloat or .set hardfloat, by command line options -msoft-float or
251      -mhard-float.  The default is false.  */
252   bfd_boolean soft_float;
253
254   /* True if only single-precision floating-point operations are allowed.
255      Changed by .set singlefloat or .set doublefloat, command-line options
256      -msingle-float or -mdouble-float.  The default is false.  */
257   bfd_boolean single_float;
258 };
259
260 /* This is the struct we use to hold the current set of options.  Note
261    that we must set the isa field to ISA_UNKNOWN and the ASE fields to
262    -1 to indicate that they have not been initialized.  */
263
264 /* True if -mgp32 was passed.  */
265 static int file_mips_gp32 = -1;
266
267 /* True if -mfp32 was passed.  */
268 static int file_mips_fp32 = -1;
269
270 /* 1 if -msoft-float, 0 if -mhard-float.  The default is 0.  */
271 static int file_mips_soft_float = 0;
272
273 /* 1 if -msingle-float, 0 if -mdouble-float.  The default is 0.   */
274 static int file_mips_single_float = 0;
275
276 /* True if -mnan=2008, false if -mnan=legacy.  */
277 static bfd_boolean mips_flag_nan2008 = FALSE;
278
279 static struct mips_set_options mips_opts =
280 {
281   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
282   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
283   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ FALSE,
284   /* gp32 */ 0, /* fp32 */ 0, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
285   /* soft_float */ FALSE, /* single_float */ FALSE
286 };
287
288 /* The set of ASEs that were selected on the command line, either
289    explicitly via ASE options or implicitly through things like -march.  */
290 static unsigned int file_ase;
291
292 /* Which bits of file_ase were explicitly set or cleared by ASE options.  */
293 static unsigned int file_ase_explicit;
294
295 /* These variables are filled in with the masks of registers used.
296    The object format code reads them and puts them in the appropriate
297    place.  */
298 unsigned long mips_gprmask;
299 unsigned long mips_cprmask[4];
300
301 /* MIPS ISA we are using for this output file.  */
302 static int file_mips_isa = ISA_UNKNOWN;
303
304 /* True if any MIPS16 code was produced.  */
305 static int file_ase_mips16;
306
307 #define ISA_SUPPORTS_MIPS16E (mips_opts.isa == ISA_MIPS32               \
308                               || mips_opts.isa == ISA_MIPS32R2          \
309                               || mips_opts.isa == ISA_MIPS64            \
310                               || mips_opts.isa == ISA_MIPS64R2)
311
312 /* True if any microMIPS code was produced.  */
313 static int file_ase_micromips;
314
315 /* True if we want to create R_MIPS_JALR for jalr $25.  */
316 #ifdef TE_IRIX
317 #define MIPS_JALR_HINT_P(EXPR) HAVE_NEWABI
318 #else
319 /* As a GNU extension, we use R_MIPS_JALR for o32 too.  However,
320    because there's no place for any addend, the only acceptable
321    expression is a bare symbol.  */
322 #define MIPS_JALR_HINT_P(EXPR) \
323   (!HAVE_IN_PLACE_ADDENDS \
324    || ((EXPR)->X_op == O_symbol && (EXPR)->X_add_number == 0))
325 #endif
326
327 /* The argument of the -march= flag.  The architecture we are assembling.  */
328 static int file_mips_arch = CPU_UNKNOWN;
329 static const char *mips_arch_string;
330
331 /* The argument of the -mtune= flag.  The architecture for which we
332    are optimizing.  */
333 static int mips_tune = CPU_UNKNOWN;
334 static const char *mips_tune_string;
335
336 /* True when generating 32-bit code for a 64-bit processor.  */
337 static int mips_32bitmode = 0;
338
339 /* True if the given ABI requires 32-bit registers.  */
340 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
341
342 /* Likewise 64-bit registers.  */
343 #define ABI_NEEDS_64BIT_REGS(ABI)       \
344   ((ABI) == N32_ABI                     \
345    || (ABI) == N64_ABI                  \
346    || (ABI) == O64_ABI)
347
348 /*  Return true if ISA supports 64 bit wide gp registers.  */
349 #define ISA_HAS_64BIT_REGS(ISA)         \
350   ((ISA) == ISA_MIPS3                   \
351    || (ISA) == ISA_MIPS4                \
352    || (ISA) == ISA_MIPS5                \
353    || (ISA) == ISA_MIPS64               \
354    || (ISA) == ISA_MIPS64R2)
355
356 /*  Return true if ISA supports 64 bit wide float registers.  */
357 #define ISA_HAS_64BIT_FPRS(ISA)         \
358   ((ISA) == ISA_MIPS3                   \
359    || (ISA) == ISA_MIPS4                \
360    || (ISA) == ISA_MIPS5                \
361    || (ISA) == ISA_MIPS32R2             \
362    || (ISA) == ISA_MIPS64               \
363    || (ISA) == ISA_MIPS64R2)
364
365 /* Return true if ISA supports 64-bit right rotate (dror et al.)
366    instructions.  */
367 #define ISA_HAS_DROR(ISA)               \
368   ((ISA) == ISA_MIPS64R2                \
369    || (mips_opts.micromips              \
370        && ISA_HAS_64BIT_REGS (ISA))     \
371    )
372
373 /* Return true if ISA supports 32-bit right rotate (ror et al.)
374    instructions.  */
375 #define ISA_HAS_ROR(ISA)                \
376   ((ISA) == ISA_MIPS32R2                \
377    || (ISA) == ISA_MIPS64R2             \
378    || (mips_opts.ase & ASE_SMARTMIPS)   \
379    || mips_opts.micromips               \
380    )
381
382 /* Return true if ISA supports single-precision floats in odd registers.  */
383 #define ISA_HAS_ODD_SINGLE_FPR(ISA)     \
384   ((ISA) == ISA_MIPS32                  \
385    || (ISA) == ISA_MIPS32R2             \
386    || (ISA) == ISA_MIPS64               \
387    || (ISA) == ISA_MIPS64R2)
388
389 /* Return true if ISA supports move to/from high part of a 64-bit
390    floating-point register. */
391 #define ISA_HAS_MXHC1(ISA)              \
392   ((ISA) == ISA_MIPS32R2                \
393    || (ISA) == ISA_MIPS64R2)
394
395 #define HAVE_32BIT_GPRS                            \
396     (mips_opts.gp32 || !ISA_HAS_64BIT_REGS (mips_opts.isa))
397
398 #define HAVE_32BIT_FPRS                            \
399     (mips_opts.fp32 || !ISA_HAS_64BIT_FPRS (mips_opts.isa))
400
401 #define HAVE_64BIT_GPRS (!HAVE_32BIT_GPRS)
402 #define HAVE_64BIT_FPRS (!HAVE_32BIT_FPRS)
403
404 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
405
406 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
407
408 /* True if relocations are stored in-place.  */
409 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
410
411 /* The ABI-derived address size.  */
412 #define HAVE_64BIT_ADDRESSES \
413   (HAVE_64BIT_GPRS && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
414 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
415
416 /* The size of symbolic constants (i.e., expressions of the form
417    "SYMBOL" or "SYMBOL + OFFSET").  */
418 #define HAVE_32BIT_SYMBOLS \
419   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
420 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
421
422 /* Addresses are loaded in different ways, depending on the address size
423    in use.  The n32 ABI Documentation also mandates the use of additions
424    with overflow checking, but existing implementations don't follow it.  */
425 #define ADDRESS_ADD_INSN                                                \
426    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
427
428 #define ADDRESS_ADDI_INSN                                               \
429    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
430
431 #define ADDRESS_LOAD_INSN                                               \
432    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
433
434 #define ADDRESS_STORE_INSN                                              \
435    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
436
437 /* Return true if the given CPU supports the MIPS16 ASE.  */
438 #define CPU_HAS_MIPS16(cpu)                                             \
439    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
440     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
441
442 /* Return true if the given CPU supports the microMIPS ASE.  */
443 #define CPU_HAS_MICROMIPS(cpu)  0
444
445 /* True if CPU has a dror instruction.  */
446 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
447
448 /* True if CPU has a ror instruction.  */
449 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
450
451 /* True if CPU is in the Octeon family */
452 #define CPU_IS_OCTEON(CPU) ((CPU) == CPU_OCTEON || (CPU) == CPU_OCTEONP || (CPU) == CPU_OCTEON2)
453
454 /* True if CPU has seq/sne and seqi/snei instructions.  */
455 #define CPU_HAS_SEQ(CPU)        (CPU_IS_OCTEON (CPU))
456
457 /* True, if CPU has support for ldc1 and sdc1. */
458 #define CPU_HAS_LDC1_SDC1(CPU)  \
459    ((mips_opts.isa != ISA_MIPS1) && ((CPU) != CPU_R5900))
460
461 /* True if mflo and mfhi can be immediately followed by instructions
462    which write to the HI and LO registers.
463
464    According to MIPS specifications, MIPS ISAs I, II, and III need
465    (at least) two instructions between the reads of HI/LO and
466    instructions which write them, and later ISAs do not.  Contradicting
467    the MIPS specifications, some MIPS IV processor user manuals (e.g.
468    the UM for the NEC Vr5000) document needing the instructions between
469    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
470    MIPS64 and later ISAs to have the interlocks, plus any specific
471    earlier-ISA CPUs for which CPU documentation declares that the
472    instructions are really interlocked.  */
473 #define hilo_interlocks \
474   (mips_opts.isa == ISA_MIPS32                        \
475    || mips_opts.isa == ISA_MIPS32R2                   \
476    || mips_opts.isa == ISA_MIPS64                     \
477    || mips_opts.isa == ISA_MIPS64R2                   \
478    || mips_opts.arch == CPU_R4010                     \
479    || mips_opts.arch == CPU_R5900                     \
480    || mips_opts.arch == CPU_R10000                    \
481    || mips_opts.arch == CPU_R12000                    \
482    || mips_opts.arch == CPU_R14000                    \
483    || mips_opts.arch == CPU_R16000                    \
484    || mips_opts.arch == CPU_RM7000                    \
485    || mips_opts.arch == CPU_VR5500                    \
486    || mips_opts.micromips                             \
487    )
488
489 /* Whether the processor uses hardware interlocks to protect reads
490    from the GPRs after they are loaded from memory, and thus does not
491    require nops to be inserted.  This applies to instructions marked
492    INSN_LOAD_MEMORY.  These nops are only required at MIPS ISA
493    level I and microMIPS mode instructions are always interlocked.  */
494 #define gpr_interlocks                                \
495   (mips_opts.isa != ISA_MIPS1                         \
496    || mips_opts.arch == CPU_R3900                     \
497    || mips_opts.arch == CPU_R5900                     \
498    || mips_opts.micromips                             \
499    )
500
501 /* Whether the processor uses hardware interlocks to avoid delays
502    required by coprocessor instructions, and thus does not require
503    nops to be inserted.  This applies to instructions marked
504    INSN_LOAD_COPROC_DELAY, INSN_COPROC_MOVE_DELAY, and to delays
505    between instructions marked INSN_WRITE_COND_CODE and ones marked
506    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
507    levels I, II, and III and microMIPS mode instructions are always
508    interlocked.  */
509 /* Itbl support may require additional care here.  */
510 #define cop_interlocks                                \
511   ((mips_opts.isa != ISA_MIPS1                        \
512     && mips_opts.isa != ISA_MIPS2                     \
513     && mips_opts.isa != ISA_MIPS3)                    \
514    || mips_opts.arch == CPU_R4300                     \
515    || mips_opts.micromips                             \
516    )
517
518 /* Whether the processor uses hardware interlocks to protect reads
519    from coprocessor registers after they are loaded from memory, and
520    thus does not require nops to be inserted.  This applies to
521    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
522    requires at MIPS ISA level I and microMIPS mode instructions are
523    always interlocked.  */
524 #define cop_mem_interlocks                            \
525   (mips_opts.isa != ISA_MIPS1                         \
526    || mips_opts.micromips                             \
527    )
528
529 /* Is this a mfhi or mflo instruction?  */
530 #define MF_HILO_INSN(PINFO) \
531   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
532
533 /* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
534    has been selected.  This implies, in particular, that addresses of text
535    labels have their LSB set.  */
536 #define HAVE_CODE_COMPRESSION                                           \
537   ((mips_opts.mips16 | mips_opts.micromips) != 0)
538
539 /* The minimum and maximum signed values that can be stored in a GPR.  */
540 #define GPR_SMAX ((offsetT) (((valueT) 1 << (HAVE_64BIT_GPRS ? 63 : 31)) - 1))
541 #define GPR_SMIN (-GPR_SMAX - 1)
542
543 /* MIPS PIC level.  */
544
545 enum mips_pic_level mips_pic;
546
547 /* 1 if we should generate 32 bit offsets from the $gp register in
548    SVR4_PIC mode.  Currently has no meaning in other modes.  */
549 static int mips_big_got = 0;
550
551 /* 1 if trap instructions should used for overflow rather than break
552    instructions.  */
553 static int mips_trap = 0;
554
555 /* 1 if double width floating point constants should not be constructed
556    by assembling two single width halves into two single width floating
557    point registers which just happen to alias the double width destination
558    register.  On some architectures this aliasing can be disabled by a bit
559    in the status register, and the setting of this bit cannot be determined
560    automatically at assemble time.  */
561 static int mips_disable_float_construction;
562
563 /* Non-zero if any .set noreorder directives were used.  */
564
565 static int mips_any_noreorder;
566
567 /* Non-zero if nops should be inserted when the register referenced in
568    an mfhi/mflo instruction is read in the next two instructions.  */
569 static int mips_7000_hilo_fix;
570
571 /* The size of objects in the small data section.  */
572 static unsigned int g_switch_value = 8;
573 /* Whether the -G option was used.  */
574 static int g_switch_seen = 0;
575
576 #define N_RMASK 0xc4
577 #define N_VFP   0xd4
578
579 /* If we can determine in advance that GP optimization won't be
580    possible, we can skip the relaxation stuff that tries to produce
581    GP-relative references.  This makes delay slot optimization work
582    better.
583
584    This function can only provide a guess, but it seems to work for
585    gcc output.  It needs to guess right for gcc, otherwise gcc
586    will put what it thinks is a GP-relative instruction in a branch
587    delay slot.
588
589    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
590    fixed it for the non-PIC mode.  KR 95/04/07  */
591 static int nopic_need_relax (symbolS *, int);
592
593 /* handle of the OPCODE hash table */
594 static struct hash_control *op_hash = NULL;
595
596 /* The opcode hash table we use for the mips16.  */
597 static struct hash_control *mips16_op_hash = NULL;
598
599 /* The opcode hash table we use for the microMIPS ASE.  */
600 static struct hash_control *micromips_op_hash = NULL;
601
602 /* This array holds the chars that always start a comment.  If the
603     pre-processor is disabled, these aren't very useful */
604 const char comment_chars[] = "#";
605
606 /* This array holds the chars that only start a comment at the beginning of
607    a line.  If the line seems to have the form '# 123 filename'
608    .line and .file directives will appear in the pre-processed output */
609 /* Note that input_file.c hand checks for '#' at the beginning of the
610    first line of the input file.  This is because the compiler outputs
611    #NO_APP at the beginning of its output.  */
612 /* Also note that C style comments are always supported.  */
613 const char line_comment_chars[] = "#";
614
615 /* This array holds machine specific line separator characters.  */
616 const char line_separator_chars[] = ";";
617
618 /* Chars that can be used to separate mant from exp in floating point nums */
619 const char EXP_CHARS[] = "eE";
620
621 /* Chars that mean this number is a floating point constant */
622 /* As in 0f12.456 */
623 /* or    0d1.2345e12 */
624 const char FLT_CHARS[] = "rRsSfFdDxXpP";
625
626 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
627    changed in read.c .  Ideally it shouldn't have to know about it at all,
628    but nothing is ideal around here.
629  */
630
631 /* Types of printf format used for instruction-related error messages.
632    "I" means int ("%d") and "S" means string ("%s"). */
633 enum mips_insn_error_format {
634   ERR_FMT_PLAIN,
635   ERR_FMT_I,
636   ERR_FMT_SS,
637 };
638
639 /* Information about an error that was found while assembling the current
640    instruction.  */
641 struct mips_insn_error {
642   /* We sometimes need to match an instruction against more than one
643      opcode table entry.  Errors found during this matching are reported
644      against a particular syntactic argument rather than against the
645      instruction as a whole.  We grade these messages so that errors
646      against argument N have a greater priority than an error against
647      any argument < N, since the former implies that arguments up to N
648      were acceptable and that the opcode entry was therefore a closer match.
649      If several matches report an error against the same argument,
650      we only use that error if it is the same in all cases.
651
652      min_argnum is the minimum argument number for which an error message
653      should be accepted.  It is 0 if MSG is against the instruction as
654      a whole.  */
655   int min_argnum;
656
657   /* The printf()-style message, including its format and arguments.  */
658   enum mips_insn_error_format format;
659   const char *msg;
660   union {
661     int i;
662     const char *ss[2];
663   } u;
664 };
665
666 /* The error that should be reported for the current instruction.  */
667 static struct mips_insn_error insn_error;
668
669 static int auto_align = 1;
670
671 /* When outputting SVR4 PIC code, the assembler needs to know the
672    offset in the stack frame from which to restore the $gp register.
673    This is set by the .cprestore pseudo-op, and saved in this
674    variable.  */
675 static offsetT mips_cprestore_offset = -1;
676
677 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
678    more optimizations, it can use a register value instead of a memory-saved
679    offset and even an other register than $gp as global pointer.  */
680 static offsetT mips_cpreturn_offset = -1;
681 static int mips_cpreturn_register = -1;
682 static int mips_gp_register = GP;
683 static int mips_gprel_offset = 0;
684
685 /* Whether mips_cprestore_offset has been set in the current function
686    (or whether it has already been warned about, if not).  */
687 static int mips_cprestore_valid = 0;
688
689 /* This is the register which holds the stack frame, as set by the
690    .frame pseudo-op.  This is needed to implement .cprestore.  */
691 static int mips_frame_reg = SP;
692
693 /* Whether mips_frame_reg has been set in the current function
694    (or whether it has already been warned about, if not).  */
695 static int mips_frame_reg_valid = 0;
696
697 /* To output NOP instructions correctly, we need to keep information
698    about the previous two instructions.  */
699
700 /* Whether we are optimizing.  The default value of 2 means to remove
701    unneeded NOPs and swap branch instructions when possible.  A value
702    of 1 means to not swap branches.  A value of 0 means to always
703    insert NOPs.  */
704 static int mips_optimize = 2;
705
706 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
707    equivalent to seeing no -g option at all.  */
708 static int mips_debug = 0;
709
710 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
711 #define MAX_VR4130_NOPS 4
712
713 /* The maximum number of NOPs needed to fill delay slots.  */
714 #define MAX_DELAY_NOPS 2
715
716 /* The maximum number of NOPs needed for any purpose.  */
717 #define MAX_NOPS 4
718
719 /* A list of previous instructions, with index 0 being the most recent.
720    We need to look back MAX_NOPS instructions when filling delay slots
721    or working around processor errata.  We need to look back one
722    instruction further if we're thinking about using history[0] to
723    fill a branch delay slot.  */
724 static struct mips_cl_insn history[1 + MAX_NOPS];
725
726 /* Arrays of operands for each instruction.  */
727 #define MAX_OPERANDS 6
728 struct mips_operand_array {
729   const struct mips_operand *operand[MAX_OPERANDS];
730 };
731 static struct mips_operand_array *mips_operands;
732 static struct mips_operand_array *mips16_operands;
733 static struct mips_operand_array *micromips_operands;
734
735 /* Nop instructions used by emit_nop.  */
736 static struct mips_cl_insn nop_insn;
737 static struct mips_cl_insn mips16_nop_insn;
738 static struct mips_cl_insn micromips_nop16_insn;
739 static struct mips_cl_insn micromips_nop32_insn;
740
741 /* The appropriate nop for the current mode.  */
742 #define NOP_INSN (mips_opts.mips16                                      \
743                   ? &mips16_nop_insn                                    \
744                   : (mips_opts.micromips                                \
745                      ? (mips_opts.insn32                                \
746                         ? &micromips_nop32_insn                         \
747                         : &micromips_nop16_insn)                        \
748                      : &nop_insn))
749
750 /* The size of NOP_INSN in bytes.  */
751 #define NOP_INSN_SIZE ((mips_opts.mips16                                \
752                         || (mips_opts.micromips && !mips_opts.insn32))  \
753                        ? 2 : 4)
754
755 /* If this is set, it points to a frag holding nop instructions which
756    were inserted before the start of a noreorder section.  If those
757    nops turn out to be unnecessary, the size of the frag can be
758    decreased.  */
759 static fragS *prev_nop_frag;
760
761 /* The number of nop instructions we created in prev_nop_frag.  */
762 static int prev_nop_frag_holds;
763
764 /* The number of nop instructions that we know we need in
765    prev_nop_frag.  */
766 static int prev_nop_frag_required;
767
768 /* The number of instructions we've seen since prev_nop_frag.  */
769 static int prev_nop_frag_since;
770
771 /* Relocations against symbols are sometimes done in two parts, with a HI
772    relocation and a LO relocation.  Each relocation has only 16 bits of
773    space to store an addend.  This means that in order for the linker to
774    handle carries correctly, it must be able to locate both the HI and
775    the LO relocation.  This means that the relocations must appear in
776    order in the relocation table.
777
778    In order to implement this, we keep track of each unmatched HI
779    relocation.  We then sort them so that they immediately precede the
780    corresponding LO relocation.  */
781
782 struct mips_hi_fixup
783 {
784   /* Next HI fixup.  */
785   struct mips_hi_fixup *next;
786   /* This fixup.  */
787   fixS *fixp;
788   /* The section this fixup is in.  */
789   segT seg;
790 };
791
792 /* The list of unmatched HI relocs.  */
793
794 static struct mips_hi_fixup *mips_hi_fixup_list;
795
796 /* The frag containing the last explicit relocation operator.
797    Null if explicit relocations have not been used.  */
798
799 static fragS *prev_reloc_op_frag;
800
801 /* Map mips16 register numbers to normal MIPS register numbers.  */
802
803 static const unsigned int mips16_to_32_reg_map[] =
804 {
805   16, 17, 2, 3, 4, 5, 6, 7
806 };
807
808 /* Map microMIPS register numbers to normal MIPS register numbers.  */
809
810 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
811
812 /* The microMIPS registers with type h.  */
813 static const unsigned int micromips_to_32_reg_h_map1[] =
814 {
815   5, 5, 6, 4, 4, 4, 4, 4
816 };
817 static const unsigned int micromips_to_32_reg_h_map2[] =
818 {
819   6, 7, 7, 21, 22, 5, 6, 7
820 };
821
822 /* The microMIPS registers with type m.  */
823 static const unsigned int micromips_to_32_reg_m_map[] =
824 {
825   0, 17, 2, 3, 16, 18, 19, 20
826 };
827
828 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
829
830 /* Classifies the kind of instructions we're interested in when
831    implementing -mfix-vr4120.  */
832 enum fix_vr4120_class
833 {
834   FIX_VR4120_MACC,
835   FIX_VR4120_DMACC,
836   FIX_VR4120_MULT,
837   FIX_VR4120_DMULT,
838   FIX_VR4120_DIV,
839   FIX_VR4120_MTHILO,
840   NUM_FIX_VR4120_CLASSES
841 };
842
843 /* ...likewise -mfix-loongson2f-jump.  */
844 static bfd_boolean mips_fix_loongson2f_jump;
845
846 /* ...likewise -mfix-loongson2f-nop.  */
847 static bfd_boolean mips_fix_loongson2f_nop;
848
849 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
850 static bfd_boolean mips_fix_loongson2f;
851
852 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
853    there must be at least one other instruction between an instruction
854    of type X and an instruction of type Y.  */
855 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
856
857 /* True if -mfix-vr4120 is in force.  */
858 static int mips_fix_vr4120;
859
860 /* ...likewise -mfix-vr4130.  */
861 static int mips_fix_vr4130;
862
863 /* ...likewise -mfix-24k.  */
864 static int mips_fix_24k;
865
866 /* ...likewise -mfix-rm7000  */
867 static int mips_fix_rm7000;
868
869 /* ...likewise -mfix-cn63xxp1 */
870 static bfd_boolean mips_fix_cn63xxp1;
871
872 /* We don't relax branches by default, since this causes us to expand
873    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
874    fail to compute the offset before expanding the macro to the most
875    efficient expansion.  */
876
877 static int mips_relax_branch;
878 \f
879 /* The expansion of many macros depends on the type of symbol that
880    they refer to.  For example, when generating position-dependent code,
881    a macro that refers to a symbol may have two different expansions,
882    one which uses GP-relative addresses and one which uses absolute
883    addresses.  When generating SVR4-style PIC, a macro may have
884    different expansions for local and global symbols.
885
886    We handle these situations by generating both sequences and putting
887    them in variant frags.  In position-dependent code, the first sequence
888    will be the GP-relative one and the second sequence will be the
889    absolute one.  In SVR4 PIC, the first sequence will be for global
890    symbols and the second will be for local symbols.
891
892    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
893    SECOND are the lengths of the two sequences in bytes.  These fields
894    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
895    the subtype has the following flags:
896
897    RELAX_USE_SECOND
898         Set if it has been decided that we should use the second
899         sequence instead of the first.
900
901    RELAX_SECOND_LONGER
902         Set in the first variant frag if the macro's second implementation
903         is longer than its first.  This refers to the macro as a whole,
904         not an individual relaxation.
905
906    RELAX_NOMACRO
907         Set in the first variant frag if the macro appeared in a .set nomacro
908         block and if one alternative requires a warning but the other does not.
909
910    RELAX_DELAY_SLOT
911         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
912         delay slot.
913
914    RELAX_DELAY_SLOT_16BIT
915         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
916         16-bit instruction.
917
918    RELAX_DELAY_SLOT_SIZE_FIRST
919         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
920         the macro is of the wrong size for the branch delay slot.
921
922    RELAX_DELAY_SLOT_SIZE_SECOND
923         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
924         the macro is of the wrong size for the branch delay slot.
925
926    The frag's "opcode" points to the first fixup for relaxable code.
927
928    Relaxable macros are generated using a sequence such as:
929
930       relax_start (SYMBOL);
931       ... generate first expansion ...
932       relax_switch ();
933       ... generate second expansion ...
934       relax_end ();
935
936    The code and fixups for the unwanted alternative are discarded
937    by md_convert_frag.  */
938 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
939
940 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
941 #define RELAX_SECOND(X) ((X) & 0xff)
942 #define RELAX_USE_SECOND 0x10000
943 #define RELAX_SECOND_LONGER 0x20000
944 #define RELAX_NOMACRO 0x40000
945 #define RELAX_DELAY_SLOT 0x80000
946 #define RELAX_DELAY_SLOT_16BIT 0x100000
947 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x200000
948 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x400000
949
950 /* Branch without likely bit.  If label is out of range, we turn:
951
952         beq reg1, reg2, label
953         delay slot
954
955    into
956
957         bne reg1, reg2, 0f
958         nop
959         j label
960      0: delay slot
961
962    with the following opcode replacements:
963
964         beq <-> bne
965         blez <-> bgtz
966         bltz <-> bgez
967         bc1f <-> bc1t
968
969         bltzal <-> bgezal  (with jal label instead of j label)
970
971    Even though keeping the delay slot instruction in the delay slot of
972    the branch would be more efficient, it would be very tricky to do
973    correctly, because we'd have to introduce a variable frag *after*
974    the delay slot instruction, and expand that instead.  Let's do it
975    the easy way for now, even if the branch-not-taken case now costs
976    one additional instruction.  Out-of-range branches are not supposed
977    to be common, anyway.
978
979    Branch likely.  If label is out of range, we turn:
980
981         beql reg1, reg2, label
982         delay slot (annulled if branch not taken)
983
984    into
985
986         beql reg1, reg2, 1f
987         nop
988         beql $0, $0, 2f
989         nop
990      1: j[al] label
991         delay slot (executed only if branch taken)
992      2:
993
994    It would be possible to generate a shorter sequence by losing the
995    likely bit, generating something like:
996
997         bne reg1, reg2, 0f
998         nop
999         j[al] label
1000         delay slot (executed only if branch taken)
1001      0:
1002
1003         beql -> bne
1004         bnel -> beq
1005         blezl -> bgtz
1006         bgtzl -> blez
1007         bltzl -> bgez
1008         bgezl -> bltz
1009         bc1fl -> bc1t
1010         bc1tl -> bc1f
1011
1012         bltzall -> bgezal  (with jal label instead of j label)
1013         bgezall -> bltzal  (ditto)
1014
1015
1016    but it's not clear that it would actually improve performance.  */
1017 #define RELAX_BRANCH_ENCODE(at, uncond, likely, link, toofar)   \
1018   ((relax_substateT)                                            \
1019    (0xc0000000                                                  \
1020     | ((at) & 0x1f)                                             \
1021     | ((toofar) ? 0x20 : 0)                                     \
1022     | ((link) ? 0x40 : 0)                                       \
1023     | ((likely) ? 0x80 : 0)                                     \
1024     | ((uncond) ? 0x100 : 0)))
1025 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1026 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x100) != 0)
1027 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x80) != 0)
1028 #define RELAX_BRANCH_LINK(i) (((i) & 0x40) != 0)
1029 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x20) != 0)
1030 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1031
1032 /* For mips16 code, we use an entirely different form of relaxation.
1033    mips16 supports two versions of most instructions which take
1034    immediate values: a small one which takes some small value, and a
1035    larger one which takes a 16 bit value.  Since branches also follow
1036    this pattern, relaxing these values is required.
1037
1038    We can assemble both mips16 and normal MIPS code in a single
1039    object.  Therefore, we need to support this type of relaxation at
1040    the same time that we support the relaxation described above.  We
1041    use the high bit of the subtype field to distinguish these cases.
1042
1043    The information we store for this type of relaxation is the
1044    argument code found in the opcode file for this relocation, whether
1045    the user explicitly requested a small or extended form, and whether
1046    the relocation is in a jump or jal delay slot.  That tells us the
1047    size of the value, and how it should be stored.  We also store
1048    whether the fragment is considered to be extended or not.  We also
1049    store whether this is known to be a branch to a different section,
1050    whether we have tried to relax this frag yet, and whether we have
1051    ever extended a PC relative fragment because of a shift count.  */
1052 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
1053   (0x80000000                                                   \
1054    | ((type) & 0xff)                                            \
1055    | ((small) ? 0x100 : 0)                                      \
1056    | ((ext) ? 0x200 : 0)                                        \
1057    | ((dslot) ? 0x400 : 0)                                      \
1058    | ((jal_dslot) ? 0x800 : 0))
1059 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1060 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1061 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
1062 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
1063 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
1064 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
1065 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
1066 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
1067 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
1068 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
1069 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
1070 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
1071
1072 /* For microMIPS code, we use relaxation similar to one we use for
1073    MIPS16 code.  Some instructions that take immediate values support
1074    two encodings: a small one which takes some small value, and a
1075    larger one which takes a 16 bit value.  As some branches also follow
1076    this pattern, relaxing these values is required.
1077
1078    We can assemble both microMIPS and normal MIPS code in a single
1079    object.  Therefore, we need to support this type of relaxation at
1080    the same time that we support the relaxation described above.  We
1081    use one of the high bits of the subtype field to distinguish these
1082    cases.
1083
1084    The information we store for this type of relaxation is the argument
1085    code found in the opcode file for this relocation, the register
1086    selected as the assembler temporary, whether the branch is
1087    unconditional, whether it is compact, whether it stores the link
1088    address implicitly in $ra, whether relaxation of out-of-range 32-bit
1089    branches to a sequence of instructions is enabled, and whether the
1090    displacement of a branch is too large to fit as an immediate argument
1091    of a 16-bit and a 32-bit branch, respectively.  */
1092 #define RELAX_MICROMIPS_ENCODE(type, at, uncond, compact, link, \
1093                                relax32, toofar16, toofar32)     \
1094   (0x40000000                                                   \
1095    | ((type) & 0xff)                                            \
1096    | (((at) & 0x1f) << 8)                                       \
1097    | ((uncond) ? 0x2000 : 0)                                    \
1098    | ((compact) ? 0x4000 : 0)                                   \
1099    | ((link) ? 0x8000 : 0)                                      \
1100    | ((relax32) ? 0x10000 : 0)                                  \
1101    | ((toofar16) ? 0x20000 : 0)                                 \
1102    | ((toofar32) ? 0x40000 : 0))
1103 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1104 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1105 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1106 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x2000) != 0)
1107 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x4000) != 0)
1108 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x8000) != 0)
1109 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x10000) != 0)
1110
1111 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x20000) != 0)
1112 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x20000)
1113 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x20000)
1114 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x40000) != 0)
1115 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x40000)
1116 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x40000)
1117
1118 /* Sign-extend 16-bit value X.  */
1119 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1120
1121 /* Is the given value a sign-extended 32-bit value?  */
1122 #define IS_SEXT_32BIT_NUM(x)                                            \
1123   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1124    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1125
1126 /* Is the given value a sign-extended 16-bit value?  */
1127 #define IS_SEXT_16BIT_NUM(x)                                            \
1128   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1129    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1130
1131 /* Is the given value a sign-extended 12-bit value?  */
1132 #define IS_SEXT_12BIT_NUM(x)                                            \
1133   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1134
1135 /* Is the given value a sign-extended 9-bit value?  */
1136 #define IS_SEXT_9BIT_NUM(x)                                             \
1137   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1138
1139 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1140 #define IS_ZEXT_32BIT_NUM(x)                                            \
1141   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1142    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1143
1144 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1145    SHIFT places.  */
1146 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1147   (((STRUCT) >> (SHIFT)) & (MASK))
1148
1149 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1150 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1151   (!(MICROMIPS) \
1152    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1153    : EXTRACT_BITS ((INSN).insn_opcode, \
1154                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1155 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1156   EXTRACT_BITS ((INSN).insn_opcode, \
1157                 MIPS16OP_MASK_##FIELD, \
1158                 MIPS16OP_SH_##FIELD)
1159
1160 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1161 #define MIPS16_EXTEND (0xf000U << 16)
1162 \f
1163 /* Whether or not we are emitting a branch-likely macro.  */
1164 static bfd_boolean emit_branch_likely_macro = FALSE;
1165
1166 /* Global variables used when generating relaxable macros.  See the
1167    comment above RELAX_ENCODE for more details about how relaxation
1168    is used.  */
1169 static struct {
1170   /* 0 if we're not emitting a relaxable macro.
1171      1 if we're emitting the first of the two relaxation alternatives.
1172      2 if we're emitting the second alternative.  */
1173   int sequence;
1174
1175   /* The first relaxable fixup in the current frag.  (In other words,
1176      the first fixup that refers to relaxable code.)  */
1177   fixS *first_fixup;
1178
1179   /* sizes[0] says how many bytes of the first alternative are stored in
1180      the current frag.  Likewise sizes[1] for the second alternative.  */
1181   unsigned int sizes[2];
1182
1183   /* The symbol on which the choice of sequence depends.  */
1184   symbolS *symbol;
1185 } mips_relax;
1186 \f
1187 /* Global variables used to decide whether a macro needs a warning.  */
1188 static struct {
1189   /* True if the macro is in a branch delay slot.  */
1190   bfd_boolean delay_slot_p;
1191
1192   /* Set to the length in bytes required if the macro is in a delay slot
1193      that requires a specific length of instruction, otherwise zero.  */
1194   unsigned int delay_slot_length;
1195
1196   /* For relaxable macros, sizes[0] is the length of the first alternative
1197      in bytes and sizes[1] is the length of the second alternative.
1198      For non-relaxable macros, both elements give the length of the
1199      macro in bytes.  */
1200   unsigned int sizes[2];
1201
1202   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1203      instruction of the first alternative in bytes and first_insn_sizes[1]
1204      is the length of the first instruction of the second alternative.
1205      For non-relaxable macros, both elements give the length of the first
1206      instruction in bytes.
1207
1208      Set to zero if we haven't yet seen the first instruction.  */
1209   unsigned int first_insn_sizes[2];
1210
1211   /* For relaxable macros, insns[0] is the number of instructions for the
1212      first alternative and insns[1] is the number of instructions for the
1213      second alternative.
1214
1215      For non-relaxable macros, both elements give the number of
1216      instructions for the macro.  */
1217   unsigned int insns[2];
1218
1219   /* The first variant frag for this macro.  */
1220   fragS *first_frag;
1221 } mips_macro_warning;
1222 \f
1223 /* Prototypes for static functions.  */
1224
1225 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1226
1227 static void append_insn
1228   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1229    bfd_boolean expansionp);
1230 static void mips_no_prev_insn (void);
1231 static void macro_build (expressionS *, const char *, const char *, ...);
1232 static void mips16_macro_build
1233   (expressionS *, const char *, const char *, va_list *);
1234 static void load_register (int, expressionS *, int);
1235 static void macro_start (void);
1236 static void macro_end (void);
1237 static void macro (struct mips_cl_insn *ip, char *str);
1238 static void mips16_macro (struct mips_cl_insn * ip);
1239 static void mips_ip (char *str, struct mips_cl_insn * ip);
1240 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1241 static void mips16_immed
1242   (char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1243    unsigned int, unsigned long *);
1244 static size_t my_getSmallExpression
1245   (expressionS *, bfd_reloc_code_real_type *, char *);
1246 static void my_getExpression (expressionS *, char *);
1247 static void s_align (int);
1248 static void s_change_sec (int);
1249 static void s_change_section (int);
1250 static void s_cons (int);
1251 static void s_float_cons (int);
1252 static void s_mips_globl (int);
1253 static void s_option (int);
1254 static void s_mipsset (int);
1255 static void s_abicalls (int);
1256 static void s_cpload (int);
1257 static void s_cpsetup (int);
1258 static void s_cplocal (int);
1259 static void s_cprestore (int);
1260 static void s_cpreturn (int);
1261 static void s_dtprelword (int);
1262 static void s_dtpreldword (int);
1263 static void s_tprelword (int);
1264 static void s_tpreldword (int);
1265 static void s_gpvalue (int);
1266 static void s_gpword (int);
1267 static void s_gpdword (int);
1268 static void s_ehword (int);
1269 static void s_cpadd (int);
1270 static void s_insn (int);
1271 static void s_nan (int);
1272 static void md_obj_begin (void);
1273 static void md_obj_end (void);
1274 static void s_mips_ent (int);
1275 static void s_mips_end (int);
1276 static void s_mips_frame (int);
1277 static void s_mips_mask (int reg_type);
1278 static void s_mips_stab (int);
1279 static void s_mips_weakext (int);
1280 static void s_mips_file (int);
1281 static void s_mips_loc (int);
1282 static bfd_boolean pic_need_relax (symbolS *, asection *);
1283 static int relaxed_branch_length (fragS *, asection *, int);
1284 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1285 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1286
1287 /* Table and functions used to map between CPU/ISA names, and
1288    ISA levels, and CPU numbers.  */
1289
1290 struct mips_cpu_info
1291 {
1292   const char *name;           /* CPU or ISA name.  */
1293   int flags;                  /* MIPS_CPU_* flags.  */
1294   int ase;                    /* Set of ASEs implemented by the CPU.  */
1295   int isa;                    /* ISA level.  */
1296   int cpu;                    /* CPU number (default CPU if ISA).  */
1297 };
1298
1299 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1300
1301 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1302 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1303 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1304 \f
1305 /* Command-line options.  */
1306 const char *md_shortopts = "O::g::G:";
1307
1308 enum options
1309   {
1310     OPTION_MARCH = OPTION_MD_BASE,
1311     OPTION_MTUNE,
1312     OPTION_MIPS1,
1313     OPTION_MIPS2,
1314     OPTION_MIPS3,
1315     OPTION_MIPS4,
1316     OPTION_MIPS5,
1317     OPTION_MIPS32,
1318     OPTION_MIPS64,
1319     OPTION_MIPS32R2,
1320     OPTION_MIPS64R2,
1321     OPTION_MIPS16,
1322     OPTION_NO_MIPS16,
1323     OPTION_MIPS3D,
1324     OPTION_NO_MIPS3D,
1325     OPTION_MDMX,
1326     OPTION_NO_MDMX,
1327     OPTION_DSP,
1328     OPTION_NO_DSP,
1329     OPTION_MT,
1330     OPTION_NO_MT,
1331     OPTION_VIRT,
1332     OPTION_NO_VIRT,
1333     OPTION_MSA,
1334     OPTION_NO_MSA,
1335     OPTION_SMARTMIPS,
1336     OPTION_NO_SMARTMIPS,
1337     OPTION_DSPR2,
1338     OPTION_NO_DSPR2,
1339     OPTION_EVA,
1340     OPTION_NO_EVA,
1341     OPTION_MICROMIPS,
1342     OPTION_NO_MICROMIPS,
1343     OPTION_MCU,
1344     OPTION_NO_MCU,
1345     OPTION_COMPAT_ARCH_BASE,
1346     OPTION_M4650,
1347     OPTION_NO_M4650,
1348     OPTION_M4010,
1349     OPTION_NO_M4010,
1350     OPTION_M4100,
1351     OPTION_NO_M4100,
1352     OPTION_M3900,
1353     OPTION_NO_M3900,
1354     OPTION_M7000_HILO_FIX,
1355     OPTION_MNO_7000_HILO_FIX,
1356     OPTION_FIX_24K,
1357     OPTION_NO_FIX_24K,
1358     OPTION_FIX_RM7000,
1359     OPTION_NO_FIX_RM7000,
1360     OPTION_FIX_LOONGSON2F_JUMP,
1361     OPTION_NO_FIX_LOONGSON2F_JUMP,
1362     OPTION_FIX_LOONGSON2F_NOP,
1363     OPTION_NO_FIX_LOONGSON2F_NOP,
1364     OPTION_FIX_VR4120,
1365     OPTION_NO_FIX_VR4120,
1366     OPTION_FIX_VR4130,
1367     OPTION_NO_FIX_VR4130,
1368     OPTION_FIX_CN63XXP1,
1369     OPTION_NO_FIX_CN63XXP1,
1370     OPTION_TRAP,
1371     OPTION_BREAK,
1372     OPTION_EB,
1373     OPTION_EL,
1374     OPTION_FP32,
1375     OPTION_GP32,
1376     OPTION_CONSTRUCT_FLOATS,
1377     OPTION_NO_CONSTRUCT_FLOATS,
1378     OPTION_FP64,
1379     OPTION_GP64,
1380     OPTION_RELAX_BRANCH,
1381     OPTION_NO_RELAX_BRANCH,
1382     OPTION_INSN32,
1383     OPTION_NO_INSN32,
1384     OPTION_MSHARED,
1385     OPTION_MNO_SHARED,
1386     OPTION_MSYM32,
1387     OPTION_MNO_SYM32,
1388     OPTION_SOFT_FLOAT,
1389     OPTION_HARD_FLOAT,
1390     OPTION_SINGLE_FLOAT,
1391     OPTION_DOUBLE_FLOAT,
1392     OPTION_32,
1393     OPTION_CALL_SHARED,
1394     OPTION_CALL_NONPIC,
1395     OPTION_NON_SHARED,
1396     OPTION_XGOT,
1397     OPTION_MABI,
1398     OPTION_N32,
1399     OPTION_64,
1400     OPTION_MDEBUG,
1401     OPTION_NO_MDEBUG,
1402     OPTION_PDR,
1403     OPTION_NO_PDR,
1404     OPTION_MVXWORKS_PIC,
1405     OPTION_NAN,
1406     OPTION_END_OF_ENUM
1407   };
1408
1409 struct option md_longopts[] =
1410 {
1411   /* Options which specify architecture.  */
1412   {"march", required_argument, NULL, OPTION_MARCH},
1413   {"mtune", required_argument, NULL, OPTION_MTUNE},
1414   {"mips0", no_argument, NULL, OPTION_MIPS1},
1415   {"mips1", no_argument, NULL, OPTION_MIPS1},
1416   {"mips2", no_argument, NULL, OPTION_MIPS2},
1417   {"mips3", no_argument, NULL, OPTION_MIPS3},
1418   {"mips4", no_argument, NULL, OPTION_MIPS4},
1419   {"mips5", no_argument, NULL, OPTION_MIPS5},
1420   {"mips32", no_argument, NULL, OPTION_MIPS32},
1421   {"mips64", no_argument, NULL, OPTION_MIPS64},
1422   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1423   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1424
1425   /* Options which specify Application Specific Extensions (ASEs).  */
1426   {"mips16", no_argument, NULL, OPTION_MIPS16},
1427   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1428   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1429   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1430   {"mdmx", no_argument, NULL, OPTION_MDMX},
1431   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1432   {"mdsp", no_argument, NULL, OPTION_DSP},
1433   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1434   {"mmt", no_argument, NULL, OPTION_MT},
1435   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1436   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1437   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1438   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1439   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1440   {"meva", no_argument, NULL, OPTION_EVA},
1441   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1442   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1443   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1444   {"mmcu", no_argument, NULL, OPTION_MCU},
1445   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1446   {"mvirt", no_argument, NULL, OPTION_VIRT},
1447   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1448   {"mmsa", no_argument, NULL, OPTION_MSA},
1449   {"mno-msa", no_argument, NULL, OPTION_NO_MSA},
1450
1451   /* Old-style architecture options.  Don't add more of these.  */
1452   {"m4650", no_argument, NULL, OPTION_M4650},
1453   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1454   {"m4010", no_argument, NULL, OPTION_M4010},
1455   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1456   {"m4100", no_argument, NULL, OPTION_M4100},
1457   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1458   {"m3900", no_argument, NULL, OPTION_M3900},
1459   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1460
1461   /* Options which enable bug fixes.  */
1462   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1463   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1464   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1465   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1466   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1467   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1468   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1469   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1470   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1471   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1472   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1473   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1474   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1475   {"mfix-rm7000",    no_argument, NULL, OPTION_FIX_RM7000},
1476   {"mno-fix-rm7000", no_argument, NULL, OPTION_NO_FIX_RM7000},
1477   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1478   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1479
1480   /* Miscellaneous options.  */
1481   {"trap", no_argument, NULL, OPTION_TRAP},
1482   {"no-break", no_argument, NULL, OPTION_TRAP},
1483   {"break", no_argument, NULL, OPTION_BREAK},
1484   {"no-trap", no_argument, NULL, OPTION_BREAK},
1485   {"EB", no_argument, NULL, OPTION_EB},
1486   {"EL", no_argument, NULL, OPTION_EL},
1487   {"mfp32", no_argument, NULL, OPTION_FP32},
1488   {"mgp32", no_argument, NULL, OPTION_GP32},
1489   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1490   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1491   {"mfp64", no_argument, NULL, OPTION_FP64},
1492   {"mgp64", no_argument, NULL, OPTION_GP64},
1493   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1494   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1495   {"minsn32", no_argument, NULL, OPTION_INSN32},
1496   {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1497   {"mshared", no_argument, NULL, OPTION_MSHARED},
1498   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1499   {"msym32", no_argument, NULL, OPTION_MSYM32},
1500   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1501   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1502   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1503   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1504   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1505
1506   /* Strictly speaking this next option is ELF specific,
1507      but we allow it for other ports as well in order to
1508      make testing easier.  */
1509   {"32", no_argument, NULL, OPTION_32},
1510
1511   /* ELF-specific options.  */
1512   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1513   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1514   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1515   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1516   {"xgot", no_argument, NULL, OPTION_XGOT},
1517   {"mabi", required_argument, NULL, OPTION_MABI},
1518   {"n32", no_argument, NULL, OPTION_N32},
1519   {"64", no_argument, NULL, OPTION_64},
1520   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1521   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1522   {"mpdr", no_argument, NULL, OPTION_PDR},
1523   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1524   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1525   {"mnan", required_argument, NULL, OPTION_NAN},
1526
1527   {NULL, no_argument, NULL, 0}
1528 };
1529 size_t md_longopts_size = sizeof (md_longopts);
1530 \f
1531 /* Information about either an Application Specific Extension or an
1532    optional architecture feature that, for simplicity, we treat in the
1533    same way as an ASE.  */
1534 struct mips_ase
1535 {
1536   /* The name of the ASE, used in both the command-line and .set options.  */
1537   const char *name;
1538
1539   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1540      and 64-bit architectures, the flags here refer to the subset that
1541      is available on both.  */
1542   unsigned int flags;
1543
1544   /* The ASE_* flag used for instructions that are available on 64-bit
1545      architectures but that are not included in FLAGS.  */
1546   unsigned int flags64;
1547
1548   /* The command-line options that turn the ASE on and off.  */
1549   int option_on;
1550   int option_off;
1551
1552   /* The minimum required architecture revisions for MIPS32, MIPS64,
1553      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1554   int mips32_rev;
1555   int mips64_rev;
1556   int micromips32_rev;
1557   int micromips64_rev;
1558 };
1559
1560 /* A table of all supported ASEs.  */
1561 static const struct mips_ase mips_ases[] = {
1562   { "dsp", ASE_DSP, ASE_DSP64,
1563     OPTION_DSP, OPTION_NO_DSP,
1564     2, 2, 2, 2 },
1565
1566   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1567     OPTION_DSPR2, OPTION_NO_DSPR2,
1568     2, 2, 2, 2 },
1569
1570   { "eva", ASE_EVA, 0,
1571     OPTION_EVA, OPTION_NO_EVA,
1572     2, 2, 2, 2 },
1573
1574   { "mcu", ASE_MCU, 0,
1575     OPTION_MCU, OPTION_NO_MCU,
1576     2, 2, 2, 2 },
1577
1578   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1579   { "mdmx", ASE_MDMX, 0,
1580     OPTION_MDMX, OPTION_NO_MDMX,
1581     -1, 1, -1, -1 },
1582
1583   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1584   { "mips3d", ASE_MIPS3D, 0,
1585     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1586     2, 1, -1, -1 },
1587
1588   { "mt", ASE_MT, 0,
1589     OPTION_MT, OPTION_NO_MT,
1590     2, 2, -1, -1 },
1591
1592   { "smartmips", ASE_SMARTMIPS, 0,
1593     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1594     1, -1, -1, -1 },
1595
1596   { "virt", ASE_VIRT, ASE_VIRT64,
1597     OPTION_VIRT, OPTION_NO_VIRT,
1598     2, 2, 2, 2 },
1599
1600   { "msa", ASE_MSA, ASE_MSA64,
1601     OPTION_MSA, OPTION_NO_MSA,
1602     2, 2, 2, 2 }
1603 };
1604
1605 /* The set of ASEs that require -mfp64.  */
1606 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX)
1607
1608 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1609 static const unsigned int mips_ase_groups[] = {
1610   ASE_DSP | ASE_DSPR2
1611 };
1612 \f
1613 /* Pseudo-op table.
1614
1615    The following pseudo-ops from the Kane and Heinrich MIPS book
1616    should be defined here, but are currently unsupported: .alias,
1617    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1618
1619    The following pseudo-ops from the Kane and Heinrich MIPS book are
1620    specific to the type of debugging information being generated, and
1621    should be defined by the object format: .aent, .begin, .bend,
1622    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1623    .vreg.
1624
1625    The following pseudo-ops from the Kane and Heinrich MIPS book are
1626    not MIPS CPU specific, but are also not specific to the object file
1627    format.  This file is probably the best place to define them, but
1628    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1629
1630 static const pseudo_typeS mips_pseudo_table[] =
1631 {
1632   /* MIPS specific pseudo-ops.  */
1633   {"option", s_option, 0},
1634   {"set", s_mipsset, 0},
1635   {"rdata", s_change_sec, 'r'},
1636   {"sdata", s_change_sec, 's'},
1637   {"livereg", s_ignore, 0},
1638   {"abicalls", s_abicalls, 0},
1639   {"cpload", s_cpload, 0},
1640   {"cpsetup", s_cpsetup, 0},
1641   {"cplocal", s_cplocal, 0},
1642   {"cprestore", s_cprestore, 0},
1643   {"cpreturn", s_cpreturn, 0},
1644   {"dtprelword", s_dtprelword, 0},
1645   {"dtpreldword", s_dtpreldword, 0},
1646   {"tprelword", s_tprelword, 0},
1647   {"tpreldword", s_tpreldword, 0},
1648   {"gpvalue", s_gpvalue, 0},
1649   {"gpword", s_gpword, 0},
1650   {"gpdword", s_gpdword, 0},
1651   {"ehword", s_ehword, 0},
1652   {"cpadd", s_cpadd, 0},
1653   {"insn", s_insn, 0},
1654   {"nan", s_nan, 0},
1655
1656   /* Relatively generic pseudo-ops that happen to be used on MIPS
1657      chips.  */
1658   {"asciiz", stringer, 8 + 1},
1659   {"bss", s_change_sec, 'b'},
1660   {"err", s_err, 0},
1661   {"half", s_cons, 1},
1662   {"dword", s_cons, 3},
1663   {"weakext", s_mips_weakext, 0},
1664   {"origin", s_org, 0},
1665   {"repeat", s_rept, 0},
1666
1667   /* For MIPS this is non-standard, but we define it for consistency.  */
1668   {"sbss", s_change_sec, 'B'},
1669
1670   /* These pseudo-ops are defined in read.c, but must be overridden
1671      here for one reason or another.  */
1672   {"align", s_align, 0},
1673   {"byte", s_cons, 0},
1674   {"data", s_change_sec, 'd'},
1675   {"double", s_float_cons, 'd'},
1676   {"float", s_float_cons, 'f'},
1677   {"globl", s_mips_globl, 0},
1678   {"global", s_mips_globl, 0},
1679   {"hword", s_cons, 1},
1680   {"int", s_cons, 2},
1681   {"long", s_cons, 2},
1682   {"octa", s_cons, 4},
1683   {"quad", s_cons, 3},
1684   {"section", s_change_section, 0},
1685   {"short", s_cons, 1},
1686   {"single", s_float_cons, 'f'},
1687   {"stabd", s_mips_stab, 'd'},
1688   {"stabn", s_mips_stab, 'n'},
1689   {"stabs", s_mips_stab, 's'},
1690   {"text", s_change_sec, 't'},
1691   {"word", s_cons, 2},
1692
1693   { "extern", ecoff_directive_extern, 0},
1694
1695   { NULL, NULL, 0 },
1696 };
1697
1698 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1699 {
1700   /* These pseudo-ops should be defined by the object file format.
1701      However, a.out doesn't support them, so we have versions here.  */
1702   {"aent", s_mips_ent, 1},
1703   {"bgnb", s_ignore, 0},
1704   {"end", s_mips_end, 0},
1705   {"endb", s_ignore, 0},
1706   {"ent", s_mips_ent, 0},
1707   {"file", s_mips_file, 0},
1708   {"fmask", s_mips_mask, 'F'},
1709   {"frame", s_mips_frame, 0},
1710   {"loc", s_mips_loc, 0},
1711   {"mask", s_mips_mask, 'R'},
1712   {"verstamp", s_ignore, 0},
1713   { NULL, NULL, 0 },
1714 };
1715
1716 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1717    purpose of the `.dc.a' internal pseudo-op.  */
1718
1719 int
1720 mips_address_bytes (void)
1721 {
1722   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1723 }
1724
1725 extern void pop_insert (const pseudo_typeS *);
1726
1727 void
1728 mips_pop_insert (void)
1729 {
1730   pop_insert (mips_pseudo_table);
1731   if (! ECOFF_DEBUGGING)
1732     pop_insert (mips_nonecoff_pseudo_table);
1733 }
1734 \f
1735 /* Symbols labelling the current insn.  */
1736
1737 struct insn_label_list
1738 {
1739   struct insn_label_list *next;
1740   symbolS *label;
1741 };
1742
1743 static struct insn_label_list *free_insn_labels;
1744 #define label_list tc_segment_info_data.labels
1745
1746 static void mips_clear_insn_labels (void);
1747 static void mips_mark_labels (void);
1748 static void mips_compressed_mark_labels (void);
1749
1750 static inline void
1751 mips_clear_insn_labels (void)
1752 {
1753   register struct insn_label_list **pl;
1754   segment_info_type *si;
1755
1756   if (now_seg)
1757     {
1758       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1759         ;
1760       
1761       si = seg_info (now_seg);
1762       *pl = si->label_list;
1763       si->label_list = NULL;
1764     }
1765 }
1766
1767 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1768
1769 static inline void
1770 mips_mark_labels (void)
1771 {
1772   if (HAVE_CODE_COMPRESSION)
1773     mips_compressed_mark_labels ();
1774 }
1775 \f
1776 static char *expr_end;
1777
1778 /* An expression in a macro instruction.  This is set by mips_ip and
1779    mips16_ip and when populated is always an O_constant.  */
1780
1781 static expressionS imm_expr;
1782
1783 /* The relocatable field in an instruction and the relocs associated
1784    with it.  These variables are used for instructions like LUI and
1785    JAL as well as true offsets.  They are also used for address
1786    operands in macros.  */
1787
1788 static expressionS offset_expr;
1789 static bfd_reloc_code_real_type offset_reloc[3]
1790   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1791
1792 /* This is set to the resulting size of the instruction to be produced
1793    by mips16_ip if an explicit extension is used or by mips_ip if an
1794    explicit size is supplied.  */
1795
1796 static unsigned int forced_insn_length;
1797
1798 /* True if we are assembling an instruction.  All dot symbols defined during
1799    this time should be treated as code labels.  */
1800
1801 static bfd_boolean mips_assembling_insn;
1802
1803 /* The pdr segment for per procedure frame/regmask info.  Not used for
1804    ECOFF debugging.  */
1805
1806 static segT pdr_seg;
1807
1808 /* The default target format to use.  */
1809
1810 #if defined (TE_FreeBSD)
1811 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1812 #elif defined (TE_TMIPS)
1813 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1814 #else
1815 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1816 #endif
1817
1818 const char *
1819 mips_target_format (void)
1820 {
1821   switch (OUTPUT_FLAVOR)
1822     {
1823     case bfd_target_elf_flavour:
1824 #ifdef TE_VXWORKS
1825       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1826         return (target_big_endian
1827                 ? "elf32-bigmips-vxworks"
1828                 : "elf32-littlemips-vxworks");
1829 #endif
1830       return (target_big_endian
1831               ? (HAVE_64BIT_OBJECTS
1832                  ? ELF_TARGET ("elf64-", "big")
1833                  : (HAVE_NEWABI
1834                     ? ELF_TARGET ("elf32-n", "big")
1835                     : ELF_TARGET ("elf32-", "big")))
1836               : (HAVE_64BIT_OBJECTS
1837                  ? ELF_TARGET ("elf64-", "little")
1838                  : (HAVE_NEWABI
1839                     ? ELF_TARGET ("elf32-n", "little")
1840                     : ELF_TARGET ("elf32-", "little"))));
1841     default:
1842       abort ();
1843       return NULL;
1844     }
1845 }
1846
1847 /* Return the ISA revision that is currently in use, or 0 if we are
1848    generating code for MIPS V or below.  */
1849
1850 static int
1851 mips_isa_rev (void)
1852 {
1853   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
1854     return 2;
1855
1856   /* microMIPS implies revision 2 or above.  */
1857   if (mips_opts.micromips)
1858     return 2;
1859
1860   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
1861     return 1;
1862
1863   return 0;
1864 }
1865
1866 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
1867
1868 static unsigned int
1869 mips_ase_mask (unsigned int flags)
1870 {
1871   unsigned int i;
1872
1873   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
1874     if (flags & mips_ase_groups[i])
1875       flags |= mips_ase_groups[i];
1876   return flags;
1877 }
1878
1879 /* Check whether the current ISA supports ASE.  Issue a warning if
1880    appropriate.  */
1881
1882 static void
1883 mips_check_isa_supports_ase (const struct mips_ase *ase)
1884 {
1885   const char *base;
1886   int min_rev, size;
1887   static unsigned int warned_isa;
1888   static unsigned int warned_fp32;
1889
1890   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
1891     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
1892   else
1893     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
1894   if ((min_rev < 0 || mips_isa_rev () < min_rev)
1895       && (warned_isa & ase->flags) != ase->flags)
1896     {
1897       warned_isa |= ase->flags;
1898       base = mips_opts.micromips ? "microMIPS" : "MIPS";
1899       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
1900       if (min_rev < 0)
1901         as_warn (_("the %d-bit %s architecture does not support the"
1902                    " `%s' extension"), size, base, ase->name);
1903       else
1904         as_warn (_("the `%s' extension requires %s%d revision %d or greater"),
1905                  ase->name, base, size, min_rev);
1906     }
1907   if ((ase->flags & FP64_ASES)
1908       && mips_opts.fp32
1909       && (warned_fp32 & ase->flags) != ase->flags)
1910     {
1911       warned_fp32 |= ase->flags;
1912       as_warn (_("the `%s' extension requires 64-bit FPRs"), ase->name);
1913     }
1914 }
1915
1916 /* Check all enabled ASEs to see whether they are supported by the
1917    chosen architecture.  */
1918
1919 static void
1920 mips_check_isa_supports_ases (void)
1921 {
1922   unsigned int i, mask;
1923
1924   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1925     {
1926       mask = mips_ase_mask (mips_ases[i].flags);
1927       if ((mips_opts.ase & mask) == mips_ases[i].flags)
1928         mips_check_isa_supports_ase (&mips_ases[i]);
1929     }
1930 }
1931
1932 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
1933    that were affected.  */
1934
1935 static unsigned int
1936 mips_set_ase (const struct mips_ase *ase, bfd_boolean enabled_p)
1937 {
1938   unsigned int mask;
1939
1940   mask = mips_ase_mask (ase->flags);
1941   mips_opts.ase &= ~mask;
1942   if (enabled_p)
1943     mips_opts.ase |= ase->flags;
1944   return mask;
1945 }
1946
1947 /* Return the ASE called NAME, or null if none.  */
1948
1949 static const struct mips_ase *
1950 mips_lookup_ase (const char *name)
1951 {
1952   unsigned int i;
1953
1954   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1955     if (strcmp (name, mips_ases[i].name) == 0)
1956       return &mips_ases[i];
1957   return NULL;
1958 }
1959
1960 /* Return the length of a microMIPS instruction in bytes.  If bits of
1961    the mask beyond the low 16 are 0, then it is a 16-bit instruction.
1962    Otherwise assume a 32-bit instruction; 48-bit instructions (0x1f
1963    major opcode) will require further modifications to the opcode
1964    table.  */
1965
1966 static inline unsigned int
1967 micromips_insn_length (const struct mips_opcode *mo)
1968 {
1969   return (mo->mask >> 16) == 0 ? 2 : 4;
1970 }
1971
1972 /* Return the length of MIPS16 instruction OPCODE.  */
1973
1974 static inline unsigned int
1975 mips16_opcode_length (unsigned long opcode)
1976 {
1977   return (opcode >> 16) == 0 ? 2 : 4;
1978 }
1979
1980 /* Return the length of instruction INSN.  */
1981
1982 static inline unsigned int
1983 insn_length (const struct mips_cl_insn *insn)
1984 {
1985   if (mips_opts.micromips)
1986     return micromips_insn_length (insn->insn_mo);
1987   else if (mips_opts.mips16)
1988     return mips16_opcode_length (insn->insn_opcode);
1989   else
1990     return 4;
1991 }
1992
1993 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
1994
1995 static void
1996 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
1997 {
1998   size_t i;
1999
2000   insn->insn_mo = mo;
2001   insn->insn_opcode = mo->match;
2002   insn->frag = NULL;
2003   insn->where = 0;
2004   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2005     insn->fixp[i] = NULL;
2006   insn->fixed_p = (mips_opts.noreorder > 0);
2007   insn->noreorder_p = (mips_opts.noreorder > 0);
2008   insn->mips16_absolute_jump_p = 0;
2009   insn->complete_p = 0;
2010   insn->cleared_p = 0;
2011 }
2012
2013 /* Get a list of all the operands in INSN.  */
2014
2015 static const struct mips_operand_array *
2016 insn_operands (const struct mips_cl_insn *insn)
2017 {
2018   if (insn->insn_mo >= &mips_opcodes[0]
2019       && insn->insn_mo < &mips_opcodes[NUMOPCODES])
2020     return &mips_operands[insn->insn_mo - &mips_opcodes[0]];
2021
2022   if (insn->insn_mo >= &mips16_opcodes[0]
2023       && insn->insn_mo < &mips16_opcodes[bfd_mips16_num_opcodes])
2024     return &mips16_operands[insn->insn_mo - &mips16_opcodes[0]];
2025
2026   if (insn->insn_mo >= &micromips_opcodes[0]
2027       && insn->insn_mo < &micromips_opcodes[bfd_micromips_num_opcodes])
2028     return &micromips_operands[insn->insn_mo - &micromips_opcodes[0]];
2029
2030   abort ();
2031 }
2032
2033 /* Get a description of operand OPNO of INSN.  */
2034
2035 static const struct mips_operand *
2036 insn_opno (const struct mips_cl_insn *insn, unsigned opno)
2037 {
2038   const struct mips_operand_array *operands;
2039
2040   operands = insn_operands (insn);
2041   if (opno >= MAX_OPERANDS || !operands->operand[opno])
2042     abort ();
2043   return operands->operand[opno];
2044 }
2045
2046 /* Install UVAL as the value of OPERAND in INSN.  */
2047
2048 static inline void
2049 insn_insert_operand (struct mips_cl_insn *insn,
2050                      const struct mips_operand *operand, unsigned int uval)
2051 {
2052   insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
2053 }
2054
2055 /* Extract the value of OPERAND from INSN.  */
2056
2057 static inline unsigned
2058 insn_extract_operand (const struct mips_cl_insn *insn,
2059                       const struct mips_operand *operand)
2060 {
2061   return mips_extract_operand (operand, insn->insn_opcode);
2062 }
2063
2064 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2065
2066 static void
2067 mips_record_compressed_mode (void)
2068 {
2069   segment_info_type *si;
2070
2071   si = seg_info (now_seg);
2072   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2073     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2074   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2075     si->tc_segment_info_data.micromips = mips_opts.micromips;
2076 }
2077
2078 /* Read a standard MIPS instruction from BUF.  */
2079
2080 static unsigned long
2081 read_insn (char *buf)
2082 {
2083   if (target_big_endian)
2084     return bfd_getb32 ((bfd_byte *) buf);
2085   else
2086     return bfd_getl32 ((bfd_byte *) buf);
2087 }
2088
2089 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2090    the next byte.  */
2091
2092 static char *
2093 write_insn (char *buf, unsigned int insn)
2094 {
2095   md_number_to_chars (buf, insn, 4);
2096   return buf + 4;
2097 }
2098
2099 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2100    has length LENGTH.  */
2101
2102 static unsigned long
2103 read_compressed_insn (char *buf, unsigned int length)
2104 {
2105   unsigned long insn;
2106   unsigned int i;
2107
2108   insn = 0;
2109   for (i = 0; i < length; i += 2)
2110     {
2111       insn <<= 16;
2112       if (target_big_endian)
2113         insn |= bfd_getb16 ((char *) buf);
2114       else
2115         insn |= bfd_getl16 ((char *) buf);
2116       buf += 2;
2117     }
2118   return insn;
2119 }
2120
2121 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2122    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2123
2124 static char *
2125 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2126 {
2127   unsigned int i;
2128
2129   for (i = 0; i < length; i += 2)
2130     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2131   return buf + length;
2132 }
2133
2134 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2135
2136 static void
2137 install_insn (const struct mips_cl_insn *insn)
2138 {
2139   char *f = insn->frag->fr_literal + insn->where;
2140   if (HAVE_CODE_COMPRESSION)
2141     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2142   else
2143     write_insn (f, insn->insn_opcode);
2144   mips_record_compressed_mode ();
2145 }
2146
2147 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2148    and install the opcode in the new location.  */
2149
2150 static void
2151 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2152 {
2153   size_t i;
2154
2155   insn->frag = frag;
2156   insn->where = where;
2157   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2158     if (insn->fixp[i] != NULL)
2159       {
2160         insn->fixp[i]->fx_frag = frag;
2161         insn->fixp[i]->fx_where = where;
2162       }
2163   install_insn (insn);
2164 }
2165
2166 /* Add INSN to the end of the output.  */
2167
2168 static void
2169 add_fixed_insn (struct mips_cl_insn *insn)
2170 {
2171   char *f = frag_more (insn_length (insn));
2172   move_insn (insn, frag_now, f - frag_now->fr_literal);
2173 }
2174
2175 /* Start a variant frag and move INSN to the start of the variant part,
2176    marking it as fixed.  The other arguments are as for frag_var.  */
2177
2178 static void
2179 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2180                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2181 {
2182   frag_grow (max_chars);
2183   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2184   insn->fixed_p = 1;
2185   frag_var (rs_machine_dependent, max_chars, var,
2186             subtype, symbol, offset, NULL);
2187 }
2188
2189 /* Insert N copies of INSN into the history buffer, starting at
2190    position FIRST.  Neither FIRST nor N need to be clipped.  */
2191
2192 static void
2193 insert_into_history (unsigned int first, unsigned int n,
2194                      const struct mips_cl_insn *insn)
2195 {
2196   if (mips_relax.sequence != 2)
2197     {
2198       unsigned int i;
2199
2200       for (i = ARRAY_SIZE (history); i-- > first;)
2201         if (i >= first + n)
2202           history[i] = history[i - n];
2203         else
2204           history[i] = *insn;
2205     }
2206 }
2207
2208 /* Clear the error in insn_error.  */
2209
2210 static void
2211 clear_insn_error (void)
2212 {
2213   memset (&insn_error, 0, sizeof (insn_error));
2214 }
2215
2216 /* Possibly record error message MSG for the current instruction.
2217    If the error is about a particular argument, ARGNUM is the 1-based
2218    number of that argument, otherwise it is 0.  FORMAT is the format
2219    of MSG.  Return true if MSG was used, false if the current message
2220    was kept.  */
2221
2222 static bfd_boolean
2223 set_insn_error_format (int argnum, enum mips_insn_error_format format,
2224                        const char *msg)
2225 {
2226   if (argnum == 0)
2227     {
2228       /* Give priority to errors against specific arguments, and to
2229          the first whole-instruction message.  */
2230       if (insn_error.msg)
2231         return FALSE;
2232     }
2233   else
2234     {
2235       /* Keep insn_error if it is against a later argument.  */
2236       if (argnum < insn_error.min_argnum)
2237         return FALSE;
2238
2239       /* If both errors are against the same argument but are different,
2240          give up on reporting a specific error for this argument.
2241          See the comment about mips_insn_error for details.  */
2242       if (argnum == insn_error.min_argnum
2243           && insn_error.msg
2244           && strcmp (insn_error.msg, msg) != 0)
2245         {
2246           insn_error.msg = 0;
2247           insn_error.min_argnum += 1;
2248           return FALSE;
2249         }
2250     }
2251   insn_error.min_argnum = argnum;
2252   insn_error.format = format;
2253   insn_error.msg = msg;
2254   return TRUE;
2255 }
2256
2257 /* Record an instruction error with no % format fields.  ARGNUM and MSG are
2258    as for set_insn_error_format.  */
2259
2260 static void
2261 set_insn_error (int argnum, const char *msg)
2262 {
2263   set_insn_error_format (argnum, ERR_FMT_PLAIN, msg);
2264 }
2265
2266 /* Record an instruction error with one %d field I.  ARGNUM and MSG are
2267    as for set_insn_error_format.  */
2268
2269 static void
2270 set_insn_error_i (int argnum, const char *msg, int i)
2271 {
2272   if (set_insn_error_format (argnum, ERR_FMT_I, msg))
2273     insn_error.u.i = i;
2274 }
2275
2276 /* Record an instruction error with two %s fields S1 and S2.  ARGNUM and MSG
2277    are as for set_insn_error_format.  */
2278
2279 static void
2280 set_insn_error_ss (int argnum, const char *msg, const char *s1, const char *s2)
2281 {
2282   if (set_insn_error_format (argnum, ERR_FMT_SS, msg))
2283     {
2284       insn_error.u.ss[0] = s1;
2285       insn_error.u.ss[1] = s2;
2286     }
2287 }
2288
2289 /* Report the error in insn_error, which is against assembly code STR.  */
2290
2291 static void
2292 report_insn_error (const char *str)
2293 {
2294   const char *msg;
2295
2296   msg = ACONCAT ((insn_error.msg, " `%s'", NULL));
2297   switch (insn_error.format)
2298     {
2299     case ERR_FMT_PLAIN:
2300       as_bad (msg, str);
2301       break;
2302
2303     case ERR_FMT_I:
2304       as_bad (msg, insn_error.u.i, str);
2305       break;
2306
2307     case ERR_FMT_SS:
2308       as_bad (msg, insn_error.u.ss[0], insn_error.u.ss[1], str);
2309       break;
2310     }
2311 }
2312
2313 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2314    the idea is to make it obvious at a glance that each errata is
2315    included.  */
2316
2317 static void
2318 init_vr4120_conflicts (void)
2319 {
2320 #define CONFLICT(FIRST, SECOND) \
2321     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2322
2323   /* Errata 21 - [D]DIV[U] after [D]MACC */
2324   CONFLICT (MACC, DIV);
2325   CONFLICT (DMACC, DIV);
2326
2327   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2328   CONFLICT (DMULT, DMULT);
2329   CONFLICT (DMULT, DMACC);
2330   CONFLICT (DMACC, DMULT);
2331   CONFLICT (DMACC, DMACC);
2332
2333   /* Errata 24 - MT{LO,HI} after [D]MACC */
2334   CONFLICT (MACC, MTHILO);
2335   CONFLICT (DMACC, MTHILO);
2336
2337   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2338      instruction is executed immediately after a MACC or DMACC
2339      instruction, the result of [either instruction] is incorrect."  */
2340   CONFLICT (MACC, MULT);
2341   CONFLICT (MACC, DMULT);
2342   CONFLICT (DMACC, MULT);
2343   CONFLICT (DMACC, DMULT);
2344
2345   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2346      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2347      DDIV or DDIVU instruction, the result of the MACC or
2348      DMACC instruction is incorrect.".  */
2349   CONFLICT (DMULT, MACC);
2350   CONFLICT (DMULT, DMACC);
2351   CONFLICT (DIV, MACC);
2352   CONFLICT (DIV, DMACC);
2353
2354 #undef CONFLICT
2355 }
2356
2357 struct regname {
2358   const char *name;
2359   unsigned int num;
2360 };
2361
2362 #define RNUM_MASK       0x00000ff
2363 #define RTYPE_MASK      0x0ffff00
2364 #define RTYPE_NUM       0x0000100
2365 #define RTYPE_FPU       0x0000200
2366 #define RTYPE_FCC       0x0000400
2367 #define RTYPE_VEC       0x0000800
2368 #define RTYPE_GP        0x0001000
2369 #define RTYPE_CP0       0x0002000
2370 #define RTYPE_PC        0x0004000
2371 #define RTYPE_ACC       0x0008000
2372 #define RTYPE_CCC       0x0010000
2373 #define RTYPE_VI        0x0020000
2374 #define RTYPE_VF        0x0040000
2375 #define RTYPE_R5900_I   0x0080000
2376 #define RTYPE_R5900_Q   0x0100000
2377 #define RTYPE_R5900_R   0x0200000
2378 #define RTYPE_R5900_ACC 0x0400000
2379 #define RTYPE_MSA       0x0800000
2380 #define RWARN           0x8000000
2381
2382 #define GENERIC_REGISTER_NUMBERS \
2383     {"$0",      RTYPE_NUM | 0},  \
2384     {"$1",      RTYPE_NUM | 1},  \
2385     {"$2",      RTYPE_NUM | 2},  \
2386     {"$3",      RTYPE_NUM | 3},  \
2387     {"$4",      RTYPE_NUM | 4},  \
2388     {"$5",      RTYPE_NUM | 5},  \
2389     {"$6",      RTYPE_NUM | 6},  \
2390     {"$7",      RTYPE_NUM | 7},  \
2391     {"$8",      RTYPE_NUM | 8},  \
2392     {"$9",      RTYPE_NUM | 9},  \
2393     {"$10",     RTYPE_NUM | 10}, \
2394     {"$11",     RTYPE_NUM | 11}, \
2395     {"$12",     RTYPE_NUM | 12}, \
2396     {"$13",     RTYPE_NUM | 13}, \
2397     {"$14",     RTYPE_NUM | 14}, \
2398     {"$15",     RTYPE_NUM | 15}, \
2399     {"$16",     RTYPE_NUM | 16}, \
2400     {"$17",     RTYPE_NUM | 17}, \
2401     {"$18",     RTYPE_NUM | 18}, \
2402     {"$19",     RTYPE_NUM | 19}, \
2403     {"$20",     RTYPE_NUM | 20}, \
2404     {"$21",     RTYPE_NUM | 21}, \
2405     {"$22",     RTYPE_NUM | 22}, \
2406     {"$23",     RTYPE_NUM | 23}, \
2407     {"$24",     RTYPE_NUM | 24}, \
2408     {"$25",     RTYPE_NUM | 25}, \
2409     {"$26",     RTYPE_NUM | 26}, \
2410     {"$27",     RTYPE_NUM | 27}, \
2411     {"$28",     RTYPE_NUM | 28}, \
2412     {"$29",     RTYPE_NUM | 29}, \
2413     {"$30",     RTYPE_NUM | 30}, \
2414     {"$31",     RTYPE_NUM | 31} 
2415
2416 #define FPU_REGISTER_NAMES       \
2417     {"$f0",     RTYPE_FPU | 0},  \
2418     {"$f1",     RTYPE_FPU | 1},  \
2419     {"$f2",     RTYPE_FPU | 2},  \
2420     {"$f3",     RTYPE_FPU | 3},  \
2421     {"$f4",     RTYPE_FPU | 4},  \
2422     {"$f5",     RTYPE_FPU | 5},  \
2423     {"$f6",     RTYPE_FPU | 6},  \
2424     {"$f7",     RTYPE_FPU | 7},  \
2425     {"$f8",     RTYPE_FPU | 8},  \
2426     {"$f9",     RTYPE_FPU | 9},  \
2427     {"$f10",    RTYPE_FPU | 10}, \
2428     {"$f11",    RTYPE_FPU | 11}, \
2429     {"$f12",    RTYPE_FPU | 12}, \
2430     {"$f13",    RTYPE_FPU | 13}, \
2431     {"$f14",    RTYPE_FPU | 14}, \
2432     {"$f15",    RTYPE_FPU | 15}, \
2433     {"$f16",    RTYPE_FPU | 16}, \
2434     {"$f17",    RTYPE_FPU | 17}, \
2435     {"$f18",    RTYPE_FPU | 18}, \
2436     {"$f19",    RTYPE_FPU | 19}, \
2437     {"$f20",    RTYPE_FPU | 20}, \
2438     {"$f21",    RTYPE_FPU | 21}, \
2439     {"$f22",    RTYPE_FPU | 22}, \
2440     {"$f23",    RTYPE_FPU | 23}, \
2441     {"$f24",    RTYPE_FPU | 24}, \
2442     {"$f25",    RTYPE_FPU | 25}, \
2443     {"$f26",    RTYPE_FPU | 26}, \
2444     {"$f27",    RTYPE_FPU | 27}, \
2445     {"$f28",    RTYPE_FPU | 28}, \
2446     {"$f29",    RTYPE_FPU | 29}, \
2447     {"$f30",    RTYPE_FPU | 30}, \
2448     {"$f31",    RTYPE_FPU | 31}
2449
2450 #define FPU_CONDITION_CODE_NAMES \
2451     {"$fcc0",   RTYPE_FCC | 0},  \
2452     {"$fcc1",   RTYPE_FCC | 1},  \
2453     {"$fcc2",   RTYPE_FCC | 2},  \
2454     {"$fcc3",   RTYPE_FCC | 3},  \
2455     {"$fcc4",   RTYPE_FCC | 4},  \
2456     {"$fcc5",   RTYPE_FCC | 5},  \
2457     {"$fcc6",   RTYPE_FCC | 6},  \
2458     {"$fcc7",   RTYPE_FCC | 7}
2459
2460 #define COPROC_CONDITION_CODE_NAMES         \
2461     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2462     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2463     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2464     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2465     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2466     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2467     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2468     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2469
2470 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2471     {"$a4",     RTYPE_GP | 8},  \
2472     {"$a5",     RTYPE_GP | 9},  \
2473     {"$a6",     RTYPE_GP | 10}, \
2474     {"$a7",     RTYPE_GP | 11}, \
2475     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2476     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2477     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2478     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2479     {"$t0",     RTYPE_GP | 12}, \
2480     {"$t1",     RTYPE_GP | 13}, \
2481     {"$t2",     RTYPE_GP | 14}, \
2482     {"$t3",     RTYPE_GP | 15}
2483
2484 #define O32_SYMBOLIC_REGISTER_NAMES \
2485     {"$t0",     RTYPE_GP | 8},  \
2486     {"$t1",     RTYPE_GP | 9},  \
2487     {"$t2",     RTYPE_GP | 10}, \
2488     {"$t3",     RTYPE_GP | 11}, \
2489     {"$t4",     RTYPE_GP | 12}, \
2490     {"$t5",     RTYPE_GP | 13}, \
2491     {"$t6",     RTYPE_GP | 14}, \
2492     {"$t7",     RTYPE_GP | 15}, \
2493     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2494     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2495     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2496     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */ 
2497
2498 /* Remaining symbolic register names */
2499 #define SYMBOLIC_REGISTER_NAMES \
2500     {"$zero",   RTYPE_GP | 0},  \
2501     {"$at",     RTYPE_GP | 1},  \
2502     {"$AT",     RTYPE_GP | 1},  \
2503     {"$v0",     RTYPE_GP | 2},  \
2504     {"$v1",     RTYPE_GP | 3},  \
2505     {"$a0",     RTYPE_GP | 4},  \
2506     {"$a1",     RTYPE_GP | 5},  \
2507     {"$a2",     RTYPE_GP | 6},  \
2508     {"$a3",     RTYPE_GP | 7},  \
2509     {"$s0",     RTYPE_GP | 16}, \
2510     {"$s1",     RTYPE_GP | 17}, \
2511     {"$s2",     RTYPE_GP | 18}, \
2512     {"$s3",     RTYPE_GP | 19}, \
2513     {"$s4",     RTYPE_GP | 20}, \
2514     {"$s5",     RTYPE_GP | 21}, \
2515     {"$s6",     RTYPE_GP | 22}, \
2516     {"$s7",     RTYPE_GP | 23}, \
2517     {"$t8",     RTYPE_GP | 24}, \
2518     {"$t9",     RTYPE_GP | 25}, \
2519     {"$k0",     RTYPE_GP | 26}, \
2520     {"$kt0",    RTYPE_GP | 26}, \
2521     {"$k1",     RTYPE_GP | 27}, \
2522     {"$kt1",    RTYPE_GP | 27}, \
2523     {"$gp",     RTYPE_GP | 28}, \
2524     {"$sp",     RTYPE_GP | 29}, \
2525     {"$s8",     RTYPE_GP | 30}, \
2526     {"$fp",     RTYPE_GP | 30}, \
2527     {"$ra",     RTYPE_GP | 31}
2528
2529 #define MIPS16_SPECIAL_REGISTER_NAMES \
2530     {"$pc",     RTYPE_PC | 0}
2531
2532 #define MDMX_VECTOR_REGISTER_NAMES \
2533     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2534     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2535     {"$v2",     RTYPE_VEC | 2},  \
2536     {"$v3",     RTYPE_VEC | 3},  \
2537     {"$v4",     RTYPE_VEC | 4},  \
2538     {"$v5",     RTYPE_VEC | 5},  \
2539     {"$v6",     RTYPE_VEC | 6},  \
2540     {"$v7",     RTYPE_VEC | 7},  \
2541     {"$v8",     RTYPE_VEC | 8},  \
2542     {"$v9",     RTYPE_VEC | 9},  \
2543     {"$v10",    RTYPE_VEC | 10}, \
2544     {"$v11",    RTYPE_VEC | 11}, \
2545     {"$v12",    RTYPE_VEC | 12}, \
2546     {"$v13",    RTYPE_VEC | 13}, \
2547     {"$v14",    RTYPE_VEC | 14}, \
2548     {"$v15",    RTYPE_VEC | 15}, \
2549     {"$v16",    RTYPE_VEC | 16}, \
2550     {"$v17",    RTYPE_VEC | 17}, \
2551     {"$v18",    RTYPE_VEC | 18}, \
2552     {"$v19",    RTYPE_VEC | 19}, \
2553     {"$v20",    RTYPE_VEC | 20}, \
2554     {"$v21",    RTYPE_VEC | 21}, \
2555     {"$v22",    RTYPE_VEC | 22}, \
2556     {"$v23",    RTYPE_VEC | 23}, \
2557     {"$v24",    RTYPE_VEC | 24}, \
2558     {"$v25",    RTYPE_VEC | 25}, \
2559     {"$v26",    RTYPE_VEC | 26}, \
2560     {"$v27",    RTYPE_VEC | 27}, \
2561     {"$v28",    RTYPE_VEC | 28}, \
2562     {"$v29",    RTYPE_VEC | 29}, \
2563     {"$v30",    RTYPE_VEC | 30}, \
2564     {"$v31",    RTYPE_VEC | 31}
2565
2566 #define R5900_I_NAMES \
2567     {"$I",      RTYPE_R5900_I | 0}
2568
2569 #define R5900_Q_NAMES \
2570     {"$Q",      RTYPE_R5900_Q | 0}
2571
2572 #define R5900_R_NAMES \
2573     {"$R",      RTYPE_R5900_R | 0}
2574
2575 #define R5900_ACC_NAMES \
2576     {"$ACC",    RTYPE_R5900_ACC | 0 }
2577
2578 #define MIPS_DSP_ACCUMULATOR_NAMES \
2579     {"$ac0",    RTYPE_ACC | 0}, \
2580     {"$ac1",    RTYPE_ACC | 1}, \
2581     {"$ac2",    RTYPE_ACC | 2}, \
2582     {"$ac3",    RTYPE_ACC | 3}
2583
2584 static const struct regname reg_names[] = {
2585   GENERIC_REGISTER_NUMBERS,
2586   FPU_REGISTER_NAMES,
2587   FPU_CONDITION_CODE_NAMES,
2588   COPROC_CONDITION_CODE_NAMES,
2589
2590   /* The $txx registers depends on the abi,
2591      these will be added later into the symbol table from
2592      one of the tables below once mips_abi is set after 
2593      parsing of arguments from the command line. */
2594   SYMBOLIC_REGISTER_NAMES,
2595
2596   MIPS16_SPECIAL_REGISTER_NAMES,
2597   MDMX_VECTOR_REGISTER_NAMES,
2598   R5900_I_NAMES,
2599   R5900_Q_NAMES,
2600   R5900_R_NAMES,
2601   R5900_ACC_NAMES,
2602   MIPS_DSP_ACCUMULATOR_NAMES,
2603   {0, 0}
2604 };
2605
2606 static const struct regname reg_names_o32[] = {
2607   O32_SYMBOLIC_REGISTER_NAMES,
2608   {0, 0}
2609 };
2610
2611 static const struct regname reg_names_n32n64[] = {
2612   N32N64_SYMBOLIC_REGISTER_NAMES,
2613   {0, 0}
2614 };
2615
2616 /* Register symbols $v0 and $v1 map to GPRs 2 and 3, but they can also be
2617    interpreted as vector registers 0 and 1.  If SYMVAL is the value of one
2618    of these register symbols, return the associated vector register,
2619    otherwise return SYMVAL itself.  */
2620
2621 static unsigned int
2622 mips_prefer_vec_regno (unsigned int symval)
2623 {
2624   if ((symval & -2) == (RTYPE_GP | 2))
2625     return RTYPE_VEC | (symval & 1);
2626   return symval;
2627 }
2628
2629 /* Return true if string [S, E) is a valid register name, storing its
2630    symbol value in *SYMVAL_PTR if so.  */
2631
2632 static bfd_boolean
2633 mips_parse_register_1 (char *s, char *e, unsigned int *symval_ptr)
2634 {
2635   char save_c;
2636   symbolS *symbol;
2637
2638   /* Terminate name.  */
2639   save_c = *e;
2640   *e = '\0';
2641
2642   /* Look up the name.  */
2643   symbol = symbol_find (s);
2644   *e = save_c;
2645
2646   if (!symbol || S_GET_SEGMENT (symbol) != reg_section)
2647     return FALSE;
2648
2649   *symval_ptr = S_GET_VALUE (symbol);
2650   return TRUE;
2651 }
2652
2653 /* Return true if the string at *SPTR is a valid register name.  Allow it
2654    to have a VU0-style channel suffix of the form x?y?z?w? if CHANNELS_PTR
2655    is nonnull.
2656
2657    When returning true, move *SPTR past the register, store the
2658    register's symbol value in *SYMVAL_PTR and the channel mask in
2659    *CHANNELS_PTR (if nonnull).  The symbol value includes the register
2660    number (RNUM_MASK) and register type (RTYPE_MASK).  The channel mask
2661    is a 4-bit value of the form XYZW and is 0 if no suffix was given.  */
2662
2663 static bfd_boolean
2664 mips_parse_register (char **sptr, unsigned int *symval_ptr,
2665                      unsigned int *channels_ptr)
2666 {
2667   char *s, *e, *m;
2668   const char *q;
2669   unsigned int channels, symval, bit;
2670
2671   /* Find end of name.  */
2672   s = e = *sptr;
2673   if (is_name_beginner (*e))
2674     ++e;
2675   while (is_part_of_name (*e))
2676     ++e;
2677
2678   channels = 0;
2679   if (!mips_parse_register_1 (s, e, &symval))
2680     {
2681       if (!channels_ptr)
2682         return FALSE;
2683
2684       /* Eat characters from the end of the string that are valid
2685          channel suffixes.  The preceding register must be $ACC or
2686          end with a digit, so there is no ambiguity.  */
2687       bit = 1;
2688       m = e;
2689       for (q = "wzyx"; *q; q++, bit <<= 1)
2690         if (m > s && m[-1] == *q)
2691           {
2692             --m;
2693             channels |= bit;
2694           }
2695
2696       if (channels == 0
2697           || !mips_parse_register_1 (s, m, &symval)
2698           || (symval & (RTYPE_VI | RTYPE_VF | RTYPE_R5900_ACC)) == 0)
2699         return FALSE;
2700     }
2701
2702   *sptr = e;
2703   *symval_ptr = symval;
2704   if (channels_ptr)
2705     *channels_ptr = channels;
2706   return TRUE;
2707 }
2708
2709 /* Check if SPTR points at a valid register specifier according to TYPES.
2710    If so, then return 1, advance S to consume the specifier and store
2711    the register's number in REGNOP, otherwise return 0.  */
2712
2713 static int
2714 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2715 {
2716   unsigned int regno;
2717
2718   if (mips_parse_register (s, &regno, NULL))
2719     {
2720       if (types & RTYPE_VEC)
2721         regno = mips_prefer_vec_regno (regno);
2722       if (regno & types)
2723         regno &= RNUM_MASK;
2724       else
2725         regno = ~0;
2726     }
2727   else
2728     {
2729       if (types & RWARN)
2730         as_warn (_("unrecognized register name `%s'"), *s);
2731       regno = ~0;
2732     }
2733   if (regnop)
2734     *regnop = regno;
2735   return regno <= RNUM_MASK;
2736 }
2737
2738 /* Parse a VU0 "x?y?z?w?" channel mask at S and store the associated
2739    mask in *CHANNELS.  Return a pointer to the first unconsumed character.  */
2740
2741 static char *
2742 mips_parse_vu0_channels (char *s, unsigned int *channels)
2743 {
2744   unsigned int i;
2745
2746   *channels = 0;
2747   for (i = 0; i < 4; i++)
2748     if (*s == "xyzw"[i])
2749       {
2750         *channels |= 1 << (3 - i);
2751         ++s;
2752       }
2753   return s;
2754 }
2755
2756 /* Token types for parsed operand lists.  */
2757 enum mips_operand_token_type {
2758   /* A plain register, e.g. $f2.  */
2759   OT_REG,
2760
2761   /* A 4-bit XYZW channel mask.  */
2762   OT_CHANNELS,
2763
2764   /* A constant vector index, e.g. [1].  */
2765   OT_INTEGER_INDEX,
2766
2767   /* A register vector index, e.g. [$2].  */
2768   OT_REG_INDEX,
2769
2770   /* A continuous range of registers, e.g. $s0-$s4.  */
2771   OT_REG_RANGE,
2772
2773   /* A (possibly relocated) expression.  */
2774   OT_INTEGER,
2775
2776   /* A floating-point value.  */
2777   OT_FLOAT,
2778
2779   /* A single character.  This can be '(', ')' or ',', but '(' only appears
2780      before OT_REGs.  */
2781   OT_CHAR,
2782
2783   /* A doubled character, either "--" or "++".  */
2784   OT_DOUBLE_CHAR,
2785
2786   /* The end of the operand list.  */
2787   OT_END
2788 };
2789
2790 /* A parsed operand token.  */
2791 struct mips_operand_token
2792 {
2793   /* The type of token.  */
2794   enum mips_operand_token_type type;
2795   union
2796   {
2797     /* The register symbol value for an OT_REG or OT_REG_INDEX.  */
2798     unsigned int regno;
2799
2800     /* The 4-bit channel mask for an OT_CHANNEL_SUFFIX.  */
2801     unsigned int channels;
2802
2803     /* The integer value of an OT_INTEGER_INDEX.  */
2804     addressT index;
2805
2806     /* The two register symbol values involved in an OT_REG_RANGE.  */
2807     struct {
2808       unsigned int regno1;
2809       unsigned int regno2;
2810     } reg_range;
2811
2812     /* The value of an OT_INTEGER.  The value is represented as an
2813        expression and the relocation operators that were applied to
2814        that expression.  The reloc entries are BFD_RELOC_UNUSED if no
2815        relocation operators were used.  */
2816     struct {
2817       expressionS value;
2818       bfd_reloc_code_real_type relocs[3];
2819     } integer;
2820
2821     /* The binary data for an OT_FLOAT constant, and the number of bytes
2822        in the constant.  */
2823     struct {
2824       unsigned char data[8];
2825       int length;
2826     } flt;
2827
2828     /* The character represented by an OT_CHAR or OT_DOUBLE_CHAR.  */
2829     char ch;
2830   } u;
2831 };
2832
2833 /* An obstack used to construct lists of mips_operand_tokens.  */
2834 static struct obstack mips_operand_tokens;
2835
2836 /* Give TOKEN type TYPE and add it to mips_operand_tokens.  */
2837
2838 static void
2839 mips_add_token (struct mips_operand_token *token,
2840                 enum mips_operand_token_type type)
2841 {
2842   token->type = type;
2843   obstack_grow (&mips_operand_tokens, token, sizeof (*token));
2844 }
2845
2846 /* Check whether S is '(' followed by a register name.  Add OT_CHAR
2847    and OT_REG tokens for them if so, and return a pointer to the first
2848    unconsumed character.  Return null otherwise.  */
2849
2850 static char *
2851 mips_parse_base_start (char *s)
2852 {
2853   struct mips_operand_token token;
2854   unsigned int regno, channels;
2855   bfd_boolean decrement_p;
2856
2857   if (*s != '(')
2858     return 0;
2859
2860   ++s;
2861   SKIP_SPACE_TABS (s);
2862
2863   /* Only match "--" as part of a base expression.  In other contexts "--X"
2864      is a double negative.  */
2865   decrement_p = (s[0] == '-' && s[1] == '-');
2866   if (decrement_p)
2867     {
2868       s += 2;
2869       SKIP_SPACE_TABS (s);
2870     }
2871
2872   /* Allow a channel specifier because that leads to better error messages
2873      than treating something like "$vf0x++" as an expression.  */
2874   if (!mips_parse_register (&s, &regno, &channels))
2875     return 0;
2876
2877   token.u.ch = '(';
2878   mips_add_token (&token, OT_CHAR);
2879
2880   if (decrement_p)
2881     {
2882       token.u.ch = '-';
2883       mips_add_token (&token, OT_DOUBLE_CHAR);
2884     }
2885
2886   token.u.regno = regno;
2887   mips_add_token (&token, OT_REG);
2888
2889   if (channels)
2890     {
2891       token.u.channels = channels;
2892       mips_add_token (&token, OT_CHANNELS);
2893     }
2894
2895   /* For consistency, only match "++" as part of base expressions too.  */
2896   SKIP_SPACE_TABS (s);
2897   if (s[0] == '+' && s[1] == '+')
2898     {
2899       s += 2;
2900       token.u.ch = '+';
2901       mips_add_token (&token, OT_DOUBLE_CHAR);
2902     }
2903
2904   return s;
2905 }
2906
2907 /* Parse one or more tokens from S.  Return a pointer to the first
2908    unconsumed character on success.  Return null if an error was found
2909    and store the error text in insn_error.  FLOAT_FORMAT is as for
2910    mips_parse_arguments.  */
2911
2912 static char *
2913 mips_parse_argument_token (char *s, char float_format)
2914 {
2915   char *end, *save_in, *err;
2916   unsigned int regno1, regno2, channels;
2917   struct mips_operand_token token;
2918
2919   /* First look for "($reg", since we want to treat that as an
2920      OT_CHAR and OT_REG rather than an expression.  */
2921   end = mips_parse_base_start (s);
2922   if (end)
2923     return end;
2924
2925   /* Handle other characters that end up as OT_CHARs.  */
2926   if (*s == ')' || *s == ',')
2927     {
2928       token.u.ch = *s;
2929       mips_add_token (&token, OT_CHAR);
2930       ++s;
2931       return s;
2932     }
2933
2934   /* Handle tokens that start with a register.  */
2935   if (mips_parse_register (&s, &regno1, &channels))
2936     {
2937       if (channels)
2938         {
2939           /* A register and a VU0 channel suffix.  */
2940           token.u.regno = regno1;
2941           mips_add_token (&token, OT_REG);
2942
2943           token.u.channels = channels;
2944           mips_add_token (&token, OT_CHANNELS);
2945           return s;
2946         }
2947
2948       SKIP_SPACE_TABS (s);
2949       if (*s == '-')
2950         {
2951           /* A register range.  */
2952           ++s;
2953           SKIP_SPACE_TABS (s);
2954           if (!mips_parse_register (&s, &regno2, NULL))
2955             {
2956               set_insn_error (0, _("invalid register range"));
2957               return 0;
2958             }
2959
2960           token.u.reg_range.regno1 = regno1;
2961           token.u.reg_range.regno2 = regno2;
2962           mips_add_token (&token, OT_REG_RANGE);
2963           return s;
2964         }
2965
2966       /* Add the register itself.  */
2967       token.u.regno = regno1;
2968       mips_add_token (&token, OT_REG);
2969
2970       /* Check for a vector index.  */
2971       if (*s == '[')
2972         {
2973           ++s;
2974           SKIP_SPACE_TABS (s);
2975           if (mips_parse_register (&s, &token.u.regno, NULL))
2976             mips_add_token (&token, OT_REG_INDEX);
2977           else
2978             {
2979               expressionS element;
2980
2981               my_getExpression (&element, s);
2982               if (element.X_op != O_constant)
2983                 {
2984                   set_insn_error (0, _("vector element must be constant"));
2985                   return 0;
2986                 }
2987               s = expr_end;
2988               token.u.index = element.X_add_number;
2989               mips_add_token (&token, OT_INTEGER_INDEX);
2990             }
2991           SKIP_SPACE_TABS (s);
2992           if (*s != ']')
2993             {
2994               set_insn_error (0, _("missing `]'"));
2995               return 0;
2996             }
2997           ++s;
2998         }
2999       return s;
3000     }
3001
3002   if (float_format)
3003     {
3004       /* First try to treat expressions as floats.  */
3005       save_in = input_line_pointer;
3006       input_line_pointer = s;
3007       err = md_atof (float_format, (char *) token.u.flt.data,
3008                      &token.u.flt.length);
3009       end = input_line_pointer;
3010       input_line_pointer = save_in;
3011       if (err && *err)
3012         {
3013           set_insn_error (0, err);
3014           return 0;
3015         }
3016       if (s != end)
3017         {
3018           mips_add_token (&token, OT_FLOAT);
3019           return end;
3020         }
3021     }
3022
3023   /* Treat everything else as an integer expression.  */
3024   token.u.integer.relocs[0] = BFD_RELOC_UNUSED;
3025   token.u.integer.relocs[1] = BFD_RELOC_UNUSED;
3026   token.u.integer.relocs[2] = BFD_RELOC_UNUSED;
3027   my_getSmallExpression (&token.u.integer.value, token.u.integer.relocs, s);
3028   s = expr_end;
3029   mips_add_token (&token, OT_INTEGER);
3030   return s;
3031 }
3032
3033 /* S points to the operand list for an instruction.  FLOAT_FORMAT is 'f'
3034    if expressions should be treated as 32-bit floating-point constants,
3035    'd' if they should be treated as 64-bit floating-point constants,
3036    or 0 if they should be treated as integer expressions (the usual case).
3037
3038    Return a list of tokens on success, otherwise return 0.  The caller
3039    must obstack_free the list after use.  */
3040
3041 static struct mips_operand_token *
3042 mips_parse_arguments (char *s, char float_format)
3043 {
3044   struct mips_operand_token token;
3045
3046   SKIP_SPACE_TABS (s);
3047   while (*s)
3048     {
3049       s = mips_parse_argument_token (s, float_format);
3050       if (!s)
3051         {
3052           obstack_free (&mips_operand_tokens,
3053                         obstack_finish (&mips_operand_tokens));
3054           return 0;
3055         }
3056       SKIP_SPACE_TABS (s);
3057     }
3058   mips_add_token (&token, OT_END);
3059   return (struct mips_operand_token *) obstack_finish (&mips_operand_tokens);
3060 }
3061
3062 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
3063    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
3064
3065 static bfd_boolean
3066 is_opcode_valid (const struct mips_opcode *mo)
3067 {
3068   int isa = mips_opts.isa;
3069   int ase = mips_opts.ase;
3070   int fp_s, fp_d;
3071   unsigned int i;
3072
3073   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
3074     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
3075       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
3076         ase |= mips_ases[i].flags64;
3077
3078   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
3079     return FALSE;
3080
3081   /* Check whether the instruction or macro requires single-precision or
3082      double-precision floating-point support.  Note that this information is
3083      stored differently in the opcode table for insns and macros.  */
3084   if (mo->pinfo == INSN_MACRO)
3085     {
3086       fp_s = mo->pinfo2 & INSN2_M_FP_S;
3087       fp_d = mo->pinfo2 & INSN2_M_FP_D;
3088     }
3089   else
3090     {
3091       fp_s = mo->pinfo & FP_S;
3092       fp_d = mo->pinfo & FP_D;
3093     }
3094
3095   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
3096     return FALSE;
3097
3098   if (fp_s && mips_opts.soft_float)
3099     return FALSE;
3100
3101   return TRUE;
3102 }
3103
3104 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
3105    selected ISA and architecture.  */
3106
3107 static bfd_boolean
3108 is_opcode_valid_16 (const struct mips_opcode *mo)
3109 {
3110   return opcode_is_member (mo, mips_opts.isa, 0, mips_opts.arch);
3111 }
3112
3113 /* Return TRUE if the size of the microMIPS opcode MO matches one
3114    explicitly requested.  Always TRUE in the standard MIPS mode.  */
3115
3116 static bfd_boolean
3117 is_size_valid (const struct mips_opcode *mo)
3118 {
3119   if (!mips_opts.micromips)
3120     return TRUE;
3121
3122   if (mips_opts.insn32)
3123     {
3124       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
3125         return FALSE;
3126       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
3127         return FALSE;
3128     }
3129   if (!forced_insn_length)
3130     return TRUE;
3131   if (mo->pinfo == INSN_MACRO)
3132     return FALSE;
3133   return forced_insn_length == micromips_insn_length (mo);
3134 }
3135
3136 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
3137    of the preceding instruction.  Always TRUE in the standard MIPS mode.
3138
3139    We don't accept macros in 16-bit delay slots to avoid a case where
3140    a macro expansion fails because it relies on a preceding 32-bit real
3141    instruction to have matched and does not handle the operands correctly.
3142    The only macros that may expand to 16-bit instructions are JAL that
3143    cannot be placed in a delay slot anyway, and corner cases of BALIGN
3144    and BGT (that likewise cannot be placed in a delay slot) that decay to
3145    a NOP.  In all these cases the macros precede any corresponding real
3146    instruction definitions in the opcode table, so they will match in the
3147    second pass where the size of the delay slot is ignored and therefore
3148    produce correct code.  */
3149
3150 static bfd_boolean
3151 is_delay_slot_valid (const struct mips_opcode *mo)
3152 {
3153   if (!mips_opts.micromips)
3154     return TRUE;
3155
3156   if (mo->pinfo == INSN_MACRO)
3157     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
3158   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
3159       && micromips_insn_length (mo) != 4)
3160     return FALSE;
3161   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
3162       && micromips_insn_length (mo) != 2)
3163     return FALSE;
3164
3165   return TRUE;
3166 }
3167
3168 /* For consistency checking, verify that all bits of OPCODE are specified
3169    either by the match/mask part of the instruction definition, or by the
3170    operand list.  Also build up a list of operands in OPERANDS.
3171
3172    INSN_BITS says which bits of the instruction are significant.
3173    If OPCODE is a standard or microMIPS instruction, DECODE_OPERAND
3174    provides the mips_operand description of each operand.  DECODE_OPERAND
3175    is null for MIPS16 instructions.  */
3176
3177 static int
3178 validate_mips_insn (const struct mips_opcode *opcode,
3179                     unsigned long insn_bits,
3180                     const struct mips_operand *(*decode_operand) (const char *),
3181                     struct mips_operand_array *operands)
3182 {
3183   const char *s;
3184   unsigned long used_bits, doubled, undefined, opno, mask;
3185   const struct mips_operand *operand;
3186
3187   mask = (opcode->pinfo == INSN_MACRO ? 0 : opcode->mask);
3188   if ((mask & opcode->match) != opcode->match)
3189     {
3190       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
3191               opcode->name, opcode->args);
3192       return 0;
3193     }
3194   used_bits = 0;
3195   opno = 0;
3196   if (opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX)
3197     used_bits = mips_insert_operand (&mips_vu0_channel_mask, used_bits, -1);
3198   for (s = opcode->args; *s; ++s)
3199     switch (*s)
3200       {
3201       case ',':
3202       case '(':
3203       case ')':
3204         break;
3205
3206       case '#':
3207         s++;
3208         break;
3209
3210       default:
3211         if (!decode_operand)
3212           operand = decode_mips16_operand (*s, FALSE);
3213         else
3214           operand = decode_operand (s);
3215         if (!operand && opcode->pinfo != INSN_MACRO)
3216           {
3217             as_bad (_("internal: unknown operand type: %s %s"),
3218                     opcode->name, opcode->args);
3219             return 0;
3220           }
3221         gas_assert (opno < MAX_OPERANDS);
3222         operands->operand[opno] = operand;
3223         if (operand && operand->type != OP_VU0_MATCH_SUFFIX)
3224           {
3225             used_bits = mips_insert_operand (operand, used_bits, -1);
3226             if (operand->type == OP_MDMX_IMM_REG)
3227               /* Bit 5 is the format selector (OB vs QH).  The opcode table
3228                  has separate entries for each format.  */
3229               used_bits &= ~(1 << (operand->lsb + 5));
3230             if (operand->type == OP_ENTRY_EXIT_LIST)
3231               used_bits &= ~(mask & 0x700);
3232           }
3233         /* Skip prefix characters.  */
3234         if (decode_operand && (*s == '+' || *s == 'm'))
3235           ++s;
3236         opno += 1;
3237         break;
3238       }
3239   doubled = used_bits & mask & insn_bits;
3240   if (doubled)
3241     {
3242       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
3243                 " %s %s"), doubled, opcode->name, opcode->args);
3244       return 0;
3245     }
3246   used_bits |= mask;
3247   undefined = ~used_bits & insn_bits;
3248   if (opcode->pinfo != INSN_MACRO && undefined)
3249     {
3250       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
3251               undefined, opcode->name, opcode->args);
3252       return 0;
3253     }
3254   used_bits &= ~insn_bits;
3255   if (used_bits)
3256     {
3257       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
3258               used_bits, opcode->name, opcode->args);
3259       return 0;
3260     }
3261   return 1;
3262 }
3263
3264 /* The MIPS16 version of validate_mips_insn.  */
3265
3266 static int
3267 validate_mips16_insn (const struct mips_opcode *opcode,
3268                       struct mips_operand_array *operands)
3269 {
3270   if (opcode->args[0] == 'a' || opcode->args[0] == 'i')
3271     {
3272       /* In this case OPCODE defines the first 16 bits in a 32-bit jump
3273          instruction.  Use TMP to describe the full instruction.  */
3274       struct mips_opcode tmp;
3275
3276       tmp = *opcode;
3277       tmp.match <<= 16;
3278       tmp.mask <<= 16;
3279       return validate_mips_insn (&tmp, 0xffffffff, 0, operands);
3280     }
3281   return validate_mips_insn (opcode, 0xffff, 0, operands);
3282 }
3283
3284 /* The microMIPS version of validate_mips_insn.  */
3285
3286 static int
3287 validate_micromips_insn (const struct mips_opcode *opc,
3288                          struct mips_operand_array *operands)
3289 {
3290   unsigned long insn_bits;
3291   unsigned long major;
3292   unsigned int length;
3293
3294   if (opc->pinfo == INSN_MACRO)
3295     return validate_mips_insn (opc, 0xffffffff, decode_micromips_operand,
3296                                operands);
3297
3298   length = micromips_insn_length (opc);
3299   if (length != 2 && length != 4)
3300     {
3301       as_bad (_("internal error: bad microMIPS opcode (incorrect length: %u): "
3302                 "%s %s"), length, opc->name, opc->args);
3303       return 0;
3304     }
3305   major = opc->match >> (10 + 8 * (length - 2));
3306   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
3307       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
3308     {
3309       as_bad (_("internal error: bad microMIPS opcode "
3310                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
3311       return 0;
3312     }
3313
3314   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
3315   insn_bits = 1 << 4 * length;
3316   insn_bits <<= 4 * length;
3317   insn_bits -= 1;
3318   return validate_mips_insn (opc, insn_bits, decode_micromips_operand,
3319                              operands);
3320 }
3321
3322 /* This function is called once, at assembler startup time.  It should set up
3323    all the tables, etc. that the MD part of the assembler will need.  */
3324
3325 void
3326 md_begin (void)
3327 {
3328   const char *retval = NULL;
3329   int i = 0;
3330   int broken = 0;
3331
3332   if (mips_pic != NO_PIC)
3333     {
3334       if (g_switch_seen && g_switch_value != 0)
3335         as_bad (_("-G may not be used in position-independent code"));
3336       g_switch_value = 0;
3337     }
3338
3339   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_arch))
3340     as_warn (_("could not set architecture and machine"));
3341
3342   op_hash = hash_new ();
3343
3344   mips_operands = XCNEWVEC (struct mips_operand_array, NUMOPCODES);
3345   for (i = 0; i < NUMOPCODES;)
3346     {
3347       const char *name = mips_opcodes[i].name;
3348
3349       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
3350       if (retval != NULL)
3351         {
3352           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
3353                    mips_opcodes[i].name, retval);
3354           /* Probably a memory allocation problem?  Give up now.  */
3355           as_fatal (_("broken assembler, no assembly attempted"));
3356         }
3357       do
3358         {
3359           if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
3360                                    decode_mips_operand, &mips_operands[i]))
3361             broken = 1;
3362           if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3363             {
3364               create_insn (&nop_insn, mips_opcodes + i);
3365               if (mips_fix_loongson2f_nop)
3366                 nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
3367               nop_insn.fixed_p = 1;
3368             }
3369           ++i;
3370         }
3371       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
3372     }
3373
3374   mips16_op_hash = hash_new ();
3375   mips16_operands = XCNEWVEC (struct mips_operand_array,
3376                               bfd_mips16_num_opcodes);
3377
3378   i = 0;
3379   while (i < bfd_mips16_num_opcodes)
3380     {
3381       const char *name = mips16_opcodes[i].name;
3382
3383       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
3384       if (retval != NULL)
3385         as_fatal (_("internal: can't hash `%s': %s"),
3386                   mips16_opcodes[i].name, retval);
3387       do
3388         {
3389           if (!validate_mips16_insn (&mips16_opcodes[i], &mips16_operands[i]))
3390             broken = 1;
3391           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3392             {
3393               create_insn (&mips16_nop_insn, mips16_opcodes + i);
3394               mips16_nop_insn.fixed_p = 1;
3395             }
3396           ++i;
3397         }
3398       while (i < bfd_mips16_num_opcodes
3399              && strcmp (mips16_opcodes[i].name, name) == 0);
3400     }
3401
3402   micromips_op_hash = hash_new ();
3403   micromips_operands = XCNEWVEC (struct mips_operand_array,
3404                                  bfd_micromips_num_opcodes);
3405
3406   i = 0;
3407   while (i < bfd_micromips_num_opcodes)
3408     {
3409       const char *name = micromips_opcodes[i].name;
3410
3411       retval = hash_insert (micromips_op_hash, name,
3412                             (void *) &micromips_opcodes[i]);
3413       if (retval != NULL)
3414         as_fatal (_("internal: can't hash `%s': %s"),
3415                   micromips_opcodes[i].name, retval);
3416       do
3417         {
3418           struct mips_cl_insn *micromips_nop_insn;
3419
3420           if (!validate_micromips_insn (&micromips_opcodes[i],
3421                                         &micromips_operands[i]))
3422             broken = 1;
3423
3424           if (micromips_opcodes[i].pinfo != INSN_MACRO)
3425             {
3426               if (micromips_insn_length (micromips_opcodes + i) == 2)
3427                 micromips_nop_insn = &micromips_nop16_insn;
3428               else if (micromips_insn_length (micromips_opcodes + i) == 4)
3429                 micromips_nop_insn = &micromips_nop32_insn;
3430               else
3431                 continue;
3432
3433               if (micromips_nop_insn->insn_mo == NULL
3434                   && strcmp (name, "nop") == 0)
3435                 {
3436                   create_insn (micromips_nop_insn, micromips_opcodes + i);
3437                   micromips_nop_insn->fixed_p = 1;
3438                 }
3439             }
3440         }
3441       while (++i < bfd_micromips_num_opcodes
3442              && strcmp (micromips_opcodes[i].name, name) == 0);
3443     }
3444
3445   if (broken)
3446     as_fatal (_("broken assembler, no assembly attempted"));
3447
3448   /* We add all the general register names to the symbol table.  This
3449      helps us detect invalid uses of them.  */
3450   for (i = 0; reg_names[i].name; i++) 
3451     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
3452                                      reg_names[i].num, /* & RNUM_MASK, */
3453                                      &zero_address_frag));
3454   if (HAVE_NEWABI)
3455     for (i = 0; reg_names_n32n64[i].name; i++) 
3456       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
3457                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
3458                                        &zero_address_frag));
3459   else
3460     for (i = 0; reg_names_o32[i].name; i++) 
3461       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
3462                                        reg_names_o32[i].num, /* & RNUM_MASK, */
3463                                        &zero_address_frag));
3464
3465   for (i = 0; i < 32; i++)
3466     {
3467       char regname[7];
3468
3469       /* R5900 VU0 floating-point register.  */
3470       regname[sizeof (rename) - 1] = 0;
3471       snprintf (regname, sizeof (regname) - 1, "$vf%d", i);
3472       symbol_table_insert (symbol_new (regname, reg_section,
3473                                        RTYPE_VF | i, &zero_address_frag));
3474
3475       /* R5900 VU0 integer register.  */
3476       snprintf (regname, sizeof (regname) - 1, "$vi%d", i);
3477       symbol_table_insert (symbol_new (regname, reg_section,
3478                                        RTYPE_VI | i, &zero_address_frag));
3479
3480       /* MSA register.  */
3481       snprintf (regname, sizeof (regname) - 1, "$w%d", i);
3482       symbol_table_insert (symbol_new (regname, reg_section,
3483                                        RTYPE_MSA | i, &zero_address_frag));
3484     }
3485
3486   obstack_init (&mips_operand_tokens);
3487
3488   mips_no_prev_insn ();
3489
3490   mips_gprmask = 0;
3491   mips_cprmask[0] = 0;
3492   mips_cprmask[1] = 0;
3493   mips_cprmask[2] = 0;
3494   mips_cprmask[3] = 0;
3495
3496   /* set the default alignment for the text section (2**2) */
3497   record_alignment (text_section, 2);
3498
3499   bfd_set_gp_size (stdoutput, g_switch_value);
3500
3501   /* On a native system other than VxWorks, sections must be aligned
3502      to 16 byte boundaries.  When configured for an embedded ELF
3503      target, we don't bother.  */
3504   if (strncmp (TARGET_OS, "elf", 3) != 0
3505       && strncmp (TARGET_OS, "vxworks", 7) != 0)
3506     {
3507       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
3508       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
3509       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
3510     }
3511
3512   /* Create a .reginfo section for register masks and a .mdebug
3513      section for debugging information.  */
3514   {
3515     segT seg;
3516     subsegT subseg;
3517     flagword flags;
3518     segT sec;
3519
3520     seg = now_seg;
3521     subseg = now_subseg;
3522
3523     /* The ABI says this section should be loaded so that the
3524        running program can access it.  However, we don't load it
3525        if we are configured for an embedded target */
3526     flags = SEC_READONLY | SEC_DATA;
3527     if (strncmp (TARGET_OS, "elf", 3) != 0)
3528       flags |= SEC_ALLOC | SEC_LOAD;
3529
3530     if (mips_abi != N64_ABI)
3531       {
3532         sec = subseg_new (".reginfo", (subsegT) 0);
3533
3534         bfd_set_section_flags (stdoutput, sec, flags);
3535         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
3536
3537         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
3538       }
3539     else
3540       {
3541         /* The 64-bit ABI uses a .MIPS.options section rather than
3542            .reginfo section.  */
3543         sec = subseg_new (".MIPS.options", (subsegT) 0);
3544         bfd_set_section_flags (stdoutput, sec, flags);
3545         bfd_set_section_alignment (stdoutput, sec, 3);
3546
3547         /* Set up the option header.  */
3548         {
3549           Elf_Internal_Options opthdr;
3550           char *f;
3551
3552           opthdr.kind = ODK_REGINFO;
3553           opthdr.size = (sizeof (Elf_External_Options)
3554                          + sizeof (Elf64_External_RegInfo));
3555           opthdr.section = 0;
3556           opthdr.info = 0;
3557           f = frag_more (sizeof (Elf_External_Options));
3558           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
3559                                          (Elf_External_Options *) f);
3560
3561           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
3562         }
3563       }
3564
3565     if (ECOFF_DEBUGGING)
3566       {
3567         sec = subseg_new (".mdebug", (subsegT) 0);
3568         (void) bfd_set_section_flags (stdoutput, sec,
3569                                       SEC_HAS_CONTENTS | SEC_READONLY);
3570         (void) bfd_set_section_alignment (stdoutput, sec, 2);
3571       }
3572     else if (mips_flag_pdr)
3573       {
3574         pdr_seg = subseg_new (".pdr", (subsegT) 0);
3575         (void) bfd_set_section_flags (stdoutput, pdr_seg,
3576                                       SEC_READONLY | SEC_RELOC
3577                                       | SEC_DEBUGGING);
3578         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
3579       }
3580
3581     subseg_set (seg, subseg);
3582   }
3583
3584   if (! ECOFF_DEBUGGING)
3585     md_obj_begin ();
3586
3587   if (mips_fix_vr4120)
3588     init_vr4120_conflicts ();
3589 }
3590
3591 void
3592 md_mips_end (void)
3593 {
3594   mips_emit_delays ();
3595   if (! ECOFF_DEBUGGING)
3596     md_obj_end ();
3597 }
3598
3599 void
3600 md_assemble (char *str)
3601 {
3602   struct mips_cl_insn insn;
3603   bfd_reloc_code_real_type unused_reloc[3]
3604     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
3605
3606   imm_expr.X_op = O_absent;
3607   offset_expr.X_op = O_absent;
3608   offset_reloc[0] = BFD_RELOC_UNUSED;
3609   offset_reloc[1] = BFD_RELOC_UNUSED;
3610   offset_reloc[2] = BFD_RELOC_UNUSED;
3611
3612   mips_mark_labels ();
3613   mips_assembling_insn = TRUE;
3614   clear_insn_error ();
3615
3616   if (mips_opts.mips16)
3617     mips16_ip (str, &insn);
3618   else
3619     {
3620       mips_ip (str, &insn);
3621       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
3622             str, insn.insn_opcode));
3623     }
3624
3625   if (insn_error.msg)
3626     report_insn_error (str);
3627   else if (insn.insn_mo->pinfo == INSN_MACRO)
3628     {
3629       macro_start ();
3630       if (mips_opts.mips16)
3631         mips16_macro (&insn);
3632       else
3633         macro (&insn, str);
3634       macro_end ();
3635     }
3636   else
3637     {
3638       if (offset_expr.X_op != O_absent)
3639         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
3640       else
3641         append_insn (&insn, NULL, unused_reloc, FALSE);
3642     }
3643
3644   mips_assembling_insn = FALSE;
3645 }
3646
3647 /* Convenience functions for abstracting away the differences between
3648    MIPS16 and non-MIPS16 relocations.  */
3649
3650 static inline bfd_boolean
3651 mips16_reloc_p (bfd_reloc_code_real_type reloc)
3652 {
3653   switch (reloc)
3654     {
3655     case BFD_RELOC_MIPS16_JMP:
3656     case BFD_RELOC_MIPS16_GPREL:
3657     case BFD_RELOC_MIPS16_GOT16:
3658     case BFD_RELOC_MIPS16_CALL16:
3659     case BFD_RELOC_MIPS16_HI16_S:
3660     case BFD_RELOC_MIPS16_HI16:
3661     case BFD_RELOC_MIPS16_LO16:
3662       return TRUE;
3663
3664     default:
3665       return FALSE;
3666     }
3667 }
3668
3669 static inline bfd_boolean
3670 micromips_reloc_p (bfd_reloc_code_real_type reloc)
3671 {
3672   switch (reloc)
3673     {
3674     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3675     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3676     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3677     case BFD_RELOC_MICROMIPS_GPREL16:
3678     case BFD_RELOC_MICROMIPS_JMP:
3679     case BFD_RELOC_MICROMIPS_HI16:
3680     case BFD_RELOC_MICROMIPS_HI16_S:
3681     case BFD_RELOC_MICROMIPS_LO16:
3682     case BFD_RELOC_MICROMIPS_LITERAL:
3683     case BFD_RELOC_MICROMIPS_GOT16:
3684     case BFD_RELOC_MICROMIPS_CALL16:
3685     case BFD_RELOC_MICROMIPS_GOT_HI16:
3686     case BFD_RELOC_MICROMIPS_GOT_LO16:
3687     case BFD_RELOC_MICROMIPS_CALL_HI16:
3688     case BFD_RELOC_MICROMIPS_CALL_LO16:
3689     case BFD_RELOC_MICROMIPS_SUB:
3690     case BFD_RELOC_MICROMIPS_GOT_PAGE:
3691     case BFD_RELOC_MICROMIPS_GOT_OFST:
3692     case BFD_RELOC_MICROMIPS_GOT_DISP:
3693     case BFD_RELOC_MICROMIPS_HIGHEST:
3694     case BFD_RELOC_MICROMIPS_HIGHER:
3695     case BFD_RELOC_MICROMIPS_SCN_DISP:
3696     case BFD_RELOC_MICROMIPS_JALR:
3697       return TRUE;
3698
3699     default:
3700       return FALSE;
3701     }
3702 }
3703
3704 static inline bfd_boolean
3705 jmp_reloc_p (bfd_reloc_code_real_type reloc)
3706 {
3707   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
3708 }
3709
3710 static inline bfd_boolean
3711 got16_reloc_p (bfd_reloc_code_real_type reloc)
3712 {
3713   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
3714           || reloc == BFD_RELOC_MICROMIPS_GOT16);
3715 }
3716
3717 static inline bfd_boolean
3718 hi16_reloc_p (bfd_reloc_code_real_type reloc)
3719 {
3720   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
3721           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
3722 }
3723
3724 static inline bfd_boolean
3725 lo16_reloc_p (bfd_reloc_code_real_type reloc)
3726 {
3727   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
3728           || reloc == BFD_RELOC_MICROMIPS_LO16);
3729 }
3730
3731 static inline bfd_boolean
3732 jalr_reloc_p (bfd_reloc_code_real_type reloc)
3733 {
3734   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
3735 }
3736
3737 static inline bfd_boolean
3738 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
3739 {
3740   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
3741           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
3742 }
3743
3744 /* Return true if RELOC is a PC-relative relocation that does not have
3745    full address range.  */
3746
3747 static inline bfd_boolean
3748 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
3749 {
3750   switch (reloc)
3751     {
3752     case BFD_RELOC_16_PCREL_S2:
3753     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3754     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3755     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3756       return TRUE;
3757
3758     case BFD_RELOC_32_PCREL:
3759       return HAVE_64BIT_ADDRESSES;
3760
3761     default:
3762       return FALSE;
3763     }
3764 }
3765
3766 /* Return true if the given relocation might need a matching %lo().
3767    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
3768    need a matching %lo() when applied to local symbols.  */
3769
3770 static inline bfd_boolean
3771 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
3772 {
3773   return (HAVE_IN_PLACE_ADDENDS
3774           && (hi16_reloc_p (reloc)
3775               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
3776                  all GOT16 relocations evaluate to "G".  */
3777               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
3778 }
3779
3780 /* Return the type of %lo() reloc needed by RELOC, given that
3781    reloc_needs_lo_p.  */
3782
3783 static inline bfd_reloc_code_real_type
3784 matching_lo_reloc (bfd_reloc_code_real_type reloc)
3785 {
3786   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
3787           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
3788              : BFD_RELOC_LO16));
3789 }
3790
3791 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
3792    relocation.  */
3793
3794 static inline bfd_boolean
3795 fixup_has_matching_lo_p (fixS *fixp)
3796 {
3797   return (fixp->fx_next != NULL
3798           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
3799           && fixp->fx_addsy == fixp->fx_next->fx_addsy
3800           && fixp->fx_offset == fixp->fx_next->fx_offset);
3801 }
3802
3803 /* Move all labels in LABELS to the current insertion point.  TEXT_P
3804    says whether the labels refer to text or data.  */
3805
3806 static void
3807 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
3808 {
3809   struct insn_label_list *l;
3810   valueT val;
3811
3812   for (l = labels; l != NULL; l = l->next)
3813     {
3814       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
3815       symbol_set_frag (l->label, frag_now);
3816       val = (valueT) frag_now_fix ();
3817       /* MIPS16/microMIPS text labels are stored as odd.  */
3818       if (text_p && HAVE_CODE_COMPRESSION)
3819         ++val;
3820       S_SET_VALUE (l->label, val);
3821     }
3822 }
3823
3824 /* Move all labels in insn_labels to the current insertion point
3825    and treat them as text labels.  */
3826
3827 static void
3828 mips_move_text_labels (void)
3829 {
3830   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
3831 }
3832
3833 static bfd_boolean
3834 s_is_linkonce (symbolS *sym, segT from_seg)
3835 {
3836   bfd_boolean linkonce = FALSE;
3837   segT symseg = S_GET_SEGMENT (sym);
3838
3839   if (symseg != from_seg && !S_IS_LOCAL (sym))
3840     {
3841       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
3842         linkonce = TRUE;
3843       /* The GNU toolchain uses an extension for ELF: a section
3844          beginning with the magic string .gnu.linkonce is a
3845          linkonce section.  */
3846       if (strncmp (segment_name (symseg), ".gnu.linkonce",
3847                    sizeof ".gnu.linkonce" - 1) == 0)
3848         linkonce = TRUE;
3849     }
3850   return linkonce;
3851 }
3852
3853 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
3854    linker to handle them specially, such as generating jalx instructions
3855    when needed.  We also make them odd for the duration of the assembly,
3856    in order to generate the right sort of code.  We will make them even
3857    in the adjust_symtab routine, while leaving them marked.  This is
3858    convenient for the debugger and the disassembler.  The linker knows
3859    to make them odd again.  */
3860
3861 static void
3862 mips_compressed_mark_label (symbolS *label)
3863 {
3864   gas_assert (HAVE_CODE_COMPRESSION);
3865
3866   if (mips_opts.mips16)
3867     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
3868   else
3869     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
3870   if ((S_GET_VALUE (label) & 1) == 0
3871       /* Don't adjust the address if the label is global or weak, or
3872          in a link-once section, since we'll be emitting symbol reloc
3873          references to it which will be patched up by the linker, and
3874          the final value of the symbol may or may not be MIPS16/microMIPS.  */
3875       && !S_IS_WEAK (label)
3876       && !S_IS_EXTERNAL (label)
3877       && !s_is_linkonce (label, now_seg))
3878     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
3879 }
3880
3881 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
3882
3883 static void
3884 mips_compressed_mark_labels (void)
3885 {
3886   struct insn_label_list *l;
3887
3888   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
3889     mips_compressed_mark_label (l->label);
3890 }
3891
3892 /* End the current frag.  Make it a variant frag and record the
3893    relaxation info.  */
3894
3895 static void
3896 relax_close_frag (void)
3897 {
3898   mips_macro_warning.first_frag = frag_now;
3899   frag_var (rs_machine_dependent, 0, 0,
3900             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
3901             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
3902
3903   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
3904   mips_relax.first_fixup = 0;
3905 }
3906
3907 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
3908    See the comment above RELAX_ENCODE for more details.  */
3909
3910 static void
3911 relax_start (symbolS *symbol)
3912 {
3913   gas_assert (mips_relax.sequence == 0);
3914   mips_relax.sequence = 1;
3915   mips_relax.symbol = symbol;
3916 }
3917
3918 /* Start generating the second version of a relaxable sequence.
3919    See the comment above RELAX_ENCODE for more details.  */
3920
3921 static void
3922 relax_switch (void)
3923 {
3924   gas_assert (mips_relax.sequence == 1);
3925   mips_relax.sequence = 2;
3926 }
3927
3928 /* End the current relaxable sequence.  */
3929
3930 static void
3931 relax_end (void)
3932 {
3933   gas_assert (mips_relax.sequence == 2);
3934   relax_close_frag ();
3935   mips_relax.sequence = 0;
3936 }
3937
3938 /* Return true if IP is a delayed branch or jump.  */
3939
3940 static inline bfd_boolean
3941 delayed_branch_p (const struct mips_cl_insn *ip)
3942 {
3943   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
3944                                 | INSN_COND_BRANCH_DELAY
3945                                 | INSN_COND_BRANCH_LIKELY)) != 0;
3946 }
3947
3948 /* Return true if IP is a compact branch or jump.  */
3949
3950 static inline bfd_boolean
3951 compact_branch_p (const struct mips_cl_insn *ip)
3952 {
3953   return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
3954                                  | INSN2_COND_BRANCH)) != 0;
3955 }
3956
3957 /* Return true if IP is an unconditional branch or jump.  */
3958
3959 static inline bfd_boolean
3960 uncond_branch_p (const struct mips_cl_insn *ip)
3961 {
3962   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
3963           || (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0);
3964 }
3965
3966 /* Return true if IP is a branch-likely instruction.  */
3967
3968 static inline bfd_boolean
3969 branch_likely_p (const struct mips_cl_insn *ip)
3970 {
3971   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
3972 }
3973
3974 /* Return the type of nop that should be used to fill the delay slot
3975    of delayed branch IP.  */
3976
3977 static struct mips_cl_insn *
3978 get_delay_slot_nop (const struct mips_cl_insn *ip)
3979 {
3980   if (mips_opts.micromips
3981       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
3982     return &micromips_nop32_insn;
3983   return NOP_INSN;
3984 }
3985
3986 /* Return a mask that has bit N set if OPCODE reads the register(s)
3987    in operand N.  */
3988
3989 static unsigned int
3990 insn_read_mask (const struct mips_opcode *opcode)
3991 {
3992   return (opcode->pinfo & INSN_READ_ALL) >> INSN_READ_SHIFT;
3993 }
3994
3995 /* Return a mask that has bit N set if OPCODE writes to the register(s)
3996    in operand N.  */
3997
3998 static unsigned int
3999 insn_write_mask (const struct mips_opcode *opcode)
4000 {
4001   return (opcode->pinfo & INSN_WRITE_ALL) >> INSN_WRITE_SHIFT;
4002 }
4003
4004 /* Return a mask of the registers specified by operand OPERAND of INSN.
4005    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4006    is set.  */
4007
4008 static unsigned int
4009 operand_reg_mask (const struct mips_cl_insn *insn,
4010                   const struct mips_operand *operand,
4011                   unsigned int type_mask)
4012 {
4013   unsigned int uval, vsel;
4014
4015   switch (operand->type)
4016     {
4017     case OP_INT:
4018     case OP_MAPPED_INT:
4019     case OP_MSB:
4020     case OP_PCREL:
4021     case OP_PERF_REG:
4022     case OP_ADDIUSP_INT:
4023     case OP_ENTRY_EXIT_LIST:
4024     case OP_REPEAT_DEST_REG:
4025     case OP_REPEAT_PREV_REG:
4026     case OP_PC:
4027     case OP_VU0_SUFFIX:
4028     case OP_VU0_MATCH_SUFFIX:
4029     case OP_IMM_INDEX:
4030       abort ();
4031
4032     case OP_REG:
4033     case OP_OPTIONAL_REG:
4034       {
4035         const struct mips_reg_operand *reg_op;
4036
4037         reg_op = (const struct mips_reg_operand *) operand;
4038         if (!(type_mask & (1 << reg_op->reg_type)))
4039           return 0;
4040         uval = insn_extract_operand (insn, operand);
4041         return 1 << mips_decode_reg_operand (reg_op, uval);
4042       }
4043
4044     case OP_REG_PAIR:
4045       {
4046         const struct mips_reg_pair_operand *pair_op;
4047
4048         pair_op = (const struct mips_reg_pair_operand *) operand;
4049         if (!(type_mask & (1 << pair_op->reg_type)))
4050           return 0;
4051         uval = insn_extract_operand (insn, operand);
4052         return (1 << pair_op->reg1_map[uval]) | (1 << pair_op->reg2_map[uval]);
4053       }
4054
4055     case OP_CLO_CLZ_DEST:
4056       if (!(type_mask & (1 << OP_REG_GP)))
4057         return 0;
4058       uval = insn_extract_operand (insn, operand);
4059       return (1 << (uval & 31)) | (1 << (uval >> 5));
4060
4061     case OP_LWM_SWM_LIST:
4062       abort ();
4063
4064     case OP_SAVE_RESTORE_LIST:
4065       abort ();
4066
4067     case OP_MDMX_IMM_REG:
4068       if (!(type_mask & (1 << OP_REG_VEC)))
4069         return 0;
4070       uval = insn_extract_operand (insn, operand);
4071       vsel = uval >> 5;
4072       if ((vsel & 0x18) == 0x18)
4073         return 0;
4074       return 1 << (uval & 31);
4075
4076     case OP_REG_INDEX:
4077       if (!(type_mask & (1 << OP_REG_GP)))
4078         return 0;
4079       return 1 << insn_extract_operand (insn, operand);
4080     }
4081   abort ();
4082 }
4083
4084 /* Return a mask of the registers specified by operands OPNO_MASK of INSN,
4085    where bit N of OPNO_MASK is set if operand N should be included.
4086    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4087    is set.  */
4088
4089 static unsigned int
4090 insn_reg_mask (const struct mips_cl_insn *insn,
4091                unsigned int type_mask, unsigned int opno_mask)
4092 {
4093   unsigned int opno, reg_mask;
4094
4095   opno = 0;
4096   reg_mask = 0;
4097   while (opno_mask != 0)
4098     {
4099       if (opno_mask & 1)
4100         reg_mask |= operand_reg_mask (insn, insn_opno (insn, opno), type_mask);
4101       opno_mask >>= 1;
4102       opno += 1;
4103     }
4104   return reg_mask;
4105 }
4106
4107 /* Return the mask of core registers that IP reads.  */
4108
4109 static unsigned int
4110 gpr_read_mask (const struct mips_cl_insn *ip)
4111 {
4112   unsigned long pinfo, pinfo2;
4113   unsigned int mask;
4114
4115   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_read_mask (ip->insn_mo));
4116   pinfo = ip->insn_mo->pinfo;
4117   pinfo2 = ip->insn_mo->pinfo2;
4118   if (pinfo & INSN_UDI)
4119     {
4120       /* UDI instructions have traditionally been assumed to read RS
4121          and RT.  */
4122       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
4123       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
4124     }
4125   if (pinfo & INSN_READ_GPR_24)
4126     mask |= 1 << 24;
4127   if (pinfo2 & INSN2_READ_GPR_16)
4128     mask |= 1 << 16;
4129   if (pinfo2 & INSN2_READ_SP)
4130     mask |= 1 << SP;
4131   if (pinfo2 & INSN2_READ_GPR_31)
4132     mask |= 1 << 31;
4133   /* Don't include register 0.  */
4134   return mask & ~1;
4135 }
4136
4137 /* Return the mask of core registers that IP writes.  */
4138
4139 static unsigned int
4140 gpr_write_mask (const struct mips_cl_insn *ip)
4141 {
4142   unsigned long pinfo, pinfo2;
4143   unsigned int mask;
4144
4145   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_write_mask (ip->insn_mo));
4146   pinfo = ip->insn_mo->pinfo;
4147   pinfo2 = ip->insn_mo->pinfo2;
4148   if (pinfo & INSN_WRITE_GPR_24)
4149     mask |= 1 << 24;
4150   if (pinfo & INSN_WRITE_GPR_31)
4151     mask |= 1 << 31;
4152   if (pinfo & INSN_UDI)
4153     /* UDI instructions have traditionally been assumed to write to RD.  */
4154     mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
4155   if (pinfo2 & INSN2_WRITE_SP)
4156     mask |= 1 << SP;
4157   /* Don't include register 0.  */
4158   return mask & ~1;
4159 }
4160
4161 /* Return the mask of floating-point registers that IP reads.  */
4162
4163 static unsigned int
4164 fpr_read_mask (const struct mips_cl_insn *ip)
4165 {
4166   unsigned long pinfo;
4167   unsigned int mask;
4168
4169   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4170                              | (1 << OP_REG_MSA)),
4171                         insn_read_mask (ip->insn_mo));
4172   pinfo = ip->insn_mo->pinfo;
4173   /* Conservatively treat all operands to an FP_D instruction are doubles.
4174      (This is overly pessimistic for things like cvt.d.s.)  */
4175   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
4176     mask |= mask << 1;
4177   return mask;
4178 }
4179
4180 /* Return the mask of floating-point registers that IP writes.  */
4181
4182 static unsigned int
4183 fpr_write_mask (const struct mips_cl_insn *ip)
4184 {
4185   unsigned long pinfo;
4186   unsigned int mask;
4187
4188   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4189                              | (1 << OP_REG_MSA)),
4190                         insn_write_mask (ip->insn_mo));
4191   pinfo = ip->insn_mo->pinfo;
4192   /* Conservatively treat all operands to an FP_D instruction are doubles.
4193      (This is overly pessimistic for things like cvt.s.d.)  */
4194   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
4195     mask |= mask << 1;
4196   return mask;
4197 }
4198
4199 /* Operand OPNUM of INSN is an odd-numbered floating-point register.
4200    Check whether that is allowed.  */
4201
4202 static bfd_boolean
4203 mips_oddfpreg_ok (const struct mips_opcode *insn, int opnum)
4204 {
4205   const char *s = insn->name;
4206
4207   if (insn->pinfo == INSN_MACRO)
4208     /* Let a macro pass, we'll catch it later when it is expanded.  */
4209     return TRUE;
4210
4211   if (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa) || mips_opts.arch == CPU_R5900)
4212     {
4213       /* Allow odd registers for single-precision ops.  */
4214       switch (insn->pinfo & (FP_S | FP_D))
4215         {
4216         case FP_S:
4217         case 0:
4218           return TRUE;
4219         case FP_D:
4220           return FALSE;
4221         default:
4222           break;
4223         }
4224
4225       /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
4226       s = strchr (insn->name, '.');
4227       if (s != NULL && opnum == 2)
4228         s = strchr (s + 1, '.');
4229       return (s != NULL && (s[1] == 'w' || s[1] == 's'));
4230     }
4231
4232   /* Single-precision coprocessor loads and moves are OK too.  */
4233   if ((insn->pinfo & FP_S)
4234       && (insn->pinfo & (INSN_COPROC_MEMORY_DELAY | INSN_STORE_MEMORY
4235                          | INSN_LOAD_COPROC_DELAY | INSN_COPROC_MOVE_DELAY)))
4236     return TRUE;
4237
4238   return FALSE;
4239 }
4240
4241 /* Information about an instruction argument that we're trying to match.  */
4242 struct mips_arg_info
4243 {
4244   /* The instruction so far.  */
4245   struct mips_cl_insn *insn;
4246
4247   /* The first unconsumed operand token.  */
4248   struct mips_operand_token *token;
4249
4250   /* The 1-based operand number, in terms of insn->insn_mo->args.  */
4251   int opnum;
4252
4253   /* The 1-based argument number, for error reporting.  This does not
4254      count elided optional registers, etc..  */
4255   int argnum;
4256
4257   /* The last OP_REG operand seen, or ILLEGAL_REG if none.  */
4258   unsigned int last_regno;
4259
4260   /* If the first operand was an OP_REG, this is the register that it
4261      specified, otherwise it is ILLEGAL_REG.  */
4262   unsigned int dest_regno;
4263
4264   /* The value of the last OP_INT operand.  Only used for OP_MSB,
4265      where it gives the lsb position.  */
4266   unsigned int last_op_int;
4267
4268   /* If true, match routines should assume that no later instruction
4269      alternative matches and should therefore be as accomodating as
4270      possible.  Match routines should not report errors if something
4271      is only invalid for !LAX_MATCH.  */
4272   bfd_boolean lax_match;
4273
4274   /* True if a reference to the current AT register was seen.  */
4275   bfd_boolean seen_at;
4276 };
4277
4278 /* Record that the argument is out of range.  */
4279
4280 static void
4281 match_out_of_range (struct mips_arg_info *arg)
4282 {
4283   set_insn_error_i (arg->argnum, _("operand %d out of range"), arg->argnum);
4284 }
4285
4286 /* Record that the argument isn't constant but needs to be.  */
4287
4288 static void
4289 match_not_constant (struct mips_arg_info *arg)
4290 {
4291   set_insn_error_i (arg->argnum, _("operand %d must be constant"),
4292                     arg->argnum);
4293 }
4294
4295 /* Try to match an OT_CHAR token for character CH.  Consume the token
4296    and return true on success, otherwise return false.  */
4297
4298 static bfd_boolean
4299 match_char (struct mips_arg_info *arg, char ch)
4300 {
4301   if (arg->token->type == OT_CHAR && arg->token->u.ch == ch)
4302     {
4303       ++arg->token;
4304       if (ch == ',')
4305         arg->argnum += 1;
4306       return TRUE;
4307     }
4308   return FALSE;
4309 }
4310
4311 /* Try to get an expression from the next tokens in ARG.  Consume the
4312    tokens and return true on success, storing the expression value in
4313    VALUE and relocation types in R.  */
4314
4315 static bfd_boolean
4316 match_expression (struct mips_arg_info *arg, expressionS *value,
4317                   bfd_reloc_code_real_type *r)
4318 {
4319   /* If the next token is a '(' that was parsed as being part of a base
4320      expression, assume we have an elided offset.  The later match will fail
4321      if this turns out to be wrong.  */
4322   if (arg->token->type == OT_CHAR && arg->token->u.ch == '(')
4323     {
4324       value->X_op = O_constant;
4325       value->X_add_number = 0;
4326       r[0] = r[1] = r[2] = BFD_RELOC_UNUSED;
4327       return TRUE;
4328     }
4329
4330   /* Reject register-based expressions such as "0+$2" and "(($2))".
4331      For plain registers the default error seems more appropriate.  */
4332   if (arg->token->type == OT_INTEGER
4333       && arg->token->u.integer.value.X_op == O_register)
4334     {
4335       set_insn_error (arg->argnum, _("register value used as expression"));
4336       return FALSE;
4337     }
4338
4339   if (arg->token->type == OT_INTEGER)
4340     {
4341       *value = arg->token->u.integer.value;
4342       memcpy (r, arg->token->u.integer.relocs, 3 * sizeof (*r));
4343       ++arg->token;
4344       return TRUE;
4345     }
4346
4347   set_insn_error_i
4348     (arg->argnum, _("operand %d must be an immediate expression"),
4349      arg->argnum);
4350   return FALSE;
4351 }
4352
4353 /* Try to get a constant expression from the next tokens in ARG.  Consume
4354    the tokens and return return true on success, storing the constant value
4355    in *VALUE.  Use FALLBACK as the value if the match succeeded with an
4356    error.  */
4357
4358 static bfd_boolean
4359 match_const_int (struct mips_arg_info *arg, offsetT *value)
4360 {
4361   expressionS ex;
4362   bfd_reloc_code_real_type r[3];
4363
4364   if (!match_expression (arg, &ex, r))
4365     return FALSE;
4366
4367   if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_constant)
4368     *value = ex.X_add_number;
4369   else
4370     {
4371       match_not_constant (arg);
4372       return FALSE;
4373     }
4374   return TRUE;
4375 }
4376
4377 /* Return the RTYPE_* flags for a register operand of type TYPE that
4378    appears in instruction OPCODE.  */
4379
4380 static unsigned int
4381 convert_reg_type (const struct mips_opcode *opcode,
4382                   enum mips_reg_operand_type type)
4383 {
4384   switch (type)
4385     {
4386     case OP_REG_GP:
4387       return RTYPE_NUM | RTYPE_GP;
4388
4389     case OP_REG_FP:
4390       /* Allow vector register names for MDMX if the instruction is a 64-bit
4391          FPR load, store or move (including moves to and from GPRs).  */
4392       if ((mips_opts.ase & ASE_MDMX)
4393           && (opcode->pinfo & FP_D)
4394           && (opcode->pinfo & (INSN_COPROC_MOVE_DELAY
4395                                | INSN_COPROC_MEMORY_DELAY
4396                                | INSN_LOAD_COPROC_DELAY
4397                                | INSN_LOAD_MEMORY
4398                                | INSN_STORE_MEMORY)))
4399         return RTYPE_FPU | RTYPE_VEC;
4400       return RTYPE_FPU;
4401
4402     case OP_REG_CCC:
4403       if (opcode->pinfo & (FP_D | FP_S))
4404         return RTYPE_CCC | RTYPE_FCC;
4405       return RTYPE_CCC;
4406
4407     case OP_REG_VEC:
4408       if (opcode->membership & INSN_5400)
4409         return RTYPE_FPU;
4410       return RTYPE_FPU | RTYPE_VEC;
4411
4412     case OP_REG_ACC:
4413       return RTYPE_ACC;
4414
4415     case OP_REG_COPRO:
4416       if (opcode->name[strlen (opcode->name) - 1] == '0')
4417         return RTYPE_NUM | RTYPE_CP0;
4418       return RTYPE_NUM;
4419
4420     case OP_REG_HW:
4421       return RTYPE_NUM;
4422
4423     case OP_REG_VI:
4424       return RTYPE_NUM | RTYPE_VI;
4425
4426     case OP_REG_VF:
4427       return RTYPE_NUM | RTYPE_VF;
4428
4429     case OP_REG_R5900_I:
4430       return RTYPE_R5900_I;
4431
4432     case OP_REG_R5900_Q:
4433       return RTYPE_R5900_Q;
4434
4435     case OP_REG_R5900_R:
4436       return RTYPE_R5900_R;
4437
4438     case OP_REG_R5900_ACC:
4439       return RTYPE_R5900_ACC;
4440
4441     case OP_REG_MSA:
4442       return RTYPE_MSA;
4443
4444     case OP_REG_MSA_CTRL:
4445       return RTYPE_NUM;
4446     }
4447   abort ();
4448 }
4449
4450 /* ARG is register REGNO, of type TYPE.  Warn about any dubious registers.  */
4451
4452 static void
4453 check_regno (struct mips_arg_info *arg,
4454              enum mips_reg_operand_type type, unsigned int regno)
4455 {
4456   if (AT && type == OP_REG_GP && regno == AT)
4457     arg->seen_at = TRUE;
4458
4459   if (type == OP_REG_FP
4460       && (regno & 1) != 0
4461       && HAVE_32BIT_FPRS
4462       && !mips_oddfpreg_ok (arg->insn->insn_mo, arg->opnum))
4463     as_warn (_("float register should be even, was %d"), regno);
4464
4465   if (type == OP_REG_CCC)
4466     {
4467       const char *name;
4468       size_t length;
4469
4470       name = arg->insn->insn_mo->name;
4471       length = strlen (name);
4472       if ((regno & 1) != 0
4473           && ((length >= 3 && strcmp (name + length - 3, ".ps") == 0)
4474               || (length >= 5 && strncmp (name + length - 5, "any2", 4) == 0)))
4475         as_warn (_("condition code register should be even for %s, was %d"),
4476                  name, regno);
4477
4478       if ((regno & 3) != 0
4479           && (length >= 5 && strncmp (name + length - 5, "any4", 4) == 0))
4480         as_warn (_("condition code register should be 0 or 4 for %s, was %d"),
4481                  name, regno);
4482     }
4483 }
4484
4485 /* ARG is a register with symbol value SYMVAL.  Try to interpret it as
4486    a register of type TYPE.  Return true on success, storing the register
4487    number in *REGNO and warning about any dubious uses.  */
4488
4489 static bfd_boolean
4490 match_regno (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4491              unsigned int symval, unsigned int *regno)
4492 {
4493   if (type == OP_REG_VEC)
4494     symval = mips_prefer_vec_regno (symval);
4495   if (!(symval & convert_reg_type (arg->insn->insn_mo, type)))
4496     return FALSE;
4497
4498   *regno = symval & RNUM_MASK;
4499   check_regno (arg, type, *regno);
4500   return TRUE;
4501 }
4502
4503 /* Try to interpret the next token in ARG as a register of type TYPE.
4504    Consume the token and return true on success, storing the register
4505    number in *REGNO.  Return false on failure.  */
4506
4507 static bfd_boolean
4508 match_reg (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4509            unsigned int *regno)
4510 {
4511   if (arg->token->type == OT_REG
4512       && match_regno (arg, type, arg->token->u.regno, regno))
4513     {
4514       ++arg->token;
4515       return TRUE;
4516     }
4517   return FALSE;
4518 }
4519
4520 /* Try to interpret the next token in ARG as a range of registers of type TYPE.
4521    Consume the token and return true on success, storing the register numbers
4522    in *REGNO1 and *REGNO2.  Return false on failure.  */
4523
4524 static bfd_boolean
4525 match_reg_range (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4526                  unsigned int *regno1, unsigned int *regno2)
4527 {
4528   if (match_reg (arg, type, regno1))
4529     {
4530       *regno2 = *regno1;
4531       return TRUE;
4532     }
4533   if (arg->token->type == OT_REG_RANGE
4534       && match_regno (arg, type, arg->token->u.reg_range.regno1, regno1)
4535       && match_regno (arg, type, arg->token->u.reg_range.regno2, regno2)
4536       && *regno1 <= *regno2)
4537     {
4538       ++arg->token;
4539       return TRUE;
4540     }
4541   return FALSE;
4542 }
4543
4544 /* OP_INT matcher.  */
4545
4546 static bfd_boolean
4547 match_int_operand (struct mips_arg_info *arg,
4548                    const struct mips_operand *operand_base)
4549 {
4550   const struct mips_int_operand *operand;
4551   unsigned int uval;
4552   int min_val, max_val, factor;
4553   offsetT sval;
4554
4555   operand = (const struct mips_int_operand *) operand_base;
4556   factor = 1 << operand->shift;
4557   min_val = mips_int_operand_min (operand);
4558   max_val = mips_int_operand_max (operand);
4559
4560   if (operand_base->lsb == 0
4561       && operand_base->size == 16
4562       && operand->shift == 0
4563       && operand->bias == 0
4564       && (operand->max_val == 32767 || operand->max_val == 65535))
4565     {
4566       /* The operand can be relocated.  */
4567       if (!match_expression (arg, &offset_expr, offset_reloc))
4568         return FALSE;
4569
4570       if (offset_reloc[0] != BFD_RELOC_UNUSED)
4571         /* Relocation operators were used.  Accept the arguent and
4572            leave the relocation value in offset_expr and offset_relocs
4573            for the caller to process.  */
4574         return TRUE;
4575
4576       if (offset_expr.X_op != O_constant)
4577         {
4578           /* Accept non-constant operands if no later alternative matches,
4579              leaving it for the caller to process.  */
4580           if (!arg->lax_match)
4581             return FALSE;
4582           offset_reloc[0] = BFD_RELOC_LO16;
4583           return TRUE;
4584         }
4585
4586       /* Clear the global state; we're going to install the operand
4587          ourselves.  */
4588       sval = offset_expr.X_add_number;
4589       offset_expr.X_op = O_absent;
4590
4591       /* For compatibility with older assemblers, we accept
4592          0x8000-0xffff as signed 16-bit numbers when only
4593          signed numbers are allowed.  */
4594       if (sval > max_val)
4595         {
4596           max_val = ((1 << operand_base->size) - 1) << operand->shift;
4597           if (!arg->lax_match && sval <= max_val)
4598             return FALSE;
4599         }
4600     }
4601   else
4602     {
4603       if (!match_const_int (arg, &sval))
4604         return FALSE;
4605     }
4606
4607   arg->last_op_int = sval;
4608
4609   if (sval < min_val || sval > max_val || sval % factor)
4610     {
4611       match_out_of_range (arg);
4612       return FALSE;
4613     }
4614
4615   uval = (unsigned int) sval >> operand->shift;
4616   uval -= operand->bias;
4617
4618   /* Handle -mfix-cn63xxp1.  */
4619   if (arg->opnum == 1
4620       && mips_fix_cn63xxp1
4621       && !mips_opts.micromips
4622       && strcmp ("pref", arg->insn->insn_mo->name) == 0)
4623     switch (uval)
4624       {
4625       case 5:
4626       case 25:
4627       case 26:
4628       case 27:
4629       case 28:
4630       case 29:
4631       case 30:
4632       case 31:
4633         /* These are ok.  */
4634         break;
4635
4636       default:
4637         /* The rest must be changed to 28.  */
4638         uval = 28;
4639         break;
4640       }
4641
4642   insn_insert_operand (arg->insn, operand_base, uval);
4643   return TRUE;
4644 }
4645
4646 /* OP_MAPPED_INT matcher.  */
4647
4648 static bfd_boolean
4649 match_mapped_int_operand (struct mips_arg_info *arg,
4650                           const struct mips_operand *operand_base)
4651 {
4652   const struct mips_mapped_int_operand *operand;
4653   unsigned int uval, num_vals;
4654   offsetT sval;
4655
4656   operand = (const struct mips_mapped_int_operand *) operand_base;
4657   if (!match_const_int (arg, &sval))
4658     return FALSE;
4659
4660   num_vals = 1 << operand_base->size;
4661   for (uval = 0; uval < num_vals; uval++)
4662     if (operand->int_map[uval] == sval)
4663       break;
4664   if (uval == num_vals)
4665     {
4666       match_out_of_range (arg);
4667       return FALSE;
4668     }
4669
4670   insn_insert_operand (arg->insn, operand_base, uval);
4671   return TRUE;
4672 }
4673
4674 /* OP_MSB matcher.  */
4675
4676 static bfd_boolean
4677 match_msb_operand (struct mips_arg_info *arg,
4678                    const struct mips_operand *operand_base)
4679 {
4680   const struct mips_msb_operand *operand;
4681   int min_val, max_val, max_high;
4682   offsetT size, sval, high;
4683
4684   operand = (const struct mips_msb_operand *) operand_base;
4685   min_val = operand->bias;
4686   max_val = min_val + (1 << operand_base->size) - 1;
4687   max_high = operand->opsize;
4688
4689   if (!match_const_int (arg, &size))
4690     return FALSE;
4691
4692   high = size + arg->last_op_int;
4693   sval = operand->add_lsb ? high : size;
4694
4695   if (size < 0 || high > max_high || sval < min_val || sval > max_val)
4696     {
4697       match_out_of_range (arg);
4698       return FALSE;
4699     }
4700   insn_insert_operand (arg->insn, operand_base, sval - min_val);
4701   return TRUE;
4702 }
4703
4704 /* OP_REG matcher.  */
4705
4706 static bfd_boolean
4707 match_reg_operand (struct mips_arg_info *arg,
4708                    const struct mips_operand *operand_base)
4709 {
4710   const struct mips_reg_operand *operand;
4711   unsigned int regno, uval, num_vals;
4712
4713   operand = (const struct mips_reg_operand *) operand_base;
4714   if (!match_reg (arg, operand->reg_type, &regno))
4715     return FALSE;
4716
4717   if (operand->reg_map)
4718     {
4719       num_vals = 1 << operand->root.size;
4720       for (uval = 0; uval < num_vals; uval++)
4721         if (operand->reg_map[uval] == regno)
4722           break;
4723       if (num_vals == uval)
4724         return FALSE;
4725     }
4726   else
4727     uval = regno;
4728
4729   arg->last_regno = regno;
4730   if (arg->opnum == 1)
4731     arg->dest_regno = regno;
4732   insn_insert_operand (arg->insn, operand_base, uval);
4733   return TRUE;
4734 }
4735
4736 /* OP_REG_PAIR matcher.  */
4737
4738 static bfd_boolean
4739 match_reg_pair_operand (struct mips_arg_info *arg,
4740                         const struct mips_operand *operand_base)
4741 {
4742   const struct mips_reg_pair_operand *operand;
4743   unsigned int regno1, regno2, uval, num_vals;
4744
4745   operand = (const struct mips_reg_pair_operand *) operand_base;
4746   if (!match_reg (arg, operand->reg_type, &regno1)
4747       || !match_char (arg, ',')
4748       || !match_reg (arg, operand->reg_type, &regno2))
4749     return FALSE;
4750
4751   num_vals = 1 << operand_base->size;
4752   for (uval = 0; uval < num_vals; uval++)
4753     if (operand->reg1_map[uval] == regno1 && operand->reg2_map[uval] == regno2)
4754       break;
4755   if (uval == num_vals)
4756     return FALSE;
4757
4758   insn_insert_operand (arg->insn, operand_base, uval);
4759   return TRUE;
4760 }
4761
4762 /* OP_PCREL matcher.  The caller chooses the relocation type.  */
4763
4764 static bfd_boolean
4765 match_pcrel_operand (struct mips_arg_info *arg)
4766 {
4767   bfd_reloc_code_real_type r[3];
4768
4769   return match_expression (arg, &offset_expr, r) && r[0] == BFD_RELOC_UNUSED;
4770 }
4771
4772 /* OP_PERF_REG matcher.  */
4773
4774 static bfd_boolean
4775 match_perf_reg_operand (struct mips_arg_info *arg,
4776                         const struct mips_operand *operand)
4777 {
4778   offsetT sval;
4779
4780   if (!match_const_int (arg, &sval))
4781     return FALSE;
4782
4783   if (sval != 0
4784       && (sval != 1
4785           || (mips_opts.arch == CPU_R5900
4786               && (strcmp (arg->insn->insn_mo->name, "mfps") == 0
4787                   || strcmp (arg->insn->insn_mo->name, "mtps") == 0))))
4788     {
4789       set_insn_error (arg->argnum, _("invalid performance register"));
4790       return FALSE;
4791     }
4792
4793   insn_insert_operand (arg->insn, operand, sval);
4794   return TRUE;
4795 }
4796
4797 /* OP_ADDIUSP matcher.  */
4798
4799 static bfd_boolean
4800 match_addiusp_operand (struct mips_arg_info *arg,
4801                        const struct mips_operand *operand)
4802 {
4803   offsetT sval;
4804   unsigned int uval;
4805
4806   if (!match_const_int (arg, &sval))
4807     return FALSE;
4808
4809   if (sval % 4)
4810     {
4811       match_out_of_range (arg);
4812       return FALSE;
4813     }
4814
4815   sval /= 4;
4816   if (!(sval >= -258 && sval <= 257) || (sval >= -2 && sval <= 1))
4817     {
4818       match_out_of_range (arg);
4819       return FALSE;
4820     }
4821
4822   uval = (unsigned int) sval;
4823   uval = ((uval >> 1) & ~0xff) | (uval & 0xff);
4824   insn_insert_operand (arg->insn, operand, uval);
4825   return TRUE;
4826 }
4827
4828 /* OP_CLO_CLZ_DEST matcher.  */
4829
4830 static bfd_boolean
4831 match_clo_clz_dest_operand (struct mips_arg_info *arg,
4832                             const struct mips_operand *operand)
4833 {
4834   unsigned int regno;
4835
4836   if (!match_reg (arg, OP_REG_GP, &regno))
4837     return FALSE;
4838
4839   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
4840   return TRUE;
4841 }
4842
4843 /* OP_LWM_SWM_LIST matcher.  */
4844
4845 static bfd_boolean
4846 match_lwm_swm_list_operand (struct mips_arg_info *arg,
4847                             const struct mips_operand *operand)
4848 {
4849   unsigned int reglist, sregs, ra, regno1, regno2;
4850   struct mips_arg_info reset;
4851
4852   reglist = 0;
4853   if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4854     return FALSE;
4855   do
4856     {
4857       if (regno2 == FP && regno1 >= S0 && regno1 <= S7)
4858         {
4859           reglist |= 1 << FP;
4860           regno2 = S7;
4861         }
4862       reglist |= ((1U << regno2 << 1) - 1) & -(1U << regno1);
4863       reset = *arg;
4864     }
4865   while (match_char (arg, ',')
4866          && match_reg_range (arg, OP_REG_GP, &regno1, &regno2));
4867   *arg = reset;
4868
4869   if (operand->size == 2)
4870     {
4871       /* The list must include both ra and s0-sN, for 0 <= N <= 3.  E.g.:
4872
4873          s0, ra
4874          s0, s1, ra, s2, s3
4875          s0-s2, ra
4876
4877          and any permutations of these.  */
4878       if ((reglist & 0xfff1ffff) != 0x80010000)
4879         return FALSE;
4880
4881       sregs = (reglist >> 17) & 7;
4882       ra = 0;
4883     }
4884   else
4885     {
4886       /* The list must include at least one of ra and s0-sN,
4887          for 0 <= N <= 8.  (Note that there is a gap between s7 and s8,
4888          which are $23 and $30 respectively.)  E.g.:
4889
4890          ra
4891          s0
4892          ra, s0, s1, s2
4893          s0-s8
4894          s0-s5, ra
4895
4896          and any permutations of these.  */
4897       if ((reglist & 0x3f00ffff) != 0)
4898         return FALSE;
4899
4900       ra = (reglist >> 27) & 0x10;
4901       sregs = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
4902     }
4903   sregs += 1;
4904   if ((sregs & -sregs) != sregs)
4905     return FALSE;
4906
4907   insn_insert_operand (arg->insn, operand, (ffs (sregs) - 1) | ra);
4908   return TRUE;
4909 }
4910
4911 /* OP_ENTRY_EXIT_LIST matcher.  */
4912
4913 static unsigned int
4914 match_entry_exit_operand (struct mips_arg_info *arg,
4915                           const struct mips_operand *operand)
4916 {
4917   unsigned int mask;
4918   bfd_boolean is_exit;
4919
4920   /* The format is the same for both ENTRY and EXIT, but the constraints
4921      are different.  */
4922   is_exit = strcmp (arg->insn->insn_mo->name, "exit") == 0;
4923   mask = (is_exit ? 7 << 3 : 0);
4924   do
4925     {
4926       unsigned int regno1, regno2;
4927       bfd_boolean is_freg;
4928
4929       if (match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4930         is_freg = FALSE;
4931       else if (match_reg_range (arg, OP_REG_FP, &regno1, &regno2))
4932         is_freg = TRUE;
4933       else
4934         return FALSE;
4935
4936       if (is_exit && is_freg && regno1 == 0 && regno2 < 2)
4937         {
4938           mask &= ~(7 << 3);
4939           mask |= (5 + regno2) << 3;
4940         }
4941       else if (!is_exit && regno1 == 4 && regno2 >= 4 && regno2 <= 7)
4942         mask |= (regno2 - 3) << 3;
4943       else if (regno1 == 16 && regno2 >= 16 && regno2 <= 17)
4944         mask |= (regno2 - 15) << 1;
4945       else if (regno1 == RA && regno2 == RA)
4946         mask |= 1;
4947       else
4948         return FALSE;
4949     }
4950   while (match_char (arg, ','));
4951
4952   insn_insert_operand (arg->insn, operand, mask);
4953   return TRUE;
4954 }
4955
4956 /* OP_SAVE_RESTORE_LIST matcher.  */
4957
4958 static bfd_boolean
4959 match_save_restore_list_operand (struct mips_arg_info *arg)
4960 {
4961   unsigned int opcode, args, statics, sregs;
4962   unsigned int num_frame_sizes, num_args, num_statics, num_sregs;
4963   offsetT frame_size;
4964
4965   opcode = arg->insn->insn_opcode;
4966   frame_size = 0;
4967   num_frame_sizes = 0;
4968   args = 0;
4969   statics = 0;
4970   sregs = 0;
4971   do
4972     {
4973       unsigned int regno1, regno2;
4974
4975       if (arg->token->type == OT_INTEGER)
4976         {
4977           /* Handle the frame size.  */
4978           if (!match_const_int (arg, &frame_size))
4979             return FALSE;
4980           num_frame_sizes += 1;
4981         }
4982       else
4983         {
4984           if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4985             return FALSE;
4986
4987           while (regno1 <= regno2)
4988             {
4989               if (regno1 >= 4 && regno1 <= 7)
4990                 {
4991                   if (num_frame_sizes == 0)
4992                     /* args $a0-$a3 */
4993                     args |= 1 << (regno1 - 4);
4994                   else
4995                     /* statics $a0-$a3 */
4996                     statics |= 1 << (regno1 - 4);
4997                 }
4998               else if (regno1 >= 16 && regno1 <= 23)
4999                 /* $s0-$s7 */
5000                 sregs |= 1 << (regno1 - 16);
5001               else if (regno1 == 30)
5002                 /* $s8 */
5003                 sregs |= 1 << 8;
5004               else if (regno1 == 31)
5005                 /* Add $ra to insn.  */
5006                 opcode |= 0x40;
5007               else
5008                 return FALSE;
5009               regno1 += 1;
5010               if (regno1 == 24)
5011                 regno1 = 30;
5012             }
5013         }
5014     }
5015   while (match_char (arg, ','));
5016
5017   /* Encode args/statics combination.  */
5018   if (args & statics)
5019     return FALSE;
5020   else if (args == 0xf)
5021     /* All $a0-$a3 are args.  */
5022     opcode |= MIPS16_ALL_ARGS << 16;
5023   else if (statics == 0xf)
5024     /* All $a0-$a3 are statics.  */
5025     opcode |= MIPS16_ALL_STATICS << 16;
5026   else
5027     {
5028       /* Count arg registers.  */
5029       num_args = 0;
5030       while (args & 0x1)
5031         {
5032           args >>= 1;
5033           num_args += 1;
5034         }
5035       if (args != 0)
5036         return FALSE;
5037
5038       /* Count static registers.  */
5039       num_statics = 0;
5040       while (statics & 0x8)
5041         {
5042           statics = (statics << 1) & 0xf;
5043           num_statics += 1;
5044         }
5045       if (statics != 0)
5046         return FALSE;
5047
5048       /* Encode args/statics.  */
5049       opcode |= ((num_args << 2) | num_statics) << 16;
5050     }
5051
5052   /* Encode $s0/$s1.  */
5053   if (sregs & (1 << 0))         /* $s0 */
5054     opcode |= 0x20;
5055   if (sregs & (1 << 1))         /* $s1 */
5056     opcode |= 0x10;
5057   sregs >>= 2;
5058
5059   /* Encode $s2-$s8. */
5060   num_sregs = 0;
5061   while (sregs & 1)
5062     {
5063       sregs >>= 1;
5064       num_sregs += 1;
5065     }
5066   if (sregs != 0)
5067     return FALSE;
5068   opcode |= num_sregs << 24;
5069
5070   /* Encode frame size.  */
5071   if (num_frame_sizes == 0)
5072     {
5073       set_insn_error (arg->argnum, _("missing frame size"));
5074       return FALSE;
5075     }
5076   if (num_frame_sizes > 1)
5077     {
5078       set_insn_error (arg->argnum, _("frame size specified twice"));
5079       return FALSE;
5080     }
5081   if ((frame_size & 7) != 0 || frame_size < 0 || frame_size > 0xff * 8)
5082     {
5083       set_insn_error (arg->argnum, _("invalid frame size"));
5084       return FALSE;
5085     }
5086   if (frame_size != 128 || (opcode >> 16) != 0)
5087     {
5088       frame_size /= 8;
5089       opcode |= (((frame_size & 0xf0) << 16)
5090                  | (frame_size & 0x0f));
5091     }
5092
5093   /* Finally build the instruction.  */
5094   if ((opcode >> 16) != 0 || frame_size == 0)
5095     opcode |= MIPS16_EXTEND;
5096   arg->insn->insn_opcode = opcode;
5097   return TRUE;
5098 }
5099
5100 /* OP_MDMX_IMM_REG matcher.  */
5101
5102 static bfd_boolean
5103 match_mdmx_imm_reg_operand (struct mips_arg_info *arg,
5104                             const struct mips_operand *operand)
5105 {
5106   unsigned int regno, uval;
5107   bfd_boolean is_qh;
5108   const struct mips_opcode *opcode;
5109
5110   /* The mips_opcode records whether this is an octobyte or quadhalf
5111      instruction.  Start out with that bit in place.  */
5112   opcode = arg->insn->insn_mo;
5113   uval = mips_extract_operand (operand, opcode->match);
5114   is_qh = (uval != 0);
5115
5116   if (arg->token->type == OT_REG)
5117     {
5118       if ((opcode->membership & INSN_5400)
5119           && strcmp (opcode->name, "rzu.ob") == 0)
5120         {
5121           set_insn_error_i (arg->argnum, _("operand %d must be an immediate"),
5122                             arg->argnum);
5123           return FALSE;
5124         }
5125
5126       if (!match_regno (arg, OP_REG_VEC, arg->token->u.regno, &regno))
5127         return FALSE;
5128       ++arg->token;
5129
5130       /* Check whether this is a vector register or a broadcast of
5131          a single element.  */
5132       if (arg->token->type == OT_INTEGER_INDEX)
5133         {
5134           if (arg->token->u.index > (is_qh ? 3 : 7))
5135             {
5136               set_insn_error (arg->argnum, _("invalid element selector"));
5137               return FALSE;
5138             }
5139           uval |= arg->token->u.index << (is_qh ? 2 : 1) << 5;
5140           ++arg->token;
5141         }
5142       else
5143         {
5144           /* A full vector.  */
5145           if ((opcode->membership & INSN_5400)
5146               && (strcmp (opcode->name, "sll.ob") == 0
5147                   || strcmp (opcode->name, "srl.ob") == 0))
5148             {
5149               set_insn_error_i (arg->argnum, _("operand %d must be scalar"),
5150                                 arg->argnum);
5151               return FALSE;
5152             }
5153
5154           if (is_qh)
5155             uval |= MDMX_FMTSEL_VEC_QH << 5;
5156           else
5157             uval |= MDMX_FMTSEL_VEC_OB << 5;
5158         }
5159       uval |= regno;
5160     }
5161   else
5162     {
5163       offsetT sval;
5164
5165       if (!match_const_int (arg, &sval))
5166         return FALSE;
5167       if (sval < 0 || sval > 31)
5168         {
5169           match_out_of_range (arg);
5170           return FALSE;
5171         }
5172       uval |= (sval & 31);
5173       if (is_qh)
5174         uval |= MDMX_FMTSEL_IMM_QH << 5;
5175       else
5176         uval |= MDMX_FMTSEL_IMM_OB << 5;
5177     }
5178   insn_insert_operand (arg->insn, operand, uval);
5179   return TRUE;
5180 }
5181
5182 /* OP_IMM_INDEX matcher.  */
5183
5184 static bfd_boolean
5185 match_imm_index_operand (struct mips_arg_info *arg,
5186                          const struct mips_operand *operand)
5187 {
5188   unsigned int max_val;
5189
5190   if (arg->token->type != OT_INTEGER_INDEX)
5191     return FALSE;
5192
5193   max_val = (1 << operand->size) - 1;
5194   if (arg->token->u.index > max_val)
5195     {
5196       match_out_of_range (arg);
5197       return FALSE;
5198     }
5199   insn_insert_operand (arg->insn, operand, arg->token->u.index);
5200   ++arg->token;
5201   return TRUE;
5202 }
5203
5204 /* OP_REG_INDEX matcher.  */
5205
5206 static bfd_boolean
5207 match_reg_index_operand (struct mips_arg_info *arg,
5208                          const struct mips_operand *operand)
5209 {
5210   unsigned int regno;
5211
5212   if (arg->token->type != OT_REG_INDEX)
5213     return FALSE;
5214
5215   if (!match_regno (arg, OP_REG_GP, arg->token->u.regno, &regno))
5216     return FALSE;
5217
5218   insn_insert_operand (arg->insn, operand, regno);
5219   ++arg->token;
5220   return TRUE;
5221 }
5222
5223 /* OP_PC matcher.  */
5224
5225 static bfd_boolean
5226 match_pc_operand (struct mips_arg_info *arg)
5227 {
5228   if (arg->token->type == OT_REG && (arg->token->u.regno & RTYPE_PC))
5229     {
5230       ++arg->token;
5231       return TRUE;
5232     }
5233   return FALSE;
5234 }
5235
5236 /* OP_REPEAT_DEST_REG and OP_REPEAT_PREV_REG matcher.  OTHER_REGNO is the
5237    register that we need to match.  */
5238
5239 static bfd_boolean
5240 match_tied_reg_operand (struct mips_arg_info *arg, unsigned int other_regno)
5241 {
5242   unsigned int regno;
5243
5244   return match_reg (arg, OP_REG_GP, &regno) && regno == other_regno;
5245 }
5246
5247 /* Read a floating-point constant from S for LI.S or LI.D.  LENGTH is
5248    the length of the value in bytes (4 for float, 8 for double) and
5249    USING_GPRS says whether the destination is a GPR rather than an FPR.
5250
5251    Return the constant in IMM and OFFSET as follows:
5252
5253    - If the constant should be loaded via memory, set IMM to O_absent and
5254      OFFSET to the memory address.
5255
5256    - Otherwise, if the constant should be loaded into two 32-bit registers,
5257      set IMM to the O_constant to load into the high register and OFFSET
5258      to the corresponding value for the low register.
5259
5260    - Otherwise, set IMM to the full O_constant and set OFFSET to O_absent.
5261
5262    These constants only appear as the last operand in an instruction,
5263    and every instruction that accepts them in any variant accepts them
5264    in all variants.  This means we don't have to worry about backing out
5265    any changes if the instruction does not match.  We just match
5266    unconditionally and report an error if the constant is invalid.  */
5267
5268 static bfd_boolean
5269 match_float_constant (struct mips_arg_info *arg, expressionS *imm,
5270                       expressionS *offset, int length, bfd_boolean using_gprs)
5271 {
5272   char *p;
5273   segT seg, new_seg;
5274   subsegT subseg;
5275   const char *newname;
5276   unsigned char *data;
5277
5278   /* Where the constant is placed is based on how the MIPS assembler
5279      does things:
5280
5281      length == 4 && using_gprs  -- immediate value only
5282      length == 8 && using_gprs  -- .rdata or immediate value
5283      length == 4 && !using_gprs -- .lit4 or immediate value
5284      length == 8 && !using_gprs -- .lit8 or immediate value
5285
5286      The .lit4 and .lit8 sections are only used if permitted by the
5287      -G argument.  */
5288   if (arg->token->type != OT_FLOAT)
5289     {
5290       set_insn_error (arg->argnum, _("floating-point expression required"));
5291       return FALSE;
5292     }
5293
5294   gas_assert (arg->token->u.flt.length == length);
5295   data = arg->token->u.flt.data;
5296   ++arg->token;
5297
5298   /* Handle 32-bit constants for which an immediate value is best.  */
5299   if (length == 4
5300       && (using_gprs
5301           || g_switch_value < 4
5302           || (data[0] == 0 && data[1] == 0)
5303           || (data[2] == 0 && data[3] == 0)))
5304     {
5305       imm->X_op = O_constant;
5306       if (!target_big_endian)
5307         imm->X_add_number = bfd_getl32 (data);
5308       else
5309         imm->X_add_number = bfd_getb32 (data);
5310       offset->X_op = O_absent;
5311       return TRUE;
5312     }
5313
5314   /* Handle 64-bit constants for which an immediate value is best.  */
5315   if (length == 8
5316       && !mips_disable_float_construction
5317       /* Constants can only be constructed in GPRs and copied
5318          to FPRs if the GPRs are at least as wide as the FPRs.
5319          Force the constant into memory if we are using 64-bit FPRs
5320          but the GPRs are only 32 bits wide.  */
5321       /* ??? No longer true with the addition of MTHC1, but this
5322          is legacy code...  */
5323       && (using_gprs || !(HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
5324       && ((data[0] == 0 && data[1] == 0)
5325           || (data[2] == 0 && data[3] == 0))
5326       && ((data[4] == 0 && data[5] == 0)
5327           || (data[6] == 0 && data[7] == 0)))
5328     {
5329       /* The value is simple enough to load with a couple of instructions.
5330          If using 32-bit registers, set IMM to the high order 32 bits and
5331          OFFSET to the low order 32 bits.  Otherwise, set IMM to the entire
5332          64 bit constant.  */
5333       if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
5334         {
5335           imm->X_op = O_constant;
5336           offset->X_op = O_constant;
5337           if (!target_big_endian)
5338             {
5339               imm->X_add_number = bfd_getl32 (data + 4);
5340               offset->X_add_number = bfd_getl32 (data);
5341             }
5342           else
5343             {
5344               imm->X_add_number = bfd_getb32 (data);
5345               offset->X_add_number = bfd_getb32 (data + 4);
5346             }
5347           if (offset->X_add_number == 0)
5348             offset->X_op = O_absent;
5349         }
5350       else
5351         {
5352           imm->X_op = O_constant;
5353           if (!target_big_endian)
5354             imm->X_add_number = bfd_getl64 (data);
5355           else
5356             imm->X_add_number = bfd_getb64 (data);
5357           offset->X_op = O_absent;
5358         }
5359       return TRUE;
5360     }
5361
5362   /* Switch to the right section.  */
5363   seg = now_seg;
5364   subseg = now_subseg;
5365   if (length == 4)
5366     {
5367       gas_assert (!using_gprs && g_switch_value >= 4);
5368       newname = ".lit4";
5369     }
5370   else
5371     {
5372       if (using_gprs || g_switch_value < 8)
5373         newname = RDATA_SECTION_NAME;
5374       else
5375         newname = ".lit8";
5376     }
5377
5378   new_seg = subseg_new (newname, (subsegT) 0);
5379   bfd_set_section_flags (stdoutput, new_seg,
5380                          SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA);
5381   frag_align (length == 4 ? 2 : 3, 0, 0);
5382   if (strncmp (TARGET_OS, "elf", 3) != 0)
5383     record_alignment (new_seg, 4);
5384   else
5385     record_alignment (new_seg, length == 4 ? 2 : 3);
5386   if (seg == now_seg)
5387     as_bad (_("cannot use `%s' in this section"), arg->insn->insn_mo->name);
5388
5389   /* Set the argument to the current address in the section.  */
5390   imm->X_op = O_absent;
5391   offset->X_op = O_symbol;
5392   offset->X_add_symbol = symbol_temp_new_now ();
5393   offset->X_add_number = 0;
5394
5395   /* Put the floating point number into the section.  */
5396   p = frag_more (length);
5397   memcpy (p, data, length);
5398
5399   /* Switch back to the original section.  */
5400   subseg_set (seg, subseg);
5401   return TRUE;
5402 }
5403
5404 /* OP_VU0_SUFFIX and OP_VU0_MATCH_SUFFIX matcher; MATCH_P selects between
5405    them.  */
5406
5407 static bfd_boolean
5408 match_vu0_suffix_operand (struct mips_arg_info *arg,
5409                           const struct mips_operand *operand,
5410                           bfd_boolean match_p)
5411 {
5412   unsigned int uval;
5413
5414   /* The operand can be an XYZW mask or a single 2-bit channel index
5415      (with X being 0).  */
5416   gas_assert (operand->size == 2 || operand->size == 4);
5417
5418   /* The suffix can be omitted when it is already part of the opcode.  */
5419   if (arg->token->type != OT_CHANNELS)
5420     return match_p;
5421
5422   uval = arg->token->u.channels;
5423   if (operand->size == 2)
5424     {
5425       /* Check that a single bit is set and convert it into a 2-bit index.  */
5426       if ((uval & -uval) != uval)
5427         return FALSE;
5428       uval = 4 - ffs (uval);
5429     }
5430
5431   if (match_p && insn_extract_operand (arg->insn, operand) != uval)
5432     return FALSE;
5433
5434   ++arg->token;
5435   if (!match_p)
5436     insn_insert_operand (arg->insn, operand, uval);
5437   return TRUE;
5438 }
5439
5440 /* S is the text seen for ARG.  Match it against OPERAND.  Return the end
5441    of the argument text if the match is successful, otherwise return null.  */
5442
5443 static bfd_boolean
5444 match_operand (struct mips_arg_info *arg,
5445                const struct mips_operand *operand)
5446 {
5447   switch (operand->type)
5448     {
5449     case OP_INT:
5450       return match_int_operand (arg, operand);
5451
5452     case OP_MAPPED_INT:
5453       return match_mapped_int_operand (arg, operand);
5454
5455     case OP_MSB:
5456       return match_msb_operand (arg, operand);
5457
5458     case OP_REG:
5459     case OP_OPTIONAL_REG:
5460       return match_reg_operand (arg, operand);
5461
5462     case OP_REG_PAIR:
5463       return match_reg_pair_operand (arg, operand);
5464
5465     case OP_PCREL:
5466       return match_pcrel_operand (arg);
5467
5468     case OP_PERF_REG:
5469       return match_perf_reg_operand (arg, operand);
5470
5471     case OP_ADDIUSP_INT:
5472       return match_addiusp_operand (arg, operand);
5473
5474     case OP_CLO_CLZ_DEST:
5475       return match_clo_clz_dest_operand (arg, operand);
5476
5477     case OP_LWM_SWM_LIST:
5478       return match_lwm_swm_list_operand (arg, operand);
5479
5480     case OP_ENTRY_EXIT_LIST:
5481       return match_entry_exit_operand (arg, operand);
5482
5483     case OP_SAVE_RESTORE_LIST:
5484       return match_save_restore_list_operand (arg);
5485
5486     case OP_MDMX_IMM_REG:
5487       return match_mdmx_imm_reg_operand (arg, operand);
5488
5489     case OP_REPEAT_DEST_REG:
5490       return match_tied_reg_operand (arg, arg->dest_regno);
5491
5492     case OP_REPEAT_PREV_REG:
5493       return match_tied_reg_operand (arg, arg->last_regno);
5494
5495     case OP_PC:
5496       return match_pc_operand (arg);
5497
5498     case OP_VU0_SUFFIX:
5499       return match_vu0_suffix_operand (arg, operand, FALSE);
5500
5501     case OP_VU0_MATCH_SUFFIX:
5502       return match_vu0_suffix_operand (arg, operand, TRUE);
5503
5504     case OP_IMM_INDEX:
5505       return match_imm_index_operand (arg, operand);
5506
5507     case OP_REG_INDEX:
5508       return match_reg_index_operand (arg, operand);
5509     }
5510   abort ();
5511 }
5512
5513 /* ARG is the state after successfully matching an instruction.
5514    Issue any queued-up warnings.  */
5515
5516 static void
5517 check_completed_insn (struct mips_arg_info *arg)
5518 {
5519   if (arg->seen_at)
5520     {
5521       if (AT == ATREG)
5522         as_warn (_("used $at without \".set noat\""));
5523       else
5524         as_warn (_("used $%u with \".set at=$%u\""), AT, AT);
5525     }
5526 }
5527
5528 /* Return true if modifying general-purpose register REG needs a delay.  */
5529
5530 static bfd_boolean
5531 reg_needs_delay (unsigned int reg)
5532 {
5533   unsigned long prev_pinfo;
5534
5535   prev_pinfo = history[0].insn_mo->pinfo;
5536   if (!mips_opts.noreorder
5537       && (((prev_pinfo & INSN_LOAD_MEMORY) && !gpr_interlocks)
5538           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY) && !cop_interlocks))
5539       && (gpr_write_mask (&history[0]) & (1 << reg)))
5540     return TRUE;
5541
5542   return FALSE;
5543 }
5544
5545 /* Classify an instruction according to the FIX_VR4120_* enumeration.
5546    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
5547    by VR4120 errata.  */
5548
5549 static unsigned int
5550 classify_vr4120_insn (const char *name)
5551 {
5552   if (strncmp (name, "macc", 4) == 0)
5553     return FIX_VR4120_MACC;
5554   if (strncmp (name, "dmacc", 5) == 0)
5555     return FIX_VR4120_DMACC;
5556   if (strncmp (name, "mult", 4) == 0)
5557     return FIX_VR4120_MULT;
5558   if (strncmp (name, "dmult", 5) == 0)
5559     return FIX_VR4120_DMULT;
5560   if (strstr (name, "div"))
5561     return FIX_VR4120_DIV;
5562   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
5563     return FIX_VR4120_MTHILO;
5564   return NUM_FIX_VR4120_CLASSES;
5565 }
5566
5567 #define INSN_ERET       0x42000018
5568 #define INSN_DERET      0x4200001f
5569 #define INSN_DMULT      0x1c
5570 #define INSN_DMULTU     0x1d
5571
5572 /* Return the number of instructions that must separate INSN1 and INSN2,
5573    where INSN1 is the earlier instruction.  Return the worst-case value
5574    for any INSN2 if INSN2 is null.  */
5575
5576 static unsigned int
5577 insns_between (const struct mips_cl_insn *insn1,
5578                const struct mips_cl_insn *insn2)
5579 {
5580   unsigned long pinfo1, pinfo2;
5581   unsigned int mask;
5582
5583   /* If INFO2 is null, pessimistically assume that all flags are set for
5584      the second instruction.  */
5585   pinfo1 = insn1->insn_mo->pinfo;
5586   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
5587
5588   /* For most targets, write-after-read dependencies on the HI and LO
5589      registers must be separated by at least two instructions.  */
5590   if (!hilo_interlocks)
5591     {
5592       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
5593         return 2;
5594       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
5595         return 2;
5596     }
5597
5598   /* If we're working around r7000 errata, there must be two instructions
5599      between an mfhi or mflo and any instruction that uses the result.  */
5600   if (mips_7000_hilo_fix
5601       && !mips_opts.micromips
5602       && MF_HILO_INSN (pinfo1)
5603       && (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1))))
5604     return 2;
5605
5606   /* If we're working around 24K errata, one instruction is required
5607      if an ERET or DERET is followed by a branch instruction.  */
5608   if (mips_fix_24k && !mips_opts.micromips)
5609     {
5610       if (insn1->insn_opcode == INSN_ERET
5611           || insn1->insn_opcode == INSN_DERET)
5612         {
5613           if (insn2 == NULL
5614               || insn2->insn_opcode == INSN_ERET
5615               || insn2->insn_opcode == INSN_DERET
5616               || delayed_branch_p (insn2))
5617             return 1;
5618         }
5619     }
5620
5621   /* If we're working around PMC RM7000 errata, there must be three
5622      nops between a dmult and a load instruction.  */
5623   if (mips_fix_rm7000 && !mips_opts.micromips)
5624     {
5625       if ((insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULT
5626           || (insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULTU)
5627         {
5628           if (pinfo2 & INSN_LOAD_MEMORY)
5629            return 3;
5630         }
5631     }
5632
5633   /* If working around VR4120 errata, check for combinations that need
5634      a single intervening instruction.  */
5635   if (mips_fix_vr4120 && !mips_opts.micromips)
5636     {
5637       unsigned int class1, class2;
5638
5639       class1 = classify_vr4120_insn (insn1->insn_mo->name);
5640       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
5641         {
5642           if (insn2 == NULL)
5643             return 1;
5644           class2 = classify_vr4120_insn (insn2->insn_mo->name);
5645           if (vr4120_conflicts[class1] & (1 << class2))
5646             return 1;
5647         }
5648     }
5649
5650   if (!HAVE_CODE_COMPRESSION)
5651     {
5652       /* Check for GPR or coprocessor load delays.  All such delays
5653          are on the RT register.  */
5654       /* Itbl support may require additional care here.  */
5655       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY))
5656           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
5657         {
5658           if (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1)))
5659             return 1;
5660         }
5661
5662       /* Check for generic coprocessor hazards.
5663
5664          This case is not handled very well.  There is no special
5665          knowledge of CP0 handling, and the coprocessors other than
5666          the floating point unit are not distinguished at all.  */
5667       /* Itbl support may require additional care here. FIXME!
5668          Need to modify this to include knowledge about
5669          user specified delays!  */
5670       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
5671                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
5672         {
5673           /* Handle cases where INSN1 writes to a known general coprocessor
5674              register.  There must be a one instruction delay before INSN2
5675              if INSN2 reads that register, otherwise no delay is needed.  */
5676           mask = fpr_write_mask (insn1);
5677           if (mask != 0)
5678             {
5679               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
5680                 return 1;
5681             }
5682           else
5683             {
5684               /* Read-after-write dependencies on the control registers
5685                  require a two-instruction gap.  */
5686               if ((pinfo1 & INSN_WRITE_COND_CODE)
5687                   && (pinfo2 & INSN_READ_COND_CODE))
5688                 return 2;
5689
5690               /* We don't know exactly what INSN1 does.  If INSN2 is
5691                  also a coprocessor instruction, assume there must be
5692                  a one instruction gap.  */
5693               if (pinfo2 & INSN_COP)
5694                 return 1;
5695             }
5696         }
5697
5698       /* Check for read-after-write dependencies on the coprocessor
5699          control registers in cases where INSN1 does not need a general
5700          coprocessor delay.  This means that INSN1 is a floating point
5701          comparison instruction.  */
5702       /* Itbl support may require additional care here.  */
5703       else if (!cop_interlocks
5704                && (pinfo1 & INSN_WRITE_COND_CODE)
5705                && (pinfo2 & INSN_READ_COND_CODE))
5706         return 1;
5707     }
5708
5709   return 0;
5710 }
5711
5712 /* Return the number of nops that would be needed to work around the
5713    VR4130 mflo/mfhi errata if instruction INSN immediately followed
5714    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
5715    that are contained within the first IGNORE instructions of HIST.  */
5716
5717 static int
5718 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
5719                  const struct mips_cl_insn *insn)
5720 {
5721   int i, j;
5722   unsigned int mask;
5723
5724   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
5725      are not affected by the errata.  */
5726   if (insn != 0
5727       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
5728           || strcmp (insn->insn_mo->name, "mtlo") == 0
5729           || strcmp (insn->insn_mo->name, "mthi") == 0))
5730     return 0;
5731
5732   /* Search for the first MFLO or MFHI.  */
5733   for (i = 0; i < MAX_VR4130_NOPS; i++)
5734     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
5735       {
5736         /* Extract the destination register.  */
5737         mask = gpr_write_mask (&hist[i]);
5738
5739         /* No nops are needed if INSN reads that register.  */
5740         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
5741           return 0;
5742
5743         /* ...or if any of the intervening instructions do.  */
5744         for (j = 0; j < i; j++)
5745           if (gpr_read_mask (&hist[j]) & mask)
5746             return 0;
5747
5748         if (i >= ignore)
5749           return MAX_VR4130_NOPS - i;
5750       }
5751   return 0;
5752 }
5753
5754 #define BASE_REG_EQ(INSN1, INSN2)       \
5755   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
5756       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
5757
5758 /* Return the minimum alignment for this store instruction.  */
5759
5760 static int
5761 fix_24k_align_to (const struct mips_opcode *mo)
5762 {
5763   if (strcmp (mo->name, "sh") == 0)
5764     return 2;
5765
5766   if (strcmp (mo->name, "swc1") == 0
5767       || strcmp (mo->name, "swc2") == 0
5768       || strcmp (mo->name, "sw") == 0
5769       || strcmp (mo->name, "sc") == 0
5770       || strcmp (mo->name, "s.s") == 0)
5771     return 4;
5772
5773   if (strcmp (mo->name, "sdc1") == 0
5774       || strcmp (mo->name, "sdc2") == 0
5775       || strcmp (mo->name, "s.d") == 0)
5776     return 8;
5777
5778   /* sb, swl, swr */
5779   return 1;
5780 }
5781
5782 struct fix_24k_store_info
5783   {
5784     /* Immediate offset, if any, for this store instruction.  */
5785     short off;
5786     /* Alignment required by this store instruction.  */
5787     int align_to;
5788     /* True for register offsets.  */
5789     int register_offset;
5790   };
5791
5792 /* Comparison function used by qsort.  */
5793
5794 static int
5795 fix_24k_sort (const void *a, const void *b)
5796 {
5797   const struct fix_24k_store_info *pos1 = a;
5798   const struct fix_24k_store_info *pos2 = b;
5799
5800   return (pos1->off - pos2->off);
5801 }
5802
5803 /* INSN is a store instruction.  Try to record the store information
5804    in STINFO.  Return false if the information isn't known.  */
5805
5806 static bfd_boolean
5807 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
5808                            const struct mips_cl_insn *insn)
5809 {
5810   /* The instruction must have a known offset.  */
5811   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
5812     return FALSE;
5813
5814   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
5815   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
5816   return TRUE;
5817 }
5818
5819 /* Return the number of nops that would be needed to work around the 24k
5820    "lost data on stores during refill" errata if instruction INSN
5821    immediately followed the 2 instructions described by HIST.
5822    Ignore hazards that are contained within the first IGNORE
5823    instructions of HIST.
5824
5825    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
5826    for the data cache refills and store data. The following describes
5827    the scenario where the store data could be lost.
5828
5829    * A data cache miss, due to either a load or a store, causing fill
5830      data to be supplied by the memory subsystem
5831    * The first three doublewords of fill data are returned and written
5832      into the cache
5833    * A sequence of four stores occurs in consecutive cycles around the
5834      final doubleword of the fill:
5835    * Store A
5836    * Store B
5837    * Store C
5838    * Zero, One or more instructions
5839    * Store D
5840
5841    The four stores A-D must be to different doublewords of the line that
5842    is being filled. The fourth instruction in the sequence above permits
5843    the fill of the final doubleword to be transferred from the FSB into
5844    the cache. In the sequence above, the stores may be either integer
5845    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
5846    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
5847    different doublewords on the line. If the floating point unit is
5848    running in 1:2 mode, it is not possible to create the sequence above
5849    using only floating point store instructions.
5850
5851    In this case, the cache line being filled is incorrectly marked
5852    invalid, thereby losing the data from any store to the line that
5853    occurs between the original miss and the completion of the five
5854    cycle sequence shown above.
5855
5856    The workarounds are:
5857
5858    * Run the data cache in write-through mode.
5859    * Insert a non-store instruction between
5860      Store A and Store B or Store B and Store C.  */
5861   
5862 static int
5863 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
5864               const struct mips_cl_insn *insn)
5865 {
5866   struct fix_24k_store_info pos[3];
5867   int align, i, base_offset;
5868
5869   if (ignore >= 2)
5870     return 0;
5871
5872   /* If the previous instruction wasn't a store, there's nothing to
5873      worry about.  */
5874   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5875     return 0;
5876
5877   /* If the instructions after the previous one are unknown, we have
5878      to assume the worst.  */
5879   if (!insn)
5880     return 1;
5881
5882   /* Check whether we are dealing with three consecutive stores.  */
5883   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
5884       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5885     return 0;
5886
5887   /* If we don't know the relationship between the store addresses,
5888      assume the worst.  */
5889   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
5890       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
5891     return 1;
5892
5893   if (!fix_24k_record_store_info (&pos[0], insn)
5894       || !fix_24k_record_store_info (&pos[1], &hist[0])
5895       || !fix_24k_record_store_info (&pos[2], &hist[1]))
5896     return 1;
5897
5898   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
5899
5900   /* Pick a value of ALIGN and X such that all offsets are adjusted by
5901      X bytes and such that the base register + X is known to be aligned
5902      to align bytes.  */
5903
5904   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
5905     align = 8;
5906   else
5907     {
5908       align = pos[0].align_to;
5909       base_offset = pos[0].off;
5910       for (i = 1; i < 3; i++)
5911         if (align < pos[i].align_to)
5912           {
5913             align = pos[i].align_to;
5914             base_offset = pos[i].off;
5915           }
5916       for (i = 0; i < 3; i++)
5917         pos[i].off -= base_offset;
5918     }
5919
5920   pos[0].off &= ~align + 1;
5921   pos[1].off &= ~align + 1;
5922   pos[2].off &= ~align + 1;
5923
5924   /* If any two stores write to the same chunk, they also write to the
5925      same doubleword.  The offsets are still sorted at this point.  */
5926   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
5927     return 0;
5928
5929   /* A range of at least 9 bytes is needed for the stores to be in
5930      non-overlapping doublewords.  */
5931   if (pos[2].off - pos[0].off <= 8)
5932     return 0;
5933
5934   if (pos[2].off - pos[1].off >= 24
5935       || pos[1].off - pos[0].off >= 24
5936       || pos[2].off - pos[0].off >= 32)
5937     return 0;
5938
5939   return 1;
5940 }
5941
5942 /* Return the number of nops that would be needed if instruction INSN
5943    immediately followed the MAX_NOPS instructions given by HIST,
5944    where HIST[0] is the most recent instruction.  Ignore hazards
5945    between INSN and the first IGNORE instructions in HIST.
5946
5947    If INSN is null, return the worse-case number of nops for any
5948    instruction.  */
5949
5950 static int
5951 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
5952                const struct mips_cl_insn *insn)
5953 {
5954   int i, nops, tmp_nops;
5955
5956   nops = 0;
5957   for (i = ignore; i < MAX_DELAY_NOPS; i++)
5958     {
5959       tmp_nops = insns_between (hist + i, insn) - i;
5960       if (tmp_nops > nops)
5961         nops = tmp_nops;
5962     }
5963
5964   if (mips_fix_vr4130 && !mips_opts.micromips)
5965     {
5966       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
5967       if (tmp_nops > nops)
5968         nops = tmp_nops;
5969     }
5970
5971   if (mips_fix_24k && !mips_opts.micromips)
5972     {
5973       tmp_nops = nops_for_24k (ignore, hist, insn);
5974       if (tmp_nops > nops)
5975         nops = tmp_nops;
5976     }
5977
5978   return nops;
5979 }
5980
5981 /* The variable arguments provide NUM_INSNS extra instructions that
5982    might be added to HIST.  Return the largest number of nops that
5983    would be needed after the extended sequence, ignoring hazards
5984    in the first IGNORE instructions.  */
5985
5986 static int
5987 nops_for_sequence (int num_insns, int ignore,
5988                    const struct mips_cl_insn *hist, ...)
5989 {
5990   va_list args;
5991   struct mips_cl_insn buffer[MAX_NOPS];
5992   struct mips_cl_insn *cursor;
5993   int nops;
5994
5995   va_start (args, hist);
5996   cursor = buffer + num_insns;
5997   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
5998   while (cursor > buffer)
5999     *--cursor = *va_arg (args, const struct mips_cl_insn *);
6000
6001   nops = nops_for_insn (ignore, buffer, NULL);
6002   va_end (args);
6003   return nops;
6004 }
6005
6006 /* Like nops_for_insn, but if INSN is a branch, take into account the
6007    worst-case delay for the branch target.  */
6008
6009 static int
6010 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
6011                          const struct mips_cl_insn *insn)
6012 {
6013   int nops, tmp_nops;
6014
6015   nops = nops_for_insn (ignore, hist, insn);
6016   if (delayed_branch_p (insn))
6017     {
6018       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
6019                                     hist, insn, get_delay_slot_nop (insn));
6020       if (tmp_nops > nops)
6021         nops = tmp_nops;
6022     }
6023   else if (compact_branch_p (insn))
6024     {
6025       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
6026       if (tmp_nops > nops)
6027         nops = tmp_nops;
6028     }
6029   return nops;
6030 }
6031
6032 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
6033
6034 static void
6035 fix_loongson2f_nop (struct mips_cl_insn * ip)
6036 {
6037   gas_assert (!HAVE_CODE_COMPRESSION);
6038   if (strcmp (ip->insn_mo->name, "nop") == 0)
6039     ip->insn_opcode = LOONGSON2F_NOP_INSN;
6040 }
6041
6042 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
6043                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
6044
6045 static void
6046 fix_loongson2f_jump (struct mips_cl_insn * ip)
6047 {
6048   gas_assert (!HAVE_CODE_COMPRESSION);
6049   if (strcmp (ip->insn_mo->name, "j") == 0
6050       || strcmp (ip->insn_mo->name, "jr") == 0
6051       || strcmp (ip->insn_mo->name, "jalr") == 0)
6052     {
6053       int sreg;
6054       expressionS ep;
6055
6056       if (! mips_opts.at)
6057         return;
6058
6059       sreg = EXTRACT_OPERAND (0, RS, *ip);
6060       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
6061         return;
6062
6063       ep.X_op = O_constant;
6064       ep.X_add_number = 0xcfff0000;
6065       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
6066       ep.X_add_number = 0xffff;
6067       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
6068       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
6069     }
6070 }
6071
6072 static void
6073 fix_loongson2f (struct mips_cl_insn * ip)
6074 {
6075   if (mips_fix_loongson2f_nop)
6076     fix_loongson2f_nop (ip);
6077
6078   if (mips_fix_loongson2f_jump)
6079     fix_loongson2f_jump (ip);
6080 }
6081
6082 /* IP is a branch that has a delay slot, and we need to fill it
6083    automatically.   Return true if we can do that by swapping IP
6084    with the previous instruction.
6085    ADDRESS_EXPR is an operand of the instruction to be used with
6086    RELOC_TYPE.  */
6087
6088 static bfd_boolean
6089 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
6090                    bfd_reloc_code_real_type *reloc_type)
6091 {
6092   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
6093   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
6094   unsigned int fpr_read, prev_fpr_write;
6095
6096   /* -O2 and above is required for this optimization.  */
6097   if (mips_optimize < 2)
6098     return FALSE;
6099
6100   /* If we have seen .set volatile or .set nomove, don't optimize.  */
6101   if (mips_opts.nomove)
6102     return FALSE;
6103
6104   /* We can't swap if the previous instruction's position is fixed.  */
6105   if (history[0].fixed_p)
6106     return FALSE;
6107
6108   /* If the previous previous insn was in a .set noreorder, we can't
6109      swap.  Actually, the MIPS assembler will swap in this situation.
6110      However, gcc configured -with-gnu-as will generate code like
6111
6112         .set    noreorder
6113         lw      $4,XXX
6114         .set    reorder
6115         INSN
6116         bne     $4,$0,foo
6117
6118      in which we can not swap the bne and INSN.  If gcc is not configured
6119      -with-gnu-as, it does not output the .set pseudo-ops.  */
6120   if (history[1].noreorder_p)
6121     return FALSE;
6122
6123   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
6124      This means that the previous instruction was a 4-byte one anyhow.  */
6125   if (mips_opts.mips16 && history[0].fixp[0])
6126     return FALSE;
6127
6128   /* If the branch is itself the target of a branch, we can not swap.
6129      We cheat on this; all we check for is whether there is a label on
6130      this instruction.  If there are any branches to anything other than
6131      a label, users must use .set noreorder.  */
6132   if (seg_info (now_seg)->label_list)
6133     return FALSE;
6134
6135   /* If the previous instruction is in a variant frag other than this
6136      branch's one, we cannot do the swap.  This does not apply to
6137      MIPS16 code, which uses variant frags for different purposes.  */
6138   if (!mips_opts.mips16
6139       && history[0].frag
6140       && history[0].frag->fr_type == rs_machine_dependent)
6141     return FALSE;
6142
6143   /* We do not swap with instructions that cannot architecturally
6144      be placed in a branch delay slot, such as SYNC or ERET.  We
6145      also refrain from swapping with a trap instruction, since it
6146      complicates trap handlers to have the trap instruction be in
6147      a delay slot.  */
6148   prev_pinfo = history[0].insn_mo->pinfo;
6149   if (prev_pinfo & INSN_NO_DELAY_SLOT)
6150     return FALSE;
6151
6152   /* Check for conflicts between the branch and the instructions
6153      before the candidate delay slot.  */
6154   if (nops_for_insn (0, history + 1, ip) > 0)
6155     return FALSE;
6156
6157   /* Check for conflicts between the swapped sequence and the
6158      target of the branch.  */
6159   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
6160     return FALSE;
6161
6162   /* If the branch reads a register that the previous
6163      instruction sets, we can not swap.  */
6164   gpr_read = gpr_read_mask (ip);
6165   prev_gpr_write = gpr_write_mask (&history[0]);
6166   if (gpr_read & prev_gpr_write)
6167     return FALSE;
6168
6169   fpr_read = fpr_read_mask (ip);
6170   prev_fpr_write = fpr_write_mask (&history[0]);
6171   if (fpr_read & prev_fpr_write)
6172     return FALSE;
6173
6174   /* If the branch writes a register that the previous
6175      instruction sets, we can not swap.  */
6176   gpr_write = gpr_write_mask (ip);
6177   if (gpr_write & prev_gpr_write)
6178     return FALSE;
6179
6180   /* If the branch writes a register that the previous
6181      instruction reads, we can not swap.  */
6182   prev_gpr_read = gpr_read_mask (&history[0]);
6183   if (gpr_write & prev_gpr_read)
6184     return FALSE;
6185
6186   /* If one instruction sets a condition code and the
6187      other one uses a condition code, we can not swap.  */
6188   pinfo = ip->insn_mo->pinfo;
6189   if ((pinfo & INSN_READ_COND_CODE)
6190       && (prev_pinfo & INSN_WRITE_COND_CODE))
6191     return FALSE;
6192   if ((pinfo & INSN_WRITE_COND_CODE)
6193       && (prev_pinfo & INSN_READ_COND_CODE))
6194     return FALSE;
6195
6196   /* If the previous instruction uses the PC, we can not swap.  */
6197   prev_pinfo2 = history[0].insn_mo->pinfo2;
6198   if (prev_pinfo2 & INSN2_READ_PC)
6199     return FALSE;
6200
6201   /* If the previous instruction has an incorrect size for a fixed
6202      branch delay slot in microMIPS mode, we cannot swap.  */
6203   pinfo2 = ip->insn_mo->pinfo2;
6204   if (mips_opts.micromips
6205       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
6206       && insn_length (history) != 2)
6207     return FALSE;
6208   if (mips_opts.micromips
6209       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
6210       && insn_length (history) != 4)
6211     return FALSE;
6212
6213   /* On R5900 short loops need to be fixed by inserting a nop in
6214      the branch delay slots.
6215      A short loop can be terminated too early.  */
6216   if (mips_opts.arch == CPU_R5900
6217       /* Check if instruction has a parameter, ignore "j $31". */
6218       && (address_expr != NULL)
6219       /* Parameter must be 16 bit. */
6220       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
6221       /* Branch to same segment. */
6222       && (S_GET_SEGMENT(address_expr->X_add_symbol) == now_seg)
6223       /* Branch to same code fragment. */
6224       && (symbol_get_frag(address_expr->X_add_symbol) == frag_now)
6225       /* Can only calculate branch offset if value is known. */
6226       && symbol_constant_p(address_expr->X_add_symbol)
6227       /* Check if branch is really conditional. */
6228       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
6229         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
6230         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
6231     {
6232       int distance;
6233       /* Check if loop is shorter than 6 instructions including
6234          branch and delay slot.  */
6235       distance = frag_now_fix() - S_GET_VALUE(address_expr->X_add_symbol);
6236       if (distance <= 20)
6237         {
6238           int i;
6239           int rv;
6240
6241           rv = FALSE;
6242           /* When the loop includes branches or jumps,
6243              it is not a short loop. */
6244           for (i = 0; i < (distance / 4); i++)
6245             {
6246               if ((history[i].cleared_p)
6247                   || delayed_branch_p(&history[i]))
6248                 {
6249                   rv = TRUE;
6250                   break;
6251                 }
6252             }
6253           if (rv == FALSE)
6254             {
6255               /* Insert nop after branch to fix short loop. */
6256               return FALSE;
6257             }
6258         }
6259     }
6260
6261   return TRUE;
6262 }
6263
6264 /* Decide how we should add IP to the instruction stream.
6265    ADDRESS_EXPR is an operand of the instruction to be used with
6266    RELOC_TYPE.  */
6267
6268 static enum append_method
6269 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
6270                    bfd_reloc_code_real_type *reloc_type)
6271 {
6272   /* The relaxed version of a macro sequence must be inherently
6273      hazard-free.  */
6274   if (mips_relax.sequence == 2)
6275     return APPEND_ADD;
6276
6277   /* We must not dabble with instructions in a ".set norerorder" block.  */
6278   if (mips_opts.noreorder)
6279     return APPEND_ADD;
6280
6281   /* Otherwise, it's our responsibility to fill branch delay slots.  */
6282   if (delayed_branch_p (ip))
6283     {
6284       if (!branch_likely_p (ip)
6285           && can_swap_branch_p (ip, address_expr, reloc_type))
6286         return APPEND_SWAP;
6287
6288       if (mips_opts.mips16
6289           && ISA_SUPPORTS_MIPS16E
6290           && gpr_read_mask (ip) != 0)
6291         return APPEND_ADD_COMPACT;
6292
6293       return APPEND_ADD_WITH_NOP;
6294     }
6295
6296   return APPEND_ADD;
6297 }
6298
6299 /* IP is a MIPS16 instruction whose opcode we have just changed.
6300    Point IP->insn_mo to the new opcode's definition.  */
6301
6302 static void
6303 find_altered_mips16_opcode (struct mips_cl_insn *ip)
6304 {
6305   const struct mips_opcode *mo, *end;
6306
6307   end = &mips16_opcodes[bfd_mips16_num_opcodes];
6308   for (mo = ip->insn_mo; mo < end; mo++)
6309     if ((ip->insn_opcode & mo->mask) == mo->match)
6310       {
6311         ip->insn_mo = mo;
6312         return;
6313       }
6314   abort ();
6315 }
6316
6317 /* For microMIPS macros, we need to generate a local number label
6318    as the target of branches.  */
6319 #define MICROMIPS_LABEL_CHAR            '\037'
6320 static unsigned long micromips_target_label;
6321 static char micromips_target_name[32];
6322
6323 static char *
6324 micromips_label_name (void)
6325 {
6326   char *p = micromips_target_name;
6327   char symbol_name_temporary[24];
6328   unsigned long l;
6329   int i;
6330
6331   if (*p)
6332     return p;
6333
6334   i = 0;
6335   l = micromips_target_label;
6336 #ifdef LOCAL_LABEL_PREFIX
6337   *p++ = LOCAL_LABEL_PREFIX;
6338 #endif
6339   *p++ = 'L';
6340   *p++ = MICROMIPS_LABEL_CHAR;
6341   do
6342     {
6343       symbol_name_temporary[i++] = l % 10 + '0';
6344       l /= 10;
6345     }
6346   while (l != 0);
6347   while (i > 0)
6348     *p++ = symbol_name_temporary[--i];
6349   *p = '\0';
6350
6351   return micromips_target_name;
6352 }
6353
6354 static void
6355 micromips_label_expr (expressionS *label_expr)
6356 {
6357   label_expr->X_op = O_symbol;
6358   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
6359   label_expr->X_add_number = 0;
6360 }
6361
6362 static void
6363 micromips_label_inc (void)
6364 {
6365   micromips_target_label++;
6366   *micromips_target_name = '\0';
6367 }
6368
6369 static void
6370 micromips_add_label (void)
6371 {
6372   symbolS *s;
6373
6374   s = colon (micromips_label_name ());
6375   micromips_label_inc ();
6376   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
6377 }
6378
6379 /* If assembling microMIPS code, then return the microMIPS reloc
6380    corresponding to the requested one if any.  Otherwise return
6381    the reloc unchanged.  */
6382
6383 static bfd_reloc_code_real_type
6384 micromips_map_reloc (bfd_reloc_code_real_type reloc)
6385 {
6386   static const bfd_reloc_code_real_type relocs[][2] =
6387     {
6388       /* Keep sorted incrementally by the left-hand key.  */
6389       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
6390       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
6391       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
6392       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
6393       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
6394       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
6395       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
6396       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
6397       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
6398       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
6399       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
6400       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
6401       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
6402       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
6403       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
6404       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
6405       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
6406       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
6407       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
6408       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
6409       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
6410       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
6411       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
6412       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
6413       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
6414       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
6415       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
6416     };
6417   bfd_reloc_code_real_type r;
6418   size_t i;
6419
6420   if (!mips_opts.micromips)
6421     return reloc;
6422   for (i = 0; i < ARRAY_SIZE (relocs); i++)
6423     {
6424       r = relocs[i][0];
6425       if (r > reloc)
6426         return reloc;
6427       if (r == reloc)
6428         return relocs[i][1];
6429     }
6430   return reloc;
6431 }
6432
6433 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
6434    Return true on success, storing the resolved value in RESULT.  */
6435
6436 static bfd_boolean
6437 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
6438                  offsetT *result)
6439 {
6440   switch (reloc)
6441     {
6442     case BFD_RELOC_MIPS_HIGHEST:
6443     case BFD_RELOC_MICROMIPS_HIGHEST:
6444       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
6445       return TRUE;
6446
6447     case BFD_RELOC_MIPS_HIGHER:
6448     case BFD_RELOC_MICROMIPS_HIGHER:
6449       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
6450       return TRUE;
6451
6452     case BFD_RELOC_HI16_S:
6453     case BFD_RELOC_MICROMIPS_HI16_S:
6454     case BFD_RELOC_MIPS16_HI16_S:
6455       *result = ((operand + 0x8000) >> 16) & 0xffff;
6456       return TRUE;
6457
6458     case BFD_RELOC_HI16:
6459     case BFD_RELOC_MICROMIPS_HI16:
6460     case BFD_RELOC_MIPS16_HI16:
6461       *result = (operand >> 16) & 0xffff;
6462       return TRUE;
6463
6464     case BFD_RELOC_LO16:
6465     case BFD_RELOC_MICROMIPS_LO16:
6466     case BFD_RELOC_MIPS16_LO16:
6467       *result = operand & 0xffff;
6468       return TRUE;
6469
6470     case BFD_RELOC_UNUSED:
6471       *result = operand;
6472       return TRUE;
6473
6474     default:
6475       return FALSE;
6476     }
6477 }
6478
6479 /* Output an instruction.  IP is the instruction information.
6480    ADDRESS_EXPR is an operand of the instruction to be used with
6481    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
6482    a macro expansion.  */
6483
6484 static void
6485 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
6486              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
6487 {
6488   unsigned long prev_pinfo2, pinfo;
6489   bfd_boolean relaxed_branch = FALSE;
6490   enum append_method method;
6491   bfd_boolean relax32;
6492   int branch_disp;
6493
6494   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
6495     fix_loongson2f (ip);
6496
6497   file_ase_mips16 |= mips_opts.mips16;
6498   file_ase_micromips |= mips_opts.micromips;
6499
6500   prev_pinfo2 = history[0].insn_mo->pinfo2;
6501   pinfo = ip->insn_mo->pinfo;
6502
6503   if (mips_opts.micromips
6504       && !expansionp
6505       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
6506            && micromips_insn_length (ip->insn_mo) != 2)
6507           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
6508               && micromips_insn_length (ip->insn_mo) != 4)))
6509     as_warn (_("wrong size instruction in a %u-bit branch delay slot"),
6510              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
6511
6512   if (address_expr == NULL)
6513     ip->complete_p = 1;
6514   else if (reloc_type[0] <= BFD_RELOC_UNUSED
6515            && reloc_type[1] == BFD_RELOC_UNUSED
6516            && reloc_type[2] == BFD_RELOC_UNUSED
6517            && address_expr->X_op == O_constant)
6518     {
6519       switch (*reloc_type)
6520         {
6521         case BFD_RELOC_MIPS_JMP:
6522           {
6523             int shift;
6524
6525             shift = mips_opts.micromips ? 1 : 2;
6526             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
6527               as_bad (_("jump to misaligned address (0x%lx)"),
6528                       (unsigned long) address_expr->X_add_number);
6529             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
6530                                 & 0x3ffffff);
6531             ip->complete_p = 1;
6532           }
6533           break;
6534
6535         case BFD_RELOC_MIPS16_JMP:
6536           if ((address_expr->X_add_number & 3) != 0)
6537             as_bad (_("jump to misaligned address (0x%lx)"),
6538                     (unsigned long) address_expr->X_add_number);
6539           ip->insn_opcode |=
6540             (((address_expr->X_add_number & 0x7c0000) << 3)
6541                | ((address_expr->X_add_number & 0xf800000) >> 7)
6542                | ((address_expr->X_add_number & 0x3fffc) >> 2));
6543           ip->complete_p = 1;
6544           break;
6545
6546         case BFD_RELOC_16_PCREL_S2:
6547           {
6548             int shift;
6549
6550             shift = mips_opts.micromips ? 1 : 2;
6551             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
6552               as_bad (_("branch to misaligned address (0x%lx)"),
6553                       (unsigned long) address_expr->X_add_number);
6554             if (!mips_relax_branch)
6555               {
6556                 if ((address_expr->X_add_number + (1 << (shift + 15)))
6557                     & ~((1 << (shift + 16)) - 1))
6558                   as_bad (_("branch address range overflow (0x%lx)"),
6559                           (unsigned long) address_expr->X_add_number);
6560                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
6561                                     & 0xffff);
6562               }
6563           }
6564           break;
6565
6566         default:
6567           {
6568             offsetT value;
6569
6570             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
6571                                  &value))
6572               {
6573                 ip->insn_opcode |= value & 0xffff;
6574                 ip->complete_p = 1;
6575               }
6576           }
6577           break;
6578         }
6579     }
6580
6581   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
6582     {
6583       /* There are a lot of optimizations we could do that we don't.
6584          In particular, we do not, in general, reorder instructions.
6585          If you use gcc with optimization, it will reorder
6586          instructions and generally do much more optimization then we
6587          do here; repeating all that work in the assembler would only
6588          benefit hand written assembly code, and does not seem worth
6589          it.  */
6590       int nops = (mips_optimize == 0
6591                   ? nops_for_insn (0, history, NULL)
6592                   : nops_for_insn_or_target (0, history, ip));
6593       if (nops > 0)
6594         {
6595           fragS *old_frag;
6596           unsigned long old_frag_offset;
6597           int i;
6598
6599           old_frag = frag_now;
6600           old_frag_offset = frag_now_fix ();
6601
6602           for (i = 0; i < nops; i++)
6603             add_fixed_insn (NOP_INSN);
6604           insert_into_history (0, nops, NOP_INSN);
6605
6606           if (listing)
6607             {
6608               listing_prev_line ();
6609               /* We may be at the start of a variant frag.  In case we
6610                  are, make sure there is enough space for the frag
6611                  after the frags created by listing_prev_line.  The
6612                  argument to frag_grow here must be at least as large
6613                  as the argument to all other calls to frag_grow in
6614                  this file.  We don't have to worry about being in the
6615                  middle of a variant frag, because the variants insert
6616                  all needed nop instructions themselves.  */
6617               frag_grow (40);
6618             }
6619
6620           mips_move_text_labels ();
6621
6622 #ifndef NO_ECOFF_DEBUGGING
6623           if (ECOFF_DEBUGGING)
6624             ecoff_fix_loc (old_frag, old_frag_offset);
6625 #endif
6626         }
6627     }
6628   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
6629     {
6630       int nops;
6631
6632       /* Work out how many nops in prev_nop_frag are needed by IP,
6633          ignoring hazards generated by the first prev_nop_frag_since
6634          instructions.  */
6635       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
6636       gas_assert (nops <= prev_nop_frag_holds);
6637
6638       /* Enforce NOPS as a minimum.  */
6639       if (nops > prev_nop_frag_required)
6640         prev_nop_frag_required = nops;
6641
6642       if (prev_nop_frag_holds == prev_nop_frag_required)
6643         {
6644           /* Settle for the current number of nops.  Update the history
6645              accordingly (for the benefit of any future .set reorder code).  */
6646           prev_nop_frag = NULL;
6647           insert_into_history (prev_nop_frag_since,
6648                                prev_nop_frag_holds, NOP_INSN);
6649         }
6650       else
6651         {
6652           /* Allow this instruction to replace one of the nops that was
6653              tentatively added to prev_nop_frag.  */
6654           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
6655           prev_nop_frag_holds--;
6656           prev_nop_frag_since++;
6657         }
6658     }
6659
6660   method = get_append_method (ip, address_expr, reloc_type);
6661   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
6662
6663   dwarf2_emit_insn (0);
6664   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
6665      so "move" the instruction address accordingly.
6666
6667      Also, it doesn't seem appropriate for the assembler to reorder .loc
6668      entries.  If this instruction is a branch that we are going to swap
6669      with the previous instruction, the two instructions should be
6670      treated as a unit, and the debug information for both instructions
6671      should refer to the start of the branch sequence.  Using the
6672      current position is certainly wrong when swapping a 32-bit branch
6673      and a 16-bit delay slot, since the current position would then be
6674      in the middle of a branch.  */
6675   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
6676
6677   relax32 = (mips_relax_branch
6678              /* Don't try branch relaxation within .set nomacro, or within
6679                 .set noat if we use $at for PIC computations.  If it turns
6680                 out that the branch was out-of-range, we'll get an error.  */
6681              && !mips_opts.warn_about_macros
6682              && (mips_opts.at || mips_pic == NO_PIC)
6683              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
6684                 as they have no complementing branches.  */
6685              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
6686
6687   if (!HAVE_CODE_COMPRESSION
6688       && address_expr
6689       && relax32
6690       && *reloc_type == BFD_RELOC_16_PCREL_S2
6691       && delayed_branch_p (ip))
6692     {
6693       relaxed_branch = TRUE;
6694       add_relaxed_insn (ip, (relaxed_branch_length
6695                              (NULL, NULL,
6696                               uncond_branch_p (ip) ? -1
6697                               : branch_likely_p (ip) ? 1
6698                               : 0)), 4,
6699                         RELAX_BRANCH_ENCODE
6700                         (AT,
6701                          uncond_branch_p (ip),
6702                          branch_likely_p (ip),
6703                          pinfo & INSN_WRITE_GPR_31,
6704                          0),
6705                         address_expr->X_add_symbol,
6706                         address_expr->X_add_number);
6707       *reloc_type = BFD_RELOC_UNUSED;
6708     }
6709   else if (mips_opts.micromips
6710            && address_expr
6711            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
6712                || *reloc_type > BFD_RELOC_UNUSED)
6713            && (delayed_branch_p (ip) || compact_branch_p (ip))
6714            /* Don't try branch relaxation when users specify
6715               16-bit/32-bit instructions.  */
6716            && !forced_insn_length)
6717     {
6718       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
6719       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
6720       int uncond = uncond_branch_p (ip) ? -1 : 0;
6721       int compact = compact_branch_p (ip);
6722       int al = pinfo & INSN_WRITE_GPR_31;
6723       int length32;
6724
6725       gas_assert (address_expr != NULL);
6726       gas_assert (!mips_relax.sequence);
6727
6728       relaxed_branch = TRUE;
6729       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
6730       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
6731                         RELAX_MICROMIPS_ENCODE (type, AT, uncond, compact, al,
6732                                                 relax32, 0, 0),
6733                         address_expr->X_add_symbol,
6734                         address_expr->X_add_number);
6735       *reloc_type = BFD_RELOC_UNUSED;
6736     }
6737   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
6738     {
6739       /* We need to set up a variant frag.  */
6740       gas_assert (address_expr != NULL);
6741       add_relaxed_insn (ip, 4, 0,
6742                         RELAX_MIPS16_ENCODE
6743                         (*reloc_type - BFD_RELOC_UNUSED,
6744                          forced_insn_length == 2, forced_insn_length == 4,
6745                          delayed_branch_p (&history[0]),
6746                          history[0].mips16_absolute_jump_p),
6747                         make_expr_symbol (address_expr), 0);
6748     }
6749   else if (mips_opts.mips16 && insn_length (ip) == 2)
6750     {
6751       if (!delayed_branch_p (ip))
6752         /* Make sure there is enough room to swap this instruction with
6753            a following jump instruction.  */
6754         frag_grow (6);
6755       add_fixed_insn (ip);
6756     }
6757   else
6758     {
6759       if (mips_opts.mips16
6760           && mips_opts.noreorder
6761           && delayed_branch_p (&history[0]))
6762         as_warn (_("extended instruction in delay slot"));
6763
6764       if (mips_relax.sequence)
6765         {
6766           /* If we've reached the end of this frag, turn it into a variant
6767              frag and record the information for the instructions we've
6768              written so far.  */
6769           if (frag_room () < 4)
6770             relax_close_frag ();
6771           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
6772         }
6773
6774       if (mips_relax.sequence != 2)
6775         {
6776           if (mips_macro_warning.first_insn_sizes[0] == 0)
6777             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
6778           mips_macro_warning.sizes[0] += insn_length (ip);
6779           mips_macro_warning.insns[0]++;
6780         }
6781       if (mips_relax.sequence != 1)
6782         {
6783           if (mips_macro_warning.first_insn_sizes[1] == 0)
6784             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
6785           mips_macro_warning.sizes[1] += insn_length (ip);
6786           mips_macro_warning.insns[1]++;
6787         }
6788
6789       if (mips_opts.mips16)
6790         {
6791           ip->fixed_p = 1;
6792           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
6793         }
6794       add_fixed_insn (ip);
6795     }
6796
6797   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
6798     {
6799       bfd_reloc_code_real_type final_type[3];
6800       reloc_howto_type *howto0;
6801       reloc_howto_type *howto;
6802       int i;
6803
6804       /* Perform any necessary conversion to microMIPS relocations
6805          and find out how many relocations there actually are.  */
6806       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
6807         final_type[i] = micromips_map_reloc (reloc_type[i]);
6808
6809       /* In a compound relocation, it is the final (outermost)
6810          operator that determines the relocated field.  */
6811       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
6812       if (!howto)
6813         abort ();
6814
6815       if (i > 1)
6816         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
6817       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
6818                                  bfd_get_reloc_size (howto),
6819                                  address_expr,
6820                                  howto0 && howto0->pc_relative,
6821                                  final_type[0]);
6822
6823       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
6824       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
6825         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
6826
6827       /* These relocations can have an addend that won't fit in
6828          4 octets for 64bit assembly.  */
6829       if (HAVE_64BIT_GPRS
6830           && ! howto->partial_inplace
6831           && (reloc_type[0] == BFD_RELOC_16
6832               || reloc_type[0] == BFD_RELOC_32
6833               || reloc_type[0] == BFD_RELOC_MIPS_JMP
6834               || reloc_type[0] == BFD_RELOC_GPREL16
6835               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
6836               || reloc_type[0] == BFD_RELOC_GPREL32
6837               || reloc_type[0] == BFD_RELOC_64
6838               || reloc_type[0] == BFD_RELOC_CTOR
6839               || reloc_type[0] == BFD_RELOC_MIPS_SUB
6840               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
6841               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
6842               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
6843               || reloc_type[0] == BFD_RELOC_MIPS_REL16
6844               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
6845               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
6846               || hi16_reloc_p (reloc_type[0])
6847               || lo16_reloc_p (reloc_type[0])))
6848         ip->fixp[0]->fx_no_overflow = 1;
6849
6850       /* These relocations can have an addend that won't fit in 2 octets.  */
6851       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
6852           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
6853         ip->fixp[0]->fx_no_overflow = 1;
6854
6855       if (mips_relax.sequence)
6856         {
6857           if (mips_relax.first_fixup == 0)
6858             mips_relax.first_fixup = ip->fixp[0];
6859         }
6860       else if (reloc_needs_lo_p (*reloc_type))
6861         {
6862           struct mips_hi_fixup *hi_fixup;
6863
6864           /* Reuse the last entry if it already has a matching %lo.  */
6865           hi_fixup = mips_hi_fixup_list;
6866           if (hi_fixup == 0
6867               || !fixup_has_matching_lo_p (hi_fixup->fixp))
6868             {
6869               hi_fixup = ((struct mips_hi_fixup *)
6870                           xmalloc (sizeof (struct mips_hi_fixup)));
6871               hi_fixup->next = mips_hi_fixup_list;
6872               mips_hi_fixup_list = hi_fixup;
6873             }
6874           hi_fixup->fixp = ip->fixp[0];
6875           hi_fixup->seg = now_seg;
6876         }
6877
6878       /* Add fixups for the second and third relocations, if given.
6879          Note that the ABI allows the second relocation to be
6880          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
6881          moment we only use RSS_UNDEF, but we could add support
6882          for the others if it ever becomes necessary.  */
6883       for (i = 1; i < 3; i++)
6884         if (reloc_type[i] != BFD_RELOC_UNUSED)
6885           {
6886             ip->fixp[i] = fix_new (ip->frag, ip->where,
6887                                    ip->fixp[0]->fx_size, NULL, 0,
6888                                    FALSE, final_type[i]);
6889
6890             /* Use fx_tcbit to mark compound relocs.  */
6891             ip->fixp[0]->fx_tcbit = 1;
6892             ip->fixp[i]->fx_tcbit = 1;
6893           }
6894     }
6895   install_insn (ip);
6896
6897   /* Update the register mask information.  */
6898   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
6899   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
6900
6901   switch (method)
6902     {
6903     case APPEND_ADD:
6904       insert_into_history (0, 1, ip);
6905       break;
6906
6907     case APPEND_ADD_WITH_NOP:
6908       {
6909         struct mips_cl_insn *nop;
6910
6911         insert_into_history (0, 1, ip);
6912         nop = get_delay_slot_nop (ip);
6913         add_fixed_insn (nop);
6914         insert_into_history (0, 1, nop);
6915         if (mips_relax.sequence)
6916           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
6917       }
6918       break;
6919
6920     case APPEND_ADD_COMPACT:
6921       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
6922       gas_assert (mips_opts.mips16);
6923       ip->insn_opcode |= 0x0080;
6924       find_altered_mips16_opcode (ip);
6925       install_insn (ip);
6926       insert_into_history (0, 1, ip);
6927       break;
6928
6929     case APPEND_SWAP:
6930       {
6931         struct mips_cl_insn delay = history[0];
6932         if (mips_opts.mips16)
6933           {
6934             know (delay.frag == ip->frag);
6935             move_insn (ip, delay.frag, delay.where);
6936             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
6937           }
6938         else if (relaxed_branch || delay.frag != ip->frag)
6939           {
6940             /* Add the delay slot instruction to the end of the
6941                current frag and shrink the fixed part of the
6942                original frag.  If the branch occupies the tail of
6943                the latter, move it backwards to cover the gap.  */
6944             delay.frag->fr_fix -= branch_disp;
6945             if (delay.frag == ip->frag)
6946               move_insn (ip, ip->frag, ip->where - branch_disp);
6947             add_fixed_insn (&delay);
6948           }
6949         else
6950           {
6951             move_insn (&delay, ip->frag,
6952                        ip->where - branch_disp + insn_length (ip));
6953             move_insn (ip, history[0].frag, history[0].where);
6954           }
6955         history[0] = *ip;
6956         delay.fixed_p = 1;
6957         insert_into_history (0, 1, &delay);
6958       }
6959       break;
6960     }
6961
6962   /* If we have just completed an unconditional branch, clear the history.  */
6963   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
6964       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
6965     {
6966       unsigned int i;
6967
6968       mips_no_prev_insn ();
6969
6970       for (i = 0; i < ARRAY_SIZE (history); i++)
6971         history[i].cleared_p = 1;
6972     }
6973
6974   /* We need to emit a label at the end of branch-likely macros.  */
6975   if (emit_branch_likely_macro)
6976     {
6977       emit_branch_likely_macro = FALSE;
6978       micromips_add_label ();
6979     }
6980
6981   /* We just output an insn, so the next one doesn't have a label.  */
6982   mips_clear_insn_labels ();
6983 }
6984
6985 /* Forget that there was any previous instruction or label.
6986    When BRANCH is true, the branch history is also flushed.  */
6987
6988 static void
6989 mips_no_prev_insn (void)
6990 {
6991   prev_nop_frag = NULL;
6992   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
6993   mips_clear_insn_labels ();
6994 }
6995
6996 /* This function must be called before we emit something other than
6997    instructions.  It is like mips_no_prev_insn except that it inserts
6998    any NOPS that might be needed by previous instructions.  */
6999
7000 void
7001 mips_emit_delays (void)
7002 {
7003   if (! mips_opts.noreorder)
7004     {
7005       int nops = nops_for_insn (0, history, NULL);
7006       if (nops > 0)
7007         {
7008           while (nops-- > 0)
7009             add_fixed_insn (NOP_INSN);
7010           mips_move_text_labels ();
7011         }
7012     }
7013   mips_no_prev_insn ();
7014 }
7015
7016 /* Start a (possibly nested) noreorder block.  */
7017
7018 static void
7019 start_noreorder (void)
7020 {
7021   if (mips_opts.noreorder == 0)
7022     {
7023       unsigned int i;
7024       int nops;
7025
7026       /* None of the instructions before the .set noreorder can be moved.  */
7027       for (i = 0; i < ARRAY_SIZE (history); i++)
7028         history[i].fixed_p = 1;
7029
7030       /* Insert any nops that might be needed between the .set noreorder
7031          block and the previous instructions.  We will later remove any
7032          nops that turn out not to be needed.  */
7033       nops = nops_for_insn (0, history, NULL);
7034       if (nops > 0)
7035         {
7036           if (mips_optimize != 0)
7037             {
7038               /* Record the frag which holds the nop instructions, so
7039                  that we can remove them if we don't need them.  */
7040               frag_grow (nops * NOP_INSN_SIZE);
7041               prev_nop_frag = frag_now;
7042               prev_nop_frag_holds = nops;
7043               prev_nop_frag_required = 0;
7044               prev_nop_frag_since = 0;
7045             }
7046
7047           for (; nops > 0; --nops)
7048             add_fixed_insn (NOP_INSN);
7049
7050           /* Move on to a new frag, so that it is safe to simply
7051              decrease the size of prev_nop_frag.  */
7052           frag_wane (frag_now);
7053           frag_new (0);
7054           mips_move_text_labels ();
7055         }
7056       mips_mark_labels ();
7057       mips_clear_insn_labels ();
7058     }
7059   mips_opts.noreorder++;
7060   mips_any_noreorder = 1;
7061 }
7062
7063 /* End a nested noreorder block.  */
7064
7065 static void
7066 end_noreorder (void)
7067 {
7068   mips_opts.noreorder--;
7069   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
7070     {
7071       /* Commit to inserting prev_nop_frag_required nops and go back to
7072          handling nop insertion the .set reorder way.  */
7073       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
7074                                 * NOP_INSN_SIZE);
7075       insert_into_history (prev_nop_frag_since,
7076                            prev_nop_frag_required, NOP_INSN);
7077       prev_nop_frag = NULL;
7078     }
7079 }
7080
7081 /* Sign-extend 32-bit mode constants that have bit 31 set and all
7082    higher bits unset.  */
7083
7084 static void
7085 normalize_constant_expr (expressionS *ex)
7086 {
7087   if (ex->X_op == O_constant
7088       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7089     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7090                         - 0x80000000);
7091 }
7092
7093 /* Sign-extend 32-bit mode address offsets that have bit 31 set and
7094    all higher bits unset.  */
7095
7096 static void
7097 normalize_address_expr (expressionS *ex)
7098 {
7099   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
7100         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
7101       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7102     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7103                         - 0x80000000);
7104 }
7105
7106 /* Try to match TOKENS against OPCODE, storing the result in INSN.
7107    Return true if the match was successful.
7108
7109    OPCODE_EXTRA is a value that should be ORed into the opcode
7110    (used for VU0 channel suffixes, etc.).  MORE_ALTS is true if
7111    there are more alternatives after OPCODE and SOFT_MATCH is
7112    as for mips_arg_info.  */
7113
7114 static bfd_boolean
7115 match_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7116             struct mips_operand_token *tokens, unsigned int opcode_extra,
7117             bfd_boolean lax_match, bfd_boolean complete_p)
7118 {
7119   const char *args;
7120   struct mips_arg_info arg;
7121   const struct mips_operand *operand;
7122   char c;
7123
7124   imm_expr.X_op = O_absent;
7125   offset_expr.X_op = O_absent;
7126   offset_reloc[0] = BFD_RELOC_UNUSED;
7127   offset_reloc[1] = BFD_RELOC_UNUSED;
7128   offset_reloc[2] = BFD_RELOC_UNUSED;
7129
7130   create_insn (insn, opcode);
7131   /* When no opcode suffix is specified, assume ".xyzw". */
7132   if ((opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0 && opcode_extra == 0)
7133     insn->insn_opcode |= 0xf << mips_vu0_channel_mask.lsb;
7134   else
7135     insn->insn_opcode |= opcode_extra;
7136   memset (&arg, 0, sizeof (arg));
7137   arg.insn = insn;
7138   arg.token = tokens;
7139   arg.argnum = 1;
7140   arg.last_regno = ILLEGAL_REG;
7141   arg.dest_regno = ILLEGAL_REG;
7142   arg.lax_match = lax_match;
7143   for (args = opcode->args;; ++args)
7144     {
7145       if (arg.token->type == OT_END)
7146         {
7147           /* Handle unary instructions in which only one operand is given.
7148              The source is then the same as the destination.  */
7149           if (arg.opnum == 1 && *args == ',')
7150             {
7151               operand = (mips_opts.micromips
7152                          ? decode_micromips_operand (args + 1)
7153                          : decode_mips_operand (args + 1));
7154               if (operand && mips_optional_operand_p (operand))
7155                 {
7156                   arg.token = tokens;
7157                   arg.argnum = 1;
7158                   continue;
7159                 }
7160             }
7161
7162           /* Treat elided base registers as $0.  */
7163           if (strcmp (args, "(b)") == 0)
7164             args += 3;
7165
7166           if (args[0] == '+')
7167             switch (args[1])
7168               {
7169               case 'K':
7170               case 'N':
7171                 /* The register suffix is optional. */
7172                 args += 2;
7173                 break;
7174               }
7175
7176           /* Fail the match if there were too few operands.  */
7177           if (*args)
7178             return FALSE;
7179
7180           /* Successful match.  */
7181           if (!complete_p)
7182             return TRUE;
7183           clear_insn_error ();
7184           if (arg.dest_regno == arg.last_regno
7185               && strncmp (insn->insn_mo->name, "jalr", 4) == 0)
7186             {
7187               if (arg.opnum == 2)
7188                 set_insn_error
7189                   (0, _("source and destination must be different"));
7190               else if (arg.last_regno == 31)
7191                 set_insn_error
7192                   (0, _("a destination register must be supplied"));
7193             }
7194           else if (arg.last_regno == 31
7195                    && (strncmp (insn->insn_mo->name, "bltzal", 6) == 0
7196                        || strncmp (insn->insn_mo->name, "bgezal", 6) == 0))
7197             set_insn_error (0, _("the source register must not be $31"));
7198           check_completed_insn (&arg);
7199           return TRUE;
7200         }
7201
7202       /* Fail the match if the line has too many operands.   */
7203       if (*args == 0)
7204         return FALSE;
7205
7206       /* Handle characters that need to match exactly.  */
7207       if (*args == '(' || *args == ')' || *args == ',')
7208         {
7209           if (match_char (&arg, *args))
7210             continue;
7211           return FALSE;
7212         }
7213       if (*args == '#')
7214         {
7215           ++args;
7216           if (arg.token->type == OT_DOUBLE_CHAR
7217               && arg.token->u.ch == *args)
7218             {
7219               ++arg.token;
7220               continue;
7221             }
7222           return FALSE;
7223         }
7224
7225       /* Handle special macro operands.  Work out the properties of
7226          other operands.  */
7227       arg.opnum += 1;
7228       switch (*args)
7229         {
7230         case '+':
7231           switch (args[1])
7232             {
7233             case 'i':
7234               *offset_reloc = BFD_RELOC_MIPS_JMP;
7235               break;
7236             }
7237           break;
7238
7239         case 'I':
7240           if (!match_const_int (&arg, &imm_expr.X_add_number))
7241             return FALSE;
7242           imm_expr.X_op = O_constant;
7243           if (HAVE_32BIT_GPRS)
7244             normalize_constant_expr (&imm_expr);
7245           continue;
7246
7247         case 'A':
7248           if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
7249             {
7250               /* Assume that the offset has been elided and that what
7251                  we saw was a base register.  The match will fail later
7252                  if that assumption turns out to be wrong.  */
7253               offset_expr.X_op = O_constant;
7254               offset_expr.X_add_number = 0;
7255             }
7256           else
7257             {
7258               if (!match_expression (&arg, &offset_expr, offset_reloc))
7259                 return FALSE;
7260               normalize_address_expr (&offset_expr);
7261             }
7262           continue;
7263
7264         case 'F':
7265           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7266                                      8, TRUE))
7267             return FALSE;
7268           continue;
7269
7270         case 'L':
7271           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7272                                      8, FALSE))
7273             return FALSE;
7274           continue;
7275
7276         case 'f':
7277           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7278                                      4, TRUE))
7279             return FALSE;
7280           continue;
7281
7282         case 'l':
7283           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7284                                      4, FALSE))
7285             return FALSE;
7286           continue;
7287
7288         case 'p':
7289           *offset_reloc = BFD_RELOC_16_PCREL_S2;
7290           break;
7291
7292         case 'a':
7293           *offset_reloc = BFD_RELOC_MIPS_JMP;
7294           break;
7295
7296         case 'm':
7297           gas_assert (mips_opts.micromips);
7298           c = args[1];
7299           switch (c)
7300             {
7301             case 'D':
7302             case 'E':
7303               if (!forced_insn_length)
7304                 *offset_reloc = (int) BFD_RELOC_UNUSED + c;
7305               else if (c == 'D')
7306                 *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
7307               else
7308                 *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
7309               break;
7310             }
7311           break;
7312         }
7313
7314       operand = (mips_opts.micromips
7315                  ? decode_micromips_operand (args)
7316                  : decode_mips_operand (args));
7317       if (!operand)
7318         abort ();
7319
7320       /* Skip prefixes.  */
7321       if (*args == '+' || *args == 'm')
7322         args++;
7323
7324       if (mips_optional_operand_p (operand)
7325           && args[1] == ','
7326           && (arg.token[0].type != OT_REG
7327               || arg.token[1].type == OT_END))
7328         {
7329           /* Assume that the register has been elided and is the
7330              same as the first operand.  */
7331           arg.token = tokens;
7332           arg.argnum = 1;
7333         }
7334
7335       if (!match_operand (&arg, operand))
7336         return FALSE;
7337     }
7338 }
7339
7340 /* Like match_insn, but for MIPS16.  */
7341
7342 static bfd_boolean
7343 match_mips16_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7344                    struct mips_operand_token *tokens)
7345 {
7346   const char *args;
7347   const struct mips_operand *operand;
7348   const struct mips_operand *ext_operand;
7349   struct mips_arg_info arg;
7350   int relax_char;
7351
7352   create_insn (insn, opcode);
7353   imm_expr.X_op = O_absent;
7354   offset_expr.X_op = O_absent;
7355   offset_reloc[0] = BFD_RELOC_UNUSED;
7356   offset_reloc[1] = BFD_RELOC_UNUSED;
7357   offset_reloc[2] = BFD_RELOC_UNUSED;
7358   relax_char = 0;
7359
7360   memset (&arg, 0, sizeof (arg));
7361   arg.insn = insn;
7362   arg.token = tokens;
7363   arg.argnum = 1;
7364   arg.last_regno = ILLEGAL_REG;
7365   arg.dest_regno = ILLEGAL_REG;
7366   relax_char = 0;
7367   for (args = opcode->args;; ++args)
7368     {
7369       int c;
7370
7371       if (arg.token->type == OT_END)
7372         {
7373           offsetT value;
7374
7375           /* Handle unary instructions in which only one operand is given.
7376              The source is then the same as the destination.  */
7377           if (arg.opnum == 1 && *args == ',')
7378             {
7379               operand = decode_mips16_operand (args[1], FALSE);
7380               if (operand && mips_optional_operand_p (operand))
7381                 {
7382                   arg.token = tokens;
7383                   arg.argnum = 1;
7384                   continue;
7385                 }
7386             }
7387
7388           /* Fail the match if there were too few operands.  */
7389           if (*args)
7390             return FALSE;
7391
7392           /* Successful match.  Stuff the immediate value in now, if
7393              we can.  */
7394           clear_insn_error ();
7395           if (opcode->pinfo == INSN_MACRO)
7396             {
7397               gas_assert (relax_char == 0 || relax_char == 'p');
7398               gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
7399             }
7400           else if (relax_char
7401                    && offset_expr.X_op == O_constant
7402                    && calculate_reloc (*offset_reloc,
7403                                        offset_expr.X_add_number,
7404                                        &value))
7405             {
7406               mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
7407                             forced_insn_length, &insn->insn_opcode);
7408               offset_expr.X_op = O_absent;
7409               *offset_reloc = BFD_RELOC_UNUSED;
7410             }
7411           else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
7412             {
7413               if (forced_insn_length == 2)
7414                 set_insn_error (0, _("invalid unextended operand value"));
7415               forced_insn_length = 4;
7416               insn->insn_opcode |= MIPS16_EXTEND;
7417             }
7418           else if (relax_char)
7419             *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
7420
7421           check_completed_insn (&arg);
7422           return TRUE;
7423         }
7424
7425       /* Fail the match if the line has too many operands.   */
7426       if (*args == 0)
7427         return FALSE;
7428
7429       /* Handle characters that need to match exactly.  */
7430       if (*args == '(' || *args == ')' || *args == ',')
7431         {
7432           if (match_char (&arg, *args))
7433             continue;
7434           return FALSE;
7435         }
7436
7437       arg.opnum += 1;
7438       c = *args;
7439       switch (c)
7440         {
7441         case 'p':
7442         case 'q':
7443         case 'A':
7444         case 'B':
7445         case 'E':
7446           relax_char = c;
7447           break;
7448
7449         case 'I':
7450           if (!match_const_int (&arg, &imm_expr.X_add_number))
7451             return FALSE;
7452           imm_expr.X_op = O_constant;
7453           if (HAVE_32BIT_GPRS)
7454             normalize_constant_expr (&imm_expr);
7455           continue;
7456
7457         case 'a':
7458         case 'i':
7459           *offset_reloc = BFD_RELOC_MIPS16_JMP;
7460           insn->insn_opcode <<= 16;
7461           break;
7462         }
7463
7464       operand = decode_mips16_operand (c, FALSE);
7465       if (!operand)
7466         abort ();
7467
7468       /* '6' is a special case.  It is used for BREAK and SDBBP,
7469          whose operands are only meaningful to the software that decodes
7470          them.  This means that there is no architectural reason why
7471          they cannot be prefixed by EXTEND, but in practice,
7472          exception handlers will only look at the instruction
7473          itself.  We therefore allow '6' to be extended when
7474          disassembling but not when assembling.  */
7475       if (operand->type != OP_PCREL && c != '6')
7476         {
7477           ext_operand = decode_mips16_operand (c, TRUE);
7478           if (operand != ext_operand)
7479             {
7480               if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
7481                 {
7482                   offset_expr.X_op = O_constant;
7483                   offset_expr.X_add_number = 0;
7484                   relax_char = c;
7485                   continue;
7486                 }
7487
7488               /* We need the OT_INTEGER check because some MIPS16
7489                  immediate variants are listed before the register ones.  */
7490               if (arg.token->type != OT_INTEGER
7491                   || !match_expression (&arg, &offset_expr, offset_reloc))
7492                 return FALSE;
7493
7494               /* '8' is used for SLTI(U) and has traditionally not
7495                  been allowed to take relocation operators.  */
7496               if (offset_reloc[0] != BFD_RELOC_UNUSED
7497                   && (ext_operand->size != 16 || c == '8'))
7498                 return FALSE;
7499
7500               relax_char = c;
7501               continue;
7502             }
7503         }
7504
7505       if (mips_optional_operand_p (operand)
7506           && args[1] == ','
7507           && (arg.token[0].type != OT_REG
7508               || arg.token[1].type == OT_END))
7509         {
7510           /* Assume that the register has been elided and is the
7511              same as the first operand.  */
7512           arg.token = tokens;
7513           arg.argnum = 1;
7514         }
7515
7516       if (!match_operand (&arg, operand))
7517         return FALSE;
7518     }
7519 }
7520
7521 /* Record that the current instruction is invalid for the current ISA.  */
7522
7523 static void
7524 match_invalid_for_isa (void)
7525 {
7526   set_insn_error_ss
7527     (0, _("opcode not supported on this processor: %s (%s)"),
7528      mips_cpu_info_from_arch (mips_opts.arch)->name,
7529      mips_cpu_info_from_isa (mips_opts.isa)->name);
7530 }
7531
7532 /* Try to match TOKENS against a series of opcode entries, starting at FIRST.
7533    Return true if a definite match or failure was found, storing any match
7534    in INSN.  OPCODE_EXTRA is a value that should be ORed into the opcode
7535    (to handle things like VU0 suffixes).  LAX_MATCH is true if we have already
7536    tried and failed to match under normal conditions and now want to try a
7537    more relaxed match.  */
7538
7539 static bfd_boolean
7540 match_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
7541              const struct mips_opcode *past, struct mips_operand_token *tokens,
7542              int opcode_extra, bfd_boolean lax_match)
7543 {
7544   const struct mips_opcode *opcode;
7545   const struct mips_opcode *invalid_delay_slot;
7546   bfd_boolean seen_valid_for_isa, seen_valid_for_size;
7547
7548   /* Search for a match, ignoring alternatives that don't satisfy the
7549      current ISA or forced_length.  */
7550   invalid_delay_slot = 0;
7551   seen_valid_for_isa = FALSE;
7552   seen_valid_for_size = FALSE;
7553   opcode = first;
7554   do
7555     {
7556       gas_assert (strcmp (opcode->name, first->name) == 0);
7557       if (is_opcode_valid (opcode))
7558         {
7559           seen_valid_for_isa = TRUE;
7560           if (is_size_valid (opcode))
7561             {
7562               bfd_boolean delay_slot_ok;
7563
7564               seen_valid_for_size = TRUE;
7565               delay_slot_ok = is_delay_slot_valid (opcode);
7566               if (match_insn (insn, opcode, tokens, opcode_extra,
7567                               lax_match, delay_slot_ok))
7568                 {
7569                   if (!delay_slot_ok)
7570                     {
7571                       if (!invalid_delay_slot)
7572                         invalid_delay_slot = opcode;
7573                     }
7574                   else
7575                     return TRUE;
7576                 }
7577             }
7578         }
7579       ++opcode;
7580     }
7581   while (opcode < past && strcmp (opcode->name, first->name) == 0);
7582
7583   /* If the only matches we found had the wrong length for the delay slot,
7584      pick the first such match.  We'll issue an appropriate warning later.  */
7585   if (invalid_delay_slot)
7586     {
7587       if (match_insn (insn, invalid_delay_slot, tokens, opcode_extra,
7588                       lax_match, TRUE))
7589         return TRUE;
7590       abort ();
7591     }
7592
7593   /* Handle the case where we didn't try to match an instruction because
7594      all the alternatives were incompatible with the current ISA.  */
7595   if (!seen_valid_for_isa)
7596     {
7597       match_invalid_for_isa ();
7598       return TRUE;
7599     }
7600
7601   /* Handle the case where we didn't try to match an instruction because
7602      all the alternatives were of the wrong size.  */
7603   if (!seen_valid_for_size)
7604     {
7605       if (mips_opts.insn32)
7606         set_insn_error (0, _("opcode not supported in the `insn32' mode"));
7607       else
7608         set_insn_error_i
7609           (0, _("unrecognized %d-bit version of microMIPS opcode"),
7610            8 * forced_insn_length);
7611       return TRUE;
7612     }
7613
7614   return FALSE;
7615 }
7616
7617 /* Like match_insns, but for MIPS16.  */
7618
7619 static bfd_boolean
7620 match_mips16_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
7621                     struct mips_operand_token *tokens)
7622 {
7623   const struct mips_opcode *opcode;
7624   bfd_boolean seen_valid_for_isa;
7625
7626   /* Search for a match, ignoring alternatives that don't satisfy the
7627      current ISA.  There are no separate entries for extended forms so
7628      we deal with forced_length later.  */
7629   seen_valid_for_isa = FALSE;
7630   opcode = first;
7631   do
7632     {
7633       gas_assert (strcmp (opcode->name, first->name) == 0);
7634       if (is_opcode_valid_16 (opcode))
7635         {
7636           seen_valid_for_isa = TRUE;
7637           if (match_mips16_insn (insn, opcode, tokens))
7638             return TRUE;
7639         }
7640       ++opcode;
7641     }
7642   while (opcode < &mips16_opcodes[bfd_mips16_num_opcodes]
7643          && strcmp (opcode->name, first->name) == 0);
7644
7645   /* Handle the case where we didn't try to match an instruction because
7646      all the alternatives were incompatible with the current ISA.  */
7647   if (!seen_valid_for_isa)
7648     {
7649       match_invalid_for_isa ();
7650       return TRUE;
7651     }
7652
7653   return FALSE;
7654 }
7655
7656 /* Set up global variables for the start of a new macro.  */
7657
7658 static void
7659 macro_start (void)
7660 {
7661   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
7662   memset (&mips_macro_warning.first_insn_sizes, 0,
7663           sizeof (mips_macro_warning.first_insn_sizes));
7664   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
7665   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
7666                                      && delayed_branch_p (&history[0]));
7667   switch (history[0].insn_mo->pinfo2
7668           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
7669     {
7670     case INSN2_BRANCH_DELAY_32BIT:
7671       mips_macro_warning.delay_slot_length = 4;
7672       break;
7673     case INSN2_BRANCH_DELAY_16BIT:
7674       mips_macro_warning.delay_slot_length = 2;
7675       break;
7676     default:
7677       mips_macro_warning.delay_slot_length = 0;
7678       break;
7679     }
7680   mips_macro_warning.first_frag = NULL;
7681 }
7682
7683 /* Given that a macro is longer than one instruction or of the wrong size,
7684    return the appropriate warning for it.  Return null if no warning is
7685    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
7686    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
7687    and RELAX_NOMACRO.  */
7688
7689 static const char *
7690 macro_warning (relax_substateT subtype)
7691 {
7692   if (subtype & RELAX_DELAY_SLOT)
7693     return _("macro instruction expanded into multiple instructions"
7694              " in a branch delay slot");
7695   else if (subtype & RELAX_NOMACRO)
7696     return _("macro instruction expanded into multiple instructions");
7697   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
7698                       | RELAX_DELAY_SLOT_SIZE_SECOND))
7699     return ((subtype & RELAX_DELAY_SLOT_16BIT)
7700             ? _("macro instruction expanded into a wrong size instruction"
7701                 " in a 16-bit branch delay slot")
7702             : _("macro instruction expanded into a wrong size instruction"
7703                 " in a 32-bit branch delay slot"));
7704   else
7705     return 0;
7706 }
7707
7708 /* Finish up a macro.  Emit warnings as appropriate.  */
7709
7710 static void
7711 macro_end (void)
7712 {
7713   /* Relaxation warning flags.  */
7714   relax_substateT subtype = 0;
7715
7716   /* Check delay slot size requirements.  */
7717   if (mips_macro_warning.delay_slot_length == 2)
7718     subtype |= RELAX_DELAY_SLOT_16BIT;
7719   if (mips_macro_warning.delay_slot_length != 0)
7720     {
7721       if (mips_macro_warning.delay_slot_length
7722           != mips_macro_warning.first_insn_sizes[0])
7723         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
7724       if (mips_macro_warning.delay_slot_length
7725           != mips_macro_warning.first_insn_sizes[1])
7726         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
7727     }
7728
7729   /* Check instruction count requirements.  */
7730   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
7731     {
7732       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
7733         subtype |= RELAX_SECOND_LONGER;
7734       if (mips_opts.warn_about_macros)
7735         subtype |= RELAX_NOMACRO;
7736       if (mips_macro_warning.delay_slot_p)
7737         subtype |= RELAX_DELAY_SLOT;
7738     }
7739
7740   /* If both alternatives fail to fill a delay slot correctly,
7741      emit the warning now.  */
7742   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
7743       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
7744     {
7745       relax_substateT s;
7746       const char *msg;
7747
7748       s = subtype & (RELAX_DELAY_SLOT_16BIT
7749                      | RELAX_DELAY_SLOT_SIZE_FIRST
7750                      | RELAX_DELAY_SLOT_SIZE_SECOND);
7751       msg = macro_warning (s);
7752       if (msg != NULL)
7753         as_warn ("%s", msg);
7754       subtype &= ~s;
7755     }
7756
7757   /* If both implementations are longer than 1 instruction, then emit the
7758      warning now.  */
7759   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
7760     {
7761       relax_substateT s;
7762       const char *msg;
7763
7764       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
7765       msg = macro_warning (s);
7766       if (msg != NULL)
7767         as_warn ("%s", msg);
7768       subtype &= ~s;
7769     }
7770
7771   /* If any flags still set, then one implementation might need a warning
7772      and the other either will need one of a different kind or none at all.
7773      Pass any remaining flags over to relaxation.  */
7774   if (mips_macro_warning.first_frag != NULL)
7775     mips_macro_warning.first_frag->fr_subtype |= subtype;
7776 }
7777
7778 /* Instruction operand formats used in macros that vary between
7779    standard MIPS and microMIPS code.  */
7780
7781 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
7782 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
7783 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
7784 static const char * const lui_fmt[2] = { "t,u", "s,u" };
7785 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
7786 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
7787 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
7788 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
7789
7790 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
7791 #define COP12_FMT (cop12_fmt[mips_opts.micromips])
7792 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
7793 #define LUI_FMT (lui_fmt[mips_opts.micromips])
7794 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
7795 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
7796 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
7797 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
7798
7799 /* Read a macro's relocation codes from *ARGS and store them in *R.
7800    The first argument in *ARGS will be either the code for a single
7801    relocation or -1 followed by the three codes that make up a
7802    composite relocation.  */
7803
7804 static void
7805 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
7806 {
7807   int i, next;
7808
7809   next = va_arg (*args, int);
7810   if (next >= 0)
7811     r[0] = (bfd_reloc_code_real_type) next;
7812   else
7813     {
7814       for (i = 0; i < 3; i++)
7815         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
7816       /* This function is only used for 16-bit relocation fields.
7817          To make the macro code simpler, treat an unrelocated value
7818          in the same way as BFD_RELOC_LO16.  */
7819       if (r[0] == BFD_RELOC_UNUSED)
7820         r[0] = BFD_RELOC_LO16;
7821     }
7822 }
7823
7824 /* Build an instruction created by a macro expansion.  This is passed
7825    a pointer to the count of instructions created so far, an
7826    expression, the name of the instruction to build, an operand format
7827    string, and corresponding arguments.  */
7828
7829 static void
7830 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
7831 {
7832   const struct mips_opcode *mo = NULL;
7833   bfd_reloc_code_real_type r[3];
7834   const struct mips_opcode *amo;
7835   const struct mips_operand *operand;
7836   struct hash_control *hash;
7837   struct mips_cl_insn insn;
7838   va_list args;
7839   unsigned int uval;
7840
7841   va_start (args, fmt);
7842
7843   if (mips_opts.mips16)
7844     {
7845       mips16_macro_build (ep, name, fmt, &args);
7846       va_end (args);
7847       return;
7848     }
7849
7850   r[0] = BFD_RELOC_UNUSED;
7851   r[1] = BFD_RELOC_UNUSED;
7852   r[2] = BFD_RELOC_UNUSED;
7853   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
7854   amo = (struct mips_opcode *) hash_find (hash, name);
7855   gas_assert (amo);
7856   gas_assert (strcmp (name, amo->name) == 0);
7857
7858   do
7859     {
7860       /* Search until we get a match for NAME.  It is assumed here that
7861          macros will never generate MDMX, MIPS-3D, or MT instructions.
7862          We try to match an instruction that fulfils the branch delay
7863          slot instruction length requirement (if any) of the previous
7864          instruction.  While doing this we record the first instruction
7865          seen that matches all the other conditions and use it anyway
7866          if the requirement cannot be met; we will issue an appropriate
7867          warning later on.  */
7868       if (strcmp (fmt, amo->args) == 0
7869           && amo->pinfo != INSN_MACRO
7870           && is_opcode_valid (amo)
7871           && is_size_valid (amo))
7872         {
7873           if (is_delay_slot_valid (amo))
7874             {
7875               mo = amo;
7876               break;
7877             }
7878           else if (!mo)
7879             mo = amo;
7880         }
7881
7882       ++amo;
7883       gas_assert (amo->name);
7884     }
7885   while (strcmp (name, amo->name) == 0);
7886
7887   gas_assert (mo);
7888   create_insn (&insn, mo);
7889   for (; *fmt; ++fmt)
7890     {
7891       switch (*fmt)
7892         {
7893         case ',':
7894         case '(':
7895         case ')':
7896         case 'z':
7897           break;
7898
7899         case 'i':
7900         case 'j':
7901           macro_read_relocs (&args, r);
7902           gas_assert (*r == BFD_RELOC_GPREL16
7903                       || *r == BFD_RELOC_MIPS_HIGHER
7904                       || *r == BFD_RELOC_HI16_S
7905                       || *r == BFD_RELOC_LO16
7906                       || *r == BFD_RELOC_MIPS_GOT_OFST);
7907           break;
7908
7909         case 'o':
7910           macro_read_relocs (&args, r);
7911           break;
7912
7913         case 'u':
7914           macro_read_relocs (&args, r);
7915           gas_assert (ep != NULL
7916                       && (ep->X_op == O_constant
7917                           || (ep->X_op == O_symbol
7918                               && (*r == BFD_RELOC_MIPS_HIGHEST
7919                                   || *r == BFD_RELOC_HI16_S
7920                                   || *r == BFD_RELOC_HI16
7921                                   || *r == BFD_RELOC_GPREL16
7922                                   || *r == BFD_RELOC_MIPS_GOT_HI16
7923                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
7924           break;
7925
7926         case 'p':
7927           gas_assert (ep != NULL);
7928
7929           /*
7930            * This allows macro() to pass an immediate expression for
7931            * creating short branches without creating a symbol.
7932            *
7933            * We don't allow branch relaxation for these branches, as
7934            * they should only appear in ".set nomacro" anyway.
7935            */
7936           if (ep->X_op == O_constant)
7937             {
7938               /* For microMIPS we always use relocations for branches.
7939                  So we should not resolve immediate values.  */
7940               gas_assert (!mips_opts.micromips);
7941
7942               if ((ep->X_add_number & 3) != 0)
7943                 as_bad (_("branch to misaligned address (0x%lx)"),
7944                         (unsigned long) ep->X_add_number);
7945               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
7946                 as_bad (_("branch address range overflow (0x%lx)"),
7947                         (unsigned long) ep->X_add_number);
7948               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
7949               ep = NULL;
7950             }
7951           else
7952             *r = BFD_RELOC_16_PCREL_S2;
7953           break;
7954
7955         case 'a':
7956           gas_assert (ep != NULL);
7957           *r = BFD_RELOC_MIPS_JMP;
7958           break;
7959
7960         default:
7961           operand = (mips_opts.micromips
7962                      ? decode_micromips_operand (fmt)
7963                      : decode_mips_operand (fmt));
7964           if (!operand)
7965             abort ();
7966
7967           uval = va_arg (args, int);
7968           if (operand->type == OP_CLO_CLZ_DEST)
7969             uval |= (uval << 5);
7970           insn_insert_operand (&insn, operand, uval);
7971
7972           if (*fmt == '+' || *fmt == 'm')
7973             ++fmt;
7974           break;
7975         }
7976     }
7977   va_end (args);
7978   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
7979
7980   append_insn (&insn, ep, r, TRUE);
7981 }
7982
7983 static void
7984 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
7985                     va_list *args)
7986 {
7987   struct mips_opcode *mo;
7988   struct mips_cl_insn insn;
7989   const struct mips_operand *operand;
7990   bfd_reloc_code_real_type r[3]
7991     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
7992
7993   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
7994   gas_assert (mo);
7995   gas_assert (strcmp (name, mo->name) == 0);
7996
7997   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
7998     {
7999       ++mo;
8000       gas_assert (mo->name);
8001       gas_assert (strcmp (name, mo->name) == 0);
8002     }
8003
8004   create_insn (&insn, mo);
8005   for (; *fmt; ++fmt)
8006     {
8007       int c;
8008
8009       c = *fmt;
8010       switch (c)
8011         {
8012         case ',':
8013         case '(':
8014         case ')':
8015           break;
8016
8017         case '0':
8018         case 'S':
8019         case 'P':
8020         case 'R':
8021           break;
8022
8023         case '<':
8024         case '>':
8025         case '4':
8026         case '5':
8027         case 'H':
8028         case 'W':
8029         case 'D':
8030         case 'j':
8031         case '8':
8032         case 'V':
8033         case 'C':
8034         case 'U':
8035         case 'k':
8036         case 'K':
8037         case 'p':
8038         case 'q':
8039           {
8040             offsetT value;
8041
8042             gas_assert (ep != NULL);
8043
8044             if (ep->X_op != O_constant)
8045               *r = (int) BFD_RELOC_UNUSED + c;
8046             else if (calculate_reloc (*r, ep->X_add_number, &value))
8047               {
8048                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
8049                 ep = NULL;
8050                 *r = BFD_RELOC_UNUSED;
8051               }
8052           }
8053           break;
8054
8055         default:
8056           operand = decode_mips16_operand (c, FALSE);
8057           if (!operand)
8058             abort ();
8059
8060           insn_insert_operand (&insn, operand, va_arg (*args, int));
8061           break;
8062         }
8063     }
8064
8065   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
8066
8067   append_insn (&insn, ep, r, TRUE);
8068 }
8069
8070 /*
8071  * Generate a "jalr" instruction with a relocation hint to the called
8072  * function.  This occurs in NewABI PIC code.
8073  */
8074 static void
8075 macro_build_jalr (expressionS *ep, int cprestore)
8076 {
8077   static const bfd_reloc_code_real_type jalr_relocs[2]
8078     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
8079   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
8080   const char *jalr;
8081   char *f = NULL;
8082
8083   if (MIPS_JALR_HINT_P (ep))
8084     {
8085       frag_grow (8);
8086       f = frag_more (0);
8087     }
8088   if (mips_opts.micromips)
8089     {
8090       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
8091               ? "jalr" : "jalrs");
8092       if (MIPS_JALR_HINT_P (ep)
8093           || mips_opts.insn32
8094           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8095         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
8096       else
8097         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
8098     }
8099   else
8100     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
8101   if (MIPS_JALR_HINT_P (ep))
8102     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
8103 }
8104
8105 /*
8106  * Generate a "lui" instruction.
8107  */
8108 static void
8109 macro_build_lui (expressionS *ep, int regnum)
8110 {
8111   gas_assert (! mips_opts.mips16);
8112
8113   if (ep->X_op != O_constant)
8114     {
8115       gas_assert (ep->X_op == O_symbol);
8116       /* _gp_disp is a special case, used from s_cpload.
8117          __gnu_local_gp is used if mips_no_shared.  */
8118       gas_assert (mips_pic == NO_PIC
8119               || (! HAVE_NEWABI
8120                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
8121               || (! mips_in_shared
8122                   && strcmp (S_GET_NAME (ep->X_add_symbol),
8123                              "__gnu_local_gp") == 0));
8124     }
8125
8126   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
8127 }
8128
8129 /* Generate a sequence of instructions to do a load or store from a constant
8130    offset off of a base register (breg) into/from a target register (treg),
8131    using AT if necessary.  */
8132 static void
8133 macro_build_ldst_constoffset (expressionS *ep, const char *op,
8134                               int treg, int breg, int dbl)
8135 {
8136   gas_assert (ep->X_op == O_constant);
8137
8138   /* Sign-extending 32-bit constants makes their handling easier.  */
8139   if (!dbl)
8140     normalize_constant_expr (ep);
8141
8142   /* Right now, this routine can only handle signed 32-bit constants.  */
8143   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
8144     as_warn (_("operand overflow"));
8145
8146   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
8147     {
8148       /* Signed 16-bit offset will fit in the op.  Easy!  */
8149       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
8150     }
8151   else
8152     {
8153       /* 32-bit offset, need multiple instructions and AT, like:
8154            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
8155            addu     $tempreg,$tempreg,$breg
8156            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
8157          to handle the complete offset.  */
8158       macro_build_lui (ep, AT);
8159       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
8160       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
8161
8162       if (!mips_opts.at)
8163         as_bad (_("macro used $at after \".set noat\""));
8164     }
8165 }
8166
8167 /*                      set_at()
8168  * Generates code to set the $at register to true (one)
8169  * if reg is less than the immediate expression.
8170  */
8171 static void
8172 set_at (int reg, int unsignedp)
8173 {
8174   if (imm_expr.X_add_number >= -0x8000
8175       && imm_expr.X_add_number < 0x8000)
8176     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
8177                  AT, reg, BFD_RELOC_LO16);
8178   else
8179     {
8180       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
8181       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
8182     }
8183 }
8184
8185 /* Count the leading zeroes by performing a binary chop. This is a
8186    bulky bit of source, but performance is a LOT better for the
8187    majority of values than a simple loop to count the bits:
8188        for (lcnt = 0; (lcnt < 32); lcnt++)
8189          if ((v) & (1 << (31 - lcnt)))
8190            break;
8191   However it is not code size friendly, and the gain will drop a bit
8192   on certain cached systems.
8193 */
8194 #define COUNT_TOP_ZEROES(v)             \
8195   (((v) & ~0xffff) == 0                 \
8196    ? ((v) & ~0xff) == 0                 \
8197      ? ((v) & ~0xf) == 0                \
8198        ? ((v) & ~0x3) == 0              \
8199          ? ((v) & ~0x1) == 0            \
8200            ? !(v)                       \
8201              ? 32                       \
8202              : 31                       \
8203            : 30                         \
8204          : ((v) & ~0x7) == 0            \
8205            ? 29                         \
8206            : 28                         \
8207        : ((v) & ~0x3f) == 0             \
8208          ? ((v) & ~0x1f) == 0           \
8209            ? 27                         \
8210            : 26                         \
8211          : ((v) & ~0x7f) == 0           \
8212            ? 25                         \
8213            : 24                         \
8214      : ((v) & ~0xfff) == 0              \
8215        ? ((v) & ~0x3ff) == 0            \
8216          ? ((v) & ~0x1ff) == 0          \
8217            ? 23                         \
8218            : 22                         \
8219          : ((v) & ~0x7ff) == 0          \
8220            ? 21                         \
8221            : 20                         \
8222        : ((v) & ~0x3fff) == 0           \
8223          ? ((v) & ~0x1fff) == 0         \
8224            ? 19                         \
8225            : 18                         \
8226          : ((v) & ~0x7fff) == 0         \
8227            ? 17                         \
8228            : 16                         \
8229    : ((v) & ~0xffffff) == 0             \
8230      ? ((v) & ~0xfffff) == 0            \
8231        ? ((v) & ~0x3ffff) == 0          \
8232          ? ((v) & ~0x1ffff) == 0        \
8233            ? 15                         \
8234            : 14                         \
8235          : ((v) & ~0x7ffff) == 0        \
8236            ? 13                         \
8237            : 12                         \
8238        : ((v) & ~0x3fffff) == 0         \
8239          ? ((v) & ~0x1fffff) == 0       \
8240            ? 11                         \
8241            : 10                         \
8242          : ((v) & ~0x7fffff) == 0       \
8243            ? 9                          \
8244            : 8                          \
8245      : ((v) & ~0xfffffff) == 0          \
8246        ? ((v) & ~0x3ffffff) == 0        \
8247          ? ((v) & ~0x1ffffff) == 0      \
8248            ? 7                          \
8249            : 6                          \
8250          : ((v) & ~0x7ffffff) == 0      \
8251            ? 5                          \
8252            : 4                          \
8253        : ((v) & ~0x3fffffff) == 0       \
8254          ? ((v) & ~0x1fffffff) == 0     \
8255            ? 3                          \
8256            : 2                          \
8257          : ((v) & ~0x7fffffff) == 0     \
8258            ? 1                          \
8259            : 0)
8260
8261 /*                      load_register()
8262  *  This routine generates the least number of instructions necessary to load
8263  *  an absolute expression value into a register.
8264  */
8265 static void
8266 load_register (int reg, expressionS *ep, int dbl)
8267 {
8268   int freg;
8269   expressionS hi32, lo32;
8270
8271   if (ep->X_op != O_big)
8272     {
8273       gas_assert (ep->X_op == O_constant);
8274
8275       /* Sign-extending 32-bit constants makes their handling easier.  */
8276       if (!dbl)
8277         normalize_constant_expr (ep);
8278
8279       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
8280         {
8281           /* We can handle 16 bit signed values with an addiu to
8282              $zero.  No need to ever use daddiu here, since $zero and
8283              the result are always correct in 32 bit mode.  */
8284           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8285           return;
8286         }
8287       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
8288         {
8289           /* We can handle 16 bit unsigned values with an ori to
8290              $zero.  */
8291           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
8292           return;
8293         }
8294       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
8295         {
8296           /* 32 bit values require an lui.  */
8297           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8298           if ((ep->X_add_number & 0xffff) != 0)
8299             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
8300           return;
8301         }
8302     }
8303
8304   /* The value is larger than 32 bits.  */
8305
8306   if (!dbl || HAVE_32BIT_GPRS)
8307     {
8308       char value[32];
8309
8310       sprintf_vma (value, ep->X_add_number);
8311       as_bad (_("number (0x%s) larger than 32 bits"), value);
8312       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8313       return;
8314     }
8315
8316   if (ep->X_op != O_big)
8317     {
8318       hi32 = *ep;
8319       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
8320       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
8321       hi32.X_add_number &= 0xffffffff;
8322       lo32 = *ep;
8323       lo32.X_add_number &= 0xffffffff;
8324     }
8325   else
8326     {
8327       gas_assert (ep->X_add_number > 2);
8328       if (ep->X_add_number == 3)
8329         generic_bignum[3] = 0;
8330       else if (ep->X_add_number > 4)
8331         as_bad (_("number larger than 64 bits"));
8332       lo32.X_op = O_constant;
8333       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
8334       hi32.X_op = O_constant;
8335       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
8336     }
8337
8338   if (hi32.X_add_number == 0)
8339     freg = 0;
8340   else
8341     {
8342       int shift, bit;
8343       unsigned long hi, lo;
8344
8345       if (hi32.X_add_number == (offsetT) 0xffffffff)
8346         {
8347           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
8348             {
8349               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8350               return;
8351             }
8352           if (lo32.X_add_number & 0x80000000)
8353             {
8354               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8355               if (lo32.X_add_number & 0xffff)
8356                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
8357               return;
8358             }
8359         }
8360
8361       /* Check for 16bit shifted constant.  We know that hi32 is
8362          non-zero, so start the mask on the first bit of the hi32
8363          value.  */
8364       shift = 17;
8365       do
8366         {
8367           unsigned long himask, lomask;
8368
8369           if (shift < 32)
8370             {
8371               himask = 0xffff >> (32 - shift);
8372               lomask = (0xffff << shift) & 0xffffffff;
8373             }
8374           else
8375             {
8376               himask = 0xffff << (shift - 32);
8377               lomask = 0;
8378             }
8379           if ((hi32.X_add_number & ~(offsetT) himask) == 0
8380               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
8381             {
8382               expressionS tmp;
8383
8384               tmp.X_op = O_constant;
8385               if (shift < 32)
8386                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
8387                                     | (lo32.X_add_number >> shift));
8388               else
8389                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
8390               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
8391               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
8392                            reg, reg, (shift >= 32) ? shift - 32 : shift);
8393               return;
8394             }
8395           ++shift;
8396         }
8397       while (shift <= (64 - 16));
8398
8399       /* Find the bit number of the lowest one bit, and store the
8400          shifted value in hi/lo.  */
8401       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
8402       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
8403       if (lo != 0)
8404         {
8405           bit = 0;
8406           while ((lo & 1) == 0)
8407             {
8408               lo >>= 1;
8409               ++bit;
8410             }
8411           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
8412           hi >>= bit;
8413         }
8414       else
8415         {
8416           bit = 32;
8417           while ((hi & 1) == 0)
8418             {
8419               hi >>= 1;
8420               ++bit;
8421             }
8422           lo = hi;
8423           hi = 0;
8424         }
8425
8426       /* Optimize if the shifted value is a (power of 2) - 1.  */
8427       if ((hi == 0 && ((lo + 1) & lo) == 0)
8428           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
8429         {
8430           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
8431           if (shift != 0)
8432             {
8433               expressionS tmp;
8434
8435               /* This instruction will set the register to be all
8436                  ones.  */
8437               tmp.X_op = O_constant;
8438               tmp.X_add_number = (offsetT) -1;
8439               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8440               if (bit != 0)
8441                 {
8442                   bit += shift;
8443                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
8444                                reg, reg, (bit >= 32) ? bit - 32 : bit);
8445                 }
8446               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
8447                            reg, reg, (shift >= 32) ? shift - 32 : shift);
8448               return;
8449             }
8450         }
8451
8452       /* Sign extend hi32 before calling load_register, because we can
8453          generally get better code when we load a sign extended value.  */
8454       if ((hi32.X_add_number & 0x80000000) != 0)
8455         hi32.X_add_number |= ~(offsetT) 0xffffffff;
8456       load_register (reg, &hi32, 0);
8457       freg = reg;
8458     }
8459   if ((lo32.X_add_number & 0xffff0000) == 0)
8460     {
8461       if (freg != 0)
8462         {
8463           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
8464           freg = reg;
8465         }
8466     }
8467   else
8468     {
8469       expressionS mid16;
8470
8471       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
8472         {
8473           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8474           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
8475           return;
8476         }
8477
8478       if (freg != 0)
8479         {
8480           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
8481           freg = reg;
8482         }
8483       mid16 = lo32;
8484       mid16.X_add_number >>= 16;
8485       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
8486       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8487       freg = reg;
8488     }
8489   if ((lo32.X_add_number & 0xffff) != 0)
8490     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
8491 }
8492
8493 static inline void
8494 load_delay_nop (void)
8495 {
8496   if (!gpr_interlocks)
8497     macro_build (NULL, "nop", "");
8498 }
8499
8500 /* Load an address into a register.  */
8501
8502 static void
8503 load_address (int reg, expressionS *ep, int *used_at)
8504 {
8505   if (ep->X_op != O_constant
8506       && ep->X_op != O_symbol)
8507     {
8508       as_bad (_("expression too complex"));
8509       ep->X_op = O_constant;
8510     }
8511
8512   if (ep->X_op == O_constant)
8513     {
8514       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
8515       return;
8516     }
8517
8518   if (mips_pic == NO_PIC)
8519     {
8520       /* If this is a reference to a GP relative symbol, we want
8521            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
8522          Otherwise we want
8523            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
8524            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8525          If we have an addend, we always use the latter form.
8526
8527          With 64bit address space and a usable $at we want
8528            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
8529            lui          $at,<sym>               (BFD_RELOC_HI16_S)
8530            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
8531            daddiu       $at,<sym>               (BFD_RELOC_LO16)
8532            dsll32       $reg,0
8533            daddu        $reg,$reg,$at
8534
8535          If $at is already in use, we use a path which is suboptimal
8536          on superscalar processors.
8537            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
8538            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
8539            dsll         $reg,16
8540            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
8541            dsll         $reg,16
8542            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
8543
8544          For GP relative symbols in 64bit address space we can use
8545          the same sequence as in 32bit address space.  */
8546       if (HAVE_64BIT_SYMBOLS)
8547         {
8548           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
8549               && !nopic_need_relax (ep->X_add_symbol, 1))
8550             {
8551               relax_start (ep->X_add_symbol);
8552               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
8553                            mips_gp_register, BFD_RELOC_GPREL16);
8554               relax_switch ();
8555             }
8556
8557           if (*used_at == 0 && mips_opts.at)
8558             {
8559               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
8560               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
8561               macro_build (ep, "daddiu", "t,r,j", reg, reg,
8562                            BFD_RELOC_MIPS_HIGHER);
8563               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
8564               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
8565               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
8566               *used_at = 1;
8567             }
8568           else
8569             {
8570               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
8571               macro_build (ep, "daddiu", "t,r,j", reg, reg,
8572                            BFD_RELOC_MIPS_HIGHER);
8573               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8574               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
8575               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8576               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
8577             }
8578
8579           if (mips_relax.sequence)
8580             relax_end ();
8581         }
8582       else
8583         {
8584           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
8585               && !nopic_need_relax (ep->X_add_symbol, 1))
8586             {
8587               relax_start (ep->X_add_symbol);
8588               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
8589                            mips_gp_register, BFD_RELOC_GPREL16);
8590               relax_switch ();
8591             }
8592           macro_build_lui (ep, reg);
8593           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
8594                        reg, reg, BFD_RELOC_LO16);
8595           if (mips_relax.sequence)
8596             relax_end ();
8597         }
8598     }
8599   else if (!mips_big_got)
8600     {
8601       expressionS ex;
8602
8603       /* If this is a reference to an external symbol, we want
8604            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8605          Otherwise we want
8606            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8607            nop
8608            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8609          If there is a constant, it must be added in after.
8610
8611          If we have NewABI, we want
8612            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8613          unless we're referencing a global symbol with a non-zero
8614          offset, in which case cst must be added separately.  */
8615       if (HAVE_NEWABI)
8616         {
8617           if (ep->X_add_number)
8618             {
8619               ex.X_add_number = ep->X_add_number;
8620               ep->X_add_number = 0;
8621               relax_start (ep->X_add_symbol);
8622               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8623                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8624               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8625                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8626               ex.X_op = O_constant;
8627               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
8628                            reg, reg, BFD_RELOC_LO16);
8629               ep->X_add_number = ex.X_add_number;
8630               relax_switch ();
8631             }
8632           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8633                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8634           if (mips_relax.sequence)
8635             relax_end ();
8636         }
8637       else
8638         {
8639           ex.X_add_number = ep->X_add_number;
8640           ep->X_add_number = 0;
8641           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8642                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8643           load_delay_nop ();
8644           relax_start (ep->X_add_symbol);
8645           relax_switch ();
8646           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8647                        BFD_RELOC_LO16);
8648           relax_end ();
8649
8650           if (ex.X_add_number != 0)
8651             {
8652               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8653                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8654               ex.X_op = O_constant;
8655               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
8656                            reg, reg, BFD_RELOC_LO16);
8657             }
8658         }
8659     }
8660   else if (mips_big_got)
8661     {
8662       expressionS ex;
8663
8664       /* This is the large GOT case.  If this is a reference to an
8665          external symbol, we want
8666            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
8667            addu         $reg,$reg,$gp
8668            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
8669
8670          Otherwise, for a reference to a local symbol in old ABI, we want
8671            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8672            nop
8673            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8674          If there is a constant, it must be added in after.
8675
8676          In the NewABI, for local symbols, with or without offsets, we want:
8677            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
8678            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
8679       */
8680       if (HAVE_NEWABI)
8681         {
8682           ex.X_add_number = ep->X_add_number;
8683           ep->X_add_number = 0;
8684           relax_start (ep->X_add_symbol);
8685           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
8686           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8687                        reg, reg, mips_gp_register);
8688           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
8689                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
8690           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8691             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8692           else if (ex.X_add_number)
8693             {
8694               ex.X_op = O_constant;
8695               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8696                            BFD_RELOC_LO16);
8697             }
8698
8699           ep->X_add_number = ex.X_add_number;
8700           relax_switch ();
8701           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8702                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
8703           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8704                        BFD_RELOC_MIPS_GOT_OFST);
8705           relax_end ();
8706         }
8707       else
8708         {
8709           ex.X_add_number = ep->X_add_number;
8710           ep->X_add_number = 0;
8711           relax_start (ep->X_add_symbol);
8712           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
8713           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8714                        reg, reg, mips_gp_register);
8715           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
8716                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
8717           relax_switch ();
8718           if (reg_needs_delay (mips_gp_register))
8719             {
8720               /* We need a nop before loading from $gp.  This special
8721                  check is required because the lui which starts the main
8722                  instruction stream does not refer to $gp, and so will not
8723                  insert the nop which may be required.  */
8724               macro_build (NULL, "nop", "");
8725             }
8726           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8727                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8728           load_delay_nop ();
8729           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8730                        BFD_RELOC_LO16);
8731           relax_end ();
8732
8733           if (ex.X_add_number != 0)
8734             {
8735               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8736                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8737               ex.X_op = O_constant;
8738               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8739                            BFD_RELOC_LO16);
8740             }
8741         }
8742     }
8743   else
8744     abort ();
8745
8746   if (!mips_opts.at && *used_at == 1)
8747     as_bad (_("macro used $at after \".set noat\""));
8748 }
8749
8750 /* Move the contents of register SOURCE into register DEST.  */
8751
8752 static void
8753 move_register (int dest, int source)
8754 {
8755   /* Prefer to use a 16-bit microMIPS instruction unless the previous
8756      instruction specifically requires a 32-bit one.  */
8757   if (mips_opts.micromips
8758       && !mips_opts.insn32
8759       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8760     macro_build (NULL, "move", "mp,mj", dest, source);
8761   else
8762     macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
8763                  dest, source, 0);
8764 }
8765
8766 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
8767    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
8768    The two alternatives are:
8769
8770    Global symbol                Local sybmol
8771    -------------                ------------
8772    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
8773    ...                          ...
8774    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
8775
8776    load_got_offset emits the first instruction and add_got_offset
8777    emits the second for a 16-bit offset or add_got_offset_hilo emits
8778    a sequence to add a 32-bit offset using a scratch register.  */
8779
8780 static void
8781 load_got_offset (int dest, expressionS *local)
8782 {
8783   expressionS global;
8784
8785   global = *local;
8786   global.X_add_number = 0;
8787
8788   relax_start (local->X_add_symbol);
8789   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
8790                BFD_RELOC_MIPS_GOT16, mips_gp_register);
8791   relax_switch ();
8792   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
8793                BFD_RELOC_MIPS_GOT16, mips_gp_register);
8794   relax_end ();
8795 }
8796
8797 static void
8798 add_got_offset (int dest, expressionS *local)
8799 {
8800   expressionS global;
8801
8802   global.X_op = O_constant;
8803   global.X_op_symbol = NULL;
8804   global.X_add_symbol = NULL;
8805   global.X_add_number = local->X_add_number;
8806
8807   relax_start (local->X_add_symbol);
8808   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
8809                dest, dest, BFD_RELOC_LO16);
8810   relax_switch ();
8811   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
8812   relax_end ();
8813 }
8814
8815 static void
8816 add_got_offset_hilo (int dest, expressionS *local, int tmp)
8817 {
8818   expressionS global;
8819   int hold_mips_optimize;
8820
8821   global.X_op = O_constant;
8822   global.X_op_symbol = NULL;
8823   global.X_add_symbol = NULL;
8824   global.X_add_number = local->X_add_number;
8825
8826   relax_start (local->X_add_symbol);
8827   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
8828   relax_switch ();
8829   /* Set mips_optimize around the lui instruction to avoid
8830      inserting an unnecessary nop after the lw.  */
8831   hold_mips_optimize = mips_optimize;
8832   mips_optimize = 2;
8833   macro_build_lui (&global, tmp);
8834   mips_optimize = hold_mips_optimize;
8835   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
8836   relax_end ();
8837
8838   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
8839 }
8840
8841 /* Emit a sequence of instructions to emulate a branch likely operation.
8842    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
8843    is its complementing branch with the original condition negated.
8844    CALL is set if the original branch specified the link operation.
8845    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
8846
8847    Code like this is produced in the noreorder mode:
8848
8849         BRNEG   <args>, 1f
8850          nop
8851         b       <sym>
8852          delay slot (executed only if branch taken)
8853     1:
8854
8855    or, if CALL is set:
8856
8857         BRNEG   <args>, 1f
8858          nop
8859         bal     <sym>
8860          delay slot (executed only if branch taken)
8861     1:
8862
8863    In the reorder mode the delay slot would be filled with a nop anyway,
8864    so code produced is simply:
8865
8866         BR      <args>, <sym>
8867          nop
8868
8869    This function is used when producing code for the microMIPS ASE that
8870    does not implement branch likely instructions in hardware.  */
8871
8872 static void
8873 macro_build_branch_likely (const char *br, const char *brneg,
8874                            int call, expressionS *ep, const char *fmt,
8875                            unsigned int sreg, unsigned int treg)
8876 {
8877   int noreorder = mips_opts.noreorder;
8878   expressionS expr1;
8879
8880   gas_assert (mips_opts.micromips);
8881   start_noreorder ();
8882   if (noreorder)
8883     {
8884       micromips_label_expr (&expr1);
8885       macro_build (&expr1, brneg, fmt, sreg, treg);
8886       macro_build (NULL, "nop", "");
8887       macro_build (ep, call ? "bal" : "b", "p");
8888
8889       /* Set to true so that append_insn adds a label.  */
8890       emit_branch_likely_macro = TRUE;
8891     }
8892   else
8893     {
8894       macro_build (ep, br, fmt, sreg, treg);
8895       macro_build (NULL, "nop", "");
8896     }
8897   end_noreorder ();
8898 }
8899
8900 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
8901    the condition code tested.  EP specifies the branch target.  */
8902
8903 static void
8904 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
8905 {
8906   const int call = 0;
8907   const char *brneg;
8908   const char *br;
8909
8910   switch (type)
8911     {
8912     case M_BC1FL:
8913       br = "bc1f";
8914       brneg = "bc1t";
8915       break;
8916     case M_BC1TL:
8917       br = "bc1t";
8918       brneg = "bc1f";
8919       break;
8920     case M_BC2FL:
8921       br = "bc2f";
8922       brneg = "bc2t";
8923       break;
8924     case M_BC2TL:
8925       br = "bc2t";
8926       brneg = "bc2f";
8927       break;
8928     default:
8929       abort ();
8930     }
8931   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
8932 }
8933
8934 /* Emit a two-argument branch macro specified by TYPE, using SREG as
8935    the register tested.  EP specifies the branch target.  */
8936
8937 static void
8938 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
8939 {
8940   const char *brneg = NULL;
8941   const char *br;
8942   int call = 0;
8943
8944   switch (type)
8945     {
8946     case M_BGEZ:
8947       br = "bgez";
8948       break;
8949     case M_BGEZL:
8950       br = mips_opts.micromips ? "bgez" : "bgezl";
8951       brneg = "bltz";
8952       break;
8953     case M_BGEZALL:
8954       gas_assert (mips_opts.micromips);
8955       br = mips_opts.insn32 ? "bgezal" : "bgezals";
8956       brneg = "bltz";
8957       call = 1;
8958       break;
8959     case M_BGTZ:
8960       br = "bgtz";
8961       break;
8962     case M_BGTZL:
8963       br = mips_opts.micromips ? "bgtz" : "bgtzl";
8964       brneg = "blez";
8965       break;
8966     case M_BLEZ:
8967       br = "blez";
8968       break;
8969     case M_BLEZL:
8970       br = mips_opts.micromips ? "blez" : "blezl";
8971       brneg = "bgtz";
8972       break;
8973     case M_BLTZ:
8974       br = "bltz";
8975       break;
8976     case M_BLTZL:
8977       br = mips_opts.micromips ? "bltz" : "bltzl";
8978       brneg = "bgez";
8979       break;
8980     case M_BLTZALL:
8981       gas_assert (mips_opts.micromips);
8982       br = mips_opts.insn32 ? "bltzal" : "bltzals";
8983       brneg = "bgez";
8984       call = 1;
8985       break;
8986     default:
8987       abort ();
8988     }
8989   if (mips_opts.micromips && brneg)
8990     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
8991   else
8992     macro_build (ep, br, "s,p", sreg);
8993 }
8994
8995 /* Emit a three-argument branch macro specified by TYPE, using SREG and
8996    TREG as the registers tested.  EP specifies the branch target.  */
8997
8998 static void
8999 macro_build_branch_rsrt (int type, expressionS *ep,
9000                          unsigned int sreg, unsigned int treg)
9001 {
9002   const char *brneg = NULL;
9003   const int call = 0;
9004   const char *br;
9005
9006   switch (type)
9007     {
9008     case M_BEQ:
9009     case M_BEQ_I:
9010       br = "beq";
9011       break;
9012     case M_BEQL:
9013     case M_BEQL_I:
9014       br = mips_opts.micromips ? "beq" : "beql";
9015       brneg = "bne";
9016       break;
9017     case M_BNE:
9018     case M_BNE_I:
9019       br = "bne";
9020       break;
9021     case M_BNEL:
9022     case M_BNEL_I:
9023       br = mips_opts.micromips ? "bne" : "bnel";
9024       brneg = "beq";
9025       break;
9026     default:
9027       abort ();
9028     }
9029   if (mips_opts.micromips && brneg)
9030     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
9031   else
9032     macro_build (ep, br, "s,t,p", sreg, treg);
9033 }
9034
9035 /* Return the high part that should be loaded in order to make the low
9036    part of VALUE accessible using an offset of OFFBITS bits.  */
9037
9038 static offsetT
9039 offset_high_part (offsetT value, unsigned int offbits)
9040 {
9041   offsetT bias;
9042   addressT low_mask;
9043
9044   if (offbits == 0)
9045     return value;
9046   bias = 1 << (offbits - 1);
9047   low_mask = bias * 2 - 1;
9048   return (value + bias) & ~low_mask;
9049 }
9050
9051 /* Return true if the value stored in offset_expr and offset_reloc
9052    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
9053    amount that the caller wants to add without inducing overflow
9054    and ALIGN is the known alignment of the value in bytes.  */
9055
9056 static bfd_boolean
9057 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
9058 {
9059   if (offbits == 16)
9060     {
9061       /* Accept any relocation operator if overflow isn't a concern.  */
9062       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
9063         return TRUE;
9064
9065       /* These relocations are guaranteed not to overflow in correct links.  */
9066       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
9067           || gprel16_reloc_p (*offset_reloc))
9068         return TRUE;
9069     }
9070   if (offset_expr.X_op == O_constant
9071       && offset_high_part (offset_expr.X_add_number, offbits) == 0
9072       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
9073     return TRUE;
9074   return FALSE;
9075 }
9076
9077 /*
9078  *                      Build macros
9079  *   This routine implements the seemingly endless macro or synthesized
9080  * instructions and addressing modes in the mips assembly language. Many
9081  * of these macros are simple and are similar to each other. These could
9082  * probably be handled by some kind of table or grammar approach instead of
9083  * this verbose method. Others are not simple macros but are more like
9084  * optimizing code generation.
9085  *   One interesting optimization is when several store macros appear
9086  * consecutively that would load AT with the upper half of the same address.
9087  * The ensuing load upper instructions are ommited. This implies some kind
9088  * of global optimization. We currently only optimize within a single macro.
9089  *   For many of the load and store macros if the address is specified as a
9090  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
9091  * first load register 'at' with zero and use it as the base register. The
9092  * mips assembler simply uses register $zero. Just one tiny optimization
9093  * we're missing.
9094  */
9095 static void
9096 macro (struct mips_cl_insn *ip, char *str)
9097 {
9098   const struct mips_operand_array *operands;
9099   unsigned int breg, i;
9100   unsigned int tempreg;
9101   int mask;
9102   int used_at = 0;
9103   expressionS label_expr;
9104   expressionS expr1;
9105   expressionS *ep;
9106   const char *s;
9107   const char *s2;
9108   const char *fmt;
9109   int likely = 0;
9110   int coproc = 0;
9111   int offbits = 16;
9112   int call = 0;
9113   int jals = 0;
9114   int dbl = 0;
9115   int imm = 0;
9116   int ust = 0;
9117   int lp = 0;
9118   bfd_boolean large_offset;
9119   int off;
9120   int hold_mips_optimize;
9121   unsigned int align;
9122   unsigned int op[MAX_OPERANDS];
9123
9124   gas_assert (! mips_opts.mips16);
9125
9126   operands = insn_operands (ip);
9127   for (i = 0; i < MAX_OPERANDS; i++)
9128     if (operands->operand[i])
9129       op[i] = insn_extract_operand (ip, operands->operand[i]);
9130     else
9131       op[i] = -1;
9132
9133   mask = ip->insn_mo->mask;
9134
9135   label_expr.X_op = O_constant;
9136   label_expr.X_op_symbol = NULL;
9137   label_expr.X_add_symbol = NULL;
9138   label_expr.X_add_number = 0;
9139
9140   expr1.X_op = O_constant;
9141   expr1.X_op_symbol = NULL;
9142   expr1.X_add_symbol = NULL;
9143   expr1.X_add_number = 1;
9144   align = 1;
9145
9146   switch (mask)
9147     {
9148     case M_DABS:
9149       dbl = 1;
9150     case M_ABS:
9151       /*    bgez    $a0,1f
9152             move    v0,$a0
9153             sub     v0,$zero,$a0
9154          1:
9155        */
9156
9157       start_noreorder ();
9158
9159       if (mips_opts.micromips)
9160         micromips_label_expr (&label_expr);
9161       else
9162         label_expr.X_add_number = 8;
9163       macro_build (&label_expr, "bgez", "s,p", op[1]);
9164       if (op[0] == op[1])
9165         macro_build (NULL, "nop", "");
9166       else
9167         move_register (op[0], op[1]);
9168       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", op[0], 0, op[1]);
9169       if (mips_opts.micromips)
9170         micromips_add_label ();
9171
9172       end_noreorder ();
9173       break;
9174
9175     case M_ADD_I:
9176       s = "addi";
9177       s2 = "add";
9178       goto do_addi;
9179     case M_ADDU_I:
9180       s = "addiu";
9181       s2 = "addu";
9182       goto do_addi;
9183     case M_DADD_I:
9184       dbl = 1;
9185       s = "daddi";
9186       s2 = "dadd";
9187       if (!mips_opts.micromips)
9188         goto do_addi;
9189       if (imm_expr.X_add_number >= -0x200
9190           && imm_expr.X_add_number < 0x200)
9191         {
9192           macro_build (NULL, s, "t,r,.", op[0], op[1],
9193                        (int) imm_expr.X_add_number);
9194           break;
9195         }
9196       goto do_addi_i;
9197     case M_DADDU_I:
9198       dbl = 1;
9199       s = "daddiu";
9200       s2 = "daddu";
9201     do_addi:
9202       if (imm_expr.X_add_number >= -0x8000
9203           && imm_expr.X_add_number < 0x8000)
9204         {
9205           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
9206           break;
9207         }
9208     do_addi_i:
9209       used_at = 1;
9210       load_register (AT, &imm_expr, dbl);
9211       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
9212       break;
9213
9214     case M_AND_I:
9215       s = "andi";
9216       s2 = "and";
9217       goto do_bit;
9218     case M_OR_I:
9219       s = "ori";
9220       s2 = "or";
9221       goto do_bit;
9222     case M_NOR_I:
9223       s = "";
9224       s2 = "nor";
9225       goto do_bit;
9226     case M_XOR_I:
9227       s = "xori";
9228       s2 = "xor";
9229     do_bit:
9230       if (imm_expr.X_add_number >= 0
9231           && imm_expr.X_add_number < 0x10000)
9232         {
9233           if (mask != M_NOR_I)
9234             macro_build (&imm_expr, s, "t,r,i", op[0], op[1], BFD_RELOC_LO16);
9235           else
9236             {
9237               macro_build (&imm_expr, "ori", "t,r,i",
9238                            op[0], op[1], BFD_RELOC_LO16);
9239               macro_build (NULL, "nor", "d,v,t", op[0], op[0], 0);
9240             }
9241           break;
9242         }
9243
9244       used_at = 1;
9245       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9246       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
9247       break;
9248
9249     case M_BALIGN:
9250       switch (imm_expr.X_add_number)
9251         {
9252         case 0:
9253           macro_build (NULL, "nop", "");
9254           break;
9255         case 2:
9256           macro_build (NULL, "packrl.ph", "d,s,t", op[0], op[0], op[1]);
9257           break;
9258         case 1:
9259         case 3:
9260           macro_build (NULL, "balign", "t,s,2", op[0], op[1],
9261                        (int) imm_expr.X_add_number);
9262           break;
9263         default:
9264           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
9265                   (unsigned long) imm_expr.X_add_number);
9266           break;
9267         }
9268       break;
9269
9270     case M_BC1FL:
9271     case M_BC1TL:
9272     case M_BC2FL:
9273     case M_BC2TL:
9274       gas_assert (mips_opts.micromips);
9275       macro_build_branch_ccl (mask, &offset_expr,
9276                               EXTRACT_OPERAND (1, BCC, *ip));
9277       break;
9278
9279     case M_BEQ_I:
9280     case M_BEQL_I:
9281     case M_BNE_I:
9282     case M_BNEL_I:
9283       if (imm_expr.X_add_number == 0)
9284         op[1] = 0;
9285       else
9286         {
9287           op[1] = AT;
9288           used_at = 1;
9289           load_register (op[1], &imm_expr, HAVE_64BIT_GPRS);
9290         }
9291       /* Fall through.  */
9292     case M_BEQL:
9293     case M_BNEL:
9294       macro_build_branch_rsrt (mask, &offset_expr, op[0], op[1]);
9295       break;
9296
9297     case M_BGEL:
9298       likely = 1;
9299     case M_BGE:
9300       if (op[1] == 0)
9301         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[0]);
9302       else if (op[0] == 0)
9303         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[1]);
9304       else
9305         {
9306           used_at = 1;
9307           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
9308           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9309                                    &offset_expr, AT, ZERO);
9310         }
9311       break;
9312
9313     case M_BGEZL:
9314     case M_BGEZALL:
9315     case M_BGTZL:
9316     case M_BLEZL:
9317     case M_BLTZL:
9318     case M_BLTZALL:
9319       macro_build_branch_rs (mask, &offset_expr, op[0]);
9320       break;
9321
9322     case M_BGTL_I:
9323       likely = 1;
9324     case M_BGT_I:
9325       /* Check for > max integer.  */
9326       if (imm_expr.X_add_number >= GPR_SMAX)
9327         {
9328         do_false:
9329           /* Result is always false.  */
9330           if (! likely)
9331             macro_build (NULL, "nop", "");
9332           else
9333             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
9334           break;
9335         }
9336       ++imm_expr.X_add_number;
9337       /* FALLTHROUGH */
9338     case M_BGE_I:
9339     case M_BGEL_I:
9340       if (mask == M_BGEL_I)
9341         likely = 1;
9342       if (imm_expr.X_add_number == 0)
9343         {
9344           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
9345                                  &offset_expr, op[0]);
9346           break;
9347         }
9348       if (imm_expr.X_add_number == 1)
9349         {
9350           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
9351                                  &offset_expr, op[0]);
9352           break;
9353         }
9354       if (imm_expr.X_add_number <= GPR_SMIN)
9355         {
9356         do_true:
9357           /* result is always true */
9358           as_warn (_("branch %s is always true"), ip->insn_mo->name);
9359           macro_build (&offset_expr, "b", "p");
9360           break;
9361         }
9362       used_at = 1;
9363       set_at (op[0], 0);
9364       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9365                                &offset_expr, AT, ZERO);
9366       break;
9367
9368     case M_BGEUL:
9369       likely = 1;
9370     case M_BGEU:
9371       if (op[1] == 0)
9372         goto do_true;
9373       else if (op[0] == 0)
9374         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9375                                  &offset_expr, ZERO, op[1]);
9376       else
9377         {
9378           used_at = 1;
9379           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
9380           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9381                                    &offset_expr, AT, ZERO);
9382         }
9383       break;
9384
9385     case M_BGTUL_I:
9386       likely = 1;
9387     case M_BGTU_I:
9388       if (op[0] == 0
9389           || (HAVE_32BIT_GPRS
9390               && imm_expr.X_add_number == -1))
9391         goto do_false;
9392       ++imm_expr.X_add_number;
9393       /* FALLTHROUGH */
9394     case M_BGEU_I:
9395     case M_BGEUL_I:
9396       if (mask == M_BGEUL_I)
9397         likely = 1;
9398       if (imm_expr.X_add_number == 0)
9399         goto do_true;
9400       else if (imm_expr.X_add_number == 1)
9401         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9402                                  &offset_expr, op[0], ZERO);
9403       else
9404         {
9405           used_at = 1;
9406           set_at (op[0], 1);
9407           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9408                                    &offset_expr, AT, ZERO);
9409         }
9410       break;
9411
9412     case M_BGTL:
9413       likely = 1;
9414     case M_BGT:
9415       if (op[1] == 0)
9416         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[0]);
9417       else if (op[0] == 0)
9418         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[1]);
9419       else
9420         {
9421           used_at = 1;
9422           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
9423           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9424                                    &offset_expr, AT, ZERO);
9425         }
9426       break;
9427
9428     case M_BGTUL:
9429       likely = 1;
9430     case M_BGTU:
9431       if (op[1] == 0)
9432         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9433                                  &offset_expr, op[0], ZERO);
9434       else if (op[0] == 0)
9435         goto do_false;
9436       else
9437         {
9438           used_at = 1;
9439           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
9440           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9441                                    &offset_expr, AT, ZERO);
9442         }
9443       break;
9444
9445     case M_BLEL:
9446       likely = 1;
9447     case M_BLE:
9448       if (op[1] == 0)
9449         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
9450       else if (op[0] == 0)
9451         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[1]);
9452       else
9453         {
9454           used_at = 1;
9455           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
9456           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9457                                    &offset_expr, AT, ZERO);
9458         }
9459       break;
9460
9461     case M_BLEL_I:
9462       likely = 1;
9463     case M_BLE_I:
9464       if (imm_expr.X_add_number >= GPR_SMAX)
9465         goto do_true;
9466       ++imm_expr.X_add_number;
9467       /* FALLTHROUGH */
9468     case M_BLT_I:
9469     case M_BLTL_I:
9470       if (mask == M_BLTL_I)
9471         likely = 1;
9472       if (imm_expr.X_add_number == 0)
9473         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
9474       else if (imm_expr.X_add_number == 1)
9475         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
9476       else
9477         {
9478           used_at = 1;
9479           set_at (op[0], 0);
9480           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9481                                    &offset_expr, AT, ZERO);
9482         }
9483       break;
9484
9485     case M_BLEUL:
9486       likely = 1;
9487     case M_BLEU:
9488       if (op[1] == 0)
9489         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9490                                  &offset_expr, op[0], ZERO);
9491       else if (op[0] == 0)
9492         goto do_true;
9493       else
9494         {
9495           used_at = 1;
9496           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
9497           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9498                                    &offset_expr, AT, ZERO);
9499         }
9500       break;
9501
9502     case M_BLEUL_I:
9503       likely = 1;
9504     case M_BLEU_I:
9505       if (op[0] == 0
9506           || (HAVE_32BIT_GPRS
9507               && imm_expr.X_add_number == -1))
9508         goto do_true;
9509       ++imm_expr.X_add_number;
9510       /* FALLTHROUGH */
9511     case M_BLTU_I:
9512     case M_BLTUL_I:
9513       if (mask == M_BLTUL_I)
9514         likely = 1;
9515       if (imm_expr.X_add_number == 0)
9516         goto do_false;
9517       else if (imm_expr.X_add_number == 1)
9518         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9519                                  &offset_expr, op[0], ZERO);
9520       else
9521         {
9522           used_at = 1;
9523           set_at (op[0], 1);
9524           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9525                                    &offset_expr, AT, ZERO);
9526         }
9527       break;
9528
9529     case M_BLTL:
9530       likely = 1;
9531     case M_BLT:
9532       if (op[1] == 0)
9533         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
9534       else if (op[0] == 0)
9535         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[1]);
9536       else
9537         {
9538           used_at = 1;
9539           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
9540           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9541                                    &offset_expr, AT, ZERO);
9542         }
9543       break;
9544
9545     case M_BLTUL:
9546       likely = 1;
9547     case M_BLTU:
9548       if (op[1] == 0)
9549         goto do_false;
9550       else if (op[0] == 0)
9551         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9552                                  &offset_expr, ZERO, op[1]);
9553       else
9554         {
9555           used_at = 1;
9556           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
9557           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9558                                    &offset_expr, AT, ZERO);
9559         }
9560       break;
9561
9562     case M_DDIV_3:
9563       dbl = 1;
9564     case M_DIV_3:
9565       s = "mflo";
9566       goto do_div3;
9567     case M_DREM_3:
9568       dbl = 1;
9569     case M_REM_3:
9570       s = "mfhi";
9571     do_div3:
9572       if (op[2] == 0)
9573         {
9574           as_warn (_("divide by zero"));
9575           if (mips_trap)
9576             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
9577           else
9578             macro_build (NULL, "break", BRK_FMT, 7);
9579           break;
9580         }
9581
9582       start_noreorder ();
9583       if (mips_trap)
9584         {
9585           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
9586           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
9587         }
9588       else
9589         {
9590           if (mips_opts.micromips)
9591             micromips_label_expr (&label_expr);
9592           else
9593             label_expr.X_add_number = 8;
9594           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
9595           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
9596           macro_build (NULL, "break", BRK_FMT, 7);
9597           if (mips_opts.micromips)
9598             micromips_add_label ();
9599         }
9600       expr1.X_add_number = -1;
9601       used_at = 1;
9602       load_register (AT, &expr1, dbl);
9603       if (mips_opts.micromips)
9604         micromips_label_expr (&label_expr);
9605       else
9606         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
9607       macro_build (&label_expr, "bne", "s,t,p", op[2], AT);
9608       if (dbl)
9609         {
9610           expr1.X_add_number = 1;
9611           load_register (AT, &expr1, dbl);
9612           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
9613         }
9614       else
9615         {
9616           expr1.X_add_number = 0x80000000;
9617           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
9618         }
9619       if (mips_trap)
9620         {
9621           macro_build (NULL, "teq", TRAP_FMT, op[1], AT, 6);
9622           /* We want to close the noreorder block as soon as possible, so
9623              that later insns are available for delay slot filling.  */
9624           end_noreorder ();
9625         }
9626       else
9627         {
9628           if (mips_opts.micromips)
9629             micromips_label_expr (&label_expr);
9630           else
9631             label_expr.X_add_number = 8;
9632           macro_build (&label_expr, "bne", "s,t,p", op[1], AT);
9633           macro_build (NULL, "nop", "");
9634
9635           /* We want to close the noreorder block as soon as possible, so
9636              that later insns are available for delay slot filling.  */
9637           end_noreorder ();
9638
9639           macro_build (NULL, "break", BRK_FMT, 6);
9640         }
9641       if (mips_opts.micromips)
9642         micromips_add_label ();
9643       macro_build (NULL, s, MFHL_FMT, op[0]);
9644       break;
9645
9646     case M_DIV_3I:
9647       s = "div";
9648       s2 = "mflo";
9649       goto do_divi;
9650     case M_DIVU_3I:
9651       s = "divu";
9652       s2 = "mflo";
9653       goto do_divi;
9654     case M_REM_3I:
9655       s = "div";
9656       s2 = "mfhi";
9657       goto do_divi;
9658     case M_REMU_3I:
9659       s = "divu";
9660       s2 = "mfhi";
9661       goto do_divi;
9662     case M_DDIV_3I:
9663       dbl = 1;
9664       s = "ddiv";
9665       s2 = "mflo";
9666       goto do_divi;
9667     case M_DDIVU_3I:
9668       dbl = 1;
9669       s = "ddivu";
9670       s2 = "mflo";
9671       goto do_divi;
9672     case M_DREM_3I:
9673       dbl = 1;
9674       s = "ddiv";
9675       s2 = "mfhi";
9676       goto do_divi;
9677     case M_DREMU_3I:
9678       dbl = 1;
9679       s = "ddivu";
9680       s2 = "mfhi";
9681     do_divi:
9682       if (imm_expr.X_add_number == 0)
9683         {
9684           as_warn (_("divide by zero"));
9685           if (mips_trap)
9686             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
9687           else
9688             macro_build (NULL, "break", BRK_FMT, 7);
9689           break;
9690         }
9691       if (imm_expr.X_add_number == 1)
9692         {
9693           if (strcmp (s2, "mflo") == 0)
9694             move_register (op[0], op[1]);
9695           else
9696             move_register (op[0], ZERO);
9697           break;
9698         }
9699       if (imm_expr.X_add_number == -1 && s[strlen (s) - 1] != 'u')
9700         {
9701           if (strcmp (s2, "mflo") == 0)
9702             macro_build (NULL, dbl ? "dneg" : "neg", "d,w", op[0], op[1]);
9703           else
9704             move_register (op[0], ZERO);
9705           break;
9706         }
9707
9708       used_at = 1;
9709       load_register (AT, &imm_expr, dbl);
9710       macro_build (NULL, s, "z,s,t", op[1], AT);
9711       macro_build (NULL, s2, MFHL_FMT, op[0]);
9712       break;
9713
9714     case M_DIVU_3:
9715       s = "divu";
9716       s2 = "mflo";
9717       goto do_divu3;
9718     case M_REMU_3:
9719       s = "divu";
9720       s2 = "mfhi";
9721       goto do_divu3;
9722     case M_DDIVU_3:
9723       s = "ddivu";
9724       s2 = "mflo";
9725       goto do_divu3;
9726     case M_DREMU_3:
9727       s = "ddivu";
9728       s2 = "mfhi";
9729     do_divu3:
9730       start_noreorder ();
9731       if (mips_trap)
9732         {
9733           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
9734           macro_build (NULL, s, "z,s,t", op[1], op[2]);
9735           /* We want to close the noreorder block as soon as possible, so
9736              that later insns are available for delay slot filling.  */
9737           end_noreorder ();
9738         }
9739       else
9740         {
9741           if (mips_opts.micromips)
9742             micromips_label_expr (&label_expr);
9743           else
9744             label_expr.X_add_number = 8;
9745           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
9746           macro_build (NULL, s, "z,s,t", op[1], op[2]);
9747
9748           /* We want to close the noreorder block as soon as possible, so
9749              that later insns are available for delay slot filling.  */
9750           end_noreorder ();
9751           macro_build (NULL, "break", BRK_FMT, 7);
9752           if (mips_opts.micromips)
9753             micromips_add_label ();
9754         }
9755       macro_build (NULL, s2, MFHL_FMT, op[0]);
9756       break;
9757
9758     case M_DLCA_AB:
9759       dbl = 1;
9760     case M_LCA_AB:
9761       call = 1;
9762       goto do_la;
9763     case M_DLA_AB:
9764       dbl = 1;
9765     case M_LA_AB:
9766     do_la:
9767       /* Load the address of a symbol into a register.  If breg is not
9768          zero, we then add a base register to it.  */
9769
9770       breg = op[2];
9771       if (dbl && HAVE_32BIT_GPRS)
9772         as_warn (_("dla used to load 32-bit register"));
9773
9774       if (!dbl && HAVE_64BIT_OBJECTS)
9775         as_warn (_("la used to load 64-bit address"));
9776
9777       if (small_offset_p (0, align, 16))
9778         {
9779           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", op[0], breg,
9780                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
9781           break;
9782         }
9783
9784       if (mips_opts.at && (op[0] == breg))
9785         {
9786           tempreg = AT;
9787           used_at = 1;
9788         }
9789       else
9790         tempreg = op[0];
9791
9792       if (offset_expr.X_op != O_symbol
9793           && offset_expr.X_op != O_constant)
9794         {
9795           as_bad (_("expression too complex"));
9796           offset_expr.X_op = O_constant;
9797         }
9798
9799       if (offset_expr.X_op == O_constant)
9800         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
9801       else if (mips_pic == NO_PIC)
9802         {
9803           /* If this is a reference to a GP relative symbol, we want
9804                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
9805              Otherwise we want
9806                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
9807                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9808              If we have a constant, we need two instructions anyhow,
9809              so we may as well always use the latter form.
9810
9811              With 64bit address space and a usable $at we want
9812                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9813                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9814                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9815                daddiu   $at,<sym>               (BFD_RELOC_LO16)
9816                dsll32   $tempreg,0
9817                daddu    $tempreg,$tempreg,$at
9818
9819              If $at is already in use, we use a path which is suboptimal
9820              on superscalar processors.
9821                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9822                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9823                dsll     $tempreg,16
9824                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9825                dsll     $tempreg,16
9826                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
9827
9828              For GP relative symbols in 64bit address space we can use
9829              the same sequence as in 32bit address space.  */
9830           if (HAVE_64BIT_SYMBOLS)
9831             {
9832               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9833                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9834                 {
9835                   relax_start (offset_expr.X_add_symbol);
9836                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9837                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
9838                   relax_switch ();
9839                 }
9840
9841               if (used_at == 0 && mips_opts.at)
9842                 {
9843                   macro_build (&offset_expr, "lui", LUI_FMT,
9844                                tempreg, BFD_RELOC_MIPS_HIGHEST);
9845                   macro_build (&offset_expr, "lui", LUI_FMT,
9846                                AT, BFD_RELOC_HI16_S);
9847                   macro_build (&offset_expr, "daddiu", "t,r,j",
9848                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
9849                   macro_build (&offset_expr, "daddiu", "t,r,j",
9850                                AT, AT, BFD_RELOC_LO16);
9851                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
9852                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
9853                   used_at = 1;
9854                 }
9855               else
9856                 {
9857                   macro_build (&offset_expr, "lui", LUI_FMT,
9858                                tempreg, BFD_RELOC_MIPS_HIGHEST);
9859                   macro_build (&offset_expr, "daddiu", "t,r,j",
9860                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
9861                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9862                   macro_build (&offset_expr, "daddiu", "t,r,j",
9863                                tempreg, tempreg, BFD_RELOC_HI16_S);
9864                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9865                   macro_build (&offset_expr, "daddiu", "t,r,j",
9866                                tempreg, tempreg, BFD_RELOC_LO16);
9867                 }
9868
9869               if (mips_relax.sequence)
9870                 relax_end ();
9871             }
9872           else
9873             {
9874               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9875                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9876                 {
9877                   relax_start (offset_expr.X_add_symbol);
9878                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9879                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
9880                   relax_switch ();
9881                 }
9882               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
9883                 as_bad (_("offset too large"));
9884               macro_build_lui (&offset_expr, tempreg);
9885               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9886                            tempreg, tempreg, BFD_RELOC_LO16);
9887               if (mips_relax.sequence)
9888                 relax_end ();
9889             }
9890         }
9891       else if (!mips_big_got && !HAVE_NEWABI)
9892         {
9893           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
9894
9895           /* If this is a reference to an external symbol, and there
9896              is no constant, we want
9897                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9898              or for lca or if tempreg is PIC_CALL_REG
9899                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
9900              For a local symbol, we want
9901                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9902                nop
9903                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9904
9905              If we have a small constant, and this is a reference to
9906              an external symbol, we want
9907                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9908                nop
9909                addiu    $tempreg,$tempreg,<constant>
9910              For a local symbol, we want the same instruction
9911              sequence, but we output a BFD_RELOC_LO16 reloc on the
9912              addiu instruction.
9913
9914              If we have a large constant, and this is a reference to
9915              an external symbol, we want
9916                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9917                lui      $at,<hiconstant>
9918                addiu    $at,$at,<loconstant>
9919                addu     $tempreg,$tempreg,$at
9920              For a local symbol, we want the same instruction
9921              sequence, but we output a BFD_RELOC_LO16 reloc on the
9922              addiu instruction.
9923            */
9924
9925           if (offset_expr.X_add_number == 0)
9926             {
9927               if (mips_pic == SVR4_PIC
9928                   && breg == 0
9929                   && (call || tempreg == PIC_CALL_REG))
9930                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
9931
9932               relax_start (offset_expr.X_add_symbol);
9933               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9934                            lw_reloc_type, mips_gp_register);
9935               if (breg != 0)
9936                 {
9937                   /* We're going to put in an addu instruction using
9938                      tempreg, so we may as well insert the nop right
9939                      now.  */
9940                   load_delay_nop ();
9941                 }
9942               relax_switch ();
9943               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9944                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
9945               load_delay_nop ();
9946               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9947                            tempreg, tempreg, BFD_RELOC_LO16);
9948               relax_end ();
9949               /* FIXME: If breg == 0, and the next instruction uses
9950                  $tempreg, then if this variant case is used an extra
9951                  nop will be generated.  */
9952             }
9953           else if (offset_expr.X_add_number >= -0x8000
9954                    && offset_expr.X_add_number < 0x8000)
9955             {
9956               load_got_offset (tempreg, &offset_expr);
9957               load_delay_nop ();
9958               add_got_offset (tempreg, &offset_expr);
9959             }
9960           else
9961             {
9962               expr1.X_add_number = offset_expr.X_add_number;
9963               offset_expr.X_add_number =
9964                 SEXT_16BIT (offset_expr.X_add_number);
9965               load_got_offset (tempreg, &offset_expr);
9966               offset_expr.X_add_number = expr1.X_add_number;
9967               /* If we are going to add in a base register, and the
9968                  target register and the base register are the same,
9969                  then we are using AT as a temporary register.  Since
9970                  we want to load the constant into AT, we add our
9971                  current AT (from the global offset table) and the
9972                  register into the register now, and pretend we were
9973                  not using a base register.  */
9974               if (breg == op[0])
9975                 {
9976                   load_delay_nop ();
9977                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9978                                op[0], AT, breg);
9979                   breg = 0;
9980                   tempreg = op[0];
9981                 }
9982               add_got_offset_hilo (tempreg, &offset_expr, AT);
9983               used_at = 1;
9984             }
9985         }
9986       else if (!mips_big_got && HAVE_NEWABI)
9987         {
9988           int add_breg_early = 0;
9989
9990           /* If this is a reference to an external, and there is no
9991              constant, or local symbol (*), with or without a
9992              constant, we want
9993                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
9994              or for lca or if tempreg is PIC_CALL_REG
9995                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
9996
9997              If we have a small constant, and this is a reference to
9998              an external symbol, we want
9999                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10000                addiu    $tempreg,$tempreg,<constant>
10001
10002              If we have a large constant, and this is a reference to
10003              an external symbol, we want
10004                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10005                lui      $at,<hiconstant>
10006                addiu    $at,$at,<loconstant>
10007                addu     $tempreg,$tempreg,$at
10008
10009              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
10010              local symbols, even though it introduces an additional
10011              instruction.  */
10012
10013           if (offset_expr.X_add_number)
10014             {
10015               expr1.X_add_number = offset_expr.X_add_number;
10016               offset_expr.X_add_number = 0;
10017
10018               relax_start (offset_expr.X_add_symbol);
10019               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10020                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10021
10022               if (expr1.X_add_number >= -0x8000
10023                   && expr1.X_add_number < 0x8000)
10024                 {
10025                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10026                                tempreg, tempreg, BFD_RELOC_LO16);
10027                 }
10028               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
10029                 {
10030                   unsigned int dreg;
10031
10032                   /* If we are going to add in a base register, and the
10033                      target register and the base register are the same,
10034                      then we are using AT as a temporary register.  Since
10035                      we want to load the constant into AT, we add our
10036                      current AT (from the global offset table) and the
10037                      register into the register now, and pretend we were
10038                      not using a base register.  */
10039                   if (breg != op[0])
10040                     dreg = tempreg;
10041                   else
10042                     {
10043                       gas_assert (tempreg == AT);
10044                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10045                                    op[0], AT, breg);
10046                       dreg = op[0];
10047                       add_breg_early = 1;
10048                     }
10049
10050                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10051                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10052                                dreg, dreg, AT);
10053
10054                   used_at = 1;
10055                 }
10056               else
10057                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
10058
10059               relax_switch ();
10060               offset_expr.X_add_number = expr1.X_add_number;
10061
10062               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10063                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10064               if (add_breg_early)
10065                 {
10066                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10067                                op[0], tempreg, breg);
10068                   breg = 0;
10069                   tempreg = op[0];
10070                 }
10071               relax_end ();
10072             }
10073           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
10074             {
10075               relax_start (offset_expr.X_add_symbol);
10076               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10077                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
10078               relax_switch ();
10079               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10080                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10081               relax_end ();
10082             }
10083           else
10084             {
10085               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10086                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10087             }
10088         }
10089       else if (mips_big_got && !HAVE_NEWABI)
10090         {
10091           int gpdelay;
10092           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10093           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10094           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10095
10096           /* This is the large GOT case.  If this is a reference to an
10097              external symbol, and there is no constant, we want
10098                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10099                addu     $tempreg,$tempreg,$gp
10100                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10101              or for lca or if tempreg is PIC_CALL_REG
10102                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10103                addu     $tempreg,$tempreg,$gp
10104                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10105              For a local symbol, we want
10106                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10107                nop
10108                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10109
10110              If we have a small constant, and this is a reference to
10111              an external symbol, we want
10112                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10113                addu     $tempreg,$tempreg,$gp
10114                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10115                nop
10116                addiu    $tempreg,$tempreg,<constant>
10117              For a local symbol, we want
10118                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10119                nop
10120                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
10121
10122              If we have a large constant, and this is a reference to
10123              an external symbol, we want
10124                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10125                addu     $tempreg,$tempreg,$gp
10126                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10127                lui      $at,<hiconstant>
10128                addiu    $at,$at,<loconstant>
10129                addu     $tempreg,$tempreg,$at
10130              For a local symbol, we want
10131                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10132                lui      $at,<hiconstant>
10133                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
10134                addu     $tempreg,$tempreg,$at
10135           */
10136
10137           expr1.X_add_number = offset_expr.X_add_number;
10138           offset_expr.X_add_number = 0;
10139           relax_start (offset_expr.X_add_symbol);
10140           gpdelay = reg_needs_delay (mips_gp_register);
10141           if (expr1.X_add_number == 0 && breg == 0
10142               && (call || tempreg == PIC_CALL_REG))
10143             {
10144               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10145               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10146             }
10147           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10148           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10149                        tempreg, tempreg, mips_gp_register);
10150           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10151                        tempreg, lw_reloc_type, tempreg);
10152           if (expr1.X_add_number == 0)
10153             {
10154               if (breg != 0)
10155                 {
10156                   /* We're going to put in an addu instruction using
10157                      tempreg, so we may as well insert the nop right
10158                      now.  */
10159                   load_delay_nop ();
10160                 }
10161             }
10162           else if (expr1.X_add_number >= -0x8000
10163                    && expr1.X_add_number < 0x8000)
10164             {
10165               load_delay_nop ();
10166               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10167                            tempreg, tempreg, BFD_RELOC_LO16);
10168             }
10169           else
10170             {
10171               unsigned int dreg;
10172
10173               /* If we are going to add in a base register, and the
10174                  target register and the base register are the same,
10175                  then we are using AT as a temporary register.  Since
10176                  we want to load the constant into AT, we add our
10177                  current AT (from the global offset table) and the
10178                  register into the register now, and pretend we were
10179                  not using a base register.  */
10180               if (breg != op[0])
10181                 dreg = tempreg;
10182               else
10183                 {
10184                   gas_assert (tempreg == AT);
10185                   load_delay_nop ();
10186                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10187                                op[0], AT, breg);
10188                   dreg = op[0];
10189                 }
10190
10191               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10192               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
10193
10194               used_at = 1;
10195             }
10196           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
10197           relax_switch ();
10198
10199           if (gpdelay)
10200             {
10201               /* This is needed because this instruction uses $gp, but
10202                  the first instruction on the main stream does not.  */
10203               macro_build (NULL, "nop", "");
10204             }
10205
10206           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10207                        local_reloc_type, mips_gp_register);
10208           if (expr1.X_add_number >= -0x8000
10209               && expr1.X_add_number < 0x8000)
10210             {
10211               load_delay_nop ();
10212               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10213                            tempreg, tempreg, BFD_RELOC_LO16);
10214               /* FIXME: If add_number is 0, and there was no base
10215                  register, the external symbol case ended with a load,
10216                  so if the symbol turns out to not be external, and
10217                  the next instruction uses tempreg, an unnecessary nop
10218                  will be inserted.  */
10219             }
10220           else
10221             {
10222               if (breg == op[0])
10223                 {
10224                   /* We must add in the base register now, as in the
10225                      external symbol case.  */
10226                   gas_assert (tempreg == AT);
10227                   load_delay_nop ();
10228                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10229                                op[0], AT, breg);
10230                   tempreg = op[0];
10231                   /* We set breg to 0 because we have arranged to add
10232                      it in in both cases.  */
10233                   breg = 0;
10234                 }
10235
10236               macro_build_lui (&expr1, AT);
10237               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10238                            AT, AT, BFD_RELOC_LO16);
10239               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10240                            tempreg, tempreg, AT);
10241               used_at = 1;
10242             }
10243           relax_end ();
10244         }
10245       else if (mips_big_got && HAVE_NEWABI)
10246         {
10247           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10248           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10249           int add_breg_early = 0;
10250
10251           /* This is the large GOT case.  If this is a reference to an
10252              external symbol, and there is no constant, we want
10253                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10254                add      $tempreg,$tempreg,$gp
10255                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10256              or for lca or if tempreg is PIC_CALL_REG
10257                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10258                add      $tempreg,$tempreg,$gp
10259                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10260
10261              If we have a small constant, and this is a reference to
10262              an external symbol, we want
10263                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10264                add      $tempreg,$tempreg,$gp
10265                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10266                addi     $tempreg,$tempreg,<constant>
10267
10268              If we have a large constant, and this is a reference to
10269              an external symbol, we want
10270                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10271                addu     $tempreg,$tempreg,$gp
10272                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10273                lui      $at,<hiconstant>
10274                addi     $at,$at,<loconstant>
10275                add      $tempreg,$tempreg,$at
10276
10277              If we have NewABI, and we know it's a local symbol, we want
10278                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
10279                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
10280              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
10281
10282           relax_start (offset_expr.X_add_symbol);
10283
10284           expr1.X_add_number = offset_expr.X_add_number;
10285           offset_expr.X_add_number = 0;
10286
10287           if (expr1.X_add_number == 0 && breg == 0
10288               && (call || tempreg == PIC_CALL_REG))
10289             {
10290               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10291               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10292             }
10293           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10294           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10295                        tempreg, tempreg, mips_gp_register);
10296           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10297                        tempreg, lw_reloc_type, tempreg);
10298
10299           if (expr1.X_add_number == 0)
10300             ;
10301           else if (expr1.X_add_number >= -0x8000
10302                    && expr1.X_add_number < 0x8000)
10303             {
10304               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10305                            tempreg, tempreg, BFD_RELOC_LO16);
10306             }
10307           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
10308             {
10309               unsigned int dreg;
10310
10311               /* If we are going to add in a base register, and the
10312                  target register and the base register are the same,
10313                  then we are using AT as a temporary register.  Since
10314                  we want to load the constant into AT, we add our
10315                  current AT (from the global offset table) and the
10316                  register into the register now, and pretend we were
10317                  not using a base register.  */
10318               if (breg != op[0])
10319                 dreg = tempreg;
10320               else
10321                 {
10322                   gas_assert (tempreg == AT);
10323                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10324                                op[0], AT, breg);
10325                   dreg = op[0];
10326                   add_breg_early = 1;
10327                 }
10328
10329               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10330               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
10331
10332               used_at = 1;
10333             }
10334           else
10335             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
10336
10337           relax_switch ();
10338           offset_expr.X_add_number = expr1.X_add_number;
10339           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10340                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
10341           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
10342                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
10343           if (add_breg_early)
10344             {
10345               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10346                            op[0], tempreg, breg);
10347               breg = 0;
10348               tempreg = op[0];
10349             }
10350           relax_end ();
10351         }
10352       else
10353         abort ();
10354
10355       if (breg != 0)
10356         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", op[0], tempreg, breg);
10357       break;
10358
10359     case M_MSGSND:
10360       gas_assert (!mips_opts.micromips);
10361       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x01);
10362       break;
10363
10364     case M_MSGLD:
10365       gas_assert (!mips_opts.micromips);
10366       macro_build (NULL, "c2", "C", 0x02);
10367       break;
10368
10369     case M_MSGLD_T:
10370       gas_assert (!mips_opts.micromips);
10371       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x02);
10372       break;
10373
10374     case M_MSGWAIT:
10375       gas_assert (!mips_opts.micromips);
10376       macro_build (NULL, "c2", "C", 3);
10377       break;
10378
10379     case M_MSGWAIT_T:
10380       gas_assert (!mips_opts.micromips);
10381       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x03);
10382       break;
10383
10384     case M_J_A:
10385       /* The j instruction may not be used in PIC code, since it
10386          requires an absolute address.  We convert it to a b
10387          instruction.  */
10388       if (mips_pic == NO_PIC)
10389         macro_build (&offset_expr, "j", "a");
10390       else
10391         macro_build (&offset_expr, "b", "p");
10392       break;
10393
10394       /* The jal instructions must be handled as macros because when
10395          generating PIC code they expand to multi-instruction
10396          sequences.  Normally they are simple instructions.  */
10397     case M_JALS_1:
10398       op[1] = op[0];
10399       op[0] = RA;
10400       /* Fall through.  */
10401     case M_JALS_2:
10402       gas_assert (mips_opts.micromips);
10403       if (mips_opts.insn32)
10404         {
10405           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
10406           break;
10407         }
10408       jals = 1;
10409       goto jal;
10410     case M_JAL_1:
10411       op[1] = op[0];
10412       op[0] = RA;
10413       /* Fall through.  */
10414     case M_JAL_2:
10415     jal:
10416       if (mips_pic == NO_PIC)
10417         {
10418           s = jals ? "jalrs" : "jalr";
10419           if (mips_opts.micromips
10420               && !mips_opts.insn32
10421               && op[0] == RA
10422               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
10423             macro_build (NULL, s, "mj", op[1]);
10424           else
10425             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
10426         }
10427       else
10428         {
10429           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
10430                            && mips_cprestore_offset >= 0);
10431
10432           if (op[1] != PIC_CALL_REG)
10433             as_warn (_("MIPS PIC call to register other than $25"));
10434
10435           s = ((mips_opts.micromips
10436                 && !mips_opts.insn32
10437                 && (!mips_opts.noreorder || cprestore))
10438                ? "jalrs" : "jalr");
10439           if (mips_opts.micromips
10440               && !mips_opts.insn32
10441               && op[0] == RA
10442               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
10443             macro_build (NULL, s, "mj", op[1]);
10444           else
10445             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
10446           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
10447             {
10448               if (mips_cprestore_offset < 0)
10449                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
10450               else
10451                 {
10452                   if (!mips_frame_reg_valid)
10453                     {
10454                       as_warn (_("no .frame pseudo-op used in PIC code"));
10455                       /* Quiet this warning.  */
10456                       mips_frame_reg_valid = 1;
10457                     }
10458                   if (!mips_cprestore_valid)
10459                     {
10460                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
10461                       /* Quiet this warning.  */
10462                       mips_cprestore_valid = 1;
10463                     }
10464                   if (mips_opts.noreorder)
10465                     macro_build (NULL, "nop", "");
10466                   expr1.X_add_number = mips_cprestore_offset;
10467                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
10468                                                 mips_gp_register,
10469                                                 mips_frame_reg,
10470                                                 HAVE_64BIT_ADDRESSES);
10471                 }
10472             }
10473         }
10474
10475       break;
10476
10477     case M_JALS_A:
10478       gas_assert (mips_opts.micromips);
10479       if (mips_opts.insn32)
10480         {
10481           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
10482           break;
10483         }
10484       jals = 1;
10485       /* Fall through.  */
10486     case M_JAL_A:
10487       if (mips_pic == NO_PIC)
10488         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
10489       else if (mips_pic == SVR4_PIC)
10490         {
10491           /* If this is a reference to an external symbol, and we are
10492              using a small GOT, we want
10493                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
10494                nop
10495                jalr     $ra,$25
10496                nop
10497                lw       $gp,cprestore($sp)
10498              The cprestore value is set using the .cprestore
10499              pseudo-op.  If we are using a big GOT, we want
10500                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
10501                addu     $25,$25,$gp
10502                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
10503                nop
10504                jalr     $ra,$25
10505                nop
10506                lw       $gp,cprestore($sp)
10507              If the symbol is not external, we want
10508                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10509                nop
10510                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
10511                jalr     $ra,$25
10512                nop
10513                lw $gp,cprestore($sp)
10514
10515              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
10516              sequences above, minus nops, unless the symbol is local,
10517              which enables us to use GOT_PAGE/GOT_OFST (big got) or
10518              GOT_DISP.  */
10519           if (HAVE_NEWABI)
10520             {
10521               if (!mips_big_got)
10522                 {
10523                   relax_start (offset_expr.X_add_symbol);
10524                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10525                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
10526                                mips_gp_register);
10527                   relax_switch ();
10528                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10529                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
10530                                mips_gp_register);
10531                   relax_end ();
10532                 }
10533               else
10534                 {
10535                   relax_start (offset_expr.X_add_symbol);
10536                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
10537                                BFD_RELOC_MIPS_CALL_HI16);
10538                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
10539                                PIC_CALL_REG, mips_gp_register);
10540                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10541                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
10542                                PIC_CALL_REG);
10543                   relax_switch ();
10544                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10545                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
10546                                mips_gp_register);
10547                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10548                                PIC_CALL_REG, PIC_CALL_REG,
10549                                BFD_RELOC_MIPS_GOT_OFST);
10550                   relax_end ();
10551                 }
10552
10553               macro_build_jalr (&offset_expr, 0);
10554             }
10555           else
10556             {
10557               relax_start (offset_expr.X_add_symbol);
10558               if (!mips_big_got)
10559                 {
10560                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10561                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
10562                                mips_gp_register);
10563                   load_delay_nop ();
10564                   relax_switch ();
10565                 }
10566               else
10567                 {
10568                   int gpdelay;
10569
10570                   gpdelay = reg_needs_delay (mips_gp_register);
10571                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
10572                                BFD_RELOC_MIPS_CALL_HI16);
10573                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
10574                                PIC_CALL_REG, mips_gp_register);
10575                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10576                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
10577                                PIC_CALL_REG);
10578                   load_delay_nop ();
10579                   relax_switch ();
10580                   if (gpdelay)
10581                     macro_build (NULL, "nop", "");
10582                 }
10583               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10584                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
10585                            mips_gp_register);
10586               load_delay_nop ();
10587               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10588                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
10589               relax_end ();
10590               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
10591
10592               if (mips_cprestore_offset < 0)
10593                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
10594               else
10595                 {
10596                   if (!mips_frame_reg_valid)
10597                     {
10598                       as_warn (_("no .frame pseudo-op used in PIC code"));
10599                       /* Quiet this warning.  */
10600                       mips_frame_reg_valid = 1;
10601                     }
10602                   if (!mips_cprestore_valid)
10603                     {
10604                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
10605                       /* Quiet this warning.  */
10606                       mips_cprestore_valid = 1;
10607                     }
10608                   if (mips_opts.noreorder)
10609                     macro_build (NULL, "nop", "");
10610                   expr1.X_add_number = mips_cprestore_offset;
10611                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
10612                                                 mips_gp_register,
10613                                                 mips_frame_reg,
10614                                                 HAVE_64BIT_ADDRESSES);
10615                 }
10616             }
10617         }
10618       else if (mips_pic == VXWORKS_PIC)
10619         as_bad (_("non-PIC jump used in PIC library"));
10620       else
10621         abort ();
10622
10623       break;
10624
10625     case M_LBUE_AB:
10626       s = "lbue";
10627       fmt = "t,+j(b)";
10628       offbits = 9;
10629       goto ld_st;
10630     case M_LHUE_AB:
10631       s = "lhue";
10632       fmt = "t,+j(b)";
10633       offbits = 9;
10634       goto ld_st;
10635     case M_LBE_AB:
10636       s = "lbe";
10637       fmt = "t,+j(b)";
10638       offbits = 9;
10639       goto ld_st;
10640     case M_LHE_AB:
10641       s = "lhe";
10642       fmt = "t,+j(b)";
10643       offbits = 9;
10644       goto ld_st;
10645     case M_LLE_AB:
10646       s = "lle";
10647       fmt = "t,+j(b)";
10648       offbits = 9;
10649       goto ld_st;
10650     case M_LWE_AB:
10651       s = "lwe";
10652       fmt = "t,+j(b)";
10653       offbits = 9;
10654       goto ld_st;
10655     case M_LWLE_AB:
10656       s = "lwle";
10657       fmt = "t,+j(b)";
10658       offbits = 9;
10659       goto ld_st;
10660     case M_LWRE_AB:
10661       s = "lwre";
10662       fmt = "t,+j(b)";
10663       offbits = 9;
10664       goto ld_st;
10665     case M_SBE_AB:
10666       s = "sbe";
10667       fmt = "t,+j(b)";
10668       offbits = 9;
10669       goto ld_st;
10670     case M_SCE_AB:
10671       s = "sce";
10672       fmt = "t,+j(b)";
10673       offbits = 9;
10674       goto ld_st;
10675     case M_SHE_AB:
10676       s = "she";
10677       fmt = "t,+j(b)";
10678       offbits = 9;
10679       goto ld_st;
10680     case M_SWE_AB:
10681       s = "swe";
10682       fmt = "t,+j(b)";
10683       offbits = 9;
10684       goto ld_st;
10685     case M_SWLE_AB:
10686       s = "swle";
10687       fmt = "t,+j(b)";
10688       offbits = 9;
10689       goto ld_st;
10690     case M_SWRE_AB:
10691       s = "swre";
10692       fmt = "t,+j(b)";
10693       offbits = 9;
10694       goto ld_st;
10695     case M_ACLR_AB:
10696       s = "aclr";
10697       fmt = "\\,~(b)";
10698       offbits = 12;
10699       goto ld_st;
10700     case M_ASET_AB:
10701       s = "aset";
10702       fmt = "\\,~(b)";
10703       offbits = 12;
10704       goto ld_st;
10705     case M_LB_AB:
10706       s = "lb";
10707       fmt = "t,o(b)";
10708       goto ld;
10709     case M_LBU_AB:
10710       s = "lbu";
10711       fmt = "t,o(b)";
10712       goto ld;
10713     case M_LH_AB:
10714       s = "lh";
10715       fmt = "t,o(b)";
10716       goto ld;
10717     case M_LHU_AB:
10718       s = "lhu";
10719       fmt = "t,o(b)";
10720       goto ld;
10721     case M_LW_AB:
10722       s = "lw";
10723       fmt = "t,o(b)";
10724       goto ld;
10725     case M_LWC0_AB:
10726       gas_assert (!mips_opts.micromips);
10727       s = "lwc0";
10728       fmt = "E,o(b)";
10729       /* Itbl support may require additional care here.  */
10730       coproc = 1;
10731       goto ld_st;
10732     case M_LWC1_AB:
10733       s = "lwc1";
10734       fmt = "T,o(b)";
10735       /* Itbl support may require additional care here.  */
10736       coproc = 1;
10737       goto ld_st;
10738     case M_LWC2_AB:
10739       s = "lwc2";
10740       fmt = COP12_FMT;
10741       offbits = (mips_opts.micromips ? 12 : 16);
10742       /* Itbl support may require additional care here.  */
10743       coproc = 1;
10744       goto ld_st;
10745     case M_LWC3_AB:
10746       gas_assert (!mips_opts.micromips);
10747       s = "lwc3";
10748       fmt = "E,o(b)";
10749       /* Itbl support may require additional care here.  */
10750       coproc = 1;
10751       goto ld_st;
10752     case M_LWL_AB:
10753       s = "lwl";
10754       fmt = MEM12_FMT;
10755       offbits = (mips_opts.micromips ? 12 : 16);
10756       goto ld_st;
10757     case M_LWR_AB:
10758       s = "lwr";
10759       fmt = MEM12_FMT;
10760       offbits = (mips_opts.micromips ? 12 : 16);
10761       goto ld_st;
10762     case M_LDC1_AB:
10763       s = "ldc1";
10764       fmt = "T,o(b)";
10765       /* Itbl support may require additional care here.  */
10766       coproc = 1;
10767       goto ld_st;
10768     case M_LDC2_AB:
10769       s = "ldc2";
10770       fmt = COP12_FMT;
10771       offbits = (mips_opts.micromips ? 12 : 16);
10772       /* Itbl support may require additional care here.  */
10773       coproc = 1;
10774       goto ld_st;
10775     case M_LQC2_AB:
10776       s = "lqc2";
10777       fmt = "+7,o(b)";
10778       /* Itbl support may require additional care here.  */
10779       coproc = 1;
10780       goto ld_st;
10781     case M_LDC3_AB:
10782       s = "ldc3";
10783       fmt = "E,o(b)";
10784       /* Itbl support may require additional care here.  */
10785       coproc = 1;
10786       goto ld_st;
10787     case M_LDL_AB:
10788       s = "ldl";
10789       fmt = MEM12_FMT;
10790       offbits = (mips_opts.micromips ? 12 : 16);
10791       goto ld_st;
10792     case M_LDR_AB:
10793       s = "ldr";
10794       fmt = MEM12_FMT;
10795       offbits = (mips_opts.micromips ? 12 : 16);
10796       goto ld_st;
10797     case M_LL_AB:
10798       s = "ll";
10799       fmt = MEM12_FMT;
10800       offbits = (mips_opts.micromips ? 12 : 16);
10801       goto ld;
10802     case M_LLD_AB:
10803       s = "lld";
10804       fmt = MEM12_FMT;
10805       offbits = (mips_opts.micromips ? 12 : 16);
10806       goto ld;
10807     case M_LWU_AB:
10808       s = "lwu";
10809       fmt = MEM12_FMT;
10810       offbits = (mips_opts.micromips ? 12 : 16);
10811       goto ld;
10812     case M_LWP_AB:
10813       gas_assert (mips_opts.micromips);
10814       s = "lwp";
10815       fmt = "t,~(b)";
10816       offbits = 12;
10817       lp = 1;
10818       goto ld;
10819     case M_LDP_AB:
10820       gas_assert (mips_opts.micromips);
10821       s = "ldp";
10822       fmt = "t,~(b)";
10823       offbits = 12;
10824       lp = 1;
10825       goto ld;
10826     case M_LWM_AB:
10827       gas_assert (mips_opts.micromips);
10828       s = "lwm";
10829       fmt = "n,~(b)";
10830       offbits = 12;
10831       goto ld_st;
10832     case M_LDM_AB:
10833       gas_assert (mips_opts.micromips);
10834       s = "ldm";
10835       fmt = "n,~(b)";
10836       offbits = 12;
10837       goto ld_st;
10838
10839     ld:
10840       /* We don't want to use $0 as tempreg.  */
10841       if (op[2] == op[0] + lp || op[0] + lp == ZERO)
10842         goto ld_st;
10843       else
10844         tempreg = op[0] + lp;
10845       goto ld_noat;
10846
10847     case M_SB_AB:
10848       s = "sb";
10849       fmt = "t,o(b)";
10850       goto ld_st;
10851     case M_SH_AB:
10852       s = "sh";
10853       fmt = "t,o(b)";
10854       goto ld_st;
10855     case M_SW_AB:
10856       s = "sw";
10857       fmt = "t,o(b)";
10858       goto ld_st;
10859     case M_SWC0_AB:
10860       gas_assert (!mips_opts.micromips);
10861       s = "swc0";
10862       fmt = "E,o(b)";
10863       /* Itbl support may require additional care here.  */
10864       coproc = 1;
10865       goto ld_st;
10866     case M_SWC1_AB:
10867       s = "swc1";
10868       fmt = "T,o(b)";
10869       /* Itbl support may require additional care here.  */
10870       coproc = 1;
10871       goto ld_st;
10872     case M_SWC2_AB:
10873       s = "swc2";
10874       fmt = COP12_FMT;
10875       offbits = (mips_opts.micromips ? 12 : 16);
10876       /* Itbl support may require additional care here.  */
10877       coproc = 1;
10878       goto ld_st;
10879     case M_SWC3_AB:
10880       gas_assert (!mips_opts.micromips);
10881       s = "swc3";
10882       fmt = "E,o(b)";
10883       /* Itbl support may require additional care here.  */
10884       coproc = 1;
10885       goto ld_st;
10886     case M_SWL_AB:
10887       s = "swl";
10888       fmt = MEM12_FMT;
10889       offbits = (mips_opts.micromips ? 12 : 16);
10890       goto ld_st;
10891     case M_SWR_AB:
10892       s = "swr";
10893       fmt = MEM12_FMT;
10894       offbits = (mips_opts.micromips ? 12 : 16);
10895       goto ld_st;
10896     case M_SC_AB:
10897       s = "sc";
10898       fmt = MEM12_FMT;
10899       offbits = (mips_opts.micromips ? 12 : 16);
10900       goto ld_st;
10901     case M_SCD_AB:
10902       s = "scd";
10903       fmt = MEM12_FMT;
10904       offbits = (mips_opts.micromips ? 12 : 16);
10905       goto ld_st;
10906     case M_CACHE_AB:
10907       s = "cache";
10908       fmt = mips_opts.micromips ? "k,~(b)" : "k,o(b)";
10909       offbits = (mips_opts.micromips ? 12 : 16);
10910       goto ld_st;
10911     case M_CACHEE_AB:
10912       s = "cachee";
10913       fmt = "k,+j(b)";
10914       offbits = 9;
10915       goto ld_st;
10916     case M_PREF_AB:
10917       s = "pref";
10918       fmt = !mips_opts.micromips ? "k,o(b)" : "k,~(b)";
10919       offbits = (mips_opts.micromips ? 12 : 16);
10920       goto ld_st;
10921     case M_PREFE_AB:
10922       s = "prefe";
10923       fmt = "k,+j(b)";
10924       offbits = 9;
10925       goto ld_st;
10926     case M_SDC1_AB:
10927       s = "sdc1";
10928       fmt = "T,o(b)";
10929       coproc = 1;
10930       /* Itbl support may require additional care here.  */
10931       goto ld_st;
10932     case M_SDC2_AB:
10933       s = "sdc2";
10934       fmt = COP12_FMT;
10935       offbits = (mips_opts.micromips ? 12 : 16);
10936       /* Itbl support may require additional care here.  */
10937       coproc = 1;
10938       goto ld_st;
10939     case M_SQC2_AB:
10940       s = "sqc2";
10941       fmt = "+7,o(b)";
10942       /* Itbl support may require additional care here.  */
10943       coproc = 1;
10944       goto ld_st;
10945     case M_SDC3_AB:
10946       gas_assert (!mips_opts.micromips);
10947       s = "sdc3";
10948       fmt = "E,o(b)";
10949       /* Itbl support may require additional care here.  */
10950       coproc = 1;
10951       goto ld_st;
10952     case M_SDL_AB:
10953       s = "sdl";
10954       fmt = MEM12_FMT;
10955       offbits = (mips_opts.micromips ? 12 : 16);
10956       goto ld_st;
10957     case M_SDR_AB:
10958       s = "sdr";
10959       fmt = MEM12_FMT;
10960       offbits = (mips_opts.micromips ? 12 : 16);
10961       goto ld_st;
10962     case M_SWP_AB:
10963       gas_assert (mips_opts.micromips);
10964       s = "swp";
10965       fmt = "t,~(b)";
10966       offbits = 12;
10967       goto ld_st;
10968     case M_SDP_AB:
10969       gas_assert (mips_opts.micromips);
10970       s = "sdp";
10971       fmt = "t,~(b)";
10972       offbits = 12;
10973       goto ld_st;
10974     case M_SWM_AB:
10975       gas_assert (mips_opts.micromips);
10976       s = "swm";
10977       fmt = "n,~(b)";
10978       offbits = 12;
10979       goto ld_st;
10980     case M_SDM_AB:
10981       gas_assert (mips_opts.micromips);
10982       s = "sdm";
10983       fmt = "n,~(b)";
10984       offbits = 12;
10985
10986     ld_st:
10987       tempreg = AT;
10988     ld_noat:
10989       breg = op[2];
10990       if (small_offset_p (0, align, 16))
10991         {
10992           /* The first case exists for M_LD_AB and M_SD_AB, which are
10993              macros for o32 but which should act like normal instructions
10994              otherwise.  */
10995           if (offbits == 16)
10996             macro_build (&offset_expr, s, fmt, op[0], -1, offset_reloc[0],
10997                          offset_reloc[1], offset_reloc[2], breg);
10998           else if (small_offset_p (0, align, offbits))
10999             {
11000               if (offbits == 0)
11001                 macro_build (NULL, s, fmt, op[0], breg);
11002               else
11003                 macro_build (NULL, s, fmt, op[0],
11004                              (int) offset_expr.X_add_number, breg);
11005             }
11006           else
11007             {
11008               if (tempreg == AT)
11009                 used_at = 1;
11010               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11011                            tempreg, breg, -1, offset_reloc[0],
11012                            offset_reloc[1], offset_reloc[2]);
11013               if (offbits == 0)
11014                 macro_build (NULL, s, fmt, op[0], tempreg);
11015               else
11016                 macro_build (NULL, s, fmt, op[0], 0, tempreg);
11017             }
11018           break;
11019         }
11020
11021       if (tempreg == AT)
11022         used_at = 1;
11023
11024       if (offset_expr.X_op != O_constant
11025           && offset_expr.X_op != O_symbol)
11026         {
11027           as_bad (_("expression too complex"));
11028           offset_expr.X_op = O_constant;
11029         }
11030
11031       if (HAVE_32BIT_ADDRESSES
11032           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
11033         {
11034           char value [32];
11035
11036           sprintf_vma (value, offset_expr.X_add_number);
11037           as_bad (_("number (0x%s) larger than 32 bits"), value);
11038         }
11039
11040       /* A constant expression in PIC code can be handled just as it
11041          is in non PIC code.  */
11042       if (offset_expr.X_op == O_constant)
11043         {
11044           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
11045                                                  offbits == 0 ? 16 : offbits);
11046           offset_expr.X_add_number -= expr1.X_add_number;
11047
11048           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
11049           if (breg != 0)
11050             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11051                          tempreg, tempreg, breg);
11052           if (offbits == 0)
11053             {
11054               if (offset_expr.X_add_number != 0)
11055                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
11056                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
11057               macro_build (NULL, s, fmt, op[0], tempreg);
11058             }
11059           else if (offbits == 16)
11060             macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11061           else
11062             macro_build (NULL, s, fmt, op[0],
11063                          (int) offset_expr.X_add_number, tempreg);
11064         }
11065       else if (offbits != 16)
11066         {
11067           /* The offset field is too narrow to be used for a low-part
11068              relocation, so load the whole address into the auxillary
11069              register.  */
11070           load_address (tempreg, &offset_expr, &used_at);
11071           if (breg != 0)
11072             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11073                          tempreg, tempreg, breg);
11074           if (offbits == 0)
11075             macro_build (NULL, s, fmt, op[0], tempreg);
11076           else
11077             macro_build (NULL, s, fmt, op[0], 0, tempreg);
11078         }
11079       else if (mips_pic == NO_PIC)
11080         {
11081           /* If this is a reference to a GP relative symbol, and there
11082              is no base register, we want
11083                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
11084              Otherwise, if there is no base register, we want
11085                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11086                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11087              If we have a constant, we need two instructions anyhow,
11088              so we always use the latter form.
11089
11090              If we have a base register, and this is a reference to a
11091              GP relative symbol, we want
11092                addu     $tempreg,$breg,$gp
11093                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_GPREL16)
11094              Otherwise we want
11095                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11096                addu     $tempreg,$tempreg,$breg
11097                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11098              With a constant we always use the latter case.
11099
11100              With 64bit address space and no base register and $at usable,
11101              we want
11102                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11103                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11104                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11105                dsll32   $tempreg,0
11106                daddu    $tempreg,$at
11107                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11108              If we have a base register, we want
11109                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11110                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11111                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11112                daddu    $at,$breg
11113                dsll32   $tempreg,0
11114                daddu    $tempreg,$at
11115                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11116
11117              Without $at we can't generate the optimal path for superscalar
11118              processors here since this would require two temporary registers.
11119                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11120                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11121                dsll     $tempreg,16
11122                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11123                dsll     $tempreg,16
11124                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11125              If we have a base register, we want
11126                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11127                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11128                dsll     $tempreg,16
11129                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11130                dsll     $tempreg,16
11131                daddu    $tempreg,$tempreg,$breg
11132                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11133
11134              For GP relative symbols in 64bit address space we can use
11135              the same sequence as in 32bit address space.  */
11136           if (HAVE_64BIT_SYMBOLS)
11137             {
11138               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11139                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11140                 {
11141                   relax_start (offset_expr.X_add_symbol);
11142                   if (breg == 0)
11143                     {
11144                       macro_build (&offset_expr, s, fmt, op[0],
11145                                    BFD_RELOC_GPREL16, mips_gp_register);
11146                     }
11147                   else
11148                     {
11149                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11150                                    tempreg, breg, mips_gp_register);
11151                       macro_build (&offset_expr, s, fmt, op[0],
11152                                    BFD_RELOC_GPREL16, tempreg);
11153                     }
11154                   relax_switch ();
11155                 }
11156
11157               if (used_at == 0 && mips_opts.at)
11158                 {
11159                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11160                                BFD_RELOC_MIPS_HIGHEST);
11161                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
11162                                BFD_RELOC_HI16_S);
11163                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11164                                tempreg, BFD_RELOC_MIPS_HIGHER);
11165                   if (breg != 0)
11166                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
11167                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
11168                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
11169                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16,
11170                                tempreg);
11171                   used_at = 1;
11172                 }
11173               else
11174                 {
11175                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11176                                BFD_RELOC_MIPS_HIGHEST);
11177                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11178                                tempreg, BFD_RELOC_MIPS_HIGHER);
11179                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11180                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11181                                tempreg, BFD_RELOC_HI16_S);
11182                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11183                   if (breg != 0)
11184                     macro_build (NULL, "daddu", "d,v,t",
11185                                  tempreg, tempreg, breg);
11186                   macro_build (&offset_expr, s, fmt, op[0],
11187                                BFD_RELOC_LO16, tempreg);
11188                 }
11189
11190               if (mips_relax.sequence)
11191                 relax_end ();
11192               break;
11193             }
11194
11195           if (breg == 0)
11196             {
11197               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11198                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11199                 {
11200                   relax_start (offset_expr.X_add_symbol);
11201                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_GPREL16,
11202                                mips_gp_register);
11203                   relax_switch ();
11204                 }
11205               macro_build_lui (&offset_expr, tempreg);
11206               macro_build (&offset_expr, s, fmt, op[0],
11207                            BFD_RELOC_LO16, tempreg);
11208               if (mips_relax.sequence)
11209                 relax_end ();
11210             }
11211           else
11212             {
11213               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11214                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11215                 {
11216                   relax_start (offset_expr.X_add_symbol);
11217                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11218                                tempreg, breg, mips_gp_register);
11219                   macro_build (&offset_expr, s, fmt, op[0],
11220                                BFD_RELOC_GPREL16, tempreg);
11221                   relax_switch ();
11222                 }
11223               macro_build_lui (&offset_expr, tempreg);
11224               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11225                            tempreg, tempreg, breg);
11226               macro_build (&offset_expr, s, fmt, op[0],
11227                            BFD_RELOC_LO16, tempreg);
11228               if (mips_relax.sequence)
11229                 relax_end ();
11230             }
11231         }
11232       else if (!mips_big_got)
11233         {
11234           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
11235
11236           /* If this is a reference to an external symbol, we want
11237                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11238                nop
11239                <op>     op[0],0($tempreg)
11240              Otherwise we want
11241                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11242                nop
11243                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11244                <op>     op[0],0($tempreg)
11245
11246              For NewABI, we want
11247                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
11248                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
11249
11250              If there is a base register, we add it to $tempreg before
11251              the <op>.  If there is a constant, we stick it in the
11252              <op> instruction.  We don't handle constants larger than
11253              16 bits, because we have no way to load the upper 16 bits
11254              (actually, we could handle them for the subset of cases
11255              in which we are not using $at).  */
11256           gas_assert (offset_expr.X_op == O_symbol);
11257           if (HAVE_NEWABI)
11258             {
11259               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11260                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11261               if (breg != 0)
11262                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11263                              tempreg, tempreg, breg);
11264               macro_build (&offset_expr, s, fmt, op[0],
11265                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
11266               break;
11267             }
11268           expr1.X_add_number = offset_expr.X_add_number;
11269           offset_expr.X_add_number = 0;
11270           if (expr1.X_add_number < -0x8000
11271               || expr1.X_add_number >= 0x8000)
11272             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11273           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11274                        lw_reloc_type, mips_gp_register);
11275           load_delay_nop ();
11276           relax_start (offset_expr.X_add_symbol);
11277           relax_switch ();
11278           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11279                        tempreg, BFD_RELOC_LO16);
11280           relax_end ();
11281           if (breg != 0)
11282             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11283                          tempreg, tempreg, breg);
11284           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11285         }
11286       else if (mips_big_got && !HAVE_NEWABI)
11287         {
11288           int gpdelay;
11289
11290           /* If this is a reference to an external symbol, we want
11291                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11292                addu     $tempreg,$tempreg,$gp
11293                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11294                <op>     op[0],0($tempreg)
11295              Otherwise we want
11296                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11297                nop
11298                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11299                <op>     op[0],0($tempreg)
11300              If there is a base register, we add it to $tempreg before
11301              the <op>.  If there is a constant, we stick it in the
11302              <op> instruction.  We don't handle constants larger than
11303              16 bits, because we have no way to load the upper 16 bits
11304              (actually, we could handle them for the subset of cases
11305              in which we are not using $at).  */
11306           gas_assert (offset_expr.X_op == O_symbol);
11307           expr1.X_add_number = offset_expr.X_add_number;
11308           offset_expr.X_add_number = 0;
11309           if (expr1.X_add_number < -0x8000
11310               || expr1.X_add_number >= 0x8000)
11311             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11312           gpdelay = reg_needs_delay (mips_gp_register);
11313           relax_start (offset_expr.X_add_symbol);
11314           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11315                        BFD_RELOC_MIPS_GOT_HI16);
11316           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
11317                        mips_gp_register);
11318           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11319                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
11320           relax_switch ();
11321           if (gpdelay)
11322             macro_build (NULL, "nop", "");
11323           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11324                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11325           load_delay_nop ();
11326           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11327                        tempreg, BFD_RELOC_LO16);
11328           relax_end ();
11329
11330           if (breg != 0)
11331             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11332                          tempreg, tempreg, breg);
11333           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11334         }
11335       else if (mips_big_got && HAVE_NEWABI)
11336         {
11337           /* If this is a reference to an external symbol, we want
11338                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11339                add      $tempreg,$tempreg,$gp
11340                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11341                <op>     op[0],<ofst>($tempreg)
11342              Otherwise, for local symbols, we want:
11343                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
11344                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
11345           gas_assert (offset_expr.X_op == O_symbol);
11346           expr1.X_add_number = offset_expr.X_add_number;
11347           offset_expr.X_add_number = 0;
11348           if (expr1.X_add_number < -0x8000
11349               || expr1.X_add_number >= 0x8000)
11350             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11351           relax_start (offset_expr.X_add_symbol);
11352           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11353                        BFD_RELOC_MIPS_GOT_HI16);
11354           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
11355                        mips_gp_register);
11356           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11357                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
11358           if (breg != 0)
11359             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11360                          tempreg, tempreg, breg);
11361           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11362
11363           relax_switch ();
11364           offset_expr.X_add_number = expr1.X_add_number;
11365           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11366                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11367           if (breg != 0)
11368             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11369                          tempreg, tempreg, breg);
11370           macro_build (&offset_expr, s, fmt, op[0],
11371                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
11372           relax_end ();
11373         }
11374       else
11375         abort ();
11376
11377       break;
11378
11379     case M_JRADDIUSP:
11380       gas_assert (mips_opts.micromips);
11381       gas_assert (mips_opts.insn32);
11382       start_noreorder ();
11383       macro_build (NULL, "jr", "s", RA);
11384       expr1.X_add_number = op[0] << 2;
11385       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
11386       end_noreorder ();
11387       break;
11388
11389     case M_JRC:
11390       gas_assert (mips_opts.micromips);
11391       gas_assert (mips_opts.insn32);
11392       macro_build (NULL, "jr", "s", op[0]);
11393       if (mips_opts.noreorder)
11394         macro_build (NULL, "nop", "");
11395       break;
11396
11397     case M_LI:
11398     case M_LI_S:
11399       load_register (op[0], &imm_expr, 0);
11400       break;
11401
11402     case M_DLI:
11403       load_register (op[0], &imm_expr, 1);
11404       break;
11405
11406     case M_LI_SS:
11407       if (imm_expr.X_op == O_constant)
11408         {
11409           used_at = 1;
11410           load_register (AT, &imm_expr, 0);
11411           macro_build (NULL, "mtc1", "t,G", AT, op[0]);
11412           break;
11413         }
11414       else
11415         {
11416           gas_assert (imm_expr.X_op == O_absent
11417                       && offset_expr.X_op == O_symbol
11418                       && strcmp (segment_name (S_GET_SEGMENT
11419                                                (offset_expr.X_add_symbol)),
11420                                  ".lit4") == 0
11421                       && offset_expr.X_add_number == 0);
11422           macro_build (&offset_expr, "lwc1", "T,o(b)", op[0],
11423                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
11424           break;
11425         }
11426
11427     case M_LI_D:
11428       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
11429          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
11430          order 32 bits of the value and the low order 32 bits are either
11431          zero or in OFFSET_EXPR.  */
11432       if (imm_expr.X_op == O_constant)
11433         {
11434           if (HAVE_64BIT_GPRS)
11435             load_register (op[0], &imm_expr, 1);
11436           else
11437             {
11438               int hreg, lreg;
11439
11440               if (target_big_endian)
11441                 {
11442                   hreg = op[0];
11443                   lreg = op[0] + 1;
11444                 }
11445               else
11446                 {
11447                   hreg = op[0] + 1;
11448                   lreg = op[0];
11449                 }
11450
11451               if (hreg <= 31)
11452                 load_register (hreg, &imm_expr, 0);
11453               if (lreg <= 31)
11454                 {
11455                   if (offset_expr.X_op == O_absent)
11456                     move_register (lreg, 0);
11457                   else
11458                     {
11459                       gas_assert (offset_expr.X_op == O_constant);
11460                       load_register (lreg, &offset_expr, 0);
11461                     }
11462                 }
11463             }
11464           break;
11465         }
11466       gas_assert (imm_expr.X_op == O_absent);
11467
11468       /* We know that sym is in the .rdata section.  First we get the
11469          upper 16 bits of the address.  */
11470       if (mips_pic == NO_PIC)
11471         {
11472           macro_build_lui (&offset_expr, AT);
11473           used_at = 1;
11474         }
11475       else
11476         {
11477           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11478                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11479           used_at = 1;
11480         }
11481
11482       /* Now we load the register(s).  */
11483       if (HAVE_64BIT_GPRS)
11484         {
11485           used_at = 1;
11486           macro_build (&offset_expr, "ld", "t,o(b)", op[0],
11487                        BFD_RELOC_LO16, AT);
11488         }
11489       else
11490         {
11491           used_at = 1;
11492           macro_build (&offset_expr, "lw", "t,o(b)", op[0],
11493                        BFD_RELOC_LO16, AT);
11494           if (op[0] != RA)
11495             {
11496               /* FIXME: How in the world do we deal with the possible
11497                  overflow here?  */
11498               offset_expr.X_add_number += 4;
11499               macro_build (&offset_expr, "lw", "t,o(b)",
11500                            op[0] + 1, BFD_RELOC_LO16, AT);
11501             }
11502         }
11503       break;
11504
11505     case M_LI_DD:
11506       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
11507          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
11508          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
11509          the value and the low order 32 bits are either zero or in
11510          OFFSET_EXPR.  */
11511       if (imm_expr.X_op == O_constant)
11512         {
11513           used_at = 1;
11514           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
11515           if (HAVE_64BIT_FPRS)
11516             {
11517               gas_assert (HAVE_64BIT_GPRS);
11518               macro_build (NULL, "dmtc1", "t,S", AT, op[0]);
11519             }
11520           else
11521             {
11522               macro_build (NULL, "mtc1", "t,G", AT, op[0] + 1);
11523               if (offset_expr.X_op == O_absent)
11524                 macro_build (NULL, "mtc1", "t,G", 0, op[0]);
11525               else
11526                 {
11527                   gas_assert (offset_expr.X_op == O_constant);
11528                   load_register (AT, &offset_expr, 0);
11529                   macro_build (NULL, "mtc1", "t,G", AT, op[0]);
11530                 }
11531             }
11532           break;
11533         }
11534
11535       gas_assert (imm_expr.X_op == O_absent
11536                   && offset_expr.X_op == O_symbol
11537                   && offset_expr.X_add_number == 0);
11538       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
11539       if (strcmp (s, ".lit8") == 0)
11540         {
11541           op[2] = mips_gp_register;
11542           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
11543           offset_reloc[1] = BFD_RELOC_UNUSED;
11544           offset_reloc[2] = BFD_RELOC_UNUSED;
11545         }
11546       else
11547         {
11548           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
11549           used_at = 1;
11550           if (mips_pic != NO_PIC)
11551             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11552                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
11553           else
11554             {
11555               /* FIXME: This won't work for a 64 bit address.  */
11556               macro_build_lui (&offset_expr, AT);
11557             }
11558
11559           op[2] = AT;
11560           offset_reloc[0] = BFD_RELOC_LO16;
11561           offset_reloc[1] = BFD_RELOC_UNUSED;
11562           offset_reloc[2] = BFD_RELOC_UNUSED;
11563         }
11564       align = 8;
11565       /* Fall through */
11566
11567     case M_L_DAB:
11568       /*
11569        * The MIPS assembler seems to check for X_add_number not
11570        * being double aligned and generating:
11571        *        lui     at,%hi(foo+1)
11572        *        addu    at,at,v1
11573        *        addiu   at,at,%lo(foo+1)
11574        *        lwc1    f2,0(at)
11575        *        lwc1    f3,4(at)
11576        * But, the resulting address is the same after relocation so why
11577        * generate the extra instruction?
11578        */
11579       /* Itbl support may require additional care here.  */
11580       coproc = 1;
11581       fmt = "T,o(b)";
11582       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
11583         {
11584           s = "ldc1";
11585           goto ld_st;
11586         }
11587       s = "lwc1";
11588       goto ldd_std;
11589
11590     case M_S_DAB:
11591       gas_assert (!mips_opts.micromips);
11592       /* Itbl support may require additional care here.  */
11593       coproc = 1;
11594       fmt = "T,o(b)";
11595       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
11596         {
11597           s = "sdc1";
11598           goto ld_st;
11599         }
11600       s = "swc1";
11601       goto ldd_std;
11602
11603     case M_LQ_AB:
11604       fmt = "t,o(b)";
11605       s = "lq";
11606       goto ld;
11607
11608     case M_SQ_AB:
11609       fmt = "t,o(b)";
11610       s = "sq";
11611       goto ld_st;
11612
11613     case M_LD_AB:
11614       fmt = "t,o(b)";
11615       if (HAVE_64BIT_GPRS)
11616         {
11617           s = "ld";
11618           goto ld;
11619         }
11620       s = "lw";
11621       goto ldd_std;
11622
11623     case M_SD_AB:
11624       fmt = "t,o(b)";
11625       if (HAVE_64BIT_GPRS)
11626         {
11627           s = "sd";
11628           goto ld_st;
11629         }
11630       s = "sw";
11631
11632     ldd_std:
11633       /* Even on a big endian machine $fn comes before $fn+1.  We have
11634          to adjust when loading from memory.  We set coproc if we must
11635          load $fn+1 first.  */
11636       /* Itbl support may require additional care here.  */
11637       if (!target_big_endian)
11638         coproc = 0;
11639
11640       breg = op[2];
11641       if (small_offset_p (0, align, 16))
11642         {
11643           ep = &offset_expr;
11644           if (!small_offset_p (4, align, 16))
11645             {
11646               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
11647                            -1, offset_reloc[0], offset_reloc[1],
11648                            offset_reloc[2]);
11649               expr1.X_add_number = 0;
11650               ep = &expr1;
11651               breg = AT;
11652               used_at = 1;
11653               offset_reloc[0] = BFD_RELOC_LO16;
11654               offset_reloc[1] = BFD_RELOC_UNUSED;
11655               offset_reloc[2] = BFD_RELOC_UNUSED;
11656             }
11657           if (strcmp (s, "lw") == 0 && op[0] == breg)
11658             {
11659               ep->X_add_number += 4;
11660               macro_build (ep, s, fmt, op[0] + 1, -1, offset_reloc[0],
11661                            offset_reloc[1], offset_reloc[2], breg);
11662               ep->X_add_number -= 4;
11663               macro_build (ep, s, fmt, op[0], -1, offset_reloc[0],
11664                            offset_reloc[1], offset_reloc[2], breg);
11665             }
11666           else
11667             {
11668               macro_build (ep, s, fmt, coproc ? op[0] + 1 : op[0], -1,
11669                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
11670                            breg);
11671               ep->X_add_number += 4;
11672               macro_build (ep, s, fmt, coproc ? op[0] : op[0] + 1, -1,
11673                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
11674                            breg);
11675             }
11676           break;
11677         }
11678
11679       if (offset_expr.X_op != O_symbol
11680           && offset_expr.X_op != O_constant)
11681         {
11682           as_bad (_("expression too complex"));
11683           offset_expr.X_op = O_constant;
11684         }
11685
11686       if (HAVE_32BIT_ADDRESSES
11687           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
11688         {
11689           char value [32];
11690
11691           sprintf_vma (value, offset_expr.X_add_number);
11692           as_bad (_("number (0x%s) larger than 32 bits"), value);
11693         }
11694
11695       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
11696         {
11697           /* If this is a reference to a GP relative symbol, we want
11698                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
11699                <op>     op[0]+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
11700              If we have a base register, we use this
11701                addu     $at,$breg,$gp
11702                <op>     op[0],<sym>($at)        (BFD_RELOC_GPREL16)
11703                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
11704              If this is not a GP relative symbol, we want
11705                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11706                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11707                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11708              If there is a base register, we add it to $at after the
11709              lui instruction.  If there is a constant, we always use
11710              the last case.  */
11711           if (offset_expr.X_op == O_symbol
11712               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11713               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11714             {
11715               relax_start (offset_expr.X_add_symbol);
11716               if (breg == 0)
11717                 {
11718                   tempreg = mips_gp_register;
11719                 }
11720               else
11721                 {
11722                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11723                                AT, breg, mips_gp_register);
11724                   tempreg = AT;
11725                   used_at = 1;
11726                 }
11727
11728               /* Itbl support may require additional care here.  */
11729               macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11730                            BFD_RELOC_GPREL16, tempreg);
11731               offset_expr.X_add_number += 4;
11732
11733               /* Set mips_optimize to 2 to avoid inserting an
11734                  undesired nop.  */
11735               hold_mips_optimize = mips_optimize;
11736               mips_optimize = 2;
11737               /* Itbl support may require additional care here.  */
11738               macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11739                            BFD_RELOC_GPREL16, tempreg);
11740               mips_optimize = hold_mips_optimize;
11741
11742               relax_switch ();
11743
11744               offset_expr.X_add_number -= 4;
11745             }
11746           used_at = 1;
11747           if (offset_high_part (offset_expr.X_add_number, 16)
11748               != offset_high_part (offset_expr.X_add_number + 4, 16))
11749             {
11750               load_address (AT, &offset_expr, &used_at);
11751               offset_expr.X_op = O_constant;
11752               offset_expr.X_add_number = 0;
11753             }
11754           else
11755             macro_build_lui (&offset_expr, AT);
11756           if (breg != 0)
11757             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11758           /* Itbl support may require additional care here.  */
11759           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11760                        BFD_RELOC_LO16, AT);
11761           /* FIXME: How do we handle overflow here?  */
11762           offset_expr.X_add_number += 4;
11763           /* Itbl support may require additional care here.  */
11764           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11765                        BFD_RELOC_LO16, AT);
11766           if (mips_relax.sequence)
11767             relax_end ();
11768         }
11769       else if (!mips_big_got)
11770         {
11771           /* If this is a reference to an external symbol, we want
11772                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11773                nop
11774                <op>     op[0],0($at)
11775                <op>     op[0]+1,4($at)
11776              Otherwise we want
11777                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11778                nop
11779                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11780                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11781              If there is a base register we add it to $at before the
11782              lwc1 instructions.  If there is a constant we include it
11783              in the lwc1 instructions.  */
11784           used_at = 1;
11785           expr1.X_add_number = offset_expr.X_add_number;
11786           if (expr1.X_add_number < -0x8000
11787               || expr1.X_add_number >= 0x8000 - 4)
11788             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11789           load_got_offset (AT, &offset_expr);
11790           load_delay_nop ();
11791           if (breg != 0)
11792             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11793
11794           /* Set mips_optimize to 2 to avoid inserting an undesired
11795              nop.  */
11796           hold_mips_optimize = mips_optimize;
11797           mips_optimize = 2;
11798
11799           /* Itbl support may require additional care here.  */
11800           relax_start (offset_expr.X_add_symbol);
11801           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
11802                        BFD_RELOC_LO16, AT);
11803           expr1.X_add_number += 4;
11804           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
11805                        BFD_RELOC_LO16, AT);
11806           relax_switch ();
11807           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11808                        BFD_RELOC_LO16, AT);
11809           offset_expr.X_add_number += 4;
11810           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11811                        BFD_RELOC_LO16, AT);
11812           relax_end ();
11813
11814           mips_optimize = hold_mips_optimize;
11815         }
11816       else if (mips_big_got)
11817         {
11818           int gpdelay;
11819
11820           /* If this is a reference to an external symbol, we want
11821                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
11822                addu     $at,$at,$gp
11823                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
11824                nop
11825                <op>     op[0],0($at)
11826                <op>     op[0]+1,4($at)
11827              Otherwise we want
11828                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11829                nop
11830                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11831                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11832              If there is a base register we add it to $at before the
11833              lwc1 instructions.  If there is a constant we include it
11834              in the lwc1 instructions.  */
11835           used_at = 1;
11836           expr1.X_add_number = offset_expr.X_add_number;
11837           offset_expr.X_add_number = 0;
11838           if (expr1.X_add_number < -0x8000
11839               || expr1.X_add_number >= 0x8000 - 4)
11840             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11841           gpdelay = reg_needs_delay (mips_gp_register);
11842           relax_start (offset_expr.X_add_symbol);
11843           macro_build (&offset_expr, "lui", LUI_FMT,
11844                        AT, BFD_RELOC_MIPS_GOT_HI16);
11845           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11846                        AT, AT, mips_gp_register);
11847           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11848                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
11849           load_delay_nop ();
11850           if (breg != 0)
11851             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11852           /* Itbl support may require additional care here.  */
11853           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
11854                        BFD_RELOC_LO16, AT);
11855           expr1.X_add_number += 4;
11856
11857           /* Set mips_optimize to 2 to avoid inserting an undesired
11858              nop.  */
11859           hold_mips_optimize = mips_optimize;
11860           mips_optimize = 2;
11861           /* Itbl support may require additional care here.  */
11862           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
11863                        BFD_RELOC_LO16, AT);
11864           mips_optimize = hold_mips_optimize;
11865           expr1.X_add_number -= 4;
11866
11867           relax_switch ();
11868           offset_expr.X_add_number = expr1.X_add_number;
11869           if (gpdelay)
11870             macro_build (NULL, "nop", "");
11871           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11872                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11873           load_delay_nop ();
11874           if (breg != 0)
11875             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11876           /* Itbl support may require additional care here.  */
11877           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11878                        BFD_RELOC_LO16, AT);
11879           offset_expr.X_add_number += 4;
11880
11881           /* Set mips_optimize to 2 to avoid inserting an undesired
11882              nop.  */
11883           hold_mips_optimize = mips_optimize;
11884           mips_optimize = 2;
11885           /* Itbl support may require additional care here.  */
11886           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11887                        BFD_RELOC_LO16, AT);
11888           mips_optimize = hold_mips_optimize;
11889           relax_end ();
11890         }
11891       else
11892         abort ();
11893
11894       break;
11895         
11896     case M_SAA_AB:
11897       s = "saa";
11898       offbits = 0;
11899       fmt = "t,(b)";
11900       goto ld_st;
11901     case M_SAAD_AB:
11902       s = "saad";
11903       offbits = 0;
11904       fmt = "t,(b)";
11905       goto ld_st;
11906
11907    /* New code added to support COPZ instructions.
11908       This code builds table entries out of the macros in mip_opcodes.
11909       R4000 uses interlocks to handle coproc delays.
11910       Other chips (like the R3000) require nops to be inserted for delays.
11911
11912       FIXME: Currently, we require that the user handle delays.
11913       In order to fill delay slots for non-interlocked chips,
11914       we must have a way to specify delays based on the coprocessor.
11915       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
11916       What are the side-effects of the cop instruction?
11917       What cache support might we have and what are its effects?
11918       Both coprocessor & memory require delays. how long???
11919       What registers are read/set/modified?
11920
11921       If an itbl is provided to interpret cop instructions,
11922       this knowledge can be encoded in the itbl spec.  */
11923
11924     case M_COP0:
11925       s = "c0";
11926       goto copz;
11927     case M_COP1:
11928       s = "c1";
11929       goto copz;
11930     case M_COP2:
11931       s = "c2";
11932       goto copz;
11933     case M_COP3:
11934       s = "c3";
11935     copz:
11936       gas_assert (!mips_opts.micromips);
11937       /* For now we just do C (same as Cz).  The parameter will be
11938          stored in insn_opcode by mips_ip.  */
11939       macro_build (NULL, s, "C", (int) ip->insn_opcode);
11940       break;
11941
11942     case M_MOVE:
11943       move_register (op[0], op[1]);
11944       break;
11945
11946     case M_MOVEP:
11947       gas_assert (mips_opts.micromips);
11948       gas_assert (mips_opts.insn32);
11949       move_register (micromips_to_32_reg_h_map1[op[0]],
11950                      micromips_to_32_reg_m_map[op[1]]);
11951       move_register (micromips_to_32_reg_h_map2[op[0]],
11952                      micromips_to_32_reg_n_map[op[2]]);
11953       break;
11954
11955     case M_DMUL:
11956       dbl = 1;
11957     case M_MUL:
11958       if (mips_opts.arch == CPU_R5900)
11959         macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", op[0], op[1],
11960                      op[2]);
11961       else
11962         {
11963           macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", op[1], op[2]);
11964           macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11965         }
11966       break;
11967
11968     case M_DMUL_I:
11969       dbl = 1;
11970     case M_MUL_I:
11971       /* The MIPS assembler some times generates shifts and adds.  I'm
11972          not trying to be that fancy. GCC should do this for us
11973          anyway.  */
11974       used_at = 1;
11975       load_register (AT, &imm_expr, dbl);
11976       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", op[1], AT);
11977       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11978       break;
11979
11980     case M_DMULO_I:
11981       dbl = 1;
11982     case M_MULO_I:
11983       imm = 1;
11984       goto do_mulo;
11985
11986     case M_DMULO:
11987       dbl = 1;
11988     case M_MULO:
11989     do_mulo:
11990       start_noreorder ();
11991       used_at = 1;
11992       if (imm)
11993         load_register (AT, &imm_expr, dbl);
11994       macro_build (NULL, dbl ? "dmult" : "mult", "s,t",
11995                    op[1], imm ? AT : op[2]);
11996       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11997       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, op[0], op[0], 31);
11998       macro_build (NULL, "mfhi", MFHL_FMT, AT);
11999       if (mips_trap)
12000         macro_build (NULL, "tne", TRAP_FMT, op[0], AT, 6);
12001       else
12002         {
12003           if (mips_opts.micromips)
12004             micromips_label_expr (&label_expr);
12005           else
12006             label_expr.X_add_number = 8;
12007           macro_build (&label_expr, "beq", "s,t,p", op[0], AT);
12008           macro_build (NULL, "nop", "");
12009           macro_build (NULL, "break", BRK_FMT, 6);
12010           if (mips_opts.micromips)
12011             micromips_add_label ();
12012         }
12013       end_noreorder ();
12014       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12015       break;
12016
12017     case M_DMULOU_I:
12018       dbl = 1;
12019     case M_MULOU_I:
12020       imm = 1;
12021       goto do_mulou;
12022
12023     case M_DMULOU:
12024       dbl = 1;
12025     case M_MULOU:
12026     do_mulou:
12027       start_noreorder ();
12028       used_at = 1;
12029       if (imm)
12030         load_register (AT, &imm_expr, dbl);
12031       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
12032                    op[1], imm ? AT : op[2]);
12033       macro_build (NULL, "mfhi", MFHL_FMT, AT);
12034       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12035       if (mips_trap)
12036         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
12037       else
12038         {
12039           if (mips_opts.micromips)
12040             micromips_label_expr (&label_expr);
12041           else
12042             label_expr.X_add_number = 8;
12043           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
12044           macro_build (NULL, "nop", "");
12045           macro_build (NULL, "break", BRK_FMT, 6);
12046           if (mips_opts.micromips)
12047             micromips_add_label ();
12048         }
12049       end_noreorder ();
12050       break;
12051
12052     case M_DROL:
12053       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12054         {
12055           if (op[0] == op[1])
12056             {
12057               tempreg = AT;
12058               used_at = 1;
12059             }
12060           else
12061             tempreg = op[0];
12062           macro_build (NULL, "dnegu", "d,w", tempreg, op[2]);
12063           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], tempreg);
12064           break;
12065         }
12066       used_at = 1;
12067       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
12068       macro_build (NULL, "dsrlv", "d,t,s", AT, op[1], AT);
12069       macro_build (NULL, "dsllv", "d,t,s", op[0], op[1], op[2]);
12070       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12071       break;
12072
12073     case M_ROL:
12074       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12075         {
12076           if (op[0] == op[1])
12077             {
12078               tempreg = AT;
12079               used_at = 1;
12080             }
12081           else
12082             tempreg = op[0];
12083           macro_build (NULL, "negu", "d,w", tempreg, op[2]);
12084           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], tempreg);
12085           break;
12086         }
12087       used_at = 1;
12088       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12089       macro_build (NULL, "srlv", "d,t,s", AT, op[1], AT);
12090       macro_build (NULL, "sllv", "d,t,s", op[0], op[1], op[2]);
12091       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12092       break;
12093
12094     case M_DROL_I:
12095       {
12096         unsigned int rot;
12097         char *l;
12098         char *rr;
12099
12100         rot = imm_expr.X_add_number & 0x3f;
12101         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12102           {
12103             rot = (64 - rot) & 0x3f;
12104             if (rot >= 32)
12105               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12106             else
12107               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12108             break;
12109           }
12110         if (rot == 0)
12111           {
12112             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12113             break;
12114           }
12115         l = (rot < 0x20) ? "dsll" : "dsll32";
12116         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
12117         rot &= 0x1f;
12118         used_at = 1;
12119         macro_build (NULL, l, SHFT_FMT, AT, op[1], rot);
12120         macro_build (NULL, rr, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12121         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12122       }
12123       break;
12124
12125     case M_ROL_I:
12126       {
12127         unsigned int rot;
12128
12129         rot = imm_expr.X_add_number & 0x1f;
12130         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12131           {
12132             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1],
12133                          (32 - rot) & 0x1f);
12134             break;
12135           }
12136         if (rot == 0)
12137           {
12138             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12139             break;
12140           }
12141         used_at = 1;
12142         macro_build (NULL, "sll", SHFT_FMT, AT, op[1], rot);
12143         macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12144         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12145       }
12146       break;
12147
12148     case M_DROR:
12149       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12150         {
12151           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], op[2]);
12152           break;
12153         }
12154       used_at = 1;
12155       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
12156       macro_build (NULL, "dsllv", "d,t,s", AT, op[1], AT);
12157       macro_build (NULL, "dsrlv", "d,t,s", op[0], op[1], op[2]);
12158       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12159       break;
12160
12161     case M_ROR:
12162       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12163         {
12164           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], op[2]);
12165           break;
12166         }
12167       used_at = 1;
12168       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12169       macro_build (NULL, "sllv", "d,t,s", AT, op[1], AT);
12170       macro_build (NULL, "srlv", "d,t,s", op[0], op[1], op[2]);
12171       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12172       break;
12173
12174     case M_DROR_I:
12175       {
12176         unsigned int rot;
12177         char *l;
12178         char *rr;
12179
12180         rot = imm_expr.X_add_number & 0x3f;
12181         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12182           {
12183             if (rot >= 32)
12184               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12185             else
12186               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12187             break;
12188           }
12189         if (rot == 0)
12190           {
12191             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12192             break;
12193           }
12194         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
12195         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
12196         rot &= 0x1f;
12197         used_at = 1;
12198         macro_build (NULL, rr, SHFT_FMT, AT, op[1], rot);
12199         macro_build (NULL, l, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12200         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12201       }
12202       break;
12203
12204     case M_ROR_I:
12205       {
12206         unsigned int rot;
12207
12208         rot = imm_expr.X_add_number & 0x1f;
12209         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12210           {
12211             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1], rot);
12212             break;
12213           }
12214         if (rot == 0)
12215           {
12216             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12217             break;
12218           }
12219         used_at = 1;
12220         macro_build (NULL, "srl", SHFT_FMT, AT, op[1], rot);
12221         macro_build (NULL, "sll", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12222         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12223       }
12224       break;
12225
12226     case M_SEQ:
12227       if (op[1] == 0)
12228         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[2], BFD_RELOC_LO16);
12229       else if (op[2] == 0)
12230         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12231       else
12232         {
12233           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
12234           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
12235         }
12236       break;
12237
12238     case M_SEQ_I:
12239       if (imm_expr.X_add_number == 0)
12240         {
12241           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12242           break;
12243         }
12244       if (op[1] == 0)
12245         {
12246           as_warn (_("instruction %s: result is always false"),
12247                    ip->insn_mo->name);
12248           move_register (op[0], 0);
12249           break;
12250         }
12251       if (CPU_HAS_SEQ (mips_opts.arch)
12252           && -512 <= imm_expr.X_add_number
12253           && imm_expr.X_add_number < 512)
12254         {
12255           macro_build (NULL, "seqi", "t,r,+Q", op[0], op[1],
12256                        (int) imm_expr.X_add_number);
12257           break;
12258         }
12259       if (imm_expr.X_add_number >= 0
12260           && imm_expr.X_add_number < 0x10000)
12261         macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1], BFD_RELOC_LO16);
12262       else if (imm_expr.X_add_number > -0x8000
12263                && imm_expr.X_add_number < 0)
12264         {
12265           imm_expr.X_add_number = -imm_expr.X_add_number;
12266           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
12267                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12268         }
12269       else if (CPU_HAS_SEQ (mips_opts.arch))
12270         {
12271           used_at = 1;
12272           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12273           macro_build (NULL, "seq", "d,v,t", op[0], op[1], AT);
12274           break;
12275         }
12276       else
12277         {
12278           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12279           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
12280           used_at = 1;
12281         }
12282       macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
12283       break;
12284
12285     case M_SGE:         /* X >= Y  <==>  not (X < Y) */
12286       s = "slt";
12287       goto sge;
12288     case M_SGEU:
12289       s = "sltu";
12290     sge:
12291       macro_build (NULL, s, "d,v,t", op[0], op[1], op[2]);
12292       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12293       break;
12294
12295     case M_SGE_I:       /* X >= I  <==>  not (X < I) */
12296     case M_SGEU_I:
12297       if (imm_expr.X_add_number >= -0x8000
12298           && imm_expr.X_add_number < 0x8000)
12299         macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
12300                      op[0], op[1], BFD_RELOC_LO16);
12301       else
12302         {
12303           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12304           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
12305                        op[0], op[1], AT);
12306           used_at = 1;
12307         }
12308       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12309       break;
12310
12311     case M_SGT:         /* X > Y  <==>  Y < X */
12312       s = "slt";
12313       goto sgt;
12314     case M_SGTU:
12315       s = "sltu";
12316     sgt:
12317       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
12318       break;
12319
12320     case M_SGT_I:       /* X > I  <==>  I < X */
12321       s = "slt";
12322       goto sgti;
12323     case M_SGTU_I:
12324       s = "sltu";
12325     sgti:
12326       used_at = 1;
12327       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12328       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
12329       break;
12330
12331     case M_SLE:         /* X <= Y  <==>  Y >= X  <==>  not (Y < X) */
12332       s = "slt";
12333       goto sle;
12334     case M_SLEU:
12335       s = "sltu";
12336     sle:
12337       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
12338       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12339       break;
12340
12341     case M_SLE_I:       /* X <= I  <==>  I >= X  <==>  not (I < X) */
12342       s = "slt";
12343       goto slei;
12344     case M_SLEU_I:
12345       s = "sltu";
12346     slei:
12347       used_at = 1;
12348       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12349       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
12350       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12351       break;
12352
12353     case M_SLT_I:
12354       if (imm_expr.X_add_number >= -0x8000
12355           && imm_expr.X_add_number < 0x8000)
12356         {
12357           macro_build (&imm_expr, "slti", "t,r,j", op[0], op[1],
12358                        BFD_RELOC_LO16);
12359           break;
12360         }
12361       used_at = 1;
12362       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12363       macro_build (NULL, "slt", "d,v,t", op[0], op[1], AT);
12364       break;
12365
12366     case M_SLTU_I:
12367       if (imm_expr.X_add_number >= -0x8000
12368           && imm_expr.X_add_number < 0x8000)
12369         {
12370           macro_build (&imm_expr, "sltiu", "t,r,j", op[0], op[1],
12371                        BFD_RELOC_LO16);
12372           break;
12373         }
12374       used_at = 1;
12375       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12376       macro_build (NULL, "sltu", "d,v,t", op[0], op[1], AT);
12377       break;
12378
12379     case M_SNE:
12380       if (op[1] == 0)
12381         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[2]);
12382       else if (op[2] == 0)
12383         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
12384       else
12385         {
12386           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
12387           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
12388         }
12389       break;
12390
12391     case M_SNE_I:
12392       if (imm_expr.X_add_number == 0)
12393         {
12394           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
12395           break;
12396         }
12397       if (op[1] == 0)
12398         {
12399           as_warn (_("instruction %s: result is always true"),
12400                    ip->insn_mo->name);
12401           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
12402                        op[0], 0, BFD_RELOC_LO16);
12403           break;
12404         }
12405       if (CPU_HAS_SEQ (mips_opts.arch)
12406           && -512 <= imm_expr.X_add_number
12407           && imm_expr.X_add_number < 512)
12408         {
12409           macro_build (NULL, "snei", "t,r,+Q", op[0], op[1],
12410                        (int) imm_expr.X_add_number);
12411           break;
12412         }
12413       if (imm_expr.X_add_number >= 0
12414           && imm_expr.X_add_number < 0x10000)
12415         {
12416           macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1],
12417                        BFD_RELOC_LO16);
12418         }
12419       else if (imm_expr.X_add_number > -0x8000
12420                && imm_expr.X_add_number < 0)
12421         {
12422           imm_expr.X_add_number = -imm_expr.X_add_number;
12423           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
12424                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12425         }
12426       else if (CPU_HAS_SEQ (mips_opts.arch))
12427         {
12428           used_at = 1;
12429           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12430           macro_build (NULL, "sne", "d,v,t", op[0], op[1], AT);
12431           break;
12432         }
12433       else
12434         {
12435           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12436           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
12437           used_at = 1;
12438         }
12439       macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
12440       break;
12441
12442     case M_SUB_I:
12443       s = "addi";
12444       s2 = "sub";
12445       goto do_subi;
12446     case M_SUBU_I:
12447       s = "addiu";
12448       s2 = "subu";
12449       goto do_subi;
12450     case M_DSUB_I:
12451       dbl = 1;
12452       s = "daddi";
12453       s2 = "dsub";
12454       if (!mips_opts.micromips)
12455         goto do_subi;
12456       if (imm_expr.X_add_number > -0x200
12457           && imm_expr.X_add_number <= 0x200)
12458         {
12459           macro_build (NULL, s, "t,r,.", op[0], op[1],
12460                        (int) -imm_expr.X_add_number);
12461           break;
12462         }
12463       goto do_subi_i;
12464     case M_DSUBU_I:
12465       dbl = 1;
12466       s = "daddiu";
12467       s2 = "dsubu";
12468     do_subi:
12469       if (imm_expr.X_add_number > -0x8000
12470           && imm_expr.X_add_number <= 0x8000)
12471         {
12472           imm_expr.X_add_number = -imm_expr.X_add_number;
12473           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12474           break;
12475         }
12476     do_subi_i:
12477       used_at = 1;
12478       load_register (AT, &imm_expr, dbl);
12479       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
12480       break;
12481
12482     case M_TEQ_I:
12483       s = "teq";
12484       goto trap;
12485     case M_TGE_I:
12486       s = "tge";
12487       goto trap;
12488     case M_TGEU_I:
12489       s = "tgeu";
12490       goto trap;
12491     case M_TLT_I:
12492       s = "tlt";
12493       goto trap;
12494     case M_TLTU_I:
12495       s = "tltu";
12496       goto trap;
12497     case M_TNE_I:
12498       s = "tne";
12499     trap:
12500       used_at = 1;
12501       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12502       macro_build (NULL, s, "s,t", op[0], AT);
12503       break;
12504
12505     case M_TRUNCWS:
12506     case M_TRUNCWD:
12507       gas_assert (!mips_opts.micromips);
12508       gas_assert (mips_opts.isa == ISA_MIPS1);
12509       used_at = 1;
12510
12511       /*
12512        * Is the double cfc1 instruction a bug in the mips assembler;
12513        * or is there a reason for it?
12514        */
12515       start_noreorder ();
12516       macro_build (NULL, "cfc1", "t,G", op[2], RA);
12517       macro_build (NULL, "cfc1", "t,G", op[2], RA);
12518       macro_build (NULL, "nop", "");
12519       expr1.X_add_number = 3;
12520       macro_build (&expr1, "ori", "t,r,i", AT, op[2], BFD_RELOC_LO16);
12521       expr1.X_add_number = 2;
12522       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
12523       macro_build (NULL, "ctc1", "t,G", AT, RA);
12524       macro_build (NULL, "nop", "");
12525       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
12526                    op[0], op[1]);
12527       macro_build (NULL, "ctc1", "t,G", op[2], RA);
12528       macro_build (NULL, "nop", "");
12529       end_noreorder ();
12530       break;
12531
12532     case M_ULH_AB:
12533       s = "lb";
12534       s2 = "lbu";
12535       off = 1;
12536       goto uld_st;
12537     case M_ULHU_AB:
12538       s = "lbu";
12539       s2 = "lbu";
12540       off = 1;
12541       goto uld_st;
12542     case M_ULW_AB:
12543       s = "lwl";
12544       s2 = "lwr";
12545       offbits = (mips_opts.micromips ? 12 : 16);
12546       off = 3;
12547       goto uld_st;
12548     case M_ULD_AB:
12549       s = "ldl";
12550       s2 = "ldr";
12551       offbits = (mips_opts.micromips ? 12 : 16);
12552       off = 7;
12553       goto uld_st;
12554     case M_USH_AB:
12555       s = "sb";
12556       s2 = "sb";
12557       off = 1;
12558       ust = 1;
12559       goto uld_st;
12560     case M_USW_AB:
12561       s = "swl";
12562       s2 = "swr";
12563       offbits = (mips_opts.micromips ? 12 : 16);
12564       off = 3;
12565       ust = 1;
12566       goto uld_st;
12567     case M_USD_AB:
12568       s = "sdl";
12569       s2 = "sdr";
12570       offbits = (mips_opts.micromips ? 12 : 16);
12571       off = 7;
12572       ust = 1;
12573
12574     uld_st:
12575       breg = op[2];
12576       large_offset = !small_offset_p (off, align, offbits);
12577       ep = &offset_expr;
12578       expr1.X_add_number = 0;
12579       if (large_offset)
12580         {
12581           used_at = 1;
12582           tempreg = AT;
12583           if (small_offset_p (0, align, 16))
12584             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
12585                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
12586           else
12587             {
12588               load_address (tempreg, ep, &used_at);
12589               if (breg != 0)
12590                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12591                              tempreg, tempreg, breg);
12592             }
12593           offset_reloc[0] = BFD_RELOC_LO16;
12594           offset_reloc[1] = BFD_RELOC_UNUSED;
12595           offset_reloc[2] = BFD_RELOC_UNUSED;
12596           breg = tempreg;
12597           tempreg = op[0];
12598           ep = &expr1;
12599         }
12600       else if (!ust && op[0] == breg)
12601         {
12602           used_at = 1;
12603           tempreg = AT;
12604         }
12605       else
12606         tempreg = op[0];
12607
12608       if (off == 1)
12609         goto ulh_sh;
12610
12611       if (!target_big_endian)
12612         ep->X_add_number += off;
12613       if (offbits == 12)
12614         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
12615       else
12616         macro_build (ep, s, "t,o(b)", tempreg, -1,
12617                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12618
12619       if (!target_big_endian)
12620         ep->X_add_number -= off;
12621       else
12622         ep->X_add_number += off;
12623       if (offbits == 12)
12624         macro_build (NULL, s2, "t,~(b)",
12625                      tempreg, (int) ep->X_add_number, breg);
12626       else
12627         macro_build (ep, s2, "t,o(b)", tempreg, -1,
12628                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12629
12630       /* If necessary, move the result in tempreg to the final destination.  */
12631       if (!ust && op[0] != tempreg)
12632         {
12633           /* Protect second load's delay slot.  */
12634           load_delay_nop ();
12635           move_register (op[0], tempreg);
12636         }
12637       break;
12638
12639     ulh_sh:
12640       used_at = 1;
12641       if (target_big_endian == ust)
12642         ep->X_add_number += off;
12643       tempreg = ust || large_offset ? op[0] : AT;
12644       macro_build (ep, s, "t,o(b)", tempreg, -1,
12645                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12646
12647       /* For halfword transfers we need a temporary register to shuffle
12648          bytes.  Unfortunately for M_USH_A we have none available before
12649          the next store as AT holds the base address.  We deal with this
12650          case by clobbering TREG and then restoring it as with ULH.  */
12651       tempreg = ust == large_offset ? op[0] : AT;
12652       if (ust)
12653         macro_build (NULL, "srl", SHFT_FMT, tempreg, op[0], 8);
12654
12655       if (target_big_endian == ust)
12656         ep->X_add_number -= off;
12657       else
12658         ep->X_add_number += off;
12659       macro_build (ep, s2, "t,o(b)", tempreg, -1,
12660                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12661
12662       /* For M_USH_A re-retrieve the LSB.  */
12663       if (ust && large_offset)
12664         {
12665           if (target_big_endian)
12666             ep->X_add_number += off;
12667           else
12668             ep->X_add_number -= off;
12669           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
12670                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
12671         }
12672       /* For ULH and M_USH_A OR the LSB in.  */
12673       if (!ust || large_offset)
12674         {
12675           tempreg = !large_offset ? AT : op[0];
12676           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
12677           macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12678         }
12679       break;
12680
12681     default:
12682       /* FIXME: Check if this is one of the itbl macros, since they
12683          are added dynamically.  */
12684       as_bad (_("macro %s not implemented yet"), ip->insn_mo->name);
12685       break;
12686     }
12687   if (!mips_opts.at && used_at)
12688     as_bad (_("macro used $at after \".set noat\""));
12689 }
12690
12691 /* Implement macros in mips16 mode.  */
12692
12693 static void
12694 mips16_macro (struct mips_cl_insn *ip)
12695 {
12696   const struct mips_operand_array *operands;
12697   int mask;
12698   int tmp;
12699   expressionS expr1;
12700   int dbl;
12701   const char *s, *s2, *s3;
12702   unsigned int op[MAX_OPERANDS];
12703   unsigned int i;
12704
12705   mask = ip->insn_mo->mask;
12706
12707   operands = insn_operands (ip);
12708   for (i = 0; i < MAX_OPERANDS; i++)
12709     if (operands->operand[i])
12710       op[i] = insn_extract_operand (ip, operands->operand[i]);
12711     else
12712       op[i] = -1;
12713
12714   expr1.X_op = O_constant;
12715   expr1.X_op_symbol = NULL;
12716   expr1.X_add_symbol = NULL;
12717   expr1.X_add_number = 1;
12718
12719   dbl = 0;
12720
12721   switch (mask)
12722     {
12723     default:
12724       abort ();
12725
12726     case M_DDIV_3:
12727       dbl = 1;
12728     case M_DIV_3:
12729       s = "mflo";
12730       goto do_div3;
12731     case M_DREM_3:
12732       dbl = 1;
12733     case M_REM_3:
12734       s = "mfhi";
12735     do_div3:
12736       start_noreorder ();
12737       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", op[1], op[2]);
12738       expr1.X_add_number = 2;
12739       macro_build (&expr1, "bnez", "x,p", op[2]);
12740       macro_build (NULL, "break", "6", 7);
12741
12742       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
12743          since that causes an overflow.  We should do that as well,
12744          but I don't see how to do the comparisons without a temporary
12745          register.  */
12746       end_noreorder ();
12747       macro_build (NULL, s, "x", op[0]);
12748       break;
12749
12750     case M_DIVU_3:
12751       s = "divu";
12752       s2 = "mflo";
12753       goto do_divu3;
12754     case M_REMU_3:
12755       s = "divu";
12756       s2 = "mfhi";
12757       goto do_divu3;
12758     case M_DDIVU_3:
12759       s = "ddivu";
12760       s2 = "mflo";
12761       goto do_divu3;
12762     case M_DREMU_3:
12763       s = "ddivu";
12764       s2 = "mfhi";
12765     do_divu3:
12766       start_noreorder ();
12767       macro_build (NULL, s, "0,x,y", op[1], op[2]);
12768       expr1.X_add_number = 2;
12769       macro_build (&expr1, "bnez", "x,p", op[2]);
12770       macro_build (NULL, "break", "6", 7);
12771       end_noreorder ();
12772       macro_build (NULL, s2, "x", op[0]);
12773       break;
12774
12775     case M_DMUL:
12776       dbl = 1;
12777     case M_MUL:
12778       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", op[1], op[2]);
12779       macro_build (NULL, "mflo", "x", op[0]);
12780       break;
12781
12782     case M_DSUBU_I:
12783       dbl = 1;
12784       goto do_subu;
12785     case M_SUBU_I:
12786     do_subu:
12787       imm_expr.X_add_number = -imm_expr.X_add_number;
12788       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", op[0], op[1]);
12789       break;
12790
12791     case M_SUBU_I_2:
12792       imm_expr.X_add_number = -imm_expr.X_add_number;
12793       macro_build (&imm_expr, "addiu", "x,k", op[0]);
12794       break;
12795
12796     case M_DSUBU_I_2:
12797       imm_expr.X_add_number = -imm_expr.X_add_number;
12798       macro_build (&imm_expr, "daddiu", "y,j", op[0]);
12799       break;
12800
12801     case M_BEQ:
12802       s = "cmp";
12803       s2 = "bteqz";
12804       goto do_branch;
12805     case M_BNE:
12806       s = "cmp";
12807       s2 = "btnez";
12808       goto do_branch;
12809     case M_BLT:
12810       s = "slt";
12811       s2 = "btnez";
12812       goto do_branch;
12813     case M_BLTU:
12814       s = "sltu";
12815       s2 = "btnez";
12816       goto do_branch;
12817     case M_BLE:
12818       s = "slt";
12819       s2 = "bteqz";
12820       goto do_reverse_branch;
12821     case M_BLEU:
12822       s = "sltu";
12823       s2 = "bteqz";
12824       goto do_reverse_branch;
12825     case M_BGE:
12826       s = "slt";
12827       s2 = "bteqz";
12828       goto do_branch;
12829     case M_BGEU:
12830       s = "sltu";
12831       s2 = "bteqz";
12832       goto do_branch;
12833     case M_BGT:
12834       s = "slt";
12835       s2 = "btnez";
12836       goto do_reverse_branch;
12837     case M_BGTU:
12838       s = "sltu";
12839       s2 = "btnez";
12840
12841     do_reverse_branch:
12842       tmp = op[1];
12843       op[1] = op[0];
12844       op[0] = tmp;
12845
12846     do_branch:
12847       macro_build (NULL, s, "x,y", op[0], op[1]);
12848       macro_build (&offset_expr, s2, "p");
12849       break;
12850
12851     case M_BEQ_I:
12852       s = "cmpi";
12853       s2 = "bteqz";
12854       s3 = "x,U";
12855       goto do_branch_i;
12856     case M_BNE_I:
12857       s = "cmpi";
12858       s2 = "btnez";
12859       s3 = "x,U";
12860       goto do_branch_i;
12861     case M_BLT_I:
12862       s = "slti";
12863       s2 = "btnez";
12864       s3 = "x,8";
12865       goto do_branch_i;
12866     case M_BLTU_I:
12867       s = "sltiu";
12868       s2 = "btnez";
12869       s3 = "x,8";
12870       goto do_branch_i;
12871     case M_BLE_I:
12872       s = "slti";
12873       s2 = "btnez";
12874       s3 = "x,8";
12875       goto do_addone_branch_i;
12876     case M_BLEU_I:
12877       s = "sltiu";
12878       s2 = "btnez";
12879       s3 = "x,8";
12880       goto do_addone_branch_i;
12881     case M_BGE_I:
12882       s = "slti";
12883       s2 = "bteqz";
12884       s3 = "x,8";
12885       goto do_branch_i;
12886     case M_BGEU_I:
12887       s = "sltiu";
12888       s2 = "bteqz";
12889       s3 = "x,8";
12890       goto do_branch_i;
12891     case M_BGT_I:
12892       s = "slti";
12893       s2 = "bteqz";
12894       s3 = "x,8";
12895       goto do_addone_branch_i;
12896     case M_BGTU_I:
12897       s = "sltiu";
12898       s2 = "bteqz";
12899       s3 = "x,8";
12900
12901     do_addone_branch_i:
12902       ++imm_expr.X_add_number;
12903
12904     do_branch_i:
12905       macro_build (&imm_expr, s, s3, op[0]);
12906       macro_build (&offset_expr, s2, "p");
12907       break;
12908
12909     case M_ABS:
12910       expr1.X_add_number = 0;
12911       macro_build (&expr1, "slti", "x,8", op[1]);
12912       if (op[0] != op[1])
12913         macro_build (NULL, "move", "y,X", op[0], mips16_to_32_reg_map[op[1]]);
12914       expr1.X_add_number = 2;
12915       macro_build (&expr1, "bteqz", "p");
12916       macro_build (NULL, "neg", "x,w", op[0], op[0]);
12917       break;
12918     }
12919 }
12920
12921 /* Look up instruction [START, START + LENGTH) in HASH.  Record any extra
12922    opcode bits in *OPCODE_EXTRA.  */
12923
12924 static struct mips_opcode *
12925 mips_lookup_insn (struct hash_control *hash, const char *start,
12926                   ssize_t length, unsigned int *opcode_extra)
12927 {
12928   char *name, *dot, *p;
12929   unsigned int mask, suffix;
12930   ssize_t opend;
12931   struct mips_opcode *insn;
12932
12933   /* Make a copy of the instruction so that we can fiddle with it.  */
12934   name = alloca (length + 1);
12935   memcpy (name, start, length);
12936   name[length] = '\0';
12937
12938   /* Look up the instruction as-is.  */
12939   insn = (struct mips_opcode *) hash_find (hash, name);
12940   if (insn)
12941     return insn;
12942
12943   dot = strchr (name, '.');
12944   if (dot && dot[1])
12945     {
12946       /* Try to interpret the text after the dot as a VU0 channel suffix.  */
12947       p = mips_parse_vu0_channels (dot + 1, &mask);
12948       if (*p == 0 && mask != 0)
12949         {
12950           *dot = 0;
12951           insn = (struct mips_opcode *) hash_find (hash, name);
12952           *dot = '.';
12953           if (insn && (insn->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0)
12954             {
12955               *opcode_extra |= mask << mips_vu0_channel_mask.lsb;
12956               return insn;
12957             }
12958         }
12959     }
12960
12961   if (mips_opts.micromips)
12962     {
12963       /* See if there's an instruction size override suffix,
12964          either `16' or `32', at the end of the mnemonic proper,
12965          that defines the operation, i.e. before the first `.'
12966          character if any.  Strip it and retry.  */
12967       opend = dot != NULL ? dot - name : length;
12968       if (opend >= 3 && name[opend - 2] == '1' && name[opend - 1] == '6')
12969         suffix = 2;
12970       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
12971         suffix = 4;
12972       else
12973         suffix = 0;
12974       if (suffix)
12975         {
12976           memcpy (name + opend - 2, name + opend, length - opend + 1);
12977           insn = (struct mips_opcode *) hash_find (hash, name);
12978           if (insn)
12979             {
12980               forced_insn_length = suffix;
12981               return insn;
12982             }
12983         }
12984     }
12985
12986   return NULL;
12987 }
12988
12989 /* Assemble an instruction into its binary format.  If the instruction
12990    is a macro, set imm_expr and offset_expr to the values associated
12991    with "I" and "A" operands respectively.  Otherwise store the value
12992    of the relocatable field (if any) in offset_expr.  In both cases
12993    set offset_reloc to the relocation operators applied to offset_expr.  */
12994
12995 static void
12996 mips_ip (char *str, struct mips_cl_insn *insn)
12997 {
12998   const struct mips_opcode *first, *past;
12999   struct hash_control *hash;
13000   char format;
13001   size_t end;
13002   struct mips_operand_token *tokens;
13003   unsigned int opcode_extra;
13004
13005   if (mips_opts.micromips)
13006     {
13007       hash = micromips_op_hash;
13008       past = &micromips_opcodes[bfd_micromips_num_opcodes];
13009     }
13010   else
13011     {
13012       hash = op_hash;
13013       past = &mips_opcodes[NUMOPCODES];
13014     }
13015   forced_insn_length = 0;
13016   opcode_extra = 0;
13017
13018   /* We first try to match an instruction up to a space or to the end.  */
13019   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
13020     continue;
13021
13022   first = mips_lookup_insn (hash, str, end, &opcode_extra);
13023   if (first == NULL)
13024     {
13025       set_insn_error (0, _("unrecognized opcode"));
13026       return;
13027     }
13028
13029   if (strcmp (first->name, "li.s") == 0)
13030     format = 'f';
13031   else if (strcmp (first->name, "li.d") == 0)
13032     format = 'd';
13033   else
13034     format = 0;
13035   tokens = mips_parse_arguments (str + end, format);
13036   if (!tokens)
13037     return;
13038
13039   if (!match_insns (insn, first, past, tokens, opcode_extra, FALSE)
13040       && !match_insns (insn, first, past, tokens, opcode_extra, TRUE))
13041     set_insn_error (0, _("invalid operands"));
13042
13043   obstack_free (&mips_operand_tokens, tokens);
13044 }
13045
13046 /* As for mips_ip, but used when assembling MIPS16 code.
13047    Also set forced_insn_length to the resulting instruction size in
13048    bytes if the user explicitly requested a small or extended instruction.  */
13049
13050 static void
13051 mips16_ip (char *str, struct mips_cl_insn *insn)
13052 {
13053   char *end, *s, c;
13054   struct mips_opcode *first;
13055   struct mips_operand_token *tokens;
13056
13057   forced_insn_length = 0;
13058
13059   for (s = str; ISLOWER (*s); ++s)
13060     ;
13061   end = s;
13062   c = *end;
13063   switch (c)
13064     {
13065     case '\0':
13066       break;
13067
13068     case ' ':
13069       s++;
13070       break;
13071
13072     case '.':
13073       if (s[1] == 't' && s[2] == ' ')
13074         {
13075           forced_insn_length = 2;
13076           s += 3;
13077           break;
13078         }
13079       else if (s[1] == 'e' && s[2] == ' ')
13080         {
13081           forced_insn_length = 4;
13082           s += 3;
13083           break;
13084         }
13085       /* Fall through.  */
13086     default:
13087       set_insn_error (0, _("unrecognized opcode"));
13088       return;
13089     }
13090
13091   if (mips_opts.noautoextend && !forced_insn_length)
13092     forced_insn_length = 2;
13093
13094   *end = 0;
13095   first = (struct mips_opcode *) hash_find (mips16_op_hash, str);
13096   *end = c;
13097
13098   if (!first)
13099     {
13100       set_insn_error (0, _("unrecognized opcode"));
13101       return;
13102     }
13103
13104   tokens = mips_parse_arguments (s, 0);
13105   if (!tokens)
13106     return;
13107
13108   if (!match_mips16_insns (insn, first, tokens))
13109     set_insn_error (0, _("invalid operands"));
13110
13111   obstack_free (&mips_operand_tokens, tokens);
13112 }
13113
13114 /* Marshal immediate value VAL for an extended MIPS16 instruction.
13115    NBITS is the number of significant bits in VAL.  */
13116
13117 static unsigned long
13118 mips16_immed_extend (offsetT val, unsigned int nbits)
13119 {
13120   int extval;
13121   if (nbits == 16)
13122     {
13123       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
13124       val &= 0x1f;
13125     }
13126   else if (nbits == 15)
13127     {
13128       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
13129       val &= 0xf;
13130     }
13131   else
13132     {
13133       extval = ((val & 0x1f) << 6) | (val & 0x20);
13134       val = 0;
13135     }
13136   return (extval << 16) | val;
13137 }
13138
13139 /* Like decode_mips16_operand, but require the operand to be defined and
13140    require it to be an integer.  */
13141
13142 static const struct mips_int_operand *
13143 mips16_immed_operand (int type, bfd_boolean extended_p)
13144 {
13145   const struct mips_operand *operand;
13146
13147   operand = decode_mips16_operand (type, extended_p);
13148   if (!operand || (operand->type != OP_INT && operand->type != OP_PCREL))
13149     abort ();
13150   return (const struct mips_int_operand *) operand;
13151 }
13152
13153 /* Return true if SVAL fits OPERAND.  RELOC is as for mips16_immed.  */
13154
13155 static bfd_boolean
13156 mips16_immed_in_range_p (const struct mips_int_operand *operand,
13157                          bfd_reloc_code_real_type reloc, offsetT sval)
13158 {
13159   int min_val, max_val;
13160
13161   min_val = mips_int_operand_min (operand);
13162   max_val = mips_int_operand_max (operand);
13163   if (reloc != BFD_RELOC_UNUSED)
13164     {
13165       if (min_val < 0)
13166         sval = SEXT_16BIT (sval);
13167       else
13168         sval &= 0xffff;
13169     }
13170
13171   return (sval >= min_val
13172           && sval <= max_val
13173           && (sval & ((1 << operand->shift) - 1)) == 0);
13174 }
13175
13176 /* Install immediate value VAL into MIPS16 instruction *INSN,
13177    extending it if necessary.  The instruction in *INSN may
13178    already be extended.
13179
13180    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
13181    if none.  In the former case, VAL is a 16-bit number with no
13182    defined signedness.
13183
13184    TYPE is the type of the immediate field.  USER_INSN_LENGTH
13185    is the length that the user requested, or 0 if none.  */
13186
13187 static void
13188 mips16_immed (char *file, unsigned int line, int type,
13189               bfd_reloc_code_real_type reloc, offsetT val,
13190               unsigned int user_insn_length, unsigned long *insn)
13191 {
13192   const struct mips_int_operand *operand;
13193   unsigned int uval, length;
13194
13195   operand = mips16_immed_operand (type, FALSE);
13196   if (!mips16_immed_in_range_p (operand, reloc, val))
13197     {
13198       /* We need an extended instruction.  */
13199       if (user_insn_length == 2)
13200         as_bad_where (file, line, _("invalid unextended operand value"));
13201       else
13202         *insn |= MIPS16_EXTEND;
13203     }
13204   else if (user_insn_length == 4)
13205     {
13206       /* The operand doesn't force an unextended instruction to be extended.
13207          Warn if the user wanted an extended instruction anyway.  */
13208       *insn |= MIPS16_EXTEND;
13209       as_warn_where (file, line,
13210                      _("extended operand requested but not required"));
13211     }
13212
13213   length = mips16_opcode_length (*insn);
13214   if (length == 4)
13215     {
13216       operand = mips16_immed_operand (type, TRUE);
13217       if (!mips16_immed_in_range_p (operand, reloc, val))
13218         as_bad_where (file, line,
13219                       _("operand value out of range for instruction"));
13220     }
13221   uval = ((unsigned int) val >> operand->shift) - operand->bias;
13222   if (length == 2)
13223     *insn = mips_insert_operand (&operand->root, *insn, uval);
13224   else
13225     *insn |= mips16_immed_extend (uval, operand->root.size);
13226 }
13227 \f
13228 struct percent_op_match
13229 {
13230   const char *str;
13231   bfd_reloc_code_real_type reloc;
13232 };
13233
13234 static const struct percent_op_match mips_percent_op[] =
13235 {
13236   {"%lo", BFD_RELOC_LO16},
13237   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
13238   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
13239   {"%call16", BFD_RELOC_MIPS_CALL16},
13240   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
13241   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
13242   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
13243   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
13244   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
13245   {"%got", BFD_RELOC_MIPS_GOT16},
13246   {"%gp_rel", BFD_RELOC_GPREL16},
13247   {"%half", BFD_RELOC_16},
13248   {"%highest", BFD_RELOC_MIPS_HIGHEST},
13249   {"%higher", BFD_RELOC_MIPS_HIGHER},
13250   {"%neg", BFD_RELOC_MIPS_SUB},
13251   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
13252   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
13253   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
13254   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
13255   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
13256   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
13257   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
13258   {"%hi", BFD_RELOC_HI16_S}
13259 };
13260
13261 static const struct percent_op_match mips16_percent_op[] =
13262 {
13263   {"%lo", BFD_RELOC_MIPS16_LO16},
13264   {"%gprel", BFD_RELOC_MIPS16_GPREL},
13265   {"%got", BFD_RELOC_MIPS16_GOT16},
13266   {"%call16", BFD_RELOC_MIPS16_CALL16},
13267   {"%hi", BFD_RELOC_MIPS16_HI16_S},
13268   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
13269   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
13270   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
13271   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
13272   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
13273   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
13274   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
13275 };
13276
13277
13278 /* Return true if *STR points to a relocation operator.  When returning true,
13279    move *STR over the operator and store its relocation code in *RELOC.
13280    Leave both *STR and *RELOC alone when returning false.  */
13281
13282 static bfd_boolean
13283 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
13284 {
13285   const struct percent_op_match *percent_op;
13286   size_t limit, i;
13287
13288   if (mips_opts.mips16)
13289     {
13290       percent_op = mips16_percent_op;
13291       limit = ARRAY_SIZE (mips16_percent_op);
13292     }
13293   else
13294     {
13295       percent_op = mips_percent_op;
13296       limit = ARRAY_SIZE (mips_percent_op);
13297     }
13298
13299   for (i = 0; i < limit; i++)
13300     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
13301       {
13302         int len = strlen (percent_op[i].str);
13303
13304         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
13305           continue;
13306
13307         *str += strlen (percent_op[i].str);
13308         *reloc = percent_op[i].reloc;
13309
13310         /* Check whether the output BFD supports this relocation.
13311            If not, issue an error and fall back on something safe.  */
13312         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
13313           {
13314             as_bad (_("relocation %s isn't supported by the current ABI"),
13315                     percent_op[i].str);
13316             *reloc = BFD_RELOC_UNUSED;
13317           }
13318         return TRUE;
13319       }
13320   return FALSE;
13321 }
13322
13323
13324 /* Parse string STR as a 16-bit relocatable operand.  Store the
13325    expression in *EP and the relocations in the array starting
13326    at RELOC.  Return the number of relocation operators used.
13327
13328    On exit, EXPR_END points to the first character after the expression.  */
13329
13330 static size_t
13331 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
13332                        char *str)
13333 {
13334   bfd_reloc_code_real_type reversed_reloc[3];
13335   size_t reloc_index, i;
13336   int crux_depth, str_depth;
13337   char *crux;
13338
13339   /* Search for the start of the main expression, recoding relocations
13340      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
13341      of the main expression and with CRUX_DEPTH containing the number
13342      of open brackets at that point.  */
13343   reloc_index = -1;
13344   str_depth = 0;
13345   do
13346     {
13347       reloc_index++;
13348       crux = str;
13349       crux_depth = str_depth;
13350
13351       /* Skip over whitespace and brackets, keeping count of the number
13352          of brackets.  */
13353       while (*str == ' ' || *str == '\t' || *str == '(')
13354         if (*str++ == '(')
13355           str_depth++;
13356     }
13357   while (*str == '%'
13358          && reloc_index < (HAVE_NEWABI ? 3 : 1)
13359          && parse_relocation (&str, &reversed_reloc[reloc_index]));
13360
13361   my_getExpression (ep, crux);
13362   str = expr_end;
13363
13364   /* Match every open bracket.  */
13365   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
13366     if (*str++ == ')')
13367       crux_depth--;
13368
13369   if (crux_depth > 0)
13370     as_bad (_("unclosed '('"));
13371
13372   expr_end = str;
13373
13374   if (reloc_index != 0)
13375     {
13376       prev_reloc_op_frag = frag_now;
13377       for (i = 0; i < reloc_index; i++)
13378         reloc[i] = reversed_reloc[reloc_index - 1 - i];
13379     }
13380
13381   return reloc_index;
13382 }
13383
13384 static void
13385 my_getExpression (expressionS *ep, char *str)
13386 {
13387   char *save_in;
13388
13389   save_in = input_line_pointer;
13390   input_line_pointer = str;
13391   expression (ep);
13392   expr_end = input_line_pointer;
13393   input_line_pointer = save_in;
13394 }
13395
13396 char *
13397 md_atof (int type, char *litP, int *sizeP)
13398 {
13399   return ieee_md_atof (type, litP, sizeP, target_big_endian);
13400 }
13401
13402 void
13403 md_number_to_chars (char *buf, valueT val, int n)
13404 {
13405   if (target_big_endian)
13406     number_to_chars_bigendian (buf, val, n);
13407   else
13408     number_to_chars_littleendian (buf, val, n);
13409 }
13410 \f
13411 static int support_64bit_objects(void)
13412 {
13413   const char **list, **l;
13414   int yes;
13415
13416   list = bfd_target_list ();
13417   for (l = list; *l != NULL; l++)
13418     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
13419         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
13420       break;
13421   yes = (*l != NULL);
13422   free (list);
13423   return yes;
13424 }
13425
13426 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
13427    NEW_VALUE.  Warn if another value was already specified.  Note:
13428    we have to defer parsing the -march and -mtune arguments in order
13429    to handle 'from-abi' correctly, since the ABI might be specified
13430    in a later argument.  */
13431
13432 static void
13433 mips_set_option_string (const char **string_ptr, const char *new_value)
13434 {
13435   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
13436     as_warn (_("a different %s was already specified, is now %s"),
13437              string_ptr == &mips_arch_string ? "-march" : "-mtune",
13438              new_value);
13439
13440   *string_ptr = new_value;
13441 }
13442
13443 int
13444 md_parse_option (int c, char *arg)
13445 {
13446   unsigned int i;
13447
13448   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
13449     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
13450       {
13451         file_ase_explicit |= mips_set_ase (&mips_ases[i],
13452                                            c == mips_ases[i].option_on);
13453         return 1;
13454       }
13455
13456   switch (c)
13457     {
13458     case OPTION_CONSTRUCT_FLOATS:
13459       mips_disable_float_construction = 0;
13460       break;
13461
13462     case OPTION_NO_CONSTRUCT_FLOATS:
13463       mips_disable_float_construction = 1;
13464       break;
13465
13466     case OPTION_TRAP:
13467       mips_trap = 1;
13468       break;
13469
13470     case OPTION_BREAK:
13471       mips_trap = 0;
13472       break;
13473
13474     case OPTION_EB:
13475       target_big_endian = 1;
13476       break;
13477
13478     case OPTION_EL:
13479       target_big_endian = 0;
13480       break;
13481
13482     case 'O':
13483       if (arg == NULL)
13484         mips_optimize = 1;
13485       else if (arg[0] == '0')
13486         mips_optimize = 0;
13487       else if (arg[0] == '1')
13488         mips_optimize = 1;
13489       else
13490         mips_optimize = 2;
13491       break;
13492
13493     case 'g':
13494       if (arg == NULL)
13495         mips_debug = 2;
13496       else
13497         mips_debug = atoi (arg);
13498       break;
13499
13500     case OPTION_MIPS1:
13501       file_mips_isa = ISA_MIPS1;
13502       break;
13503
13504     case OPTION_MIPS2:
13505       file_mips_isa = ISA_MIPS2;
13506       break;
13507
13508     case OPTION_MIPS3:
13509       file_mips_isa = ISA_MIPS3;
13510       break;
13511
13512     case OPTION_MIPS4:
13513       file_mips_isa = ISA_MIPS4;
13514       break;
13515
13516     case OPTION_MIPS5:
13517       file_mips_isa = ISA_MIPS5;
13518       break;
13519
13520     case OPTION_MIPS32:
13521       file_mips_isa = ISA_MIPS32;
13522       break;
13523
13524     case OPTION_MIPS32R2:
13525       file_mips_isa = ISA_MIPS32R2;
13526       break;
13527
13528     case OPTION_MIPS64R2:
13529       file_mips_isa = ISA_MIPS64R2;
13530       break;
13531
13532     case OPTION_MIPS64:
13533       file_mips_isa = ISA_MIPS64;
13534       break;
13535
13536     case OPTION_MTUNE:
13537       mips_set_option_string (&mips_tune_string, arg);
13538       break;
13539
13540     case OPTION_MARCH:
13541       mips_set_option_string (&mips_arch_string, arg);
13542       break;
13543
13544     case OPTION_M4650:
13545       mips_set_option_string (&mips_arch_string, "4650");
13546       mips_set_option_string (&mips_tune_string, "4650");
13547       break;
13548
13549     case OPTION_NO_M4650:
13550       break;
13551
13552     case OPTION_M4010:
13553       mips_set_option_string (&mips_arch_string, "4010");
13554       mips_set_option_string (&mips_tune_string, "4010");
13555       break;
13556
13557     case OPTION_NO_M4010:
13558       break;
13559
13560     case OPTION_M4100:
13561       mips_set_option_string (&mips_arch_string, "4100");
13562       mips_set_option_string (&mips_tune_string, "4100");
13563       break;
13564
13565     case OPTION_NO_M4100:
13566       break;
13567
13568     case OPTION_M3900:
13569       mips_set_option_string (&mips_arch_string, "3900");
13570       mips_set_option_string (&mips_tune_string, "3900");
13571       break;
13572
13573     case OPTION_NO_M3900:
13574       break;
13575
13576     case OPTION_MICROMIPS:
13577       if (mips_opts.mips16 == 1)
13578         {
13579           as_bad (_("-mmicromips cannot be used with -mips16"));
13580           return 0;
13581         }
13582       mips_opts.micromips = 1;
13583       mips_no_prev_insn ();
13584       break;
13585
13586     case OPTION_NO_MICROMIPS:
13587       mips_opts.micromips = 0;
13588       mips_no_prev_insn ();
13589       break;
13590
13591     case OPTION_MIPS16:
13592       if (mips_opts.micromips == 1)
13593         {
13594           as_bad (_("-mips16 cannot be used with -micromips"));
13595           return 0;
13596         }
13597       mips_opts.mips16 = 1;
13598       mips_no_prev_insn ();
13599       break;
13600
13601     case OPTION_NO_MIPS16:
13602       mips_opts.mips16 = 0;
13603       mips_no_prev_insn ();
13604       break;
13605
13606     case OPTION_FIX_24K:
13607       mips_fix_24k = 1;
13608       break;
13609
13610     case OPTION_NO_FIX_24K:
13611       mips_fix_24k = 0;
13612       break;
13613
13614     case OPTION_FIX_RM7000:
13615       mips_fix_rm7000 = 1;
13616       break;
13617
13618     case OPTION_NO_FIX_RM7000:
13619       mips_fix_rm7000 = 0;
13620       break;
13621
13622     case OPTION_FIX_LOONGSON2F_JUMP:
13623       mips_fix_loongson2f_jump = TRUE;
13624       break;
13625
13626     case OPTION_NO_FIX_LOONGSON2F_JUMP:
13627       mips_fix_loongson2f_jump = FALSE;
13628       break;
13629
13630     case OPTION_FIX_LOONGSON2F_NOP:
13631       mips_fix_loongson2f_nop = TRUE;
13632       break;
13633
13634     case OPTION_NO_FIX_LOONGSON2F_NOP:
13635       mips_fix_loongson2f_nop = FALSE;
13636       break;
13637
13638     case OPTION_FIX_VR4120:
13639       mips_fix_vr4120 = 1;
13640       break;
13641
13642     case OPTION_NO_FIX_VR4120:
13643       mips_fix_vr4120 = 0;
13644       break;
13645
13646     case OPTION_FIX_VR4130:
13647       mips_fix_vr4130 = 1;
13648       break;
13649
13650     case OPTION_NO_FIX_VR4130:
13651       mips_fix_vr4130 = 0;
13652       break;
13653
13654     case OPTION_FIX_CN63XXP1:
13655       mips_fix_cn63xxp1 = TRUE;
13656       break;
13657
13658     case OPTION_NO_FIX_CN63XXP1:
13659       mips_fix_cn63xxp1 = FALSE;
13660       break;
13661
13662     case OPTION_RELAX_BRANCH:
13663       mips_relax_branch = 1;
13664       break;
13665
13666     case OPTION_NO_RELAX_BRANCH:
13667       mips_relax_branch = 0;
13668       break;
13669
13670     case OPTION_INSN32:
13671       mips_opts.insn32 = TRUE;
13672       break;
13673
13674     case OPTION_NO_INSN32:
13675       mips_opts.insn32 = FALSE;
13676       break;
13677
13678     case OPTION_MSHARED:
13679       mips_in_shared = TRUE;
13680       break;
13681
13682     case OPTION_MNO_SHARED:
13683       mips_in_shared = FALSE;
13684       break;
13685
13686     case OPTION_MSYM32:
13687       mips_opts.sym32 = TRUE;
13688       break;
13689
13690     case OPTION_MNO_SYM32:
13691       mips_opts.sym32 = FALSE;
13692       break;
13693
13694       /* When generating ELF code, we permit -KPIC and -call_shared to
13695          select SVR4_PIC, and -non_shared to select no PIC.  This is
13696          intended to be compatible with Irix 5.  */
13697     case OPTION_CALL_SHARED:
13698       mips_pic = SVR4_PIC;
13699       mips_abicalls = TRUE;
13700       break;
13701
13702     case OPTION_CALL_NONPIC:
13703       mips_pic = NO_PIC;
13704       mips_abicalls = TRUE;
13705       break;
13706
13707     case OPTION_NON_SHARED:
13708       mips_pic = NO_PIC;
13709       mips_abicalls = FALSE;
13710       break;
13711
13712       /* The -xgot option tells the assembler to use 32 bit offsets
13713          when accessing the got in SVR4_PIC mode.  It is for Irix
13714          compatibility.  */
13715     case OPTION_XGOT:
13716       mips_big_got = 1;
13717       break;
13718
13719     case 'G':
13720       g_switch_value = atoi (arg);
13721       g_switch_seen = 1;
13722       break;
13723
13724       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
13725          and -mabi=64.  */
13726     case OPTION_32:
13727       mips_abi = O32_ABI;
13728       break;
13729
13730     case OPTION_N32:
13731       mips_abi = N32_ABI;
13732       break;
13733
13734     case OPTION_64:
13735       mips_abi = N64_ABI;
13736       if (!support_64bit_objects())
13737         as_fatal (_("no compiled in support for 64 bit object file format"));
13738       break;
13739
13740     case OPTION_GP32:
13741       file_mips_gp32 = 1;
13742       break;
13743
13744     case OPTION_GP64:
13745       file_mips_gp32 = 0;
13746       break;
13747
13748     case OPTION_FP32:
13749       file_mips_fp32 = 1;
13750       break;
13751
13752     case OPTION_FP64:
13753       file_mips_fp32 = 0;
13754       break;
13755
13756     case OPTION_SINGLE_FLOAT:
13757       file_mips_single_float = 1;
13758       break;
13759
13760     case OPTION_DOUBLE_FLOAT:
13761       file_mips_single_float = 0;
13762       break;
13763
13764     case OPTION_SOFT_FLOAT:
13765       file_mips_soft_float = 1;
13766       break;
13767
13768     case OPTION_HARD_FLOAT:
13769       file_mips_soft_float = 0;
13770       break;
13771
13772     case OPTION_MABI:
13773       if (strcmp (arg, "32") == 0)
13774         mips_abi = O32_ABI;
13775       else if (strcmp (arg, "o64") == 0)
13776         mips_abi = O64_ABI;
13777       else if (strcmp (arg, "n32") == 0)
13778         mips_abi = N32_ABI;
13779       else if (strcmp (arg, "64") == 0)
13780         {
13781           mips_abi = N64_ABI;
13782           if (! support_64bit_objects())
13783             as_fatal (_("no compiled in support for 64 bit object file "
13784                         "format"));
13785         }
13786       else if (strcmp (arg, "eabi") == 0)
13787         mips_abi = EABI_ABI;
13788       else
13789         {
13790           as_fatal (_("invalid abi -mabi=%s"), arg);
13791           return 0;
13792         }
13793       break;
13794
13795     case OPTION_M7000_HILO_FIX:
13796       mips_7000_hilo_fix = TRUE;
13797       break;
13798
13799     case OPTION_MNO_7000_HILO_FIX:
13800       mips_7000_hilo_fix = FALSE;
13801       break;
13802
13803     case OPTION_MDEBUG:
13804       mips_flag_mdebug = TRUE;
13805       break;
13806
13807     case OPTION_NO_MDEBUG:
13808       mips_flag_mdebug = FALSE;
13809       break;
13810
13811     case OPTION_PDR:
13812       mips_flag_pdr = TRUE;
13813       break;
13814
13815     case OPTION_NO_PDR:
13816       mips_flag_pdr = FALSE;
13817       break;
13818
13819     case OPTION_MVXWORKS_PIC:
13820       mips_pic = VXWORKS_PIC;
13821       break;
13822
13823     case OPTION_NAN:
13824       if (strcmp (arg, "2008") == 0)
13825         mips_flag_nan2008 = TRUE;
13826       else if (strcmp (arg, "legacy") == 0)
13827         mips_flag_nan2008 = FALSE;
13828       else
13829         {
13830           as_fatal (_("invalid NaN setting -mnan=%s"), arg);
13831           return 0;
13832         }
13833       break;
13834
13835     default:
13836       return 0;
13837     }
13838
13839     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
13840
13841   return 1;
13842 }
13843 \f
13844 /* Set up globals to generate code for the ISA or processor
13845    described by INFO.  */
13846
13847 static void
13848 mips_set_architecture (const struct mips_cpu_info *info)
13849 {
13850   if (info != 0)
13851     {
13852       file_mips_arch = info->cpu;
13853       mips_opts.arch = info->cpu;
13854       mips_opts.isa = info->isa;
13855     }
13856 }
13857
13858
13859 /* Likewise for tuning.  */
13860
13861 static void
13862 mips_set_tune (const struct mips_cpu_info *info)
13863 {
13864   if (info != 0)
13865     mips_tune = info->cpu;
13866 }
13867
13868
13869 void
13870 mips_after_parse_args (void)
13871 {
13872   const struct mips_cpu_info *arch_info = 0;
13873   const struct mips_cpu_info *tune_info = 0;
13874
13875   /* GP relative stuff not working for PE */
13876   if (strncmp (TARGET_OS, "pe", 2) == 0)
13877     {
13878       if (g_switch_seen && g_switch_value != 0)
13879         as_bad (_("-G not supported in this configuration"));
13880       g_switch_value = 0;
13881     }
13882
13883   if (mips_abi == NO_ABI)
13884     mips_abi = MIPS_DEFAULT_ABI;
13885
13886   /* The following code determines the architecture and register size.
13887      Similar code was added to GCC 3.3 (see override_options() in
13888      config/mips/mips.c).  The GAS and GCC code should be kept in sync
13889      as much as possible.  */
13890
13891   if (mips_arch_string != 0)
13892     arch_info = mips_parse_cpu ("-march", mips_arch_string);
13893
13894   if (file_mips_isa != ISA_UNKNOWN)
13895     {
13896       /* Handle -mipsN.  At this point, file_mips_isa contains the
13897          ISA level specified by -mipsN, while arch_info->isa contains
13898          the -march selection (if any).  */
13899       if (arch_info != 0)
13900         {
13901           /* -march takes precedence over -mipsN, since it is more descriptive.
13902              There's no harm in specifying both as long as the ISA levels
13903              are the same.  */
13904           if (file_mips_isa != arch_info->isa)
13905             as_bad (_("-%s conflicts with the other architecture options,"
13906                       " which imply -%s"),
13907                     mips_cpu_info_from_isa (file_mips_isa)->name,
13908                     mips_cpu_info_from_isa (arch_info->isa)->name);
13909         }
13910       else
13911         arch_info = mips_cpu_info_from_isa (file_mips_isa);
13912     }
13913
13914   if (arch_info == 0)
13915     {
13916       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
13917       gas_assert (arch_info);
13918     }
13919
13920   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
13921     as_bad (_("-march=%s is not compatible with the selected ABI"),
13922             arch_info->name);
13923
13924   mips_set_architecture (arch_info);
13925
13926   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
13927   if (mips_tune_string != 0)
13928     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
13929
13930   if (tune_info == 0)
13931     mips_set_tune (arch_info);
13932   else
13933     mips_set_tune (tune_info);
13934
13935   if (file_mips_gp32 >= 0)
13936     {
13937       /* The user specified the size of the integer registers.  Make sure
13938          it agrees with the ABI and ISA.  */
13939       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
13940         as_bad (_("-mgp64 used with a 32-bit processor"));
13941       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
13942         as_bad (_("-mgp32 used with a 64-bit ABI"));
13943       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
13944         as_bad (_("-mgp64 used with a 32-bit ABI"));
13945     }
13946   else
13947     {
13948       /* Infer the integer register size from the ABI and processor.
13949          Restrict ourselves to 32-bit registers if that's all the
13950          processor has, or if the ABI cannot handle 64-bit registers.  */
13951       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
13952                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
13953     }
13954
13955   switch (file_mips_fp32)
13956     {
13957     default:
13958     case -1:
13959       /* No user specified float register size.
13960          ??? GAS treats single-float processors as though they had 64-bit
13961          float registers (although it complains when double-precision
13962          instructions are used).  As things stand, saying they have 32-bit
13963          registers would lead to spurious "register must be even" messages.
13964          So here we assume float registers are never smaller than the
13965          integer ones.  */
13966       if (file_mips_gp32 == 0)
13967         /* 64-bit integer registers implies 64-bit float registers.  */
13968         file_mips_fp32 = 0;
13969       else if ((mips_opts.ase & FP64_ASES)
13970                && ISA_HAS_64BIT_FPRS (mips_opts.isa))
13971         /* -mips3d and -mdmx imply 64-bit float registers, if possible.  */
13972         file_mips_fp32 = 0;
13973       else
13974         /* 32-bit float registers.  */
13975         file_mips_fp32 = 1;
13976       break;
13977
13978     /* The user specified the size of the float registers.  Check if it
13979        agrees with the ABI and ISA.  */
13980     case 0:
13981       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
13982         as_bad (_("-mfp64 used with a 32-bit fpu"));
13983       else if (ABI_NEEDS_32BIT_REGS (mips_abi)
13984                && !ISA_HAS_MXHC1 (mips_opts.isa))
13985         as_warn (_("-mfp64 used with a 32-bit ABI"));
13986       break;
13987     case 1:
13988       if (ABI_NEEDS_64BIT_REGS (mips_abi))
13989         as_warn (_("-mfp32 used with a 64-bit ABI"));
13990       break;
13991     }
13992
13993   /* End of GCC-shared inference code.  */
13994
13995   /* This flag is set when we have a 64-bit capable CPU but use only
13996      32-bit wide registers.  Note that EABI does not use it.  */
13997   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
13998       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
13999           || mips_abi == O32_ABI))
14000     mips_32bitmode = 1;
14001
14002   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
14003     as_bad (_("trap exception not supported at ISA 1"));
14004
14005   /* If the selected architecture includes support for ASEs, enable
14006      generation of code for them.  */
14007   if (mips_opts.mips16 == -1)
14008     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
14009   if (mips_opts.micromips == -1)
14010     mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_arch)) ? 1 : 0;
14011
14012   /* MIPS3D and MDMX require 64-bit FPRs, so -mfp32 should stop those
14013      ASEs from being selected implicitly.  */
14014   if (file_mips_fp32 == 1)
14015     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX;
14016
14017   /* If the user didn't explicitly select or deselect a particular ASE,
14018      use the default setting for the CPU.  */
14019   mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
14020
14021   file_mips_isa = mips_opts.isa;
14022   file_ase = mips_opts.ase;
14023   mips_opts.gp32 = file_mips_gp32;
14024   mips_opts.fp32 = file_mips_fp32;
14025   mips_opts.soft_float = file_mips_soft_float;
14026   mips_opts.single_float = file_mips_single_float;
14027
14028   mips_check_isa_supports_ases ();
14029
14030   if (mips_flag_mdebug < 0)
14031     mips_flag_mdebug = 0;
14032 }
14033 \f
14034 void
14035 mips_init_after_args (void)
14036 {
14037   /* initialize opcodes */
14038   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
14039   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
14040 }
14041
14042 long
14043 md_pcrel_from (fixS *fixP)
14044 {
14045   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
14046   switch (fixP->fx_r_type)
14047     {
14048     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14049     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14050       /* Return the address of the delay slot.  */
14051       return addr + 2;
14052
14053     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14054     case BFD_RELOC_MICROMIPS_JMP:
14055     case BFD_RELOC_16_PCREL_S2:
14056     case BFD_RELOC_MIPS_JMP:
14057       /* Return the address of the delay slot.  */
14058       return addr + 4;
14059
14060     default:
14061       return addr;
14062     }
14063 }
14064
14065 /* This is called before the symbol table is processed.  In order to
14066    work with gcc when using mips-tfile, we must keep all local labels.
14067    However, in other cases, we want to discard them.  If we were
14068    called with -g, but we didn't see any debugging information, it may
14069    mean that gcc is smuggling debugging information through to
14070    mips-tfile, in which case we must generate all local labels.  */
14071
14072 void
14073 mips_frob_file_before_adjust (void)
14074 {
14075 #ifndef NO_ECOFF_DEBUGGING
14076   if (ECOFF_DEBUGGING
14077       && mips_debug != 0
14078       && ! ecoff_debugging_seen)
14079     flag_keep_locals = 1;
14080 #endif
14081 }
14082
14083 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
14084    the corresponding LO16 reloc.  This is called before md_apply_fix and
14085    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
14086    relocation operators.
14087
14088    For our purposes, a %lo() expression matches a %got() or %hi()
14089    expression if:
14090
14091       (a) it refers to the same symbol; and
14092       (b) the offset applied in the %lo() expression is no lower than
14093           the offset applied in the %got() or %hi().
14094
14095    (b) allows us to cope with code like:
14096
14097         lui     $4,%hi(foo)
14098         lh      $4,%lo(foo+2)($4)
14099
14100    ...which is legal on RELA targets, and has a well-defined behaviour
14101    if the user knows that adding 2 to "foo" will not induce a carry to
14102    the high 16 bits.
14103
14104    When several %lo()s match a particular %got() or %hi(), we use the
14105    following rules to distinguish them:
14106
14107      (1) %lo()s with smaller offsets are a better match than %lo()s with
14108          higher offsets.
14109
14110      (2) %lo()s with no matching %got() or %hi() are better than those
14111          that already have a matching %got() or %hi().
14112
14113      (3) later %lo()s are better than earlier %lo()s.
14114
14115    These rules are applied in order.
14116
14117    (1) means, among other things, that %lo()s with identical offsets are
14118    chosen if they exist.
14119
14120    (2) means that we won't associate several high-part relocations with
14121    the same low-part relocation unless there's no alternative.  Having
14122    several high parts for the same low part is a GNU extension; this rule
14123    allows careful users to avoid it.
14124
14125    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
14126    with the last high-part relocation being at the front of the list.
14127    It therefore makes sense to choose the last matching low-part
14128    relocation, all other things being equal.  It's also easier
14129    to code that way.  */
14130
14131 void
14132 mips_frob_file (void)
14133 {
14134   struct mips_hi_fixup *l;
14135   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
14136
14137   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
14138     {
14139       segment_info_type *seginfo;
14140       bfd_boolean matched_lo_p;
14141       fixS **hi_pos, **lo_pos, **pos;
14142
14143       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
14144
14145       /* If a GOT16 relocation turns out to be against a global symbol,
14146          there isn't supposed to be a matching LO.  Ignore %gots against
14147          constants; we'll report an error for those later.  */
14148       if (got16_reloc_p (l->fixp->fx_r_type)
14149           && !(l->fixp->fx_addsy
14150                && pic_need_relax (l->fixp->fx_addsy, l->seg)))
14151         continue;
14152
14153       /* Check quickly whether the next fixup happens to be a matching %lo.  */
14154       if (fixup_has_matching_lo_p (l->fixp))
14155         continue;
14156
14157       seginfo = seg_info (l->seg);
14158
14159       /* Set HI_POS to the position of this relocation in the chain.
14160          Set LO_POS to the position of the chosen low-part relocation.
14161          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
14162          relocation that matches an immediately-preceding high-part
14163          relocation.  */
14164       hi_pos = NULL;
14165       lo_pos = NULL;
14166       matched_lo_p = FALSE;
14167       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
14168
14169       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
14170         {
14171           if (*pos == l->fixp)
14172             hi_pos = pos;
14173
14174           if ((*pos)->fx_r_type == looking_for_rtype
14175               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
14176               && (*pos)->fx_offset >= l->fixp->fx_offset
14177               && (lo_pos == NULL
14178                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
14179                   || (!matched_lo_p
14180                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
14181             lo_pos = pos;
14182
14183           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
14184                           && fixup_has_matching_lo_p (*pos));
14185         }
14186
14187       /* If we found a match, remove the high-part relocation from its
14188          current position and insert it before the low-part relocation.
14189          Make the offsets match so that fixup_has_matching_lo_p()
14190          will return true.
14191
14192          We don't warn about unmatched high-part relocations since some
14193          versions of gcc have been known to emit dead "lui ...%hi(...)"
14194          instructions.  */
14195       if (lo_pos != NULL)
14196         {
14197           l->fixp->fx_offset = (*lo_pos)->fx_offset;
14198           if (l->fixp->fx_next != *lo_pos)
14199             {
14200               *hi_pos = l->fixp->fx_next;
14201               l->fixp->fx_next = *lo_pos;
14202               *lo_pos = l->fixp;
14203             }
14204         }
14205     }
14206 }
14207
14208 int
14209 mips_force_relocation (fixS *fixp)
14210 {
14211   if (generic_force_reloc (fixp))
14212     return 1;
14213
14214   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
14215      so that the linker relaxation can update targets.  */
14216   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
14217       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
14218       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
14219     return 1;
14220
14221   return 0;
14222 }
14223
14224 /* Read the instruction associated with RELOC from BUF.  */
14225
14226 static unsigned int
14227 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
14228 {
14229   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14230     return read_compressed_insn (buf, 4);
14231   else
14232     return read_insn (buf);
14233 }
14234
14235 /* Write instruction INSN to BUF, given that it has been relocated
14236    by RELOC.  */
14237
14238 static void
14239 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
14240                   unsigned long insn)
14241 {
14242   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14243     write_compressed_insn (buf, insn, 4);
14244   else
14245     write_insn (buf, insn);
14246 }
14247
14248 /* Apply a fixup to the object file.  */
14249
14250 void
14251 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
14252 {
14253   char *buf;
14254   unsigned long insn;
14255   reloc_howto_type *howto;
14256
14257   if (fixP->fx_pcrel)
14258     switch (fixP->fx_r_type)
14259       {
14260       case BFD_RELOC_16_PCREL_S2:
14261       case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14262       case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14263       case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14264       case BFD_RELOC_32_PCREL:
14265         break;
14266
14267       case BFD_RELOC_32:
14268         fixP->fx_r_type = BFD_RELOC_32_PCREL;
14269         break;
14270
14271       default:
14272         as_bad_where (fixP->fx_file, fixP->fx_line,
14273                       _("PC-relative reference to a different section"));
14274         break;
14275       }
14276
14277   /* Handle BFD_RELOC_8, since it's easy.  Punt on other bfd relocations
14278      that have no MIPS ELF equivalent.  */
14279   if (fixP->fx_r_type != BFD_RELOC_8)
14280     {
14281       howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
14282       if (!howto)
14283         return;
14284     }
14285
14286   gas_assert (fixP->fx_size == 2
14287               || fixP->fx_size == 4
14288               || fixP->fx_r_type == BFD_RELOC_8
14289               || fixP->fx_r_type == BFD_RELOC_16
14290               || fixP->fx_r_type == BFD_RELOC_64
14291               || fixP->fx_r_type == BFD_RELOC_CTOR
14292               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
14293               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
14294               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
14295               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
14296               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
14297
14298   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
14299
14300   /* Don't treat parts of a composite relocation as done.  There are two
14301      reasons for this:
14302
14303      (1) The second and third parts will be against 0 (RSS_UNDEF) but
14304          should nevertheless be emitted if the first part is.
14305
14306      (2) In normal usage, composite relocations are never assembly-time
14307          constants.  The easiest way of dealing with the pathological
14308          exceptions is to generate a relocation against STN_UNDEF and
14309          leave everything up to the linker.  */
14310   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
14311     fixP->fx_done = 1;
14312
14313   switch (fixP->fx_r_type)
14314     {
14315     case BFD_RELOC_MIPS_TLS_GD:
14316     case BFD_RELOC_MIPS_TLS_LDM:
14317     case BFD_RELOC_MIPS_TLS_DTPREL32:
14318     case BFD_RELOC_MIPS_TLS_DTPREL64:
14319     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
14320     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
14321     case BFD_RELOC_MIPS_TLS_GOTTPREL:
14322     case BFD_RELOC_MIPS_TLS_TPREL32:
14323     case BFD_RELOC_MIPS_TLS_TPREL64:
14324     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
14325     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
14326     case BFD_RELOC_MICROMIPS_TLS_GD:
14327     case BFD_RELOC_MICROMIPS_TLS_LDM:
14328     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
14329     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
14330     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
14331     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
14332     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
14333     case BFD_RELOC_MIPS16_TLS_GD:
14334     case BFD_RELOC_MIPS16_TLS_LDM:
14335     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
14336     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
14337     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
14338     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
14339     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
14340       if (!fixP->fx_addsy)
14341         {
14342           as_bad_where (fixP->fx_file, fixP->fx_line,
14343                         _("TLS relocation against a constant"));
14344           break;
14345         }
14346       S_SET_THREAD_LOCAL (fixP->fx_addsy);
14347       /* fall through */
14348
14349     case BFD_RELOC_MIPS_JMP:
14350     case BFD_RELOC_MIPS_SHIFT5:
14351     case BFD_RELOC_MIPS_SHIFT6:
14352     case BFD_RELOC_MIPS_GOT_DISP:
14353     case BFD_RELOC_MIPS_GOT_PAGE:
14354     case BFD_RELOC_MIPS_GOT_OFST:
14355     case BFD_RELOC_MIPS_SUB:
14356     case BFD_RELOC_MIPS_INSERT_A:
14357     case BFD_RELOC_MIPS_INSERT_B:
14358     case BFD_RELOC_MIPS_DELETE:
14359     case BFD_RELOC_MIPS_HIGHEST:
14360     case BFD_RELOC_MIPS_HIGHER:
14361     case BFD_RELOC_MIPS_SCN_DISP:
14362     case BFD_RELOC_MIPS_REL16:
14363     case BFD_RELOC_MIPS_RELGOT:
14364     case BFD_RELOC_MIPS_JALR:
14365     case BFD_RELOC_HI16:
14366     case BFD_RELOC_HI16_S:
14367     case BFD_RELOC_LO16:
14368     case BFD_RELOC_GPREL16:
14369     case BFD_RELOC_MIPS_LITERAL:
14370     case BFD_RELOC_MIPS_CALL16:
14371     case BFD_RELOC_MIPS_GOT16:
14372     case BFD_RELOC_GPREL32:
14373     case BFD_RELOC_MIPS_GOT_HI16:
14374     case BFD_RELOC_MIPS_GOT_LO16:
14375     case BFD_RELOC_MIPS_CALL_HI16:
14376     case BFD_RELOC_MIPS_CALL_LO16:
14377     case BFD_RELOC_MIPS16_GPREL:
14378     case BFD_RELOC_MIPS16_GOT16:
14379     case BFD_RELOC_MIPS16_CALL16:
14380     case BFD_RELOC_MIPS16_HI16:
14381     case BFD_RELOC_MIPS16_HI16_S:
14382     case BFD_RELOC_MIPS16_LO16:
14383     case BFD_RELOC_MIPS16_JMP:
14384     case BFD_RELOC_MICROMIPS_JMP:
14385     case BFD_RELOC_MICROMIPS_GOT_DISP:
14386     case BFD_RELOC_MICROMIPS_GOT_PAGE:
14387     case BFD_RELOC_MICROMIPS_GOT_OFST:
14388     case BFD_RELOC_MICROMIPS_SUB:
14389     case BFD_RELOC_MICROMIPS_HIGHEST:
14390     case BFD_RELOC_MICROMIPS_HIGHER:
14391     case BFD_RELOC_MICROMIPS_SCN_DISP:
14392     case BFD_RELOC_MICROMIPS_JALR:
14393     case BFD_RELOC_MICROMIPS_HI16:
14394     case BFD_RELOC_MICROMIPS_HI16_S:
14395     case BFD_RELOC_MICROMIPS_LO16:
14396     case BFD_RELOC_MICROMIPS_GPREL16:
14397     case BFD_RELOC_MICROMIPS_LITERAL:
14398     case BFD_RELOC_MICROMIPS_CALL16:
14399     case BFD_RELOC_MICROMIPS_GOT16:
14400     case BFD_RELOC_MICROMIPS_GOT_HI16:
14401     case BFD_RELOC_MICROMIPS_GOT_LO16:
14402     case BFD_RELOC_MICROMIPS_CALL_HI16:
14403     case BFD_RELOC_MICROMIPS_CALL_LO16:
14404     case BFD_RELOC_MIPS_EH:
14405       if (fixP->fx_done)
14406         {
14407           offsetT value;
14408
14409           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
14410             {
14411               insn = read_reloc_insn (buf, fixP->fx_r_type);
14412               if (mips16_reloc_p (fixP->fx_r_type))
14413                 insn |= mips16_immed_extend (value, 16);
14414               else
14415                 insn |= (value & 0xffff);
14416               write_reloc_insn (buf, fixP->fx_r_type, insn);
14417             }
14418           else
14419             as_bad_where (fixP->fx_file, fixP->fx_line,
14420                           _("unsupported constant in relocation"));
14421         }
14422       break;
14423
14424     case BFD_RELOC_64:
14425       /* This is handled like BFD_RELOC_32, but we output a sign
14426          extended value if we are only 32 bits.  */
14427       if (fixP->fx_done)
14428         {
14429           if (8 <= sizeof (valueT))
14430             md_number_to_chars (buf, *valP, 8);
14431           else
14432             {
14433               valueT hiv;
14434
14435               if ((*valP & 0x80000000) != 0)
14436                 hiv = 0xffffffff;
14437               else
14438                 hiv = 0;
14439               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
14440               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
14441             }
14442         }
14443       break;
14444
14445     case BFD_RELOC_RVA:
14446     case BFD_RELOC_32:
14447     case BFD_RELOC_32_PCREL:
14448     case BFD_RELOC_16:
14449     case BFD_RELOC_8:
14450       /* If we are deleting this reloc entry, we must fill in the
14451          value now.  This can happen if we have a .word which is not
14452          resolved when it appears but is later defined.  */
14453       if (fixP->fx_done)
14454         md_number_to_chars (buf, *valP, fixP->fx_size);
14455       break;
14456
14457     case BFD_RELOC_16_PCREL_S2:
14458       if ((*valP & 0x3) != 0)
14459         as_bad_where (fixP->fx_file, fixP->fx_line,
14460                       _("branch to misaligned address (%lx)"), (long) *valP);
14461
14462       /* We need to save the bits in the instruction since fixup_segment()
14463          might be deleting the relocation entry (i.e., a branch within
14464          the current segment).  */
14465       if (! fixP->fx_done)
14466         break;
14467
14468       /* Update old instruction data.  */
14469       insn = read_insn (buf);
14470
14471       if (*valP + 0x20000 <= 0x3ffff)
14472         {
14473           insn |= (*valP >> 2) & 0xffff;
14474           write_insn (buf, insn);
14475         }
14476       else if (mips_pic == NO_PIC
14477                && fixP->fx_done
14478                && fixP->fx_frag->fr_address >= text_section->vma
14479                && (fixP->fx_frag->fr_address
14480                    < text_section->vma + bfd_get_section_size (text_section))
14481                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
14482                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
14483                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
14484         {
14485           /* The branch offset is too large.  If this is an
14486              unconditional branch, and we are not generating PIC code,
14487              we can convert it to an absolute jump instruction.  */
14488           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
14489             insn = 0x0c000000;  /* jal */
14490           else
14491             insn = 0x08000000;  /* j */
14492           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
14493           fixP->fx_done = 0;
14494           fixP->fx_addsy = section_symbol (text_section);
14495           *valP += md_pcrel_from (fixP);
14496           write_insn (buf, insn);
14497         }
14498       else
14499         {
14500           /* If we got here, we have branch-relaxation disabled,
14501              and there's nothing we can do to fix this instruction
14502              without turning it into a longer sequence.  */
14503           as_bad_where (fixP->fx_file, fixP->fx_line,
14504                         _("branch out of range"));
14505         }
14506       break;
14507
14508     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14509     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14510     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14511       /* We adjust the offset back to even.  */
14512       if ((*valP & 0x1) != 0)
14513         --(*valP);
14514
14515       if (! fixP->fx_done)
14516         break;
14517
14518       /* Should never visit here, because we keep the relocation.  */
14519       abort ();
14520       break;
14521
14522     case BFD_RELOC_VTABLE_INHERIT:
14523       fixP->fx_done = 0;
14524       if (fixP->fx_addsy
14525           && !S_IS_DEFINED (fixP->fx_addsy)
14526           && !S_IS_WEAK (fixP->fx_addsy))
14527         S_SET_WEAK (fixP->fx_addsy);
14528       break;
14529
14530     case BFD_RELOC_VTABLE_ENTRY:
14531       fixP->fx_done = 0;
14532       break;
14533
14534     default:
14535       abort ();
14536     }
14537
14538   /* Remember value for tc_gen_reloc.  */
14539   fixP->fx_addnumber = *valP;
14540 }
14541
14542 static symbolS *
14543 get_symbol (void)
14544 {
14545   int c;
14546   char *name;
14547   symbolS *p;
14548
14549   name = input_line_pointer;
14550   c = get_symbol_end ();
14551   p = (symbolS *) symbol_find_or_make (name);
14552   *input_line_pointer = c;
14553   return p;
14554 }
14555
14556 /* Align the current frag to a given power of two.  If a particular
14557    fill byte should be used, FILL points to an integer that contains
14558    that byte, otherwise FILL is null.
14559
14560    This function used to have the comment:
14561
14562       The MIPS assembler also automatically adjusts any preceding label.
14563
14564    The implementation therefore applied the adjustment to a maximum of
14565    one label.  However, other label adjustments are applied to batches
14566    of labels, and adjusting just one caused problems when new labels
14567    were added for the sake of debugging or unwind information.
14568    We therefore adjust all preceding labels (given as LABELS) instead.  */
14569
14570 static void
14571 mips_align (int to, int *fill, struct insn_label_list *labels)
14572 {
14573   mips_emit_delays ();
14574   mips_record_compressed_mode ();
14575   if (fill == NULL && subseg_text_p (now_seg))
14576     frag_align_code (to, 0);
14577   else
14578     frag_align (to, fill ? *fill : 0, 0);
14579   record_alignment (now_seg, to);
14580   mips_move_labels (labels, FALSE);
14581 }
14582
14583 /* Align to a given power of two.  .align 0 turns off the automatic
14584    alignment used by the data creating pseudo-ops.  */
14585
14586 static void
14587 s_align (int x ATTRIBUTE_UNUSED)
14588 {
14589   int temp, fill_value, *fill_ptr;
14590   long max_alignment = 28;
14591
14592   /* o Note that the assembler pulls down any immediately preceding label
14593        to the aligned address.
14594      o It's not documented but auto alignment is reinstated by
14595        a .align pseudo instruction.
14596      o Note also that after auto alignment is turned off the mips assembler
14597        issues an error on attempt to assemble an improperly aligned data item.
14598        We don't.  */
14599
14600   temp = get_absolute_expression ();
14601   if (temp > max_alignment)
14602     as_bad (_("alignment too large, %d assumed"), temp = max_alignment);
14603   else if (temp < 0)
14604     {
14605       as_warn (_("alignment negative, 0 assumed"));
14606       temp = 0;
14607     }
14608   if (*input_line_pointer == ',')
14609     {
14610       ++input_line_pointer;
14611       fill_value = get_absolute_expression ();
14612       fill_ptr = &fill_value;
14613     }
14614   else
14615     fill_ptr = 0;
14616   if (temp)
14617     {
14618       segment_info_type *si = seg_info (now_seg);
14619       struct insn_label_list *l = si->label_list;
14620       /* Auto alignment should be switched on by next section change.  */
14621       auto_align = 1;
14622       mips_align (temp, fill_ptr, l);
14623     }
14624   else
14625     {
14626       auto_align = 0;
14627     }
14628
14629   demand_empty_rest_of_line ();
14630 }
14631
14632 static void
14633 s_change_sec (int sec)
14634 {
14635   segT seg;
14636
14637   /* The ELF backend needs to know that we are changing sections, so
14638      that .previous works correctly.  We could do something like check
14639      for an obj_section_change_hook macro, but that might be confusing
14640      as it would not be appropriate to use it in the section changing
14641      functions in read.c, since obj-elf.c intercepts those.  FIXME:
14642      This should be cleaner, somehow.  */
14643   obj_elf_section_change_hook ();
14644
14645   mips_emit_delays ();
14646
14647   switch (sec)
14648     {
14649     case 't':
14650       s_text (0);
14651       break;
14652     case 'd':
14653       s_data (0);
14654       break;
14655     case 'b':
14656       subseg_set (bss_section, (subsegT) get_absolute_expression ());
14657       demand_empty_rest_of_line ();
14658       break;
14659
14660     case 'r':
14661       seg = subseg_new (RDATA_SECTION_NAME,
14662                         (subsegT) get_absolute_expression ());
14663       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
14664                                               | SEC_READONLY | SEC_RELOC
14665                                               | SEC_DATA));
14666       if (strncmp (TARGET_OS, "elf", 3) != 0)
14667         record_alignment (seg, 4);
14668       demand_empty_rest_of_line ();
14669       break;
14670
14671     case 's':
14672       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
14673       bfd_set_section_flags (stdoutput, seg,
14674                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
14675       if (strncmp (TARGET_OS, "elf", 3) != 0)
14676         record_alignment (seg, 4);
14677       demand_empty_rest_of_line ();
14678       break;
14679
14680     case 'B':
14681       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
14682       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
14683       if (strncmp (TARGET_OS, "elf", 3) != 0)
14684         record_alignment (seg, 4);
14685       demand_empty_rest_of_line ();
14686       break;
14687     }
14688
14689   auto_align = 1;
14690 }
14691
14692 void
14693 s_change_section (int ignore ATTRIBUTE_UNUSED)
14694 {
14695   char *section_name;
14696   char c;
14697   char next_c = 0;
14698   int section_type;
14699   int section_flag;
14700   int section_entry_size;
14701   int section_alignment;
14702
14703   section_name = input_line_pointer;
14704   c = get_symbol_end ();
14705   if (c)
14706     next_c = *(input_line_pointer + 1);
14707
14708   /* Do we have .section Name<,"flags">?  */
14709   if (c != ',' || (c == ',' && next_c == '"'))
14710     {
14711       /* just after name is now '\0'.  */
14712       *input_line_pointer = c;
14713       input_line_pointer = section_name;
14714       obj_elf_section (ignore);
14715       return;
14716     }
14717   input_line_pointer++;
14718
14719   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
14720   if (c == ',')
14721     section_type = get_absolute_expression ();
14722   else
14723     section_type = 0;
14724   if (*input_line_pointer++ == ',')
14725     section_flag = get_absolute_expression ();
14726   else
14727     section_flag = 0;
14728   if (*input_line_pointer++ == ',')
14729     section_entry_size = get_absolute_expression ();
14730   else
14731     section_entry_size = 0;
14732   if (*input_line_pointer++ == ',')
14733     section_alignment = get_absolute_expression ();
14734   else
14735     section_alignment = 0;
14736   /* FIXME: really ignore?  */
14737   (void) section_alignment;
14738
14739   section_name = xstrdup (section_name);
14740
14741   /* When using the generic form of .section (as implemented by obj-elf.c),
14742      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
14743      traditionally had to fall back on the more common @progbits instead.
14744
14745      There's nothing really harmful in this, since bfd will correct
14746      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
14747      means that, for backwards compatibility, the special_section entries
14748      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
14749
14750      Even so, we shouldn't force users of the MIPS .section syntax to
14751      incorrectly label the sections as SHT_PROGBITS.  The best compromise
14752      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
14753      generic type-checking code.  */
14754   if (section_type == SHT_MIPS_DWARF)
14755     section_type = SHT_PROGBITS;
14756
14757   obj_elf_change_section (section_name, section_type, section_flag,
14758                           section_entry_size, 0, 0, 0);
14759
14760   if (now_seg->name != section_name)
14761     free (section_name);
14762 }
14763
14764 void
14765 mips_enable_auto_align (void)
14766 {
14767   auto_align = 1;
14768 }
14769
14770 static void
14771 s_cons (int log_size)
14772 {
14773   segment_info_type *si = seg_info (now_seg);
14774   struct insn_label_list *l = si->label_list;
14775
14776   mips_emit_delays ();
14777   if (log_size > 0 && auto_align)
14778     mips_align (log_size, 0, l);
14779   cons (1 << log_size);
14780   mips_clear_insn_labels ();
14781 }
14782
14783 static void
14784 s_float_cons (int type)
14785 {
14786   segment_info_type *si = seg_info (now_seg);
14787   struct insn_label_list *l = si->label_list;
14788
14789   mips_emit_delays ();
14790
14791   if (auto_align)
14792     {
14793       if (type == 'd')
14794         mips_align (3, 0, l);
14795       else
14796         mips_align (2, 0, l);
14797     }
14798
14799   float_cons (type);
14800   mips_clear_insn_labels ();
14801 }
14802
14803 /* Handle .globl.  We need to override it because on Irix 5 you are
14804    permitted to say
14805        .globl foo .text
14806    where foo is an undefined symbol, to mean that foo should be
14807    considered to be the address of a function.  */
14808
14809 static void
14810 s_mips_globl (int x ATTRIBUTE_UNUSED)
14811 {
14812   char *name;
14813   int c;
14814   symbolS *symbolP;
14815   flagword flag;
14816
14817   do
14818     {
14819       name = input_line_pointer;
14820       c = get_symbol_end ();
14821       symbolP = symbol_find_or_make (name);
14822       S_SET_EXTERNAL (symbolP);
14823
14824       *input_line_pointer = c;
14825       SKIP_WHITESPACE ();
14826
14827       /* On Irix 5, every global symbol that is not explicitly labelled as
14828          being a function is apparently labelled as being an object.  */
14829       flag = BSF_OBJECT;
14830
14831       if (!is_end_of_line[(unsigned char) *input_line_pointer]
14832           && (*input_line_pointer != ','))
14833         {
14834           char *secname;
14835           asection *sec;
14836
14837           secname = input_line_pointer;
14838           c = get_symbol_end ();
14839           sec = bfd_get_section_by_name (stdoutput, secname);
14840           if (sec == NULL)
14841             as_bad (_("%s: no such section"), secname);
14842           *input_line_pointer = c;
14843
14844           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
14845             flag = BSF_FUNCTION;
14846         }
14847
14848       symbol_get_bfdsym (symbolP)->flags |= flag;
14849
14850       c = *input_line_pointer;
14851       if (c == ',')
14852         {
14853           input_line_pointer++;
14854           SKIP_WHITESPACE ();
14855           if (is_end_of_line[(unsigned char) *input_line_pointer])
14856             c = '\n';
14857         }
14858     }
14859   while (c == ',');
14860
14861   demand_empty_rest_of_line ();
14862 }
14863
14864 static void
14865 s_option (int x ATTRIBUTE_UNUSED)
14866 {
14867   char *opt;
14868   char c;
14869
14870   opt = input_line_pointer;
14871   c = get_symbol_end ();
14872
14873   if (*opt == 'O')
14874     {
14875       /* FIXME: What does this mean?  */
14876     }
14877   else if (strncmp (opt, "pic", 3) == 0)
14878     {
14879       int i;
14880
14881       i = atoi (opt + 3);
14882       if (i == 0)
14883         mips_pic = NO_PIC;
14884       else if (i == 2)
14885         {
14886           mips_pic = SVR4_PIC;
14887           mips_abicalls = TRUE;
14888         }
14889       else
14890         as_bad (_(".option pic%d not supported"), i);
14891
14892       if (mips_pic == SVR4_PIC)
14893         {
14894           if (g_switch_seen && g_switch_value != 0)
14895             as_warn (_("-G may not be used with SVR4 PIC code"));
14896           g_switch_value = 0;
14897           bfd_set_gp_size (stdoutput, 0);
14898         }
14899     }
14900   else
14901     as_warn (_("unrecognized option \"%s\""), opt);
14902
14903   *input_line_pointer = c;
14904   demand_empty_rest_of_line ();
14905 }
14906
14907 /* This structure is used to hold a stack of .set values.  */
14908
14909 struct mips_option_stack
14910 {
14911   struct mips_option_stack *next;
14912   struct mips_set_options options;
14913 };
14914
14915 static struct mips_option_stack *mips_opts_stack;
14916
14917 /* Handle the .set pseudo-op.  */
14918
14919 static void
14920 s_mipsset (int x ATTRIBUTE_UNUSED)
14921 {
14922   char *name = input_line_pointer, ch;
14923   const struct mips_ase *ase;
14924
14925   while (!is_end_of_line[(unsigned char) *input_line_pointer])
14926     ++input_line_pointer;
14927   ch = *input_line_pointer;
14928   *input_line_pointer = '\0';
14929
14930   if (strcmp (name, "reorder") == 0)
14931     {
14932       if (mips_opts.noreorder)
14933         end_noreorder ();
14934     }
14935   else if (strcmp (name, "noreorder") == 0)
14936     {
14937       if (!mips_opts.noreorder)
14938         start_noreorder ();
14939     }
14940   else if (strncmp (name, "at=", 3) == 0)
14941     {
14942       char *s = name + 3;
14943
14944       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
14945         as_bad (_("unrecognized register name `%s'"), s);
14946     }
14947   else if (strcmp (name, "at") == 0)
14948     {
14949       mips_opts.at = ATREG;
14950     }
14951   else if (strcmp (name, "noat") == 0)
14952     {
14953       mips_opts.at = ZERO;
14954     }
14955   else if (strcmp (name, "macro") == 0)
14956     {
14957       mips_opts.warn_about_macros = 0;
14958     }
14959   else if (strcmp (name, "nomacro") == 0)
14960     {
14961       if (mips_opts.noreorder == 0)
14962         as_bad (_("`noreorder' must be set before `nomacro'"));
14963       mips_opts.warn_about_macros = 1;
14964     }
14965   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
14966     {
14967       mips_opts.nomove = 0;
14968     }
14969   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
14970     {
14971       mips_opts.nomove = 1;
14972     }
14973   else if (strcmp (name, "bopt") == 0)
14974     {
14975       mips_opts.nobopt = 0;
14976     }
14977   else if (strcmp (name, "nobopt") == 0)
14978     {
14979       mips_opts.nobopt = 1;
14980     }
14981   else if (strcmp (name, "gp=default") == 0)
14982     mips_opts.gp32 = file_mips_gp32;
14983   else if (strcmp (name, "gp=32") == 0)
14984     mips_opts.gp32 = 1;
14985   else if (strcmp (name, "gp=64") == 0)
14986     {
14987       if (!ISA_HAS_64BIT_REGS (mips_opts.isa))
14988         as_warn (_("%s isa does not support 64-bit registers"),
14989                  mips_cpu_info_from_isa (mips_opts.isa)->name);
14990       mips_opts.gp32 = 0;
14991     }
14992   else if (strcmp (name, "fp=default") == 0)
14993     mips_opts.fp32 = file_mips_fp32;
14994   else if (strcmp (name, "fp=32") == 0)
14995     mips_opts.fp32 = 1;
14996   else if (strcmp (name, "fp=64") == 0)
14997     {
14998       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
14999         as_warn (_("%s isa does not support 64-bit floating point registers"),
15000                  mips_cpu_info_from_isa (mips_opts.isa)->name);
15001       mips_opts.fp32 = 0;
15002     }
15003   else if (strcmp (name, "softfloat") == 0)
15004     mips_opts.soft_float = 1;
15005   else if (strcmp (name, "hardfloat") == 0)
15006     mips_opts.soft_float = 0;
15007   else if (strcmp (name, "singlefloat") == 0)
15008     mips_opts.single_float = 1;
15009   else if (strcmp (name, "doublefloat") == 0)
15010     mips_opts.single_float = 0;
15011   else if (strcmp (name, "mips16") == 0
15012            || strcmp (name, "MIPS-16") == 0)
15013     {
15014       if (mips_opts.micromips == 1)
15015         as_fatal (_("`mips16' cannot be used with `micromips'"));
15016       mips_opts.mips16 = 1;
15017     }
15018   else if (strcmp (name, "nomips16") == 0
15019            || strcmp (name, "noMIPS-16") == 0)
15020     mips_opts.mips16 = 0;
15021   else if (strcmp (name, "micromips") == 0)
15022     {
15023       if (mips_opts.mips16 == 1)
15024         as_fatal (_("`micromips' cannot be used with `mips16'"));
15025       mips_opts.micromips = 1;
15026     }
15027   else if (strcmp (name, "nomicromips") == 0)
15028     mips_opts.micromips = 0;
15029   else if (name[0] == 'n'
15030            && name[1] == 'o'
15031            && (ase = mips_lookup_ase (name + 2)))
15032     mips_set_ase (ase, FALSE);
15033   else if ((ase = mips_lookup_ase (name)))
15034     mips_set_ase (ase, TRUE);
15035   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
15036     {
15037       int reset = 0;
15038
15039       /* Permit the user to change the ISA and architecture on the fly.
15040          Needless to say, misuse can cause serious problems.  */
15041       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
15042         {
15043           reset = 1;
15044           mips_opts.isa = file_mips_isa;
15045           mips_opts.arch = file_mips_arch;
15046         }
15047       else if (strncmp (name, "arch=", 5) == 0)
15048         {
15049           const struct mips_cpu_info *p;
15050
15051           p = mips_parse_cpu("internal use", name + 5);
15052           if (!p)
15053             as_bad (_("unknown architecture %s"), name + 5);
15054           else
15055             {
15056               mips_opts.arch = p->cpu;
15057               mips_opts.isa = p->isa;
15058             }
15059         }
15060       else if (strncmp (name, "mips", 4) == 0)
15061         {
15062           const struct mips_cpu_info *p;
15063
15064           p = mips_parse_cpu("internal use", name);
15065           if (!p)
15066             as_bad (_("unknown ISA level %s"), name + 4);
15067           else
15068             {
15069               mips_opts.arch = p->cpu;
15070               mips_opts.isa = p->isa;
15071             }
15072         }
15073       else
15074         as_bad (_("unknown ISA or architecture %s"), name);
15075
15076       switch (mips_opts.isa)
15077         {
15078         case  0:
15079           break;
15080         case ISA_MIPS1:
15081         case ISA_MIPS2:
15082         case ISA_MIPS32:
15083         case ISA_MIPS32R2:
15084           mips_opts.gp32 = 1;
15085           mips_opts.fp32 = 1;
15086           break;
15087         case ISA_MIPS3:
15088         case ISA_MIPS4:
15089         case ISA_MIPS5:
15090         case ISA_MIPS64:
15091         case ISA_MIPS64R2:
15092           mips_opts.gp32 = 0;
15093           if (mips_opts.arch == CPU_R5900)
15094             {
15095                 mips_opts.fp32 = 1;
15096             }
15097           else
15098             {
15099           mips_opts.fp32 = 0;
15100             }
15101           break;
15102         default:
15103           as_bad (_("unknown ISA level %s"), name + 4);
15104           break;
15105         }
15106       if (reset)
15107         {
15108           mips_opts.gp32 = file_mips_gp32;
15109           mips_opts.fp32 = file_mips_fp32;
15110         }
15111     }
15112   else if (strcmp (name, "autoextend") == 0)
15113     mips_opts.noautoextend = 0;
15114   else if (strcmp (name, "noautoextend") == 0)
15115     mips_opts.noautoextend = 1;
15116   else if (strcmp (name, "insn32") == 0)
15117     mips_opts.insn32 = TRUE;
15118   else if (strcmp (name, "noinsn32") == 0)
15119     mips_opts.insn32 = FALSE;
15120   else if (strcmp (name, "push") == 0)
15121     {
15122       struct mips_option_stack *s;
15123
15124       s = (struct mips_option_stack *) xmalloc (sizeof *s);
15125       s->next = mips_opts_stack;
15126       s->options = mips_opts;
15127       mips_opts_stack = s;
15128     }
15129   else if (strcmp (name, "pop") == 0)
15130     {
15131       struct mips_option_stack *s;
15132
15133       s = mips_opts_stack;
15134       if (s == NULL)
15135         as_bad (_(".set pop with no .set push"));
15136       else
15137         {
15138           /* If we're changing the reorder mode we need to handle
15139              delay slots correctly.  */
15140           if (s->options.noreorder && ! mips_opts.noreorder)
15141             start_noreorder ();
15142           else if (! s->options.noreorder && mips_opts.noreorder)
15143             end_noreorder ();
15144
15145           mips_opts = s->options;
15146           mips_opts_stack = s->next;
15147           free (s);
15148         }
15149     }
15150   else if (strcmp (name, "sym32") == 0)
15151     mips_opts.sym32 = TRUE;
15152   else if (strcmp (name, "nosym32") == 0)
15153     mips_opts.sym32 = FALSE;
15154   else if (strchr (name, ','))
15155     {
15156       /* Generic ".set" directive; use the generic handler.  */
15157       *input_line_pointer = ch;
15158       input_line_pointer = name;
15159       s_set (0);
15160       return;
15161     }
15162   else
15163     {
15164       as_warn (_("tried to set unrecognized symbol: %s\n"), name);
15165     }
15166   mips_check_isa_supports_ases ();
15167   *input_line_pointer = ch;
15168   demand_empty_rest_of_line ();
15169 }
15170
15171 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
15172    .option pic2.  It means to generate SVR4 PIC calls.  */
15173
15174 static void
15175 s_abicalls (int ignore ATTRIBUTE_UNUSED)
15176 {
15177   mips_pic = SVR4_PIC;
15178   mips_abicalls = TRUE;
15179
15180   if (g_switch_seen && g_switch_value != 0)
15181     as_warn (_("-G may not be used with SVR4 PIC code"));
15182   g_switch_value = 0;
15183
15184   bfd_set_gp_size (stdoutput, 0);
15185   demand_empty_rest_of_line ();
15186 }
15187
15188 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
15189    PIC code.  It sets the $gp register for the function based on the
15190    function address, which is in the register named in the argument.
15191    This uses a relocation against _gp_disp, which is handled specially
15192    by the linker.  The result is:
15193         lui     $gp,%hi(_gp_disp)
15194         addiu   $gp,$gp,%lo(_gp_disp)
15195         addu    $gp,$gp,.cpload argument
15196    The .cpload argument is normally $25 == $t9.
15197
15198    The -mno-shared option changes this to:
15199         lui     $gp,%hi(__gnu_local_gp)
15200         addiu   $gp,$gp,%lo(__gnu_local_gp)
15201    and the argument is ignored.  This saves an instruction, but the
15202    resulting code is not position independent; it uses an absolute
15203    address for __gnu_local_gp.  Thus code assembled with -mno-shared
15204    can go into an ordinary executable, but not into a shared library.  */
15205
15206 static void
15207 s_cpload (int ignore ATTRIBUTE_UNUSED)
15208 {
15209   expressionS ex;
15210   int reg;
15211   int in_shared;
15212
15213   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
15214      .cpload is ignored.  */
15215   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
15216     {
15217       s_ignore (0);
15218       return;
15219     }
15220
15221   if (mips_opts.mips16)
15222     {
15223       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
15224       ignore_rest_of_line ();
15225       return;
15226     }
15227
15228   /* .cpload should be in a .set noreorder section.  */
15229   if (mips_opts.noreorder == 0)
15230     as_warn (_(".cpload not in noreorder section"));
15231
15232   reg = tc_get_register (0);
15233
15234   /* If we need to produce a 64-bit address, we are better off using
15235      the default instruction sequence.  */
15236   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
15237
15238   ex.X_op = O_symbol;
15239   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
15240                                          "__gnu_local_gp");
15241   ex.X_op_symbol = NULL;
15242   ex.X_add_number = 0;
15243
15244   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
15245   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
15246
15247   mips_mark_labels ();
15248   mips_assembling_insn = TRUE;
15249
15250   macro_start ();
15251   macro_build_lui (&ex, mips_gp_register);
15252   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
15253                mips_gp_register, BFD_RELOC_LO16);
15254   if (in_shared)
15255     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
15256                  mips_gp_register, reg);
15257   macro_end ();
15258
15259   mips_assembling_insn = FALSE;
15260   demand_empty_rest_of_line ();
15261 }
15262
15263 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
15264      .cpsetup $reg1, offset|$reg2, label
15265
15266    If offset is given, this results in:
15267      sd         $gp, offset($sp)
15268      lui        $gp, %hi(%neg(%gp_rel(label)))
15269      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
15270      daddu      $gp, $gp, $reg1
15271
15272    If $reg2 is given, this results in:
15273      daddu      $reg2, $gp, $0
15274      lui        $gp, %hi(%neg(%gp_rel(label)))
15275      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
15276      daddu      $gp, $gp, $reg1
15277    $reg1 is normally $25 == $t9.
15278
15279    The -mno-shared option replaces the last three instructions with
15280         lui     $gp,%hi(_gp)
15281         addiu   $gp,$gp,%lo(_gp)  */
15282
15283 static void
15284 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
15285 {
15286   expressionS ex_off;
15287   expressionS ex_sym;
15288   int reg1;
15289
15290   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
15291      We also need NewABI support.  */
15292   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15293     {
15294       s_ignore (0);
15295       return;
15296     }
15297
15298   if (mips_opts.mips16)
15299     {
15300       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
15301       ignore_rest_of_line ();
15302       return;
15303     }
15304
15305   reg1 = tc_get_register (0);
15306   SKIP_WHITESPACE ();
15307   if (*input_line_pointer != ',')
15308     {
15309       as_bad (_("missing argument separator ',' for .cpsetup"));
15310       return;
15311     }
15312   else
15313     ++input_line_pointer;
15314   SKIP_WHITESPACE ();
15315   if (*input_line_pointer == '$')
15316     {
15317       mips_cpreturn_register = tc_get_register (0);
15318       mips_cpreturn_offset = -1;
15319     }
15320   else
15321     {
15322       mips_cpreturn_offset = get_absolute_expression ();
15323       mips_cpreturn_register = -1;
15324     }
15325   SKIP_WHITESPACE ();
15326   if (*input_line_pointer != ',')
15327     {
15328       as_bad (_("missing argument separator ',' for .cpsetup"));
15329       return;
15330     }
15331   else
15332     ++input_line_pointer;
15333   SKIP_WHITESPACE ();
15334   expression (&ex_sym);
15335
15336   mips_mark_labels ();
15337   mips_assembling_insn = TRUE;
15338
15339   macro_start ();
15340   if (mips_cpreturn_register == -1)
15341     {
15342       ex_off.X_op = O_constant;
15343       ex_off.X_add_symbol = NULL;
15344       ex_off.X_op_symbol = NULL;
15345       ex_off.X_add_number = mips_cpreturn_offset;
15346
15347       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
15348                    BFD_RELOC_LO16, SP);
15349     }
15350   else
15351     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
15352                  mips_gp_register, 0);
15353
15354   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
15355     {
15356       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
15357                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
15358                    BFD_RELOC_HI16_S);
15359
15360       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
15361                    mips_gp_register, -1, BFD_RELOC_GPREL16,
15362                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
15363
15364       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
15365                    mips_gp_register, reg1);
15366     }
15367   else
15368     {
15369       expressionS ex;
15370
15371       ex.X_op = O_symbol;
15372       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
15373       ex.X_op_symbol = NULL;
15374       ex.X_add_number = 0;
15375
15376       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
15377       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
15378
15379       macro_build_lui (&ex, mips_gp_register);
15380       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
15381                    mips_gp_register, BFD_RELOC_LO16);
15382     }
15383
15384   macro_end ();
15385
15386   mips_assembling_insn = FALSE;
15387   demand_empty_rest_of_line ();
15388 }
15389
15390 static void
15391 s_cplocal (int ignore ATTRIBUTE_UNUSED)
15392 {
15393   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
15394      .cplocal is ignored.  */
15395   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15396     {
15397       s_ignore (0);
15398       return;
15399     }
15400
15401   if (mips_opts.mips16)
15402     {
15403       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
15404       ignore_rest_of_line ();
15405       return;
15406     }
15407
15408   mips_gp_register = tc_get_register (0);
15409   demand_empty_rest_of_line ();
15410 }
15411
15412 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
15413    offset from $sp.  The offset is remembered, and after making a PIC
15414    call $gp is restored from that location.  */
15415
15416 static void
15417 s_cprestore (int ignore ATTRIBUTE_UNUSED)
15418 {
15419   expressionS ex;
15420
15421   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
15422      .cprestore is ignored.  */
15423   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
15424     {
15425       s_ignore (0);
15426       return;
15427     }
15428
15429   if (mips_opts.mips16)
15430     {
15431       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
15432       ignore_rest_of_line ();
15433       return;
15434     }
15435
15436   mips_cprestore_offset = get_absolute_expression ();
15437   mips_cprestore_valid = 1;
15438
15439   ex.X_op = O_constant;
15440   ex.X_add_symbol = NULL;
15441   ex.X_op_symbol = NULL;
15442   ex.X_add_number = mips_cprestore_offset;
15443
15444   mips_mark_labels ();
15445   mips_assembling_insn = TRUE;
15446
15447   macro_start ();
15448   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
15449                                 SP, HAVE_64BIT_ADDRESSES);
15450   macro_end ();
15451
15452   mips_assembling_insn = FALSE;
15453   demand_empty_rest_of_line ();
15454 }
15455
15456 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
15457    was given in the preceding .cpsetup, it results in:
15458      ld         $gp, offset($sp)
15459
15460    If a register $reg2 was given there, it results in:
15461      daddu      $gp, $reg2, $0  */
15462
15463 static void
15464 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
15465 {
15466   expressionS ex;
15467
15468   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
15469      We also need NewABI support.  */
15470   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15471     {
15472       s_ignore (0);
15473       return;
15474     }
15475
15476   if (mips_opts.mips16)
15477     {
15478       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
15479       ignore_rest_of_line ();
15480       return;
15481     }
15482
15483   mips_mark_labels ();
15484   mips_assembling_insn = TRUE;
15485
15486   macro_start ();
15487   if (mips_cpreturn_register == -1)
15488     {
15489       ex.X_op = O_constant;
15490       ex.X_add_symbol = NULL;
15491       ex.X_op_symbol = NULL;
15492       ex.X_add_number = mips_cpreturn_offset;
15493
15494       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
15495     }
15496   else
15497     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
15498                  mips_cpreturn_register, 0);
15499   macro_end ();
15500
15501   mips_assembling_insn = FALSE;
15502   demand_empty_rest_of_line ();
15503 }
15504
15505 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
15506    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
15507    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
15508    debug information or MIPS16 TLS.  */
15509
15510 static void
15511 s_tls_rel_directive (const size_t bytes, const char *dirstr,
15512                      bfd_reloc_code_real_type rtype)
15513 {
15514   expressionS ex;
15515   char *p;
15516
15517   expression (&ex);
15518
15519   if (ex.X_op != O_symbol)
15520     {
15521       as_bad (_("unsupported use of %s"), dirstr);
15522       ignore_rest_of_line ();
15523     }
15524
15525   p = frag_more (bytes);
15526   md_number_to_chars (p, 0, bytes);
15527   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
15528   demand_empty_rest_of_line ();
15529   mips_clear_insn_labels ();
15530 }
15531
15532 /* Handle .dtprelword.  */
15533
15534 static void
15535 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
15536 {
15537   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
15538 }
15539
15540 /* Handle .dtpreldword.  */
15541
15542 static void
15543 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
15544 {
15545   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
15546 }
15547
15548 /* Handle .tprelword.  */
15549
15550 static void
15551 s_tprelword (int ignore ATTRIBUTE_UNUSED)
15552 {
15553   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
15554 }
15555
15556 /* Handle .tpreldword.  */
15557
15558 static void
15559 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
15560 {
15561   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
15562 }
15563
15564 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
15565    code.  It sets the offset to use in gp_rel relocations.  */
15566
15567 static void
15568 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
15569 {
15570   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
15571      We also need NewABI support.  */
15572   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15573     {
15574       s_ignore (0);
15575       return;
15576     }
15577
15578   mips_gprel_offset = get_absolute_expression ();
15579
15580   demand_empty_rest_of_line ();
15581 }
15582
15583 /* Handle the .gpword pseudo-op.  This is used when generating PIC
15584    code.  It generates a 32 bit GP relative reloc.  */
15585
15586 static void
15587 s_gpword (int ignore ATTRIBUTE_UNUSED)
15588 {
15589   segment_info_type *si;
15590   struct insn_label_list *l;
15591   expressionS ex;
15592   char *p;
15593
15594   /* When not generating PIC code, this is treated as .word.  */
15595   if (mips_pic != SVR4_PIC)
15596     {
15597       s_cons (2);
15598       return;
15599     }
15600
15601   si = seg_info (now_seg);
15602   l = si->label_list;
15603   mips_emit_delays ();
15604   if (auto_align)
15605     mips_align (2, 0, l);
15606
15607   expression (&ex);
15608   mips_clear_insn_labels ();
15609
15610   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15611     {
15612       as_bad (_("unsupported use of .gpword"));
15613       ignore_rest_of_line ();
15614     }
15615
15616   p = frag_more (4);
15617   md_number_to_chars (p, 0, 4);
15618   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15619                BFD_RELOC_GPREL32);
15620
15621   demand_empty_rest_of_line ();
15622 }
15623
15624 static void
15625 s_gpdword (int ignore ATTRIBUTE_UNUSED)
15626 {
15627   segment_info_type *si;
15628   struct insn_label_list *l;
15629   expressionS ex;
15630   char *p;
15631
15632   /* When not generating PIC code, this is treated as .dword.  */
15633   if (mips_pic != SVR4_PIC)
15634     {
15635       s_cons (3);
15636       return;
15637     }
15638
15639   si = seg_info (now_seg);
15640   l = si->label_list;
15641   mips_emit_delays ();
15642   if (auto_align)
15643     mips_align (3, 0, l);
15644
15645   expression (&ex);
15646   mips_clear_insn_labels ();
15647
15648   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15649     {
15650       as_bad (_("unsupported use of .gpdword"));
15651       ignore_rest_of_line ();
15652     }
15653
15654   p = frag_more (8);
15655   md_number_to_chars (p, 0, 8);
15656   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15657                BFD_RELOC_GPREL32)->fx_tcbit = 1;
15658
15659   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
15660   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
15661            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
15662
15663   demand_empty_rest_of_line ();
15664 }
15665
15666 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
15667    tables.  It generates a R_MIPS_EH reloc.  */
15668
15669 static void
15670 s_ehword (int ignore ATTRIBUTE_UNUSED)
15671 {
15672   expressionS ex;
15673   char *p;
15674
15675   mips_emit_delays ();
15676
15677   expression (&ex);
15678   mips_clear_insn_labels ();
15679
15680   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15681     {
15682       as_bad (_("unsupported use of .ehword"));
15683       ignore_rest_of_line ();
15684     }
15685
15686   p = frag_more (4);
15687   md_number_to_chars (p, 0, 4);
15688   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15689                BFD_RELOC_MIPS_EH);
15690
15691   demand_empty_rest_of_line ();
15692 }
15693
15694 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
15695    tables in SVR4 PIC code.  */
15696
15697 static void
15698 s_cpadd (int ignore ATTRIBUTE_UNUSED)
15699 {
15700   int reg;
15701
15702   /* This is ignored when not generating SVR4 PIC code.  */
15703   if (mips_pic != SVR4_PIC)
15704     {
15705       s_ignore (0);
15706       return;
15707     }
15708
15709   mips_mark_labels ();
15710   mips_assembling_insn = TRUE;
15711
15712   /* Add $gp to the register named as an argument.  */
15713   macro_start ();
15714   reg = tc_get_register (0);
15715   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
15716   macro_end ();
15717
15718   mips_assembling_insn = FALSE;
15719   demand_empty_rest_of_line ();
15720 }
15721
15722 /* Handle the .insn pseudo-op.  This marks instruction labels in
15723    mips16/micromips mode.  This permits the linker to handle them specially,
15724    such as generating jalx instructions when needed.  We also make
15725    them odd for the duration of the assembly, in order to generate the
15726    right sort of code.  We will make them even in the adjust_symtab
15727    routine, while leaving them marked.  This is convenient for the
15728    debugger and the disassembler.  The linker knows to make them odd
15729    again.  */
15730
15731 static void
15732 s_insn (int ignore ATTRIBUTE_UNUSED)
15733 {
15734   mips_mark_labels ();
15735
15736   demand_empty_rest_of_line ();
15737 }
15738
15739 /* Handle the .nan pseudo-op.  */
15740
15741 static void
15742 s_nan (int ignore ATTRIBUTE_UNUSED)
15743 {
15744   static const char str_legacy[] = "legacy";
15745   static const char str_2008[] = "2008";
15746   size_t i;
15747
15748   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
15749
15750   if (i == sizeof (str_2008) - 1
15751       && memcmp (input_line_pointer, str_2008, i) == 0)
15752     mips_flag_nan2008 = TRUE;
15753   else if (i == sizeof (str_legacy) - 1
15754            && memcmp (input_line_pointer, str_legacy, i) == 0)
15755     mips_flag_nan2008 = FALSE;
15756   else
15757     as_bad (_("bad .nan directive"));
15758
15759   input_line_pointer += i;
15760   demand_empty_rest_of_line ();
15761 }
15762
15763 /* Handle a .stab[snd] directive.  Ideally these directives would be
15764    implemented in a transparent way, so that removing them would not
15765    have any effect on the generated instructions.  However, s_stab
15766    internally changes the section, so in practice we need to decide
15767    now whether the preceding label marks compressed code.  We do not
15768    support changing the compression mode of a label after a .stab*
15769    directive, such as in:
15770
15771    foo:
15772         .stabs ...
15773         .set mips16
15774
15775    so the current mode wins.  */
15776
15777 static void
15778 s_mips_stab (int type)
15779 {
15780   mips_mark_labels ();
15781   s_stab (type);
15782 }
15783
15784 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
15785
15786 static void
15787 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
15788 {
15789   char *name;
15790   int c;
15791   symbolS *symbolP;
15792   expressionS exp;
15793
15794   name = input_line_pointer;
15795   c = get_symbol_end ();
15796   symbolP = symbol_find_or_make (name);
15797   S_SET_WEAK (symbolP);
15798   *input_line_pointer = c;
15799
15800   SKIP_WHITESPACE ();
15801
15802   if (! is_end_of_line[(unsigned char) *input_line_pointer])
15803     {
15804       if (S_IS_DEFINED (symbolP))
15805         {
15806           as_bad (_("ignoring attempt to redefine symbol %s"),
15807                   S_GET_NAME (symbolP));
15808           ignore_rest_of_line ();
15809           return;
15810         }
15811
15812       if (*input_line_pointer == ',')
15813         {
15814           ++input_line_pointer;
15815           SKIP_WHITESPACE ();
15816         }
15817
15818       expression (&exp);
15819       if (exp.X_op != O_symbol)
15820         {
15821           as_bad (_("bad .weakext directive"));
15822           ignore_rest_of_line ();
15823           return;
15824         }
15825       symbol_set_value_expression (symbolP, &exp);
15826     }
15827
15828   demand_empty_rest_of_line ();
15829 }
15830
15831 /* Parse a register string into a number.  Called from the ECOFF code
15832    to parse .frame.  The argument is non-zero if this is the frame
15833    register, so that we can record it in mips_frame_reg.  */
15834
15835 int
15836 tc_get_register (int frame)
15837 {
15838   unsigned int reg;
15839
15840   SKIP_WHITESPACE ();
15841   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
15842     reg = 0;
15843   if (frame)
15844     {
15845       mips_frame_reg = reg != 0 ? reg : SP;
15846       mips_frame_reg_valid = 1;
15847       mips_cprestore_valid = 0;
15848     }
15849   return reg;
15850 }
15851
15852 valueT
15853 md_section_align (asection *seg, valueT addr)
15854 {
15855   int align = bfd_get_section_alignment (stdoutput, seg);
15856
15857   /* We don't need to align ELF sections to the full alignment.
15858      However, Irix 5 may prefer that we align them at least to a 16
15859      byte boundary.  We don't bother to align the sections if we
15860      are targeted for an embedded system.  */
15861   if (strncmp (TARGET_OS, "elf", 3) == 0)
15862     return addr;
15863   if (align > 4)
15864     align = 4;
15865
15866   return ((addr + (1 << align) - 1) & (-1 << align));
15867 }
15868
15869 /* Utility routine, called from above as well.  If called while the
15870    input file is still being read, it's only an approximation.  (For
15871    example, a symbol may later become defined which appeared to be
15872    undefined earlier.)  */
15873
15874 static int
15875 nopic_need_relax (symbolS *sym, int before_relaxing)
15876 {
15877   if (sym == 0)
15878     return 0;
15879
15880   if (g_switch_value > 0)
15881     {
15882       const char *symname;
15883       int change;
15884
15885       /* Find out whether this symbol can be referenced off the $gp
15886          register.  It can be if it is smaller than the -G size or if
15887          it is in the .sdata or .sbss section.  Certain symbols can
15888          not be referenced off the $gp, although it appears as though
15889          they can.  */
15890       symname = S_GET_NAME (sym);
15891       if (symname != (const char *) NULL
15892           && (strcmp (symname, "eprol") == 0
15893               || strcmp (symname, "etext") == 0
15894               || strcmp (symname, "_gp") == 0
15895               || strcmp (symname, "edata") == 0
15896               || strcmp (symname, "_fbss") == 0
15897               || strcmp (symname, "_fdata") == 0
15898               || strcmp (symname, "_ftext") == 0
15899               || strcmp (symname, "end") == 0
15900               || strcmp (symname, "_gp_disp") == 0))
15901         change = 1;
15902       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
15903                && (0
15904 #ifndef NO_ECOFF_DEBUGGING
15905                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
15906                        && (symbol_get_obj (sym)->ecoff_extern_size
15907                            <= g_switch_value))
15908 #endif
15909                    /* We must defer this decision until after the whole
15910                       file has been read, since there might be a .extern
15911                       after the first use of this symbol.  */
15912                    || (before_relaxing
15913 #ifndef NO_ECOFF_DEBUGGING
15914                        && symbol_get_obj (sym)->ecoff_extern_size == 0
15915 #endif
15916                        && S_GET_VALUE (sym) == 0)
15917                    || (S_GET_VALUE (sym) != 0
15918                        && S_GET_VALUE (sym) <= g_switch_value)))
15919         change = 0;
15920       else
15921         {
15922           const char *segname;
15923
15924           segname = segment_name (S_GET_SEGMENT (sym));
15925           gas_assert (strcmp (segname, ".lit8") != 0
15926                   && strcmp (segname, ".lit4") != 0);
15927           change = (strcmp (segname, ".sdata") != 0
15928                     && strcmp (segname, ".sbss") != 0
15929                     && strncmp (segname, ".sdata.", 7) != 0
15930                     && strncmp (segname, ".sbss.", 6) != 0
15931                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
15932                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
15933         }
15934       return change;
15935     }
15936   else
15937     /* We are not optimizing for the $gp register.  */
15938     return 1;
15939 }
15940
15941
15942 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
15943
15944 static bfd_boolean
15945 pic_need_relax (symbolS *sym, asection *segtype)
15946 {
15947   asection *symsec;
15948
15949   /* Handle the case of a symbol equated to another symbol.  */
15950   while (symbol_equated_reloc_p (sym))
15951     {
15952       symbolS *n;
15953
15954       /* It's possible to get a loop here in a badly written program.  */
15955       n = symbol_get_value_expression (sym)->X_add_symbol;
15956       if (n == sym)
15957         break;
15958       sym = n;
15959     }
15960
15961   if (symbol_section_p (sym))
15962     return TRUE;
15963
15964   symsec = S_GET_SEGMENT (sym);
15965
15966   /* This must duplicate the test in adjust_reloc_syms.  */
15967   return (!bfd_is_und_section (symsec)
15968           && !bfd_is_abs_section (symsec)
15969           && !bfd_is_com_section (symsec)
15970           && !s_is_linkonce (sym, segtype)
15971           /* A global or weak symbol is treated as external.  */
15972           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
15973 }
15974
15975
15976 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
15977    extended opcode.  SEC is the section the frag is in.  */
15978
15979 static int
15980 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
15981 {
15982   int type;
15983   const struct mips_int_operand *operand;
15984   offsetT val;
15985   segT symsec;
15986   fragS *sym_frag;
15987
15988   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
15989     return 0;
15990   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
15991     return 1;
15992
15993   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
15994   operand = mips16_immed_operand (type, FALSE);
15995
15996   sym_frag = symbol_get_frag (fragp->fr_symbol);
15997   val = S_GET_VALUE (fragp->fr_symbol);
15998   symsec = S_GET_SEGMENT (fragp->fr_symbol);
15999
16000   if (operand->root.type == OP_PCREL)
16001     {
16002       const struct mips_pcrel_operand *pcrel_op;
16003       addressT addr;
16004       offsetT maxtiny;
16005
16006       /* We won't have the section when we are called from
16007          mips_relax_frag.  However, we will always have been called
16008          from md_estimate_size_before_relax first.  If this is a
16009          branch to a different section, we mark it as such.  If SEC is
16010          NULL, and the frag is not marked, then it must be a branch to
16011          the same section.  */
16012       pcrel_op = (const struct mips_pcrel_operand *) operand;
16013       if (sec == NULL)
16014         {
16015           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
16016             return 1;
16017         }
16018       else
16019         {
16020           /* Must have been called from md_estimate_size_before_relax.  */
16021           if (symsec != sec)
16022             {
16023               fragp->fr_subtype =
16024                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16025
16026               /* FIXME: We should support this, and let the linker
16027                  catch branches and loads that are out of range.  */
16028               as_bad_where (fragp->fr_file, fragp->fr_line,
16029                             _("unsupported PC relative reference to different section"));
16030
16031               return 1;
16032             }
16033           if (fragp != sym_frag && sym_frag->fr_address == 0)
16034             /* Assume non-extended on the first relaxation pass.
16035                The address we have calculated will be bogus if this is
16036                a forward branch to another frag, as the forward frag
16037                will have fr_address == 0.  */
16038             return 0;
16039         }
16040
16041       /* In this case, we know for sure that the symbol fragment is in
16042          the same section.  If the relax_marker of the symbol fragment
16043          differs from the relax_marker of this fragment, we have not
16044          yet adjusted the symbol fragment fr_address.  We want to add
16045          in STRETCH in order to get a better estimate of the address.
16046          This particularly matters because of the shift bits.  */
16047       if (stretch != 0
16048           && sym_frag->relax_marker != fragp->relax_marker)
16049         {
16050           fragS *f;
16051
16052           /* Adjust stretch for any alignment frag.  Note that if have
16053              been expanding the earlier code, the symbol may be
16054              defined in what appears to be an earlier frag.  FIXME:
16055              This doesn't handle the fr_subtype field, which specifies
16056              a maximum number of bytes to skip when doing an
16057              alignment.  */
16058           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
16059             {
16060               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
16061                 {
16062                   if (stretch < 0)
16063                     stretch = - ((- stretch)
16064                                  & ~ ((1 << (int) f->fr_offset) - 1));
16065                   else
16066                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
16067                   if (stretch == 0)
16068                     break;
16069                 }
16070             }
16071           if (f != NULL)
16072             val += stretch;
16073         }
16074
16075       addr = fragp->fr_address + fragp->fr_fix;
16076
16077       /* The base address rules are complicated.  The base address of
16078          a branch is the following instruction.  The base address of a
16079          PC relative load or add is the instruction itself, but if it
16080          is in a delay slot (in which case it can not be extended) use
16081          the address of the instruction whose delay slot it is in.  */
16082       if (pcrel_op->include_isa_bit)
16083         {
16084           addr += 2;
16085
16086           /* If we are currently assuming that this frag should be
16087              extended, then, the current address is two bytes
16088              higher.  */
16089           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16090             addr += 2;
16091
16092           /* Ignore the low bit in the target, since it will be set
16093              for a text label.  */
16094           val &= -2;
16095         }
16096       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
16097         addr -= 4;
16098       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
16099         addr -= 2;
16100
16101       val -= addr & -(1 << pcrel_op->align_log2);
16102
16103       /* If any of the shifted bits are set, we must use an extended
16104          opcode.  If the address depends on the size of this
16105          instruction, this can lead to a loop, so we arrange to always
16106          use an extended opcode.  We only check this when we are in
16107          the main relaxation loop, when SEC is NULL.  */
16108       if ((val & ((1 << operand->shift) - 1)) != 0 && sec == NULL)
16109         {
16110           fragp->fr_subtype =
16111             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16112           return 1;
16113         }
16114
16115       /* If we are about to mark a frag as extended because the value
16116          is precisely the next value above maxtiny, then there is a
16117          chance of an infinite loop as in the following code:
16118              la $4,foo
16119              .skip      1020
16120              .align     2
16121            foo:
16122          In this case when the la is extended, foo is 0x3fc bytes
16123          away, so the la can be shrunk, but then foo is 0x400 away, so
16124          the la must be extended.  To avoid this loop, we mark the
16125          frag as extended if it was small, and is about to become
16126          extended with the next value above maxtiny.  */
16127       maxtiny = mips_int_operand_max (operand);
16128       if (val == maxtiny + (1 << operand->shift)
16129           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
16130           && sec == NULL)
16131         {
16132           fragp->fr_subtype =
16133             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16134           return 1;
16135         }
16136     }
16137   else if (symsec != absolute_section && sec != NULL)
16138     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
16139
16140   return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
16141 }
16142
16143 /* Compute the length of a branch sequence, and adjust the
16144    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
16145    worst-case length is computed, with UPDATE being used to indicate
16146    whether an unconditional (-1), branch-likely (+1) or regular (0)
16147    branch is to be computed.  */
16148 static int
16149 relaxed_branch_length (fragS *fragp, asection *sec, int update)
16150 {
16151   bfd_boolean toofar;
16152   int length;
16153
16154   if (fragp
16155       && S_IS_DEFINED (fragp->fr_symbol)
16156       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16157     {
16158       addressT addr;
16159       offsetT val;
16160
16161       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16162
16163       addr = fragp->fr_address + fragp->fr_fix + 4;
16164
16165       val -= addr;
16166
16167       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
16168     }
16169   else if (fragp)
16170     /* If the symbol is not defined or it's in a different segment,
16171        assume the user knows what's going on and emit a short
16172        branch.  */
16173     toofar = FALSE;
16174   else
16175     toofar = TRUE;
16176
16177   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16178     fragp->fr_subtype
16179       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
16180                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
16181                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
16182                              RELAX_BRANCH_LINK (fragp->fr_subtype),
16183                              toofar);
16184
16185   length = 4;
16186   if (toofar)
16187     {
16188       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
16189         length += 8;
16190
16191       if (mips_pic != NO_PIC)
16192         {
16193           /* Additional space for PIC loading of target address.  */
16194           length += 8;
16195           if (mips_opts.isa == ISA_MIPS1)
16196             /* Additional space for $at-stabilizing nop.  */
16197             length += 4;
16198         }
16199
16200       /* If branch is conditional.  */
16201       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
16202         length += 8;
16203     }
16204
16205   return length;
16206 }
16207
16208 /* Compute the length of a branch sequence, and adjust the
16209    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
16210    worst-case length is computed, with UPDATE being used to indicate
16211    whether an unconditional (-1), or regular (0) branch is to be
16212    computed.  */
16213
16214 static int
16215 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
16216 {
16217   bfd_boolean toofar;
16218   int length;
16219
16220   if (fragp
16221       && S_IS_DEFINED (fragp->fr_symbol)
16222       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16223     {
16224       addressT addr;
16225       offsetT val;
16226
16227       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16228       /* Ignore the low bit in the target, since it will be set
16229          for a text label.  */
16230       if ((val & 1) != 0)
16231         --val;
16232
16233       addr = fragp->fr_address + fragp->fr_fix + 4;
16234
16235       val -= addr;
16236
16237       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
16238     }
16239   else if (fragp)
16240     /* If the symbol is not defined or it's in a different segment,
16241        assume the user knows what's going on and emit a short
16242        branch.  */
16243     toofar = FALSE;
16244   else
16245     toofar = TRUE;
16246
16247   if (fragp && update
16248       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16249     fragp->fr_subtype = (toofar
16250                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
16251                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
16252
16253   length = 4;
16254   if (toofar)
16255     {
16256       bfd_boolean compact_known = fragp != NULL;
16257       bfd_boolean compact = FALSE;
16258       bfd_boolean uncond;
16259
16260       if (compact_known)
16261         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16262       if (fragp)
16263         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
16264       else
16265         uncond = update < 0;
16266
16267       /* If label is out of range, we turn branch <br>:
16268
16269                 <br>    label                   # 4 bytes
16270             0:
16271
16272          into:
16273
16274                 j       label                   # 4 bytes
16275                 nop                             # 2 bytes if compact && !PIC
16276             0:
16277        */
16278       if (mips_pic == NO_PIC && (!compact_known || compact))
16279         length += 2;
16280
16281       /* If assembling PIC code, we further turn:
16282
16283                         j       label                   # 4 bytes
16284
16285          into:
16286
16287                         lw/ld   at, %got(label)(gp)     # 4 bytes
16288                         d/addiu at, %lo(label)          # 4 bytes
16289                         jr/c    at                      # 2 bytes
16290        */
16291       if (mips_pic != NO_PIC)
16292         length += 6;
16293
16294       /* If branch <br> is conditional, we prepend negated branch <brneg>:
16295
16296                         <brneg> 0f                      # 4 bytes
16297                         nop                             # 2 bytes if !compact
16298        */
16299       if (!uncond)
16300         length += (compact_known && compact) ? 4 : 6;
16301     }
16302
16303   return length;
16304 }
16305
16306 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
16307    bit accordingly.  */
16308
16309 static int
16310 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
16311 {
16312   bfd_boolean toofar;
16313
16314   if (fragp
16315       && S_IS_DEFINED (fragp->fr_symbol)
16316       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16317     {
16318       addressT addr;
16319       offsetT val;
16320       int type;
16321
16322       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16323       /* Ignore the low bit in the target, since it will be set
16324          for a text label.  */
16325       if ((val & 1) != 0)
16326         --val;
16327
16328       /* Assume this is a 2-byte branch.  */
16329       addr = fragp->fr_address + fragp->fr_fix + 2;
16330
16331       /* We try to avoid the infinite loop by not adding 2 more bytes for
16332          long branches.  */
16333
16334       val -= addr;
16335
16336       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16337       if (type == 'D')
16338         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
16339       else if (type == 'E')
16340         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
16341       else
16342         abort ();
16343     }
16344   else
16345     /* If the symbol is not defined or it's in a different segment,
16346        we emit a normal 32-bit branch.  */
16347     toofar = TRUE;
16348
16349   if (fragp && update
16350       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16351     fragp->fr_subtype
16352       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
16353                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
16354
16355   if (toofar)
16356     return 4;
16357
16358   return 2;
16359 }
16360
16361 /* Estimate the size of a frag before relaxing.  Unless this is the
16362    mips16, we are not really relaxing here, and the final size is
16363    encoded in the subtype information.  For the mips16, we have to
16364    decide whether we are using an extended opcode or not.  */
16365
16366 int
16367 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
16368 {
16369   int change;
16370
16371   if (RELAX_BRANCH_P (fragp->fr_subtype))
16372     {
16373
16374       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
16375
16376       return fragp->fr_var;
16377     }
16378
16379   if (RELAX_MIPS16_P (fragp->fr_subtype))
16380     /* We don't want to modify the EXTENDED bit here; it might get us
16381        into infinite loops.  We change it only in mips_relax_frag().  */
16382     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
16383
16384   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16385     {
16386       int length = 4;
16387
16388       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16389         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
16390       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16391         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
16392       fragp->fr_var = length;
16393
16394       return length;
16395     }
16396
16397   if (mips_pic == NO_PIC)
16398     change = nopic_need_relax (fragp->fr_symbol, 0);
16399   else if (mips_pic == SVR4_PIC)
16400     change = pic_need_relax (fragp->fr_symbol, segtype);
16401   else if (mips_pic == VXWORKS_PIC)
16402     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
16403     change = 0;
16404   else
16405     abort ();
16406
16407   if (change)
16408     {
16409       fragp->fr_subtype |= RELAX_USE_SECOND;
16410       return -RELAX_FIRST (fragp->fr_subtype);
16411     }
16412   else
16413     return -RELAX_SECOND (fragp->fr_subtype);
16414 }
16415
16416 /* This is called to see whether a reloc against a defined symbol
16417    should be converted into a reloc against a section.  */
16418
16419 int
16420 mips_fix_adjustable (fixS *fixp)
16421 {
16422   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
16423       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16424     return 0;
16425
16426   if (fixp->fx_addsy == NULL)
16427     return 1;
16428
16429   /* If symbol SYM is in a mergeable section, relocations of the form
16430      SYM + 0 can usually be made section-relative.  The mergeable data
16431      is then identified by the section offset rather than by the symbol.
16432
16433      However, if we're generating REL LO16 relocations, the offset is split
16434      between the LO16 and parterning high part relocation.  The linker will
16435      need to recalculate the complete offset in order to correctly identify
16436      the merge data.
16437
16438      The linker has traditionally not looked for the parterning high part
16439      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
16440      placed anywhere.  Rather than break backwards compatibility by changing
16441      this, it seems better not to force the issue, and instead keep the
16442      original symbol.  This will work with either linker behavior.  */
16443   if ((lo16_reloc_p (fixp->fx_r_type)
16444        || reloc_needs_lo_p (fixp->fx_r_type))
16445       && HAVE_IN_PLACE_ADDENDS
16446       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
16447     return 0;
16448
16449   /* There is no place to store an in-place offset for JALR relocations.
16450      Likewise an in-range offset of limited PC-relative relocations may
16451      overflow the in-place relocatable field if recalculated against the
16452      start address of the symbol's containing section.  */
16453   if (HAVE_IN_PLACE_ADDENDS
16454       && (limited_pcrel_reloc_p (fixp->fx_r_type)
16455           || jalr_reloc_p (fixp->fx_r_type)))
16456     return 0;
16457
16458   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
16459      to a floating-point stub.  The same is true for non-R_MIPS16_26
16460      relocations against MIPS16 functions; in this case, the stub becomes
16461      the function's canonical address.
16462
16463      Floating-point stubs are stored in unique .mips16.call.* or
16464      .mips16.fn.* sections.  If a stub T for function F is in section S,
16465      the first relocation in section S must be against F; this is how the
16466      linker determines the target function.  All relocations that might
16467      resolve to T must also be against F.  We therefore have the following
16468      restrictions, which are given in an intentionally-redundant way:
16469
16470        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
16471           symbols.
16472
16473        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
16474           if that stub might be used.
16475
16476        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
16477           symbols.
16478
16479        4. We cannot reduce a stub's relocations against MIPS16 symbols if
16480           that stub might be used.
16481
16482      There is a further restriction:
16483
16484        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
16485           R_MICROMIPS_26_S1) against MIPS16 or microMIPS symbols on
16486           targets with in-place addends; the relocation field cannot
16487           encode the low bit.
16488
16489      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
16490      against a MIPS16 symbol.  We deal with (5) by by not reducing any
16491      such relocations on REL targets.
16492
16493      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
16494      relocation against some symbol R, no relocation against R may be
16495      reduced.  (Note that this deals with (2) as well as (1) because
16496      relocations against global symbols will never be reduced on ELF
16497      targets.)  This approach is a little simpler than trying to detect
16498      stub sections, and gives the "all or nothing" per-symbol consistency
16499      that we have for MIPS16 symbols.  */
16500   if (fixp->fx_subsy == NULL
16501       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
16502           || *symbol_get_tc (fixp->fx_addsy)
16503           || (HAVE_IN_PLACE_ADDENDS
16504               && ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
16505               && jmp_reloc_p (fixp->fx_r_type))))
16506     return 0;
16507
16508   return 1;
16509 }
16510
16511 /* Translate internal representation of relocation info to BFD target
16512    format.  */
16513
16514 arelent **
16515 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
16516 {
16517   static arelent *retval[4];
16518   arelent *reloc;
16519   bfd_reloc_code_real_type code;
16520
16521   memset (retval, 0, sizeof(retval));
16522   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
16523   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
16524   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
16525   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
16526
16527   if (fixp->fx_pcrel)
16528     {
16529       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
16530                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
16531                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
16532                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
16533                   || fixp->fx_r_type == BFD_RELOC_32_PCREL);
16534
16535       /* At this point, fx_addnumber is "symbol offset - pcrel address".
16536          Relocations want only the symbol offset.  */
16537       reloc->addend = fixp->fx_addnumber + reloc->address;
16538     }
16539   else
16540     reloc->addend = fixp->fx_addnumber;
16541
16542   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
16543      entry to be used in the relocation's section offset.  */
16544   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16545     {
16546       reloc->address = reloc->addend;
16547       reloc->addend = 0;
16548     }
16549
16550   code = fixp->fx_r_type;
16551
16552   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
16553   if (reloc->howto == NULL)
16554     {
16555       as_bad_where (fixp->fx_file, fixp->fx_line,
16556                     _("cannot represent %s relocation in this object file"
16557                       " format"),
16558                     bfd_get_reloc_code_name (code));
16559       retval[0] = NULL;
16560     }
16561
16562   return retval;
16563 }
16564
16565 /* Relax a machine dependent frag.  This returns the amount by which
16566    the current size of the frag should change.  */
16567
16568 int
16569 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
16570 {
16571   if (RELAX_BRANCH_P (fragp->fr_subtype))
16572     {
16573       offsetT old_var = fragp->fr_var;
16574
16575       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
16576
16577       return fragp->fr_var - old_var;
16578     }
16579
16580   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16581     {
16582       offsetT old_var = fragp->fr_var;
16583       offsetT new_var = 4;
16584
16585       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16586         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
16587       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16588         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
16589       fragp->fr_var = new_var;
16590
16591       return new_var - old_var;
16592     }
16593
16594   if (! RELAX_MIPS16_P (fragp->fr_subtype))
16595     return 0;
16596
16597   if (mips16_extended_frag (fragp, NULL, stretch))
16598     {
16599       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16600         return 0;
16601       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
16602       return 2;
16603     }
16604   else
16605     {
16606       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16607         return 0;
16608       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
16609       return -2;
16610     }
16611
16612   return 0;
16613 }
16614
16615 /* Convert a machine dependent frag.  */
16616
16617 void
16618 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
16619 {
16620   if (RELAX_BRANCH_P (fragp->fr_subtype))
16621     {
16622       char *buf;
16623       unsigned long insn;
16624       expressionS exp;
16625       fixS *fixp;
16626
16627       buf = fragp->fr_literal + fragp->fr_fix;
16628       insn = read_insn (buf);
16629
16630       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16631         {
16632           /* We generate a fixup instead of applying it right now
16633              because, if there are linker relaxations, we're going to
16634              need the relocations.  */
16635           exp.X_op = O_symbol;
16636           exp.X_add_symbol = fragp->fr_symbol;
16637           exp.X_add_number = fragp->fr_offset;
16638
16639           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16640                               BFD_RELOC_16_PCREL_S2);
16641           fixp->fx_file = fragp->fr_file;
16642           fixp->fx_line = fragp->fr_line;
16643
16644           buf = write_insn (buf, insn);
16645         }
16646       else
16647         {
16648           int i;
16649
16650           as_warn_where (fragp->fr_file, fragp->fr_line,
16651                          _("relaxed out-of-range branch into a jump"));
16652
16653           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
16654             goto uncond;
16655
16656           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16657             {
16658               /* Reverse the branch.  */
16659               switch ((insn >> 28) & 0xf)
16660                 {
16661                 case 4:
16662                   if ((insn & 0xff000000) == 0x47000000
16663                       || (insn & 0xff600000) == 0x45600000)
16664                     {
16665                       /* BZ.df/BNZ.df, BZ.V/BNZ.V can have the condition
16666                          reversed by tweaking bit 23.  */
16667                       insn ^= 0x00800000;
16668                     }
16669                   else
16670                     {
16671                       /* bc[0-3][tf]l? instructions can have the condition
16672                          reversed by tweaking a single TF bit, and their
16673                          opcodes all have 0x4???????.  */
16674                       gas_assert ((insn & 0xf3e00000) == 0x41000000);
16675                       insn ^= 0x00010000;
16676                     }
16677                   break;
16678
16679                 case 0:
16680                   /* bltz       0x04000000      bgez    0x04010000
16681                      bltzal     0x04100000      bgezal  0x04110000  */
16682                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
16683                   insn ^= 0x00010000;
16684                   break;
16685
16686                 case 1:
16687                   /* beq        0x10000000      bne     0x14000000
16688                      blez       0x18000000      bgtz    0x1c000000  */
16689                   insn ^= 0x04000000;
16690                   break;
16691
16692                 default:
16693                   abort ();
16694                 }
16695             }
16696
16697           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16698             {
16699               /* Clear the and-link bit.  */
16700               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
16701
16702               /* bltzal         0x04100000      bgezal  0x04110000
16703                  bltzall        0x04120000      bgezall 0x04130000  */
16704               insn &= ~0x00100000;
16705             }
16706
16707           /* Branch over the branch (if the branch was likely) or the
16708              full jump (not likely case).  Compute the offset from the
16709              current instruction to branch to.  */
16710           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16711             i = 16;
16712           else
16713             {
16714               /* How many bytes in instructions we've already emitted?  */
16715               i = buf - fragp->fr_literal - fragp->fr_fix;
16716               /* How many bytes in instructions from here to the end?  */
16717               i = fragp->fr_var - i;
16718             }
16719           /* Convert to instruction count.  */
16720           i >>= 2;
16721           /* Branch counts from the next instruction.  */
16722           i--;
16723           insn |= i;
16724           /* Branch over the jump.  */
16725           buf = write_insn (buf, insn);
16726
16727           /* nop */
16728           buf = write_insn (buf, 0);
16729
16730           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16731             {
16732               /* beql $0, $0, 2f */
16733               insn = 0x50000000;
16734               /* Compute the PC offset from the current instruction to
16735                  the end of the variable frag.  */
16736               /* How many bytes in instructions we've already emitted?  */
16737               i = buf - fragp->fr_literal - fragp->fr_fix;
16738               /* How many bytes in instructions from here to the end?  */
16739               i = fragp->fr_var - i;
16740               /* Convert to instruction count.  */
16741               i >>= 2;
16742               /* Don't decrement i, because we want to branch over the
16743                  delay slot.  */
16744               insn |= i;
16745
16746               buf = write_insn (buf, insn);
16747               buf = write_insn (buf, 0);
16748             }
16749
16750         uncond:
16751           if (mips_pic == NO_PIC)
16752             {
16753               /* j or jal.  */
16754               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
16755                       ? 0x0c000000 : 0x08000000);
16756               exp.X_op = O_symbol;
16757               exp.X_add_symbol = fragp->fr_symbol;
16758               exp.X_add_number = fragp->fr_offset;
16759
16760               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16761                                   FALSE, BFD_RELOC_MIPS_JMP);
16762               fixp->fx_file = fragp->fr_file;
16763               fixp->fx_line = fragp->fr_line;
16764
16765               buf = write_insn (buf, insn);
16766             }
16767           else
16768             {
16769               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
16770
16771               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
16772               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
16773               insn |= at << OP_SH_RT;
16774               exp.X_op = O_symbol;
16775               exp.X_add_symbol = fragp->fr_symbol;
16776               exp.X_add_number = fragp->fr_offset;
16777
16778               if (fragp->fr_offset)
16779                 {
16780                   exp.X_add_symbol = make_expr_symbol (&exp);
16781                   exp.X_add_number = 0;
16782                 }
16783
16784               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16785                                   FALSE, BFD_RELOC_MIPS_GOT16);
16786               fixp->fx_file = fragp->fr_file;
16787               fixp->fx_line = fragp->fr_line;
16788
16789               buf = write_insn (buf, insn);
16790
16791               if (mips_opts.isa == ISA_MIPS1)
16792                 /* nop */
16793                 buf = write_insn (buf, 0);
16794
16795               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
16796               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
16797               insn |= at << OP_SH_RS | at << OP_SH_RT;
16798
16799               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16800                                   FALSE, BFD_RELOC_LO16);
16801               fixp->fx_file = fragp->fr_file;
16802               fixp->fx_line = fragp->fr_line;
16803
16804               buf = write_insn (buf, insn);
16805
16806               /* j(al)r $at.  */
16807               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16808                 insn = 0x0000f809;
16809               else
16810                 insn = 0x00000008;
16811               insn |= at << OP_SH_RS;
16812
16813               buf = write_insn (buf, insn);
16814             }
16815         }
16816
16817       fragp->fr_fix += fragp->fr_var;
16818       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16819       return;
16820     }
16821
16822   /* Relax microMIPS branches.  */
16823   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16824     {
16825       char *buf = fragp->fr_literal + fragp->fr_fix;
16826       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16827       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
16828       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16829       bfd_boolean short_ds;
16830       unsigned long insn;
16831       expressionS exp;
16832       fixS *fixp;
16833
16834       exp.X_op = O_symbol;
16835       exp.X_add_symbol = fragp->fr_symbol;
16836       exp.X_add_number = fragp->fr_offset;
16837
16838       fragp->fr_fix += fragp->fr_var;
16839
16840       /* Handle 16-bit branches that fit or are forced to fit.  */
16841       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16842         {
16843           /* We generate a fixup instead of applying it right now,
16844              because if there is linker relaxation, we're going to
16845              need the relocations.  */
16846           if (type == 'D')
16847             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16848                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
16849           else if (type == 'E')
16850             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16851                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
16852           else
16853             abort ();
16854
16855           fixp->fx_file = fragp->fr_file;
16856           fixp->fx_line = fragp->fr_line;
16857
16858           /* These relocations can have an addend that won't fit in
16859              2 octets.  */
16860           fixp->fx_no_overflow = 1;
16861
16862           return;
16863         }
16864
16865       /* Handle 32-bit branches that fit or are forced to fit.  */
16866       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16867           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16868         {
16869           /* We generate a fixup instead of applying it right now,
16870              because if there is linker relaxation, we're going to
16871              need the relocations.  */
16872           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16873                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
16874           fixp->fx_file = fragp->fr_file;
16875           fixp->fx_line = fragp->fr_line;
16876
16877           if (type == 0)
16878             return;
16879         }
16880
16881       /* Relax 16-bit branches to 32-bit branches.  */
16882       if (type != 0)
16883         {
16884           insn = read_compressed_insn (buf, 2);
16885
16886           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
16887             insn = 0x94000000;                          /* beq  */
16888           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
16889             {
16890               unsigned long regno;
16891
16892               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
16893               regno = micromips_to_32_reg_d_map [regno];
16894               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
16895               insn |= regno << MICROMIPSOP_SH_RS;
16896             }
16897           else
16898             abort ();
16899
16900           /* Nothing else to do, just write it out.  */
16901           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16902               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16903             {
16904               buf = write_compressed_insn (buf, insn, 4);
16905               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16906               return;
16907             }
16908         }
16909       else
16910         insn = read_compressed_insn (buf, 4);
16911
16912       /* Relax 32-bit branches to a sequence of instructions.  */
16913       as_warn_where (fragp->fr_file, fragp->fr_line,
16914                      _("relaxed out-of-range branch into a jump"));
16915
16916       /* Set the short-delay-slot bit.  */
16917       short_ds = al && (insn & 0x02000000) != 0;
16918
16919       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
16920         {
16921           symbolS *l;
16922
16923           /* Reverse the branch.  */
16924           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
16925               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
16926             insn ^= 0x20000000;
16927           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
16928                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
16929                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
16930                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
16931                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
16932                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
16933                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
16934                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
16935                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
16936                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
16937             insn ^= 0x00400000;
16938           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
16939                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
16940                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
16941                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
16942             insn ^= 0x00200000;
16943           else if ((insn & 0xff000000) == 0x83000000            /* BZ.df
16944                                                                    BNZ.df  */
16945                     || (insn & 0xff600000) == 0x81600000)       /* BZ.V
16946                                                                    BNZ.V */
16947             insn ^= 0x00800000;
16948           else
16949             abort ();
16950
16951           if (al)
16952             {
16953               /* Clear the and-link and short-delay-slot bits.  */
16954               gas_assert ((insn & 0xfda00000) == 0x40200000);
16955
16956               /* bltzal  0x40200000     bgezal  0x40600000  */
16957               /* bltzals 0x42200000     bgezals 0x42600000  */
16958               insn &= ~0x02200000;
16959             }
16960
16961           /* Make a label at the end for use with the branch.  */
16962           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
16963           micromips_label_inc ();
16964           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
16965
16966           /* Refer to it.  */
16967           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
16968                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
16969           fixp->fx_file = fragp->fr_file;
16970           fixp->fx_line = fragp->fr_line;
16971
16972           /* Branch over the jump.  */
16973           buf = write_compressed_insn (buf, insn, 4);
16974           if (!compact)
16975             /* nop */
16976             buf = write_compressed_insn (buf, 0x0c00, 2);
16977         }
16978
16979       if (mips_pic == NO_PIC)
16980         {
16981           unsigned long jal = short_ds ? 0x74000000 : 0xf4000000; /* jal/s  */
16982
16983           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
16984           insn = al ? jal : 0xd4000000;
16985
16986           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16987                               BFD_RELOC_MICROMIPS_JMP);
16988           fixp->fx_file = fragp->fr_file;
16989           fixp->fx_line = fragp->fr_line;
16990
16991           buf = write_compressed_insn (buf, insn, 4);
16992           if (compact)
16993             /* nop */
16994             buf = write_compressed_insn (buf, 0x0c00, 2);
16995         }
16996       else
16997         {
16998           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
16999           unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;      /* jalr/s  */
17000           unsigned long jr = compact ? 0x45a0 : 0x4580;         /* jr/c  */
17001
17002           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
17003           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
17004           insn |= at << MICROMIPSOP_SH_RT;
17005
17006           if (exp.X_add_number)
17007             {
17008               exp.X_add_symbol = make_expr_symbol (&exp);
17009               exp.X_add_number = 0;
17010             }
17011
17012           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
17013                               BFD_RELOC_MICROMIPS_GOT16);
17014           fixp->fx_file = fragp->fr_file;
17015           fixp->fx_line = fragp->fr_line;
17016
17017           buf = write_compressed_insn (buf, insn, 4);
17018
17019           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
17020           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
17021           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
17022
17023           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
17024                               BFD_RELOC_MICROMIPS_LO16);
17025           fixp->fx_file = fragp->fr_file;
17026           fixp->fx_line = fragp->fr_line;
17027
17028           buf = write_compressed_insn (buf, insn, 4);
17029
17030           /* jr/jrc/jalr/jalrs $at  */
17031           insn = al ? jalr : jr;
17032           insn |= at << MICROMIPSOP_SH_MJ;
17033
17034           buf = write_compressed_insn (buf, insn, 2);
17035         }
17036
17037       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
17038       return;
17039     }
17040
17041   if (RELAX_MIPS16_P (fragp->fr_subtype))
17042     {
17043       int type;
17044       const struct mips_int_operand *operand;
17045       offsetT val;
17046       char *buf;
17047       unsigned int user_length, length;
17048       unsigned long insn;
17049       bfd_boolean ext;
17050
17051       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17052       operand = mips16_immed_operand (type, FALSE);
17053
17054       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
17055       val = resolve_symbol_value (fragp->fr_symbol);
17056       if (operand->root.type == OP_PCREL)
17057         {
17058           const struct mips_pcrel_operand *pcrel_op;
17059           addressT addr;
17060
17061           pcrel_op = (const struct mips_pcrel_operand *) operand;
17062           addr = fragp->fr_address + fragp->fr_fix;
17063
17064           /* The rules for the base address of a PC relative reloc are
17065              complicated; see mips16_extended_frag.  */
17066           if (pcrel_op->include_isa_bit)
17067             {
17068               addr += 2;
17069               if (ext)
17070                 addr += 2;
17071               /* Ignore the low bit in the target, since it will be
17072                  set for a text label.  */
17073               val &= -2;
17074             }
17075           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17076             addr -= 4;
17077           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17078             addr -= 2;
17079
17080           addr &= -(1 << pcrel_op->align_log2);
17081           val -= addr;
17082
17083           /* Make sure the section winds up with the alignment we have
17084              assumed.  */
17085           if (operand->shift > 0)
17086             record_alignment (asec, operand->shift);
17087         }
17088
17089       if (ext
17090           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
17091               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
17092         as_warn_where (fragp->fr_file, fragp->fr_line,
17093                        _("extended instruction in delay slot"));
17094
17095       buf = fragp->fr_literal + fragp->fr_fix;
17096
17097       insn = read_compressed_insn (buf, 2);
17098       if (ext)
17099         insn |= MIPS16_EXTEND;
17100
17101       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17102         user_length = 4;
17103       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
17104         user_length = 2;
17105       else
17106         user_length = 0;
17107
17108       mips16_immed (fragp->fr_file, fragp->fr_line, type,
17109                     BFD_RELOC_UNUSED, val, user_length, &insn);
17110
17111       length = (ext ? 4 : 2);
17112       gas_assert (mips16_opcode_length (insn) == length);
17113       write_compressed_insn (buf, insn, length);
17114       fragp->fr_fix += length;
17115     }
17116   else
17117     {
17118       relax_substateT subtype = fragp->fr_subtype;
17119       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
17120       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
17121       int first, second;
17122       fixS *fixp;
17123
17124       first = RELAX_FIRST (subtype);
17125       second = RELAX_SECOND (subtype);
17126       fixp = (fixS *) fragp->fr_opcode;
17127
17128       /* If the delay slot chosen does not match the size of the instruction,
17129          then emit a warning.  */
17130       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
17131            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
17132         {
17133           relax_substateT s;
17134           const char *msg;
17135
17136           s = subtype & (RELAX_DELAY_SLOT_16BIT
17137                          | RELAX_DELAY_SLOT_SIZE_FIRST
17138                          | RELAX_DELAY_SLOT_SIZE_SECOND);
17139           msg = macro_warning (s);
17140           if (msg != NULL)
17141             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
17142           subtype &= ~s;
17143         }
17144
17145       /* Possibly emit a warning if we've chosen the longer option.  */
17146       if (use_second == second_longer)
17147         {
17148           relax_substateT s;
17149           const char *msg;
17150
17151           s = (subtype
17152                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
17153           msg = macro_warning (s);
17154           if (msg != NULL)
17155             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
17156           subtype &= ~s;
17157         }
17158
17159       /* Go through all the fixups for the first sequence.  Disable them
17160          (by marking them as done) if we're going to use the second
17161          sequence instead.  */
17162       while (fixp
17163              && fixp->fx_frag == fragp
17164              && fixp->fx_where < fragp->fr_fix - second)
17165         {
17166           if (subtype & RELAX_USE_SECOND)
17167             fixp->fx_done = 1;
17168           fixp = fixp->fx_next;
17169         }
17170
17171       /* Go through the fixups for the second sequence.  Disable them if
17172          we're going to use the first sequence, otherwise adjust their
17173          addresses to account for the relaxation.  */
17174       while (fixp && fixp->fx_frag == fragp)
17175         {
17176           if (subtype & RELAX_USE_SECOND)
17177             fixp->fx_where -= first;
17178           else
17179             fixp->fx_done = 1;
17180           fixp = fixp->fx_next;
17181         }
17182
17183       /* Now modify the frag contents.  */
17184       if (subtype & RELAX_USE_SECOND)
17185         {
17186           char *start;
17187
17188           start = fragp->fr_literal + fragp->fr_fix - first - second;
17189           memmove (start, start + first, second);
17190           fragp->fr_fix -= first;
17191         }
17192       else
17193         fragp->fr_fix -= second;
17194     }
17195 }
17196
17197 /* This function is called after the relocs have been generated.
17198    We've been storing mips16 text labels as odd.  Here we convert them
17199    back to even for the convenience of the debugger.  */
17200
17201 void
17202 mips_frob_file_after_relocs (void)
17203 {
17204   asymbol **syms;
17205   unsigned int count, i;
17206
17207   syms = bfd_get_outsymbols (stdoutput);
17208   count = bfd_get_symcount (stdoutput);
17209   for (i = 0; i < count; i++, syms++)
17210     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
17211         && ((*syms)->value & 1) != 0)
17212       {
17213         (*syms)->value &= ~1;
17214         /* If the symbol has an odd size, it was probably computed
17215            incorrectly, so adjust that as well.  */
17216         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
17217           ++elf_symbol (*syms)->internal_elf_sym.st_size;
17218       }
17219 }
17220
17221 /* This function is called whenever a label is defined, including fake
17222    labels instantiated off the dot special symbol.  It is used when
17223    handling branch delays; if a branch has a label, we assume we cannot
17224    move it.  This also bumps the value of the symbol by 1 in compressed
17225    code.  */
17226
17227 static void
17228 mips_record_label (symbolS *sym)
17229 {
17230   segment_info_type *si = seg_info (now_seg);
17231   struct insn_label_list *l;
17232
17233   if (free_insn_labels == NULL)
17234     l = (struct insn_label_list *) xmalloc (sizeof *l);
17235   else
17236     {
17237       l = free_insn_labels;
17238       free_insn_labels = l->next;
17239     }
17240
17241   l->label = sym;
17242   l->next = si->label_list;
17243   si->label_list = l;
17244 }
17245
17246 /* This function is called as tc_frob_label() whenever a label is defined
17247    and adds a DWARF-2 record we only want for true labels.  */
17248
17249 void
17250 mips_define_label (symbolS *sym)
17251 {
17252   mips_record_label (sym);
17253   dwarf2_emit_label (sym);
17254 }
17255
17256 /* This function is called by tc_new_dot_label whenever a new dot symbol
17257    is defined.  */
17258
17259 void
17260 mips_add_dot_label (symbolS *sym)
17261 {
17262   mips_record_label (sym);
17263   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
17264     mips_compressed_mark_label (sym);
17265 }
17266 \f
17267 /* Some special processing for a MIPS ELF file.  */
17268
17269 void
17270 mips_elf_final_processing (void)
17271 {
17272   /* Write out the register information.  */
17273   if (mips_abi != N64_ABI)
17274     {
17275       Elf32_RegInfo s;
17276
17277       s.ri_gprmask = mips_gprmask;
17278       s.ri_cprmask[0] = mips_cprmask[0];
17279       s.ri_cprmask[1] = mips_cprmask[1];
17280       s.ri_cprmask[2] = mips_cprmask[2];
17281       s.ri_cprmask[3] = mips_cprmask[3];
17282       /* The gp_value field is set by the MIPS ELF backend.  */
17283
17284       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
17285                                        ((Elf32_External_RegInfo *)
17286                                         mips_regmask_frag));
17287     }
17288   else
17289     {
17290       Elf64_Internal_RegInfo s;
17291
17292       s.ri_gprmask = mips_gprmask;
17293       s.ri_pad = 0;
17294       s.ri_cprmask[0] = mips_cprmask[0];
17295       s.ri_cprmask[1] = mips_cprmask[1];
17296       s.ri_cprmask[2] = mips_cprmask[2];
17297       s.ri_cprmask[3] = mips_cprmask[3];
17298       /* The gp_value field is set by the MIPS ELF backend.  */
17299
17300       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
17301                                        ((Elf64_External_RegInfo *)
17302                                         mips_regmask_frag));
17303     }
17304
17305   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
17306      sort of BFD interface for this.  */
17307   if (mips_any_noreorder)
17308     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
17309   if (mips_pic != NO_PIC)
17310     {
17311       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
17312       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
17313     }
17314   if (mips_abicalls)
17315     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
17316
17317   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
17318      defined at present; this might need to change in future.  */
17319   if (file_ase_mips16)
17320     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
17321   if (file_ase_micromips)
17322     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
17323   if (file_ase & ASE_MDMX)
17324     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
17325
17326   /* Set the MIPS ELF ABI flags.  */
17327   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
17328     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
17329   else if (mips_abi == O64_ABI)
17330     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
17331   else if (mips_abi == EABI_ABI)
17332     {
17333       if (!file_mips_gp32)
17334         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
17335       else
17336         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
17337     }
17338   else if (mips_abi == N32_ABI)
17339     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
17340
17341   /* Nothing to do for N64_ABI.  */
17342
17343   if (mips_32bitmode)
17344     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
17345
17346   if (mips_flag_nan2008)
17347     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
17348
17349   /* 32 bit code with 64 bit FP registers.  */
17350   if (!file_mips_fp32 && ABI_NEEDS_32BIT_REGS (mips_abi))
17351     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_FP64;
17352 }
17353 \f
17354 typedef struct proc {
17355   symbolS *func_sym;
17356   symbolS *func_end_sym;
17357   unsigned long reg_mask;
17358   unsigned long reg_offset;
17359   unsigned long fpreg_mask;
17360   unsigned long fpreg_offset;
17361   unsigned long frame_offset;
17362   unsigned long frame_reg;
17363   unsigned long pc_reg;
17364 } procS;
17365
17366 static procS cur_proc;
17367 static procS *cur_proc_ptr;
17368 static int numprocs;
17369
17370 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
17371    as "2", and a normal nop as "0".  */
17372
17373 #define NOP_OPCODE_MIPS         0
17374 #define NOP_OPCODE_MIPS16       1
17375 #define NOP_OPCODE_MICROMIPS    2
17376
17377 char
17378 mips_nop_opcode (void)
17379 {
17380   if (seg_info (now_seg)->tc_segment_info_data.micromips)
17381     return NOP_OPCODE_MICROMIPS;
17382   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
17383     return NOP_OPCODE_MIPS16;
17384   else
17385     return NOP_OPCODE_MIPS;
17386 }
17387
17388 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
17389    32-bit microMIPS NOPs here (if applicable).  */
17390
17391 void
17392 mips_handle_align (fragS *fragp)
17393 {
17394   char nop_opcode;
17395   char *p;
17396   int bytes, size, excess;
17397   valueT opcode;
17398
17399   if (fragp->fr_type != rs_align_code)
17400     return;
17401
17402   p = fragp->fr_literal + fragp->fr_fix;
17403   nop_opcode = *p;
17404   switch (nop_opcode)
17405     {
17406     case NOP_OPCODE_MICROMIPS:
17407       opcode = micromips_nop32_insn.insn_opcode;
17408       size = 4;
17409       break;
17410     case NOP_OPCODE_MIPS16:
17411       opcode = mips16_nop_insn.insn_opcode;
17412       size = 2;
17413       break;
17414     case NOP_OPCODE_MIPS:
17415     default:
17416       opcode = nop_insn.insn_opcode;
17417       size = 4;
17418       break;
17419     }
17420
17421   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
17422   excess = bytes % size;
17423
17424   /* Handle the leading part if we're not inserting a whole number of
17425      instructions, and make it the end of the fixed part of the frag.
17426      Try to fit in a short microMIPS NOP if applicable and possible,
17427      and use zeroes otherwise.  */
17428   gas_assert (excess < 4);
17429   fragp->fr_fix += excess;
17430   switch (excess)
17431     {
17432     case 3:
17433       *p++ = '\0';
17434       /* Fall through.  */
17435     case 2:
17436       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
17437         {
17438           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
17439           break;
17440         }
17441       *p++ = '\0';
17442       /* Fall through.  */
17443     case 1:
17444       *p++ = '\0';
17445       /* Fall through.  */
17446     case 0:
17447       break;
17448     }
17449
17450   md_number_to_chars (p, opcode, size);
17451   fragp->fr_var = size;
17452 }
17453
17454 static void
17455 md_obj_begin (void)
17456 {
17457 }
17458
17459 static void
17460 md_obj_end (void)
17461 {
17462   /* Check for premature end, nesting errors, etc.  */
17463   if (cur_proc_ptr)
17464     as_warn (_("missing .end at end of assembly"));
17465 }
17466
17467 static long
17468 get_number (void)
17469 {
17470   int negative = 0;
17471   long val = 0;
17472
17473   if (*input_line_pointer == '-')
17474     {
17475       ++input_line_pointer;
17476       negative = 1;
17477     }
17478   if (!ISDIGIT (*input_line_pointer))
17479     as_bad (_("expected simple number"));
17480   if (input_line_pointer[0] == '0')
17481     {
17482       if (input_line_pointer[1] == 'x')
17483         {
17484           input_line_pointer += 2;
17485           while (ISXDIGIT (*input_line_pointer))
17486             {
17487               val <<= 4;
17488               val |= hex_value (*input_line_pointer++);
17489             }
17490           return negative ? -val : val;
17491         }
17492       else
17493         {
17494           ++input_line_pointer;
17495           while (ISDIGIT (*input_line_pointer))
17496             {
17497               val <<= 3;
17498               val |= *input_line_pointer++ - '0';
17499             }
17500           return negative ? -val : val;
17501         }
17502     }
17503   if (!ISDIGIT (*input_line_pointer))
17504     {
17505       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
17506               *input_line_pointer, *input_line_pointer);
17507       as_warn (_("invalid number"));
17508       return -1;
17509     }
17510   while (ISDIGIT (*input_line_pointer))
17511     {
17512       val *= 10;
17513       val += *input_line_pointer++ - '0';
17514     }
17515   return negative ? -val : val;
17516 }
17517
17518 /* The .file directive; just like the usual .file directive, but there
17519    is an initial number which is the ECOFF file index.  In the non-ECOFF
17520    case .file implies DWARF-2.  */
17521
17522 static void
17523 s_mips_file (int x ATTRIBUTE_UNUSED)
17524 {
17525   static int first_file_directive = 0;
17526
17527   if (ECOFF_DEBUGGING)
17528     {
17529       get_number ();
17530       s_app_file (0);
17531     }
17532   else
17533     {
17534       char *filename;
17535
17536       filename = dwarf2_directive_file (0);
17537
17538       /* Versions of GCC up to 3.1 start files with a ".file"
17539          directive even for stabs output.  Make sure that this
17540          ".file" is handled.  Note that you need a version of GCC
17541          after 3.1 in order to support DWARF-2 on MIPS.  */
17542       if (filename != NULL && ! first_file_directive)
17543         {
17544           (void) new_logical_line (filename, -1);
17545           s_app_file_string (filename, 0);
17546         }
17547       first_file_directive = 1;
17548     }
17549 }
17550
17551 /* The .loc directive, implying DWARF-2.  */
17552
17553 static void
17554 s_mips_loc (int x ATTRIBUTE_UNUSED)
17555 {
17556   if (!ECOFF_DEBUGGING)
17557     dwarf2_directive_loc (0);
17558 }
17559
17560 /* The .end directive.  */
17561
17562 static void
17563 s_mips_end (int x ATTRIBUTE_UNUSED)
17564 {
17565   symbolS *p;
17566
17567   /* Following functions need their own .frame and .cprestore directives.  */
17568   mips_frame_reg_valid = 0;
17569   mips_cprestore_valid = 0;
17570
17571   if (!is_end_of_line[(unsigned char) *input_line_pointer])
17572     {
17573       p = get_symbol ();
17574       demand_empty_rest_of_line ();
17575     }
17576   else
17577     p = NULL;
17578
17579   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17580     as_warn (_(".end not in text section"));
17581
17582   if (!cur_proc_ptr)
17583     {
17584       as_warn (_(".end directive without a preceding .ent directive"));
17585       demand_empty_rest_of_line ();
17586       return;
17587     }
17588
17589   if (p != NULL)
17590     {
17591       gas_assert (S_GET_NAME (p));
17592       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
17593         as_warn (_(".end symbol does not match .ent symbol"));
17594
17595       if (debug_type == DEBUG_STABS)
17596         stabs_generate_asm_endfunc (S_GET_NAME (p),
17597                                     S_GET_NAME (p));
17598     }
17599   else
17600     as_warn (_(".end directive missing or unknown symbol"));
17601
17602   /* Create an expression to calculate the size of the function.  */
17603   if (p && cur_proc_ptr)
17604     {
17605       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
17606       expressionS *exp = xmalloc (sizeof (expressionS));
17607
17608       obj->size = exp;
17609       exp->X_op = O_subtract;
17610       exp->X_add_symbol = symbol_temp_new_now ();
17611       exp->X_op_symbol = p;
17612       exp->X_add_number = 0;
17613
17614       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
17615     }
17616
17617   /* Generate a .pdr section.  */
17618   if (!ECOFF_DEBUGGING && mips_flag_pdr)
17619     {
17620       segT saved_seg = now_seg;
17621       subsegT saved_subseg = now_subseg;
17622       expressionS exp;
17623       char *fragp;
17624
17625 #ifdef md_flush_pending_output
17626       md_flush_pending_output ();
17627 #endif
17628
17629       gas_assert (pdr_seg);
17630       subseg_set (pdr_seg, 0);
17631
17632       /* Write the symbol.  */
17633       exp.X_op = O_symbol;
17634       exp.X_add_symbol = p;
17635       exp.X_add_number = 0;
17636       emit_expr (&exp, 4);
17637
17638       fragp = frag_more (7 * 4);
17639
17640       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
17641       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
17642       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
17643       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
17644       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
17645       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
17646       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
17647
17648       subseg_set (saved_seg, saved_subseg);
17649     }
17650
17651   cur_proc_ptr = NULL;
17652 }
17653
17654 /* The .aent and .ent directives.  */
17655
17656 static void
17657 s_mips_ent (int aent)
17658 {
17659   symbolS *symbolP;
17660
17661   symbolP = get_symbol ();
17662   if (*input_line_pointer == ',')
17663     ++input_line_pointer;
17664   SKIP_WHITESPACE ();
17665   if (ISDIGIT (*input_line_pointer)
17666       || *input_line_pointer == '-')
17667     get_number ();
17668
17669   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17670     as_warn (_(".ent or .aent not in text section"));
17671
17672   if (!aent && cur_proc_ptr)
17673     as_warn (_("missing .end"));
17674
17675   if (!aent)
17676     {
17677       /* This function needs its own .frame and .cprestore directives.  */
17678       mips_frame_reg_valid = 0;
17679       mips_cprestore_valid = 0;
17680
17681       cur_proc_ptr = &cur_proc;
17682       memset (cur_proc_ptr, '\0', sizeof (procS));
17683
17684       cur_proc_ptr->func_sym = symbolP;
17685
17686       ++numprocs;
17687
17688       if (debug_type == DEBUG_STABS)
17689         stabs_generate_asm_func (S_GET_NAME (symbolP),
17690                                  S_GET_NAME (symbolP));
17691     }
17692
17693   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
17694
17695   demand_empty_rest_of_line ();
17696 }
17697
17698 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
17699    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
17700    s_mips_frame is used so that we can set the PDR information correctly.
17701    We can't use the ecoff routines because they make reference to the ecoff
17702    symbol table (in the mdebug section).  */
17703
17704 static void
17705 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
17706 {
17707   if (ECOFF_DEBUGGING)
17708     s_ignore (ignore);
17709   else
17710     {
17711       long val;
17712
17713       if (cur_proc_ptr == (procS *) NULL)
17714         {
17715           as_warn (_(".frame outside of .ent"));
17716           demand_empty_rest_of_line ();
17717           return;
17718         }
17719
17720       cur_proc_ptr->frame_reg = tc_get_register (1);
17721
17722       SKIP_WHITESPACE ();
17723       if (*input_line_pointer++ != ','
17724           || get_absolute_expression_and_terminator (&val) != ',')
17725         {
17726           as_warn (_("bad .frame directive"));
17727           --input_line_pointer;
17728           demand_empty_rest_of_line ();
17729           return;
17730         }
17731
17732       cur_proc_ptr->frame_offset = val;
17733       cur_proc_ptr->pc_reg = tc_get_register (0);
17734
17735       demand_empty_rest_of_line ();
17736     }
17737 }
17738
17739 /* The .fmask and .mask directives. If the mdebug section is present
17740    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
17741    embedded targets, s_mips_mask is used so that we can set the PDR
17742    information correctly. We can't use the ecoff routines because they
17743    make reference to the ecoff symbol table (in the mdebug section).  */
17744
17745 static void
17746 s_mips_mask (int reg_type)
17747 {
17748   if (ECOFF_DEBUGGING)
17749     s_ignore (reg_type);
17750   else
17751     {
17752       long mask, off;
17753
17754       if (cur_proc_ptr == (procS *) NULL)
17755         {
17756           as_warn (_(".mask/.fmask outside of .ent"));
17757           demand_empty_rest_of_line ();
17758           return;
17759         }
17760
17761       if (get_absolute_expression_and_terminator (&mask) != ',')
17762         {
17763           as_warn (_("bad .mask/.fmask directive"));
17764           --input_line_pointer;
17765           demand_empty_rest_of_line ();
17766           return;
17767         }
17768
17769       off = get_absolute_expression ();
17770
17771       if (reg_type == 'F')
17772         {
17773           cur_proc_ptr->fpreg_mask = mask;
17774           cur_proc_ptr->fpreg_offset = off;
17775         }
17776       else
17777         {
17778           cur_proc_ptr->reg_mask = mask;
17779           cur_proc_ptr->reg_offset = off;
17780         }
17781
17782       demand_empty_rest_of_line ();
17783     }
17784 }
17785
17786 /* A table describing all the processors gas knows about.  Names are
17787    matched in the order listed.
17788
17789    To ease comparison, please keep this table in the same order as
17790    gcc's mips_cpu_info_table[].  */
17791 static const struct mips_cpu_info mips_cpu_info_table[] =
17792 {
17793   /* Entries for generic ISAs */
17794   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
17795   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
17796   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
17797   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
17798   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
17799   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
17800   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
17801   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
17802   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
17803
17804   /* MIPS I */
17805   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17806   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17807   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
17808
17809   /* MIPS II */
17810   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
17811
17812   /* MIPS III */
17813   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
17814   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
17815   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
17816   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17817   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17818   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17819   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17820   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
17821   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
17822   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17823   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17824   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
17825   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
17826   /* ST Microelectronics Loongson 2E and 2F cores */
17827   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
17828   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
17829
17830   /* MIPS IV */
17831   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
17832   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
17833   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
17834   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
17835   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
17836   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17837   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
17838   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
17839   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17840   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17841   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17842   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17843   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17844   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
17845   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
17846
17847   /* MIPS 32 */
17848   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17849   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17850   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17851   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
17852
17853   /* MIPS 32 Release 2 */
17854   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17855   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17856   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17857   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
17858   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17859   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17860   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17861   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17862   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17863                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17864   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17865                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17866   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17867   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17868   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17869   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17870   /* Deprecated forms of the above.  */
17871   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17872   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17873   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
17874   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17875   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17876   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17877   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17878   /* Deprecated forms of the above.  */
17879   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17880   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17881   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
17882   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17883   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17884   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17885   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17886   /* Deprecated forms of the above.  */
17887   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17888   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17889   /* 34Kn is a 34kc without DSP.  */
17890   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
17891   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
17892   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17893   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17894   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17895   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17896   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17897   /* Deprecated forms of the above.  */
17898   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17899   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17900   /* 1004K cores are multiprocessor versions of the 34K.  */
17901   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17902   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17903   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17904   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17905
17906   /* MIPS 64 */
17907   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17908   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17909   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17910   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17911
17912   /* Broadcom SB-1 CPU core */
17913   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17914   /* Broadcom SB-1A CPU core */
17915   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17916   
17917   { "loongson3a",     0, 0,                     ISA_MIPS64R2, CPU_LOONGSON_3A },
17918
17919   /* MIPS 64 Release 2 */
17920
17921   /* Cavium Networks Octeon CPU core */
17922   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
17923   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
17924   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
17925
17926   /* RMI Xlr */
17927   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
17928
17929   /* Broadcom XLP.
17930      XLP is mostly like XLR, with the prominent exception that it is
17931      MIPS64R2 rather than MIPS64.  */
17932   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
17933
17934   /* End marker */
17935   { NULL, 0, 0, 0, 0 }
17936 };
17937
17938
17939 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
17940    with a final "000" replaced by "k".  Ignore case.
17941
17942    Note: this function is shared between GCC and GAS.  */
17943
17944 static bfd_boolean
17945 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
17946 {
17947   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
17948     given++, canonical++;
17949
17950   return ((*given == 0 && *canonical == 0)
17951           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
17952 }
17953
17954
17955 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
17956    CPU name.  We've traditionally allowed a lot of variation here.
17957
17958    Note: this function is shared between GCC and GAS.  */
17959
17960 static bfd_boolean
17961 mips_matching_cpu_name_p (const char *canonical, const char *given)
17962 {
17963   /* First see if the name matches exactly, or with a final "000"
17964      turned into "k".  */
17965   if (mips_strict_matching_cpu_name_p (canonical, given))
17966     return TRUE;
17967
17968   /* If not, try comparing based on numerical designation alone.
17969      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
17970   if (TOLOWER (*given) == 'r')
17971     given++;
17972   if (!ISDIGIT (*given))
17973     return FALSE;
17974
17975   /* Skip over some well-known prefixes in the canonical name,
17976      hoping to find a number there too.  */
17977   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
17978     canonical += 2;
17979   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
17980     canonical += 2;
17981   else if (TOLOWER (canonical[0]) == 'r')
17982     canonical += 1;
17983
17984   return mips_strict_matching_cpu_name_p (canonical, given);
17985 }
17986
17987
17988 /* Parse an option that takes the name of a processor as its argument.
17989    OPTION is the name of the option and CPU_STRING is the argument.
17990    Return the corresponding processor enumeration if the CPU_STRING is
17991    recognized, otherwise report an error and return null.
17992
17993    A similar function exists in GCC.  */
17994
17995 static const struct mips_cpu_info *
17996 mips_parse_cpu (const char *option, const char *cpu_string)
17997 {
17998   const struct mips_cpu_info *p;
17999
18000   /* 'from-abi' selects the most compatible architecture for the given
18001      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
18002      EABIs, we have to decide whether we're using the 32-bit or 64-bit
18003      version.  Look first at the -mgp options, if given, otherwise base
18004      the choice on MIPS_DEFAULT_64BIT.
18005
18006      Treat NO_ABI like the EABIs.  One reason to do this is that the
18007      plain 'mips' and 'mips64' configs have 'from-abi' as their default
18008      architecture.  This code picks MIPS I for 'mips' and MIPS III for
18009      'mips64', just as we did in the days before 'from-abi'.  */
18010   if (strcasecmp (cpu_string, "from-abi") == 0)
18011     {
18012       if (ABI_NEEDS_32BIT_REGS (mips_abi))
18013         return mips_cpu_info_from_isa (ISA_MIPS1);
18014
18015       if (ABI_NEEDS_64BIT_REGS (mips_abi))
18016         return mips_cpu_info_from_isa (ISA_MIPS3);
18017
18018       if (file_mips_gp32 >= 0)
18019         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
18020
18021       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
18022                                      ? ISA_MIPS3
18023                                      : ISA_MIPS1);
18024     }
18025
18026   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
18027   if (strcasecmp (cpu_string, "default") == 0)
18028     return 0;
18029
18030   for (p = mips_cpu_info_table; p->name != 0; p++)
18031     if (mips_matching_cpu_name_p (p->name, cpu_string))
18032       return p;
18033
18034   as_bad (_("bad value (%s) for %s"), cpu_string, option);
18035   return 0;
18036 }
18037
18038 /* Return the canonical processor information for ISA (a member of the
18039    ISA_MIPS* enumeration).  */
18040
18041 static const struct mips_cpu_info *
18042 mips_cpu_info_from_isa (int isa)
18043 {
18044   int i;
18045
18046   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18047     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
18048         && isa == mips_cpu_info_table[i].isa)
18049       return (&mips_cpu_info_table[i]);
18050
18051   return NULL;
18052 }
18053
18054 static const struct mips_cpu_info *
18055 mips_cpu_info_from_arch (int arch)
18056 {
18057   int i;
18058
18059   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18060     if (arch == mips_cpu_info_table[i].cpu)
18061       return (&mips_cpu_info_table[i]);
18062
18063   return NULL;
18064 }
18065 \f
18066 static void
18067 show (FILE *stream, const char *string, int *col_p, int *first_p)
18068 {
18069   if (*first_p)
18070     {
18071       fprintf (stream, "%24s", "");
18072       *col_p = 24;
18073     }
18074   else
18075     {
18076       fprintf (stream, ", ");
18077       *col_p += 2;
18078     }
18079
18080   if (*col_p + strlen (string) > 72)
18081     {
18082       fprintf (stream, "\n%24s", "");
18083       *col_p = 24;
18084     }
18085
18086   fprintf (stream, "%s", string);
18087   *col_p += strlen (string);
18088
18089   *first_p = 0;
18090 }
18091
18092 void
18093 md_show_usage (FILE *stream)
18094 {
18095   int column, first;
18096   size_t i;
18097
18098   fprintf (stream, _("\
18099 MIPS options:\n\
18100 -EB                     generate big endian output\n\
18101 -EL                     generate little endian output\n\
18102 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
18103 -G NUM                  allow referencing objects up to NUM bytes\n\
18104                         implicitly with the gp register [default 8]\n"));
18105   fprintf (stream, _("\
18106 -mips1                  generate MIPS ISA I instructions\n\
18107 -mips2                  generate MIPS ISA II instructions\n\
18108 -mips3                  generate MIPS ISA III instructions\n\
18109 -mips4                  generate MIPS ISA IV instructions\n\
18110 -mips5                  generate MIPS ISA V instructions\n\
18111 -mips32                 generate MIPS32 ISA instructions\n\
18112 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
18113 -mips64                 generate MIPS64 ISA instructions\n\
18114 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
18115 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
18116
18117   first = 1;
18118
18119   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18120     show (stream, mips_cpu_info_table[i].name, &column, &first);
18121   show (stream, "from-abi", &column, &first);
18122   fputc ('\n', stream);
18123
18124   fprintf (stream, _("\
18125 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
18126 -no-mCPU                don't generate code specific to CPU.\n\
18127                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
18128
18129   first = 1;
18130
18131   show (stream, "3900", &column, &first);
18132   show (stream, "4010", &column, &first);
18133   show (stream, "4100", &column, &first);
18134   show (stream, "4650", &column, &first);
18135   fputc ('\n', stream);
18136
18137   fprintf (stream, _("\
18138 -mips16                 generate mips16 instructions\n\
18139 -no-mips16              do not generate mips16 instructions\n"));
18140   fprintf (stream, _("\
18141 -mmicromips             generate microMIPS instructions\n\
18142 -mno-micromips          do not generate microMIPS instructions\n"));
18143   fprintf (stream, _("\
18144 -msmartmips             generate smartmips instructions\n\
18145 -mno-smartmips          do not generate smartmips instructions\n"));  
18146   fprintf (stream, _("\
18147 -mdsp                   generate DSP instructions\n\
18148 -mno-dsp                do not generate DSP instructions\n"));
18149   fprintf (stream, _("\
18150 -mdspr2                 generate DSP R2 instructions\n\
18151 -mno-dspr2              do not generate DSP R2 instructions\n"));
18152   fprintf (stream, _("\
18153 -mmt                    generate MT instructions\n\
18154 -mno-mt                 do not generate MT instructions\n"));
18155   fprintf (stream, _("\
18156 -mmcu                   generate MCU instructions\n\
18157 -mno-mcu                do not generate MCU instructions\n"));
18158   fprintf (stream, _("\
18159 -mmsa                   generate MSA instructions\n\
18160 -mno-msa                do not generate MSA instructions\n"));
18161   fprintf (stream, _("\
18162 -mvirt                  generate Virtualization instructions\n\
18163 -mno-virt               do not generate Virtualization instructions\n"));
18164   fprintf (stream, _("\
18165 -minsn32                only generate 32-bit microMIPS instructions\n\
18166 -mno-insn32             generate all microMIPS instructions\n"));
18167   fprintf (stream, _("\
18168 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
18169 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
18170 -mfix-vr4120            work around certain VR4120 errata\n\
18171 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
18172 -mfix-24k               insert a nop after ERET and DERET instructions\n\
18173 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
18174 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
18175 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
18176 -msym32                 assume all symbols have 32-bit values\n\
18177 -O0                     remove unneeded NOPs, do not swap branches\n\
18178 -O                      remove unneeded NOPs and swap branches\n\
18179 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
18180 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
18181   fprintf (stream, _("\
18182 -mhard-float            allow floating-point instructions\n\
18183 -msoft-float            do not allow floating-point instructions\n\
18184 -msingle-float          only allow 32-bit floating-point operations\n\
18185 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
18186 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
18187 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
18188 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
18189
18190   first = 1;
18191
18192   show (stream, "legacy", &column, &first);
18193   show (stream, "2008", &column, &first);
18194
18195   fputc ('\n', stream);
18196
18197   fprintf (stream, _("\
18198 -KPIC, -call_shared     generate SVR4 position independent code\n\
18199 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
18200 -mvxworks-pic           generate VxWorks position independent code\n\
18201 -non_shared             do not generate code that can operate with DSOs\n\
18202 -xgot                   assume a 32 bit GOT\n\
18203 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
18204 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
18205                         position dependent (non shared) code\n\
18206 -mabi=ABI               create ABI conformant object file for:\n"));
18207
18208   first = 1;
18209
18210   show (stream, "32", &column, &first);
18211   show (stream, "o64", &column, &first);
18212   show (stream, "n32", &column, &first);
18213   show (stream, "64", &column, &first);
18214   show (stream, "eabi", &column, &first);
18215
18216   fputc ('\n', stream);
18217
18218   fprintf (stream, _("\
18219 -32                     create o32 ABI object file (default)\n\
18220 -n32                    create n32 ABI object file\n\
18221 -64                     create 64 ABI object file\n"));
18222 }
18223
18224 #ifdef TE_IRIX
18225 enum dwarf2_format
18226 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
18227 {
18228   if (HAVE_64BIT_SYMBOLS)
18229     return dwarf2_format_64bit_irix;
18230   else
18231     return dwarf2_format_32bit;
18232 }
18233 #endif
18234
18235 int
18236 mips_dwarf2_addr_size (void)
18237 {
18238   if (HAVE_64BIT_OBJECTS)
18239     return 8;
18240   else
18241     return 4;
18242 }
18243
18244 /* Standard calling conventions leave the CFA at SP on entry.  */
18245 void
18246 mips_cfi_frame_initial_instructions (void)
18247 {
18248   cfi_add_CFA_def_cfa_register (SP);
18249 }
18250
18251 int
18252 tc_mips_regname_to_dw2regnum (char *regname)
18253 {
18254   unsigned int regnum = -1;
18255   unsigned int reg;
18256
18257   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
18258     regnum = reg;
18259
18260   return regnum;
18261 }