include/opcode/
[external/binutils.git] / gas / config / tc-mips.c
1 /* tc-mips.c -- assemble code for a MIPS chip.
2    Copyright 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
3    2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013
4    Free Software Foundation, Inc.
5    Contributed by the OSF and Ralph Campbell.
6    Written by Keith Knowles and Ralph Campbell, working independently.
7    Modified for ECOFF and R4000 support by Ian Lance Taylor of Cygnus
8    Support.
9
10    This file is part of GAS.
11
12    GAS is free software; you can redistribute it and/or modify
13    it under the terms of the GNU General Public License as published by
14    the Free Software Foundation; either version 3, or (at your option)
15    any later version.
16
17    GAS is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License for more details.
21
22    You should have received a copy of the GNU General Public License
23    along with GAS; see the file COPYING.  If not, write to the Free
24    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
25    02110-1301, USA.  */
26
27 #include "as.h"
28 #include "config.h"
29 #include "subsegs.h"
30 #include "safe-ctype.h"
31
32 #include "opcode/mips.h"
33 #include "itbl-ops.h"
34 #include "dwarf2dbg.h"
35 #include "dw2gencfi.h"
36
37 /* Check assumptions made in this file.  */
38 typedef char static_assert1[sizeof (offsetT) < 8 ? -1 : 1];
39 typedef char static_assert2[sizeof (valueT) < 8 ? -1 : 1];
40
41 #ifdef DEBUG
42 #define DBG(x) printf x
43 #else
44 #define DBG(x)
45 #endif
46
47 #define SKIP_SPACE_TABS(S) \
48   do { while (*(S) == ' ' || *(S) == '\t') ++(S); } while (0)
49
50 /* Clean up namespace so we can include obj-elf.h too.  */
51 static int mips_output_flavor (void);
52 static int mips_output_flavor (void) { return OUTPUT_FLAVOR; }
53 #undef OBJ_PROCESS_STAB
54 #undef OUTPUT_FLAVOR
55 #undef S_GET_ALIGN
56 #undef S_GET_SIZE
57 #undef S_SET_ALIGN
58 #undef S_SET_SIZE
59 #undef obj_frob_file
60 #undef obj_frob_file_after_relocs
61 #undef obj_frob_symbol
62 #undef obj_pop_insert
63 #undef obj_sec_sym_ok_for_reloc
64 #undef OBJ_COPY_SYMBOL_ATTRIBUTES
65
66 #include "obj-elf.h"
67 /* Fix any of them that we actually care about.  */
68 #undef OUTPUT_FLAVOR
69 #define OUTPUT_FLAVOR mips_output_flavor()
70
71 #include "elf/mips.h"
72
73 #ifndef ECOFF_DEBUGGING
74 #define NO_ECOFF_DEBUGGING
75 #define ECOFF_DEBUGGING 0
76 #endif
77
78 int mips_flag_mdebug = -1;
79
80 /* Control generation of .pdr sections.  Off by default on IRIX: the native
81    linker doesn't know about and discards them, but relocations against them
82    remain, leading to rld crashes.  */
83 #ifdef TE_IRIX
84 int mips_flag_pdr = FALSE;
85 #else
86 int mips_flag_pdr = TRUE;
87 #endif
88
89 #include "ecoff.h"
90
91 static char *mips_regmask_frag;
92
93 #define ZERO 0
94 #define ATREG 1
95 #define S0  16
96 #define S7  23
97 #define TREG 24
98 #define PIC_CALL_REG 25
99 #define KT0 26
100 #define KT1 27
101 #define GP  28
102 #define SP  29
103 #define FP  30
104 #define RA  31
105
106 #define ILLEGAL_REG (32)
107
108 #define AT  mips_opts.at
109
110 extern int target_big_endian;
111
112 /* The name of the readonly data section.  */
113 #define RDATA_SECTION_NAME ".rodata"
114
115 /* Ways in which an instruction can be "appended" to the output.  */
116 enum append_method {
117   /* Just add it normally.  */
118   APPEND_ADD,
119
120   /* Add it normally and then add a nop.  */
121   APPEND_ADD_WITH_NOP,
122
123   /* Turn an instruction with a delay slot into a "compact" version.  */
124   APPEND_ADD_COMPACT,
125
126   /* Insert the instruction before the last one.  */
127   APPEND_SWAP
128 };
129
130 /* Information about an instruction, including its format, operands
131    and fixups.  */
132 struct mips_cl_insn
133 {
134   /* The opcode's entry in mips_opcodes or mips16_opcodes.  */
135   const struct mips_opcode *insn_mo;
136
137   /* The 16-bit or 32-bit bitstring of the instruction itself.  This is
138      a copy of INSN_MO->match with the operands filled in.  If we have
139      decided to use an extended MIPS16 instruction, this includes the
140      extension.  */
141   unsigned long insn_opcode;
142
143   /* The frag that contains the instruction.  */
144   struct frag *frag;
145
146   /* The offset into FRAG of the first instruction byte.  */
147   long where;
148
149   /* The relocs associated with the instruction, if any.  */
150   fixS *fixp[3];
151
152   /* True if this entry cannot be moved from its current position.  */
153   unsigned int fixed_p : 1;
154
155   /* True if this instruction occurred in a .set noreorder block.  */
156   unsigned int noreorder_p : 1;
157
158   /* True for mips16 instructions that jump to an absolute address.  */
159   unsigned int mips16_absolute_jump_p : 1;
160
161   /* True if this instruction is complete.  */
162   unsigned int complete_p : 1;
163
164   /* True if this instruction is cleared from history by unconditional
165      branch.  */
166   unsigned int cleared_p : 1;
167 };
168
169 /* The ABI to use.  */
170 enum mips_abi_level
171 {
172   NO_ABI = 0,
173   O32_ABI,
174   O64_ABI,
175   N32_ABI,
176   N64_ABI,
177   EABI_ABI
178 };
179
180 /* MIPS ABI we are using for this output file.  */
181 static enum mips_abi_level mips_abi = NO_ABI;
182
183 /* Whether or not we have code that can call pic code.  */
184 int mips_abicalls = FALSE;
185
186 /* Whether or not we have code which can be put into a shared
187    library.  */
188 static bfd_boolean mips_in_shared = TRUE;
189
190 /* This is the set of options which may be modified by the .set
191    pseudo-op.  We use a struct so that .set push and .set pop are more
192    reliable.  */
193
194 struct mips_set_options
195 {
196   /* MIPS ISA (Instruction Set Architecture) level.  This is set to -1
197      if it has not been initialized.  Changed by `.set mipsN', and the
198      -mipsN command line option, and the default CPU.  */
199   int isa;
200   /* Enabled Application Specific Extensions (ASEs).  Changed by `.set
201      <asename>', by command line options, and based on the default
202      architecture.  */
203   int ase;
204   /* Whether we are assembling for the mips16 processor.  0 if we are
205      not, 1 if we are, and -1 if the value has not been initialized.
206      Changed by `.set mips16' and `.set nomips16', and the -mips16 and
207      -nomips16 command line options, and the default CPU.  */
208   int mips16;
209   /* Whether we are assembling for the mipsMIPS ASE.  0 if we are not,
210      1 if we are, and -1 if the value has not been initialized.  Changed
211      by `.set micromips' and `.set nomicromips', and the -mmicromips
212      and -mno-micromips command line options, and the default CPU.  */
213   int micromips;
214   /* Non-zero if we should not reorder instructions.  Changed by `.set
215      reorder' and `.set noreorder'.  */
216   int noreorder;
217   /* Non-zero if we should not permit the register designated "assembler
218      temporary" to be used in instructions.  The value is the register
219      number, normally $at ($1).  Changed by `.set at=REG', `.set noat'
220      (same as `.set at=$0') and `.set at' (same as `.set at=$1').  */
221   unsigned int at;
222   /* Non-zero if we should warn when a macro instruction expands into
223      more than one machine instruction.  Changed by `.set nomacro' and
224      `.set macro'.  */
225   int warn_about_macros;
226   /* Non-zero if we should not move instructions.  Changed by `.set
227      move', `.set volatile', `.set nomove', and `.set novolatile'.  */
228   int nomove;
229   /* Non-zero if we should not optimize branches by moving the target
230      of the branch into the delay slot.  Actually, we don't perform
231      this optimization anyhow.  Changed by `.set bopt' and `.set
232      nobopt'.  */
233   int nobopt;
234   /* Non-zero if we should not autoextend mips16 instructions.
235      Changed by `.set autoextend' and `.set noautoextend'.  */
236   int noautoextend;
237   /* True if we should only emit 32-bit microMIPS instructions.
238      Changed by `.set insn32' and `.set noinsn32', and the -minsn32
239      and -mno-insn32 command line options.  */
240   bfd_boolean insn32;
241   /* Restrict general purpose registers and floating point registers
242      to 32 bit.  This is initially determined when -mgp32 or -mfp32
243      is passed but can changed if the assembler code uses .set mipsN.  */
244   int gp32;
245   int fp32;
246   /* MIPS architecture (CPU) type.  Changed by .set arch=FOO, the -march
247      command line option, and the default CPU.  */
248   int arch;
249   /* True if ".set sym32" is in effect.  */
250   bfd_boolean sym32;
251   /* True if floating-point operations are not allowed.  Changed by .set
252      softfloat or .set hardfloat, by command line options -msoft-float or
253      -mhard-float.  The default is false.  */
254   bfd_boolean soft_float;
255
256   /* True if only single-precision floating-point operations are allowed.
257      Changed by .set singlefloat or .set doublefloat, command-line options
258      -msingle-float or -mdouble-float.  The default is false.  */
259   bfd_boolean single_float;
260 };
261
262 /* This is the struct we use to hold the current set of options.  Note
263    that we must set the isa field to ISA_UNKNOWN and the ASE fields to
264    -1 to indicate that they have not been initialized.  */
265
266 /* True if -mgp32 was passed.  */
267 static int file_mips_gp32 = -1;
268
269 /* True if -mfp32 was passed.  */
270 static int file_mips_fp32 = -1;
271
272 /* 1 if -msoft-float, 0 if -mhard-float.  The default is 0.  */
273 static int file_mips_soft_float = 0;
274
275 /* 1 if -msingle-float, 0 if -mdouble-float.  The default is 0.   */
276 static int file_mips_single_float = 0;
277
278 /* True if -mnan=2008, false if -mnan=legacy.  */
279 static bfd_boolean mips_flag_nan2008 = FALSE;
280
281 static struct mips_set_options mips_opts =
282 {
283   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
284   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
285   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ FALSE,
286   /* gp32 */ 0, /* fp32 */ 0, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
287   /* soft_float */ FALSE, /* single_float */ FALSE
288 };
289
290 /* The set of ASEs that were selected on the command line, either
291    explicitly via ASE options or implicitly through things like -march.  */
292 static unsigned int file_ase;
293
294 /* Which bits of file_ase were explicitly set or cleared by ASE options.  */
295 static unsigned int file_ase_explicit;
296
297 /* These variables are filled in with the masks of registers used.
298    The object format code reads them and puts them in the appropriate
299    place.  */
300 unsigned long mips_gprmask;
301 unsigned long mips_cprmask[4];
302
303 /* MIPS ISA we are using for this output file.  */
304 static int file_mips_isa = ISA_UNKNOWN;
305
306 /* True if any MIPS16 code was produced.  */
307 static int file_ase_mips16;
308
309 #define ISA_SUPPORTS_MIPS16E (mips_opts.isa == ISA_MIPS32               \
310                               || mips_opts.isa == ISA_MIPS32R2          \
311                               || mips_opts.isa == ISA_MIPS64            \
312                               || mips_opts.isa == ISA_MIPS64R2)
313
314 /* True if any microMIPS code was produced.  */
315 static int file_ase_micromips;
316
317 /* True if we want to create R_MIPS_JALR for jalr $25.  */
318 #ifdef TE_IRIX
319 #define MIPS_JALR_HINT_P(EXPR) HAVE_NEWABI
320 #else
321 /* As a GNU extension, we use R_MIPS_JALR for o32 too.  However,
322    because there's no place for any addend, the only acceptable
323    expression is a bare symbol.  */
324 #define MIPS_JALR_HINT_P(EXPR) \
325   (!HAVE_IN_PLACE_ADDENDS \
326    || ((EXPR)->X_op == O_symbol && (EXPR)->X_add_number == 0))
327 #endif
328
329 /* The argument of the -march= flag.  The architecture we are assembling.  */
330 static int file_mips_arch = CPU_UNKNOWN;
331 static const char *mips_arch_string;
332
333 /* The argument of the -mtune= flag.  The architecture for which we
334    are optimizing.  */
335 static int mips_tune = CPU_UNKNOWN;
336 static const char *mips_tune_string;
337
338 /* True when generating 32-bit code for a 64-bit processor.  */
339 static int mips_32bitmode = 0;
340
341 /* True if the given ABI requires 32-bit registers.  */
342 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
343
344 /* Likewise 64-bit registers.  */
345 #define ABI_NEEDS_64BIT_REGS(ABI)       \
346   ((ABI) == N32_ABI                     \
347    || (ABI) == N64_ABI                  \
348    || (ABI) == O64_ABI)
349
350 /*  Return true if ISA supports 64 bit wide gp registers.  */
351 #define ISA_HAS_64BIT_REGS(ISA)         \
352   ((ISA) == ISA_MIPS3                   \
353    || (ISA) == ISA_MIPS4                \
354    || (ISA) == ISA_MIPS5                \
355    || (ISA) == ISA_MIPS64               \
356    || (ISA) == ISA_MIPS64R2)
357
358 /*  Return true if ISA supports 64 bit wide float registers.  */
359 #define ISA_HAS_64BIT_FPRS(ISA)         \
360   ((ISA) == ISA_MIPS3                   \
361    || (ISA) == ISA_MIPS4                \
362    || (ISA) == ISA_MIPS5                \
363    || (ISA) == ISA_MIPS32R2             \
364    || (ISA) == ISA_MIPS64               \
365    || (ISA) == ISA_MIPS64R2)
366
367 /* Return true if ISA supports 64-bit right rotate (dror et al.)
368    instructions.  */
369 #define ISA_HAS_DROR(ISA)               \
370   ((ISA) == ISA_MIPS64R2                \
371    || (mips_opts.micromips              \
372        && ISA_HAS_64BIT_REGS (ISA))     \
373    )
374
375 /* Return true if ISA supports 32-bit right rotate (ror et al.)
376    instructions.  */
377 #define ISA_HAS_ROR(ISA)                \
378   ((ISA) == ISA_MIPS32R2                \
379    || (ISA) == ISA_MIPS64R2             \
380    || (mips_opts.ase & ASE_SMARTMIPS)   \
381    || mips_opts.micromips               \
382    )
383
384 /* Return true if ISA supports single-precision floats in odd registers.  */
385 #define ISA_HAS_ODD_SINGLE_FPR(ISA)     \
386   ((ISA) == ISA_MIPS32                  \
387    || (ISA) == ISA_MIPS32R2             \
388    || (ISA) == ISA_MIPS64               \
389    || (ISA) == ISA_MIPS64R2)
390
391 /* Return true if ISA supports move to/from high part of a 64-bit
392    floating-point register. */
393 #define ISA_HAS_MXHC1(ISA)              \
394   ((ISA) == ISA_MIPS32R2                \
395    || (ISA) == ISA_MIPS64R2)
396
397 #define HAVE_32BIT_GPRS                            \
398     (mips_opts.gp32 || !ISA_HAS_64BIT_REGS (mips_opts.isa))
399
400 #define HAVE_32BIT_FPRS                            \
401     (mips_opts.fp32 || !ISA_HAS_64BIT_FPRS (mips_opts.isa))
402
403 #define HAVE_64BIT_GPRS (!HAVE_32BIT_GPRS)
404 #define HAVE_64BIT_FPRS (!HAVE_32BIT_FPRS)
405
406 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
407
408 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
409
410 /* True if relocations are stored in-place.  */
411 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
412
413 /* The ABI-derived address size.  */
414 #define HAVE_64BIT_ADDRESSES \
415   (HAVE_64BIT_GPRS && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
416 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
417
418 /* The size of symbolic constants (i.e., expressions of the form
419    "SYMBOL" or "SYMBOL + OFFSET").  */
420 #define HAVE_32BIT_SYMBOLS \
421   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
422 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
423
424 /* Addresses are loaded in different ways, depending on the address size
425    in use.  The n32 ABI Documentation also mandates the use of additions
426    with overflow checking, but existing implementations don't follow it.  */
427 #define ADDRESS_ADD_INSN                                                \
428    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
429
430 #define ADDRESS_ADDI_INSN                                               \
431    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
432
433 #define ADDRESS_LOAD_INSN                                               \
434    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
435
436 #define ADDRESS_STORE_INSN                                              \
437    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
438
439 /* Return true if the given CPU supports the MIPS16 ASE.  */
440 #define CPU_HAS_MIPS16(cpu)                                             \
441    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
442     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
443
444 /* Return true if the given CPU supports the microMIPS ASE.  */
445 #define CPU_HAS_MICROMIPS(cpu)  0
446
447 /* True if CPU has a dror instruction.  */
448 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
449
450 /* True if CPU has a ror instruction.  */
451 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
452
453 /* True if CPU is in the Octeon family */
454 #define CPU_IS_OCTEON(CPU) ((CPU) == CPU_OCTEON || (CPU) == CPU_OCTEONP || (CPU) == CPU_OCTEON2)
455
456 /* True if CPU has seq/sne and seqi/snei instructions.  */
457 #define CPU_HAS_SEQ(CPU)        (CPU_IS_OCTEON (CPU))
458
459 /* True, if CPU has support for ldc1 and sdc1. */
460 #define CPU_HAS_LDC1_SDC1(CPU)  \
461    ((mips_opts.isa != ISA_MIPS1) && ((CPU) != CPU_R5900))
462
463 /* True if mflo and mfhi can be immediately followed by instructions
464    which write to the HI and LO registers.
465
466    According to MIPS specifications, MIPS ISAs I, II, and III need
467    (at least) two instructions between the reads of HI/LO and
468    instructions which write them, and later ISAs do not.  Contradicting
469    the MIPS specifications, some MIPS IV processor user manuals (e.g.
470    the UM for the NEC Vr5000) document needing the instructions between
471    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
472    MIPS64 and later ISAs to have the interlocks, plus any specific
473    earlier-ISA CPUs for which CPU documentation declares that the
474    instructions are really interlocked.  */
475 #define hilo_interlocks \
476   (mips_opts.isa == ISA_MIPS32                        \
477    || mips_opts.isa == ISA_MIPS32R2                   \
478    || mips_opts.isa == ISA_MIPS64                     \
479    || mips_opts.isa == ISA_MIPS64R2                   \
480    || mips_opts.arch == CPU_R4010                     \
481    || mips_opts.arch == CPU_R5900                     \
482    || mips_opts.arch == CPU_R10000                    \
483    || mips_opts.arch == CPU_R12000                    \
484    || mips_opts.arch == CPU_R14000                    \
485    || mips_opts.arch == CPU_R16000                    \
486    || mips_opts.arch == CPU_RM7000                    \
487    || mips_opts.arch == CPU_VR5500                    \
488    || mips_opts.micromips                             \
489    )
490
491 /* Whether the processor uses hardware interlocks to protect reads
492    from the GPRs after they are loaded from memory, and thus does not
493    require nops to be inserted.  This applies to instructions marked
494    INSN_LOAD_MEMORY_DELAY.  These nops are only required at MIPS ISA
495    level I and microMIPS mode instructions are always interlocked.  */
496 #define gpr_interlocks                                \
497   (mips_opts.isa != ISA_MIPS1                         \
498    || mips_opts.arch == CPU_R3900                     \
499    || mips_opts.arch == CPU_R5900                     \
500    || mips_opts.micromips                             \
501    )
502
503 /* Whether the processor uses hardware interlocks to avoid delays
504    required by coprocessor instructions, and thus does not require
505    nops to be inserted.  This applies to instructions marked
506    INSN_LOAD_COPROC_DELAY, INSN_COPROC_MOVE_DELAY, and to delays
507    between instructions marked INSN_WRITE_COND_CODE and ones marked
508    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
509    levels I, II, and III and microMIPS mode instructions are always
510    interlocked.  */
511 /* Itbl support may require additional care here.  */
512 #define cop_interlocks                                \
513   ((mips_opts.isa != ISA_MIPS1                        \
514     && mips_opts.isa != ISA_MIPS2                     \
515     && mips_opts.isa != ISA_MIPS3)                    \
516    || mips_opts.arch == CPU_R4300                     \
517    || mips_opts.micromips                             \
518    )
519
520 /* Whether the processor uses hardware interlocks to protect reads
521    from coprocessor registers after they are loaded from memory, and
522    thus does not require nops to be inserted.  This applies to
523    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
524    requires at MIPS ISA level I and microMIPS mode instructions are
525    always interlocked.  */
526 #define cop_mem_interlocks                            \
527   (mips_opts.isa != ISA_MIPS1                         \
528    || mips_opts.micromips                             \
529    )
530
531 /* Is this a mfhi or mflo instruction?  */
532 #define MF_HILO_INSN(PINFO) \
533   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
534
535 /* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
536    has been selected.  This implies, in particular, that addresses of text
537    labels have their LSB set.  */
538 #define HAVE_CODE_COMPRESSION                                           \
539   ((mips_opts.mips16 | mips_opts.micromips) != 0)
540
541 /* The minimum and maximum signed values that can be stored in a GPR.  */
542 #define GPR_SMAX ((offsetT) (((valueT) 1 << (HAVE_64BIT_GPRS ? 63 : 31)) - 1))
543 #define GPR_SMIN (-GPR_SMAX - 1)
544
545 /* MIPS PIC level.  */
546
547 enum mips_pic_level mips_pic;
548
549 /* 1 if we should generate 32 bit offsets from the $gp register in
550    SVR4_PIC mode.  Currently has no meaning in other modes.  */
551 static int mips_big_got = 0;
552
553 /* 1 if trap instructions should used for overflow rather than break
554    instructions.  */
555 static int mips_trap = 0;
556
557 /* 1 if double width floating point constants should not be constructed
558    by assembling two single width halves into two single width floating
559    point registers which just happen to alias the double width destination
560    register.  On some architectures this aliasing can be disabled by a bit
561    in the status register, and the setting of this bit cannot be determined
562    automatically at assemble time.  */
563 static int mips_disable_float_construction;
564
565 /* Non-zero if any .set noreorder directives were used.  */
566
567 static int mips_any_noreorder;
568
569 /* Non-zero if nops should be inserted when the register referenced in
570    an mfhi/mflo instruction is read in the next two instructions.  */
571 static int mips_7000_hilo_fix;
572
573 /* The size of objects in the small data section.  */
574 static unsigned int g_switch_value = 8;
575 /* Whether the -G option was used.  */
576 static int g_switch_seen = 0;
577
578 #define N_RMASK 0xc4
579 #define N_VFP   0xd4
580
581 /* If we can determine in advance that GP optimization won't be
582    possible, we can skip the relaxation stuff that tries to produce
583    GP-relative references.  This makes delay slot optimization work
584    better.
585
586    This function can only provide a guess, but it seems to work for
587    gcc output.  It needs to guess right for gcc, otherwise gcc
588    will put what it thinks is a GP-relative instruction in a branch
589    delay slot.
590
591    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
592    fixed it for the non-PIC mode.  KR 95/04/07  */
593 static int nopic_need_relax (symbolS *, int);
594
595 /* handle of the OPCODE hash table */
596 static struct hash_control *op_hash = NULL;
597
598 /* The opcode hash table we use for the mips16.  */
599 static struct hash_control *mips16_op_hash = NULL;
600
601 /* The opcode hash table we use for the microMIPS ASE.  */
602 static struct hash_control *micromips_op_hash = NULL;
603
604 /* This array holds the chars that always start a comment.  If the
605     pre-processor is disabled, these aren't very useful */
606 const char comment_chars[] = "#";
607
608 /* This array holds the chars that only start a comment at the beginning of
609    a line.  If the line seems to have the form '# 123 filename'
610    .line and .file directives will appear in the pre-processed output */
611 /* Note that input_file.c hand checks for '#' at the beginning of the
612    first line of the input file.  This is because the compiler outputs
613    #NO_APP at the beginning of its output.  */
614 /* Also note that C style comments are always supported.  */
615 const char line_comment_chars[] = "#";
616
617 /* This array holds machine specific line separator characters.  */
618 const char line_separator_chars[] = ";";
619
620 /* Chars that can be used to separate mant from exp in floating point nums */
621 const char EXP_CHARS[] = "eE";
622
623 /* Chars that mean this number is a floating point constant */
624 /* As in 0f12.456 */
625 /* or    0d1.2345e12 */
626 const char FLT_CHARS[] = "rRsSfFdDxXpP";
627
628 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
629    changed in read.c .  Ideally it shouldn't have to know about it at all,
630    but nothing is ideal around here.
631  */
632
633 static char *insn_error;
634
635 static int auto_align = 1;
636
637 /* When outputting SVR4 PIC code, the assembler needs to know the
638    offset in the stack frame from which to restore the $gp register.
639    This is set by the .cprestore pseudo-op, and saved in this
640    variable.  */
641 static offsetT mips_cprestore_offset = -1;
642
643 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
644    more optimizations, it can use a register value instead of a memory-saved
645    offset and even an other register than $gp as global pointer.  */
646 static offsetT mips_cpreturn_offset = -1;
647 static int mips_cpreturn_register = -1;
648 static int mips_gp_register = GP;
649 static int mips_gprel_offset = 0;
650
651 /* Whether mips_cprestore_offset has been set in the current function
652    (or whether it has already been warned about, if not).  */
653 static int mips_cprestore_valid = 0;
654
655 /* This is the register which holds the stack frame, as set by the
656    .frame pseudo-op.  This is needed to implement .cprestore.  */
657 static int mips_frame_reg = SP;
658
659 /* Whether mips_frame_reg has been set in the current function
660    (or whether it has already been warned about, if not).  */
661 static int mips_frame_reg_valid = 0;
662
663 /* To output NOP instructions correctly, we need to keep information
664    about the previous two instructions.  */
665
666 /* Whether we are optimizing.  The default value of 2 means to remove
667    unneeded NOPs and swap branch instructions when possible.  A value
668    of 1 means to not swap branches.  A value of 0 means to always
669    insert NOPs.  */
670 static int mips_optimize = 2;
671
672 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
673    equivalent to seeing no -g option at all.  */
674 static int mips_debug = 0;
675
676 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
677 #define MAX_VR4130_NOPS 4
678
679 /* The maximum number of NOPs needed to fill delay slots.  */
680 #define MAX_DELAY_NOPS 2
681
682 /* The maximum number of NOPs needed for any purpose.  */
683 #define MAX_NOPS 4
684
685 /* A list of previous instructions, with index 0 being the most recent.
686    We need to look back MAX_NOPS instructions when filling delay slots
687    or working around processor errata.  We need to look back one
688    instruction further if we're thinking about using history[0] to
689    fill a branch delay slot.  */
690 static struct mips_cl_insn history[1 + MAX_NOPS];
691
692 /* Arrays of operands for each instruction.  */
693 #define MAX_OPERANDS 6
694 struct mips_operand_array {
695   const struct mips_operand *operand[MAX_OPERANDS];
696 };
697 static struct mips_operand_array *mips_operands;
698 static struct mips_operand_array *mips16_operands;
699 static struct mips_operand_array *micromips_operands;
700
701 /* Nop instructions used by emit_nop.  */
702 static struct mips_cl_insn nop_insn;
703 static struct mips_cl_insn mips16_nop_insn;
704 static struct mips_cl_insn micromips_nop16_insn;
705 static struct mips_cl_insn micromips_nop32_insn;
706
707 /* The appropriate nop for the current mode.  */
708 #define NOP_INSN (mips_opts.mips16                                      \
709                   ? &mips16_nop_insn                                    \
710                   : (mips_opts.micromips                                \
711                      ? (mips_opts.insn32                                \
712                         ? &micromips_nop32_insn                         \
713                         : &micromips_nop16_insn)                        \
714                      : &nop_insn))
715
716 /* The size of NOP_INSN in bytes.  */
717 #define NOP_INSN_SIZE ((mips_opts.mips16                                \
718                         || (mips_opts.micromips && !mips_opts.insn32))  \
719                        ? 2 : 4)
720
721 /* If this is set, it points to a frag holding nop instructions which
722    were inserted before the start of a noreorder section.  If those
723    nops turn out to be unnecessary, the size of the frag can be
724    decreased.  */
725 static fragS *prev_nop_frag;
726
727 /* The number of nop instructions we created in prev_nop_frag.  */
728 static int prev_nop_frag_holds;
729
730 /* The number of nop instructions that we know we need in
731    prev_nop_frag.  */
732 static int prev_nop_frag_required;
733
734 /* The number of instructions we've seen since prev_nop_frag.  */
735 static int prev_nop_frag_since;
736
737 /* Relocations against symbols are sometimes done in two parts, with a HI
738    relocation and a LO relocation.  Each relocation has only 16 bits of
739    space to store an addend.  This means that in order for the linker to
740    handle carries correctly, it must be able to locate both the HI and
741    the LO relocation.  This means that the relocations must appear in
742    order in the relocation table.
743
744    In order to implement this, we keep track of each unmatched HI
745    relocation.  We then sort them so that they immediately precede the
746    corresponding LO relocation.  */
747
748 struct mips_hi_fixup
749 {
750   /* Next HI fixup.  */
751   struct mips_hi_fixup *next;
752   /* This fixup.  */
753   fixS *fixp;
754   /* The section this fixup is in.  */
755   segT seg;
756 };
757
758 /* The list of unmatched HI relocs.  */
759
760 static struct mips_hi_fixup *mips_hi_fixup_list;
761
762 /* The frag containing the last explicit relocation operator.
763    Null if explicit relocations have not been used.  */
764
765 static fragS *prev_reloc_op_frag;
766
767 /* Map mips16 register numbers to normal MIPS register numbers.  */
768
769 static const unsigned int mips16_to_32_reg_map[] =
770 {
771   16, 17, 2, 3, 4, 5, 6, 7
772 };
773
774 /* Map microMIPS register numbers to normal MIPS register numbers.  */
775
776 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
777
778 /* The microMIPS registers with type h.  */
779 static const unsigned int micromips_to_32_reg_h_map1[] =
780 {
781   5, 5, 6, 4, 4, 4, 4, 4
782 };
783 static const unsigned int micromips_to_32_reg_h_map2[] =
784 {
785   6, 7, 7, 21, 22, 5, 6, 7
786 };
787
788 /* The microMIPS registers with type m.  */
789 static const unsigned int micromips_to_32_reg_m_map[] =
790 {
791   0, 17, 2, 3, 16, 18, 19, 20
792 };
793
794 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
795
796 /* Classifies the kind of instructions we're interested in when
797    implementing -mfix-vr4120.  */
798 enum fix_vr4120_class
799 {
800   FIX_VR4120_MACC,
801   FIX_VR4120_DMACC,
802   FIX_VR4120_MULT,
803   FIX_VR4120_DMULT,
804   FIX_VR4120_DIV,
805   FIX_VR4120_MTHILO,
806   NUM_FIX_VR4120_CLASSES
807 };
808
809 /* ...likewise -mfix-loongson2f-jump.  */
810 static bfd_boolean mips_fix_loongson2f_jump;
811
812 /* ...likewise -mfix-loongson2f-nop.  */
813 static bfd_boolean mips_fix_loongson2f_nop;
814
815 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
816 static bfd_boolean mips_fix_loongson2f;
817
818 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
819    there must be at least one other instruction between an instruction
820    of type X and an instruction of type Y.  */
821 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
822
823 /* True if -mfix-vr4120 is in force.  */
824 static int mips_fix_vr4120;
825
826 /* ...likewise -mfix-vr4130.  */
827 static int mips_fix_vr4130;
828
829 /* ...likewise -mfix-24k.  */
830 static int mips_fix_24k;
831
832 /* ...likewise -mfix-cn63xxp1 */
833 static bfd_boolean mips_fix_cn63xxp1;
834
835 /* We don't relax branches by default, since this causes us to expand
836    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
837    fail to compute the offset before expanding the macro to the most
838    efficient expansion.  */
839
840 static int mips_relax_branch;
841 \f
842 /* The expansion of many macros depends on the type of symbol that
843    they refer to.  For example, when generating position-dependent code,
844    a macro that refers to a symbol may have two different expansions,
845    one which uses GP-relative addresses and one which uses absolute
846    addresses.  When generating SVR4-style PIC, a macro may have
847    different expansions for local and global symbols.
848
849    We handle these situations by generating both sequences and putting
850    them in variant frags.  In position-dependent code, the first sequence
851    will be the GP-relative one and the second sequence will be the
852    absolute one.  In SVR4 PIC, the first sequence will be for global
853    symbols and the second will be for local symbols.
854
855    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
856    SECOND are the lengths of the two sequences in bytes.  These fields
857    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
858    the subtype has the following flags:
859
860    RELAX_USE_SECOND
861         Set if it has been decided that we should use the second
862         sequence instead of the first.
863
864    RELAX_SECOND_LONGER
865         Set in the first variant frag if the macro's second implementation
866         is longer than its first.  This refers to the macro as a whole,
867         not an individual relaxation.
868
869    RELAX_NOMACRO
870         Set in the first variant frag if the macro appeared in a .set nomacro
871         block and if one alternative requires a warning but the other does not.
872
873    RELAX_DELAY_SLOT
874         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
875         delay slot.
876
877    RELAX_DELAY_SLOT_16BIT
878         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
879         16-bit instruction.
880
881    RELAX_DELAY_SLOT_SIZE_FIRST
882         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
883         the macro is of the wrong size for the branch delay slot.
884
885    RELAX_DELAY_SLOT_SIZE_SECOND
886         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
887         the macro is of the wrong size for the branch delay slot.
888
889    The frag's "opcode" points to the first fixup for relaxable code.
890
891    Relaxable macros are generated using a sequence such as:
892
893       relax_start (SYMBOL);
894       ... generate first expansion ...
895       relax_switch ();
896       ... generate second expansion ...
897       relax_end ();
898
899    The code and fixups for the unwanted alternative are discarded
900    by md_convert_frag.  */
901 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
902
903 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
904 #define RELAX_SECOND(X) ((X) & 0xff)
905 #define RELAX_USE_SECOND 0x10000
906 #define RELAX_SECOND_LONGER 0x20000
907 #define RELAX_NOMACRO 0x40000
908 #define RELAX_DELAY_SLOT 0x80000
909 #define RELAX_DELAY_SLOT_16BIT 0x100000
910 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x200000
911 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x400000
912
913 /* Branch without likely bit.  If label is out of range, we turn:
914
915         beq reg1, reg2, label
916         delay slot
917
918    into
919
920         bne reg1, reg2, 0f
921         nop
922         j label
923      0: delay slot
924
925    with the following opcode replacements:
926
927         beq <-> bne
928         blez <-> bgtz
929         bltz <-> bgez
930         bc1f <-> bc1t
931
932         bltzal <-> bgezal  (with jal label instead of j label)
933
934    Even though keeping the delay slot instruction in the delay slot of
935    the branch would be more efficient, it would be very tricky to do
936    correctly, because we'd have to introduce a variable frag *after*
937    the delay slot instruction, and expand that instead.  Let's do it
938    the easy way for now, even if the branch-not-taken case now costs
939    one additional instruction.  Out-of-range branches are not supposed
940    to be common, anyway.
941
942    Branch likely.  If label is out of range, we turn:
943
944         beql reg1, reg2, label
945         delay slot (annulled if branch not taken)
946
947    into
948
949         beql reg1, reg2, 1f
950         nop
951         beql $0, $0, 2f
952         nop
953      1: j[al] label
954         delay slot (executed only if branch taken)
955      2:
956
957    It would be possible to generate a shorter sequence by losing the
958    likely bit, generating something like:
959
960         bne reg1, reg2, 0f
961         nop
962         j[al] label
963         delay slot (executed only if branch taken)
964      0:
965
966         beql -> bne
967         bnel -> beq
968         blezl -> bgtz
969         bgtzl -> blez
970         bltzl -> bgez
971         bgezl -> bltz
972         bc1fl -> bc1t
973         bc1tl -> bc1f
974
975         bltzall -> bgezal  (with jal label instead of j label)
976         bgezall -> bltzal  (ditto)
977
978
979    but it's not clear that it would actually improve performance.  */
980 #define RELAX_BRANCH_ENCODE(at, uncond, likely, link, toofar)   \
981   ((relax_substateT)                                            \
982    (0xc0000000                                                  \
983     | ((at) & 0x1f)                                             \
984     | ((toofar) ? 0x20 : 0)                                     \
985     | ((link) ? 0x40 : 0)                                       \
986     | ((likely) ? 0x80 : 0)                                     \
987     | ((uncond) ? 0x100 : 0)))
988 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
989 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x100) != 0)
990 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x80) != 0)
991 #define RELAX_BRANCH_LINK(i) (((i) & 0x40) != 0)
992 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x20) != 0)
993 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
994
995 /* For mips16 code, we use an entirely different form of relaxation.
996    mips16 supports two versions of most instructions which take
997    immediate values: a small one which takes some small value, and a
998    larger one which takes a 16 bit value.  Since branches also follow
999    this pattern, relaxing these values is required.
1000
1001    We can assemble both mips16 and normal MIPS code in a single
1002    object.  Therefore, we need to support this type of relaxation at
1003    the same time that we support the relaxation described above.  We
1004    use the high bit of the subtype field to distinguish these cases.
1005
1006    The information we store for this type of relaxation is the
1007    argument code found in the opcode file for this relocation, whether
1008    the user explicitly requested a small or extended form, and whether
1009    the relocation is in a jump or jal delay slot.  That tells us the
1010    size of the value, and how it should be stored.  We also store
1011    whether the fragment is considered to be extended or not.  We also
1012    store whether this is known to be a branch to a different section,
1013    whether we have tried to relax this frag yet, and whether we have
1014    ever extended a PC relative fragment because of a shift count.  */
1015 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
1016   (0x80000000                                                   \
1017    | ((type) & 0xff)                                            \
1018    | ((small) ? 0x100 : 0)                                      \
1019    | ((ext) ? 0x200 : 0)                                        \
1020    | ((dslot) ? 0x400 : 0)                                      \
1021    | ((jal_dslot) ? 0x800 : 0))
1022 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1023 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1024 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
1025 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
1026 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
1027 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
1028 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
1029 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
1030 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
1031 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
1032 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
1033 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
1034
1035 /* For microMIPS code, we use relaxation similar to one we use for
1036    MIPS16 code.  Some instructions that take immediate values support
1037    two encodings: a small one which takes some small value, and a
1038    larger one which takes a 16 bit value.  As some branches also follow
1039    this pattern, relaxing these values is required.
1040
1041    We can assemble both microMIPS and normal MIPS code in a single
1042    object.  Therefore, we need to support this type of relaxation at
1043    the same time that we support the relaxation described above.  We
1044    use one of the high bits of the subtype field to distinguish these
1045    cases.
1046
1047    The information we store for this type of relaxation is the argument
1048    code found in the opcode file for this relocation, the register
1049    selected as the assembler temporary, whether the branch is
1050    unconditional, whether it is compact, whether it stores the link
1051    address implicitly in $ra, whether relaxation of out-of-range 32-bit
1052    branches to a sequence of instructions is enabled, and whether the
1053    displacement of a branch is too large to fit as an immediate argument
1054    of a 16-bit and a 32-bit branch, respectively.  */
1055 #define RELAX_MICROMIPS_ENCODE(type, at, uncond, compact, link, \
1056                                relax32, toofar16, toofar32)     \
1057   (0x40000000                                                   \
1058    | ((type) & 0xff)                                            \
1059    | (((at) & 0x1f) << 8)                                       \
1060    | ((uncond) ? 0x2000 : 0)                                    \
1061    | ((compact) ? 0x4000 : 0)                                   \
1062    | ((link) ? 0x8000 : 0)                                      \
1063    | ((relax32) ? 0x10000 : 0)                                  \
1064    | ((toofar16) ? 0x20000 : 0)                                 \
1065    | ((toofar32) ? 0x40000 : 0))
1066 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1067 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1068 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1069 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x2000) != 0)
1070 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x4000) != 0)
1071 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x8000) != 0)
1072 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x10000) != 0)
1073
1074 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x20000) != 0)
1075 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x20000)
1076 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x20000)
1077 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x40000) != 0)
1078 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x40000)
1079 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x40000)
1080
1081 /* Sign-extend 16-bit value X.  */
1082 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1083
1084 /* Is the given value a sign-extended 32-bit value?  */
1085 #define IS_SEXT_32BIT_NUM(x)                                            \
1086   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1087    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1088
1089 /* Is the given value a sign-extended 16-bit value?  */
1090 #define IS_SEXT_16BIT_NUM(x)                                            \
1091   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1092    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1093
1094 /* Is the given value a sign-extended 12-bit value?  */
1095 #define IS_SEXT_12BIT_NUM(x)                                            \
1096   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1097
1098 /* Is the given value a sign-extended 9-bit value?  */
1099 #define IS_SEXT_9BIT_NUM(x)                                             \
1100   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1101
1102 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1103 #define IS_ZEXT_32BIT_NUM(x)                                            \
1104   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1105    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1106
1107 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1108    SHIFT places.  */
1109 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1110   (((STRUCT) >> (SHIFT)) & (MASK))
1111
1112 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1113 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1114   (!(MICROMIPS) \
1115    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1116    : EXTRACT_BITS ((INSN).insn_opcode, \
1117                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1118 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1119   EXTRACT_BITS ((INSN).insn_opcode, \
1120                 MIPS16OP_MASK_##FIELD, \
1121                 MIPS16OP_SH_##FIELD)
1122
1123 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1124 #define MIPS16_EXTEND (0xf000U << 16)
1125 \f
1126 /* Whether or not we are emitting a branch-likely macro.  */
1127 static bfd_boolean emit_branch_likely_macro = FALSE;
1128
1129 /* Global variables used when generating relaxable macros.  See the
1130    comment above RELAX_ENCODE for more details about how relaxation
1131    is used.  */
1132 static struct {
1133   /* 0 if we're not emitting a relaxable macro.
1134      1 if we're emitting the first of the two relaxation alternatives.
1135      2 if we're emitting the second alternative.  */
1136   int sequence;
1137
1138   /* The first relaxable fixup in the current frag.  (In other words,
1139      the first fixup that refers to relaxable code.)  */
1140   fixS *first_fixup;
1141
1142   /* sizes[0] says how many bytes of the first alternative are stored in
1143      the current frag.  Likewise sizes[1] for the second alternative.  */
1144   unsigned int sizes[2];
1145
1146   /* The symbol on which the choice of sequence depends.  */
1147   symbolS *symbol;
1148 } mips_relax;
1149 \f
1150 /* Global variables used to decide whether a macro needs a warning.  */
1151 static struct {
1152   /* True if the macro is in a branch delay slot.  */
1153   bfd_boolean delay_slot_p;
1154
1155   /* Set to the length in bytes required if the macro is in a delay slot
1156      that requires a specific length of instruction, otherwise zero.  */
1157   unsigned int delay_slot_length;
1158
1159   /* For relaxable macros, sizes[0] is the length of the first alternative
1160      in bytes and sizes[1] is the length of the second alternative.
1161      For non-relaxable macros, both elements give the length of the
1162      macro in bytes.  */
1163   unsigned int sizes[2];
1164
1165   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1166      instruction of the first alternative in bytes and first_insn_sizes[1]
1167      is the length of the first instruction of the second alternative.
1168      For non-relaxable macros, both elements give the length of the first
1169      instruction in bytes.
1170
1171      Set to zero if we haven't yet seen the first instruction.  */
1172   unsigned int first_insn_sizes[2];
1173
1174   /* For relaxable macros, insns[0] is the number of instructions for the
1175      first alternative and insns[1] is the number of instructions for the
1176      second alternative.
1177
1178      For non-relaxable macros, both elements give the number of
1179      instructions for the macro.  */
1180   unsigned int insns[2];
1181
1182   /* The first variant frag for this macro.  */
1183   fragS *first_frag;
1184 } mips_macro_warning;
1185 \f
1186 /* Prototypes for static functions.  */
1187
1188 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1189
1190 static void append_insn
1191   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1192    bfd_boolean expansionp);
1193 static void mips_no_prev_insn (void);
1194 static void macro_build (expressionS *, const char *, const char *, ...);
1195 static void mips16_macro_build
1196   (expressionS *, const char *, const char *, va_list *);
1197 static void load_register (int, expressionS *, int);
1198 static void macro_start (void);
1199 static void macro_end (void);
1200 static void macro (struct mips_cl_insn *ip, char *str);
1201 static void mips16_macro (struct mips_cl_insn * ip);
1202 static void mips_ip (char *str, struct mips_cl_insn * ip);
1203 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1204 static void mips16_immed
1205   (char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1206    unsigned int, unsigned long *);
1207 static size_t my_getSmallExpression
1208   (expressionS *, bfd_reloc_code_real_type *, char *);
1209 static void my_getExpression (expressionS *, char *);
1210 static void s_align (int);
1211 static void s_change_sec (int);
1212 static void s_change_section (int);
1213 static void s_cons (int);
1214 static void s_float_cons (int);
1215 static void s_mips_globl (int);
1216 static void s_option (int);
1217 static void s_mipsset (int);
1218 static void s_abicalls (int);
1219 static void s_cpload (int);
1220 static void s_cpsetup (int);
1221 static void s_cplocal (int);
1222 static void s_cprestore (int);
1223 static void s_cpreturn (int);
1224 static void s_dtprelword (int);
1225 static void s_dtpreldword (int);
1226 static void s_tprelword (int);
1227 static void s_tpreldword (int);
1228 static void s_gpvalue (int);
1229 static void s_gpword (int);
1230 static void s_gpdword (int);
1231 static void s_ehword (int);
1232 static void s_cpadd (int);
1233 static void s_insn (int);
1234 static void s_nan (int);
1235 static void md_obj_begin (void);
1236 static void md_obj_end (void);
1237 static void s_mips_ent (int);
1238 static void s_mips_end (int);
1239 static void s_mips_frame (int);
1240 static void s_mips_mask (int reg_type);
1241 static void s_mips_stab (int);
1242 static void s_mips_weakext (int);
1243 static void s_mips_file (int);
1244 static void s_mips_loc (int);
1245 static bfd_boolean pic_need_relax (symbolS *, asection *);
1246 static int relaxed_branch_length (fragS *, asection *, int);
1247 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1248 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1249
1250 /* Table and functions used to map between CPU/ISA names, and
1251    ISA levels, and CPU numbers.  */
1252
1253 struct mips_cpu_info
1254 {
1255   const char *name;           /* CPU or ISA name.  */
1256   int flags;                  /* MIPS_CPU_* flags.  */
1257   int ase;                    /* Set of ASEs implemented by the CPU.  */
1258   int isa;                    /* ISA level.  */
1259   int cpu;                    /* CPU number (default CPU if ISA).  */
1260 };
1261
1262 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1263
1264 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1265 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1266 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1267 \f
1268 /* Command-line options.  */
1269 const char *md_shortopts = "O::g::G:";
1270
1271 enum options
1272   {
1273     OPTION_MARCH = OPTION_MD_BASE,
1274     OPTION_MTUNE,
1275     OPTION_MIPS1,
1276     OPTION_MIPS2,
1277     OPTION_MIPS3,
1278     OPTION_MIPS4,
1279     OPTION_MIPS5,
1280     OPTION_MIPS32,
1281     OPTION_MIPS64,
1282     OPTION_MIPS32R2,
1283     OPTION_MIPS64R2,
1284     OPTION_MIPS16,
1285     OPTION_NO_MIPS16,
1286     OPTION_MIPS3D,
1287     OPTION_NO_MIPS3D,
1288     OPTION_MDMX,
1289     OPTION_NO_MDMX,
1290     OPTION_DSP,
1291     OPTION_NO_DSP,
1292     OPTION_MT,
1293     OPTION_NO_MT,
1294     OPTION_VIRT,
1295     OPTION_NO_VIRT,
1296     OPTION_SMARTMIPS,
1297     OPTION_NO_SMARTMIPS,
1298     OPTION_DSPR2,
1299     OPTION_NO_DSPR2,
1300     OPTION_EVA,
1301     OPTION_NO_EVA,
1302     OPTION_MICROMIPS,
1303     OPTION_NO_MICROMIPS,
1304     OPTION_MCU,
1305     OPTION_NO_MCU,
1306     OPTION_COMPAT_ARCH_BASE,
1307     OPTION_M4650,
1308     OPTION_NO_M4650,
1309     OPTION_M4010,
1310     OPTION_NO_M4010,
1311     OPTION_M4100,
1312     OPTION_NO_M4100,
1313     OPTION_M3900,
1314     OPTION_NO_M3900,
1315     OPTION_M7000_HILO_FIX,
1316     OPTION_MNO_7000_HILO_FIX,
1317     OPTION_FIX_24K,
1318     OPTION_NO_FIX_24K,
1319     OPTION_FIX_LOONGSON2F_JUMP,
1320     OPTION_NO_FIX_LOONGSON2F_JUMP,
1321     OPTION_FIX_LOONGSON2F_NOP,
1322     OPTION_NO_FIX_LOONGSON2F_NOP,
1323     OPTION_FIX_VR4120,
1324     OPTION_NO_FIX_VR4120,
1325     OPTION_FIX_VR4130,
1326     OPTION_NO_FIX_VR4130,
1327     OPTION_FIX_CN63XXP1,
1328     OPTION_NO_FIX_CN63XXP1,
1329     OPTION_TRAP,
1330     OPTION_BREAK,
1331     OPTION_EB,
1332     OPTION_EL,
1333     OPTION_FP32,
1334     OPTION_GP32,
1335     OPTION_CONSTRUCT_FLOATS,
1336     OPTION_NO_CONSTRUCT_FLOATS,
1337     OPTION_FP64,
1338     OPTION_GP64,
1339     OPTION_RELAX_BRANCH,
1340     OPTION_NO_RELAX_BRANCH,
1341     OPTION_INSN32,
1342     OPTION_NO_INSN32,
1343     OPTION_MSHARED,
1344     OPTION_MNO_SHARED,
1345     OPTION_MSYM32,
1346     OPTION_MNO_SYM32,
1347     OPTION_SOFT_FLOAT,
1348     OPTION_HARD_FLOAT,
1349     OPTION_SINGLE_FLOAT,
1350     OPTION_DOUBLE_FLOAT,
1351     OPTION_32,
1352     OPTION_CALL_SHARED,
1353     OPTION_CALL_NONPIC,
1354     OPTION_NON_SHARED,
1355     OPTION_XGOT,
1356     OPTION_MABI,
1357     OPTION_N32,
1358     OPTION_64,
1359     OPTION_MDEBUG,
1360     OPTION_NO_MDEBUG,
1361     OPTION_PDR,
1362     OPTION_NO_PDR,
1363     OPTION_MVXWORKS_PIC,
1364     OPTION_NAN,
1365     OPTION_END_OF_ENUM
1366   };
1367
1368 struct option md_longopts[] =
1369 {
1370   /* Options which specify architecture.  */
1371   {"march", required_argument, NULL, OPTION_MARCH},
1372   {"mtune", required_argument, NULL, OPTION_MTUNE},
1373   {"mips0", no_argument, NULL, OPTION_MIPS1},
1374   {"mips1", no_argument, NULL, OPTION_MIPS1},
1375   {"mips2", no_argument, NULL, OPTION_MIPS2},
1376   {"mips3", no_argument, NULL, OPTION_MIPS3},
1377   {"mips4", no_argument, NULL, OPTION_MIPS4},
1378   {"mips5", no_argument, NULL, OPTION_MIPS5},
1379   {"mips32", no_argument, NULL, OPTION_MIPS32},
1380   {"mips64", no_argument, NULL, OPTION_MIPS64},
1381   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1382   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1383
1384   /* Options which specify Application Specific Extensions (ASEs).  */
1385   {"mips16", no_argument, NULL, OPTION_MIPS16},
1386   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1387   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1388   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1389   {"mdmx", no_argument, NULL, OPTION_MDMX},
1390   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1391   {"mdsp", no_argument, NULL, OPTION_DSP},
1392   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1393   {"mmt", no_argument, NULL, OPTION_MT},
1394   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1395   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1396   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1397   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1398   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1399   {"meva", no_argument, NULL, OPTION_EVA},
1400   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1401   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1402   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1403   {"mmcu", no_argument, NULL, OPTION_MCU},
1404   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1405   {"mvirt", no_argument, NULL, OPTION_VIRT},
1406   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1407
1408   /* Old-style architecture options.  Don't add more of these.  */
1409   {"m4650", no_argument, NULL, OPTION_M4650},
1410   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1411   {"m4010", no_argument, NULL, OPTION_M4010},
1412   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1413   {"m4100", no_argument, NULL, OPTION_M4100},
1414   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1415   {"m3900", no_argument, NULL, OPTION_M3900},
1416   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1417
1418   /* Options which enable bug fixes.  */
1419   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1420   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1421   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1422   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1423   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1424   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1425   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1426   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1427   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1428   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1429   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1430   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1431   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1432   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1433   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1434
1435   /* Miscellaneous options.  */
1436   {"trap", no_argument, NULL, OPTION_TRAP},
1437   {"no-break", no_argument, NULL, OPTION_TRAP},
1438   {"break", no_argument, NULL, OPTION_BREAK},
1439   {"no-trap", no_argument, NULL, OPTION_BREAK},
1440   {"EB", no_argument, NULL, OPTION_EB},
1441   {"EL", no_argument, NULL, OPTION_EL},
1442   {"mfp32", no_argument, NULL, OPTION_FP32},
1443   {"mgp32", no_argument, NULL, OPTION_GP32},
1444   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1445   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1446   {"mfp64", no_argument, NULL, OPTION_FP64},
1447   {"mgp64", no_argument, NULL, OPTION_GP64},
1448   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1449   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1450   {"minsn32", no_argument, NULL, OPTION_INSN32},
1451   {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1452   {"mshared", no_argument, NULL, OPTION_MSHARED},
1453   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1454   {"msym32", no_argument, NULL, OPTION_MSYM32},
1455   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1456   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1457   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1458   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1459   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1460
1461   /* Strictly speaking this next option is ELF specific,
1462      but we allow it for other ports as well in order to
1463      make testing easier.  */
1464   {"32", no_argument, NULL, OPTION_32},
1465
1466   /* ELF-specific options.  */
1467   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1468   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1469   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1470   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1471   {"xgot", no_argument, NULL, OPTION_XGOT},
1472   {"mabi", required_argument, NULL, OPTION_MABI},
1473   {"n32", no_argument, NULL, OPTION_N32},
1474   {"64", no_argument, NULL, OPTION_64},
1475   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1476   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1477   {"mpdr", no_argument, NULL, OPTION_PDR},
1478   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1479   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1480   {"mnan", required_argument, NULL, OPTION_NAN},
1481
1482   {NULL, no_argument, NULL, 0}
1483 };
1484 size_t md_longopts_size = sizeof (md_longopts);
1485 \f
1486 /* Information about either an Application Specific Extension or an
1487    optional architecture feature that, for simplicity, we treat in the
1488    same way as an ASE.  */
1489 struct mips_ase
1490 {
1491   /* The name of the ASE, used in both the command-line and .set options.  */
1492   const char *name;
1493
1494   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1495      and 64-bit architectures, the flags here refer to the subset that
1496      is available on both.  */
1497   unsigned int flags;
1498
1499   /* The ASE_* flag used for instructions that are available on 64-bit
1500      architectures but that are not included in FLAGS.  */
1501   unsigned int flags64;
1502
1503   /* The command-line options that turn the ASE on and off.  */
1504   int option_on;
1505   int option_off;
1506
1507   /* The minimum required architecture revisions for MIPS32, MIPS64,
1508      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1509   int mips32_rev;
1510   int mips64_rev;
1511   int micromips32_rev;
1512   int micromips64_rev;
1513 };
1514
1515 /* A table of all supported ASEs.  */
1516 static const struct mips_ase mips_ases[] = {
1517   { "dsp", ASE_DSP, ASE_DSP64,
1518     OPTION_DSP, OPTION_NO_DSP,
1519     2, 2, 2, 2 },
1520
1521   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1522     OPTION_DSPR2, OPTION_NO_DSPR2,
1523     2, 2, 2, 2 },
1524
1525   { "eva", ASE_EVA, 0,
1526     OPTION_EVA, OPTION_NO_EVA,
1527     2, 2, 2, 2 },
1528
1529   { "mcu", ASE_MCU, 0,
1530     OPTION_MCU, OPTION_NO_MCU,
1531     2, 2, 2, 2 },
1532
1533   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1534   { "mdmx", ASE_MDMX, 0,
1535     OPTION_MDMX, OPTION_NO_MDMX,
1536     -1, 1, -1, -1 },
1537
1538   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1539   { "mips3d", ASE_MIPS3D, 0,
1540     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1541     2, 1, -1, -1 },
1542
1543   { "mt", ASE_MT, 0,
1544     OPTION_MT, OPTION_NO_MT,
1545     2, 2, -1, -1 },
1546
1547   { "smartmips", ASE_SMARTMIPS, 0,
1548     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1549     1, -1, -1, -1 },
1550
1551   { "virt", ASE_VIRT, ASE_VIRT64,
1552     OPTION_VIRT, OPTION_NO_VIRT,
1553     2, 2, 2, 2 }
1554 };
1555
1556 /* The set of ASEs that require -mfp64.  */
1557 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX)
1558
1559 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1560 static const unsigned int mips_ase_groups[] = {
1561   ASE_DSP | ASE_DSPR2
1562 };
1563 \f
1564 /* Pseudo-op table.
1565
1566    The following pseudo-ops from the Kane and Heinrich MIPS book
1567    should be defined here, but are currently unsupported: .alias,
1568    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1569
1570    The following pseudo-ops from the Kane and Heinrich MIPS book are
1571    specific to the type of debugging information being generated, and
1572    should be defined by the object format: .aent, .begin, .bend,
1573    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1574    .vreg.
1575
1576    The following pseudo-ops from the Kane and Heinrich MIPS book are
1577    not MIPS CPU specific, but are also not specific to the object file
1578    format.  This file is probably the best place to define them, but
1579    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1580
1581 static const pseudo_typeS mips_pseudo_table[] =
1582 {
1583   /* MIPS specific pseudo-ops.  */
1584   {"option", s_option, 0},
1585   {"set", s_mipsset, 0},
1586   {"rdata", s_change_sec, 'r'},
1587   {"sdata", s_change_sec, 's'},
1588   {"livereg", s_ignore, 0},
1589   {"abicalls", s_abicalls, 0},
1590   {"cpload", s_cpload, 0},
1591   {"cpsetup", s_cpsetup, 0},
1592   {"cplocal", s_cplocal, 0},
1593   {"cprestore", s_cprestore, 0},
1594   {"cpreturn", s_cpreturn, 0},
1595   {"dtprelword", s_dtprelword, 0},
1596   {"dtpreldword", s_dtpreldword, 0},
1597   {"tprelword", s_tprelword, 0},
1598   {"tpreldword", s_tpreldword, 0},
1599   {"gpvalue", s_gpvalue, 0},
1600   {"gpword", s_gpword, 0},
1601   {"gpdword", s_gpdword, 0},
1602   {"ehword", s_ehword, 0},
1603   {"cpadd", s_cpadd, 0},
1604   {"insn", s_insn, 0},
1605   {"nan", s_nan, 0},
1606
1607   /* Relatively generic pseudo-ops that happen to be used on MIPS
1608      chips.  */
1609   {"asciiz", stringer, 8 + 1},
1610   {"bss", s_change_sec, 'b'},
1611   {"err", s_err, 0},
1612   {"half", s_cons, 1},
1613   {"dword", s_cons, 3},
1614   {"weakext", s_mips_weakext, 0},
1615   {"origin", s_org, 0},
1616   {"repeat", s_rept, 0},
1617
1618   /* For MIPS this is non-standard, but we define it for consistency.  */
1619   {"sbss", s_change_sec, 'B'},
1620
1621   /* These pseudo-ops are defined in read.c, but must be overridden
1622      here for one reason or another.  */
1623   {"align", s_align, 0},
1624   {"byte", s_cons, 0},
1625   {"data", s_change_sec, 'd'},
1626   {"double", s_float_cons, 'd'},
1627   {"float", s_float_cons, 'f'},
1628   {"globl", s_mips_globl, 0},
1629   {"global", s_mips_globl, 0},
1630   {"hword", s_cons, 1},
1631   {"int", s_cons, 2},
1632   {"long", s_cons, 2},
1633   {"octa", s_cons, 4},
1634   {"quad", s_cons, 3},
1635   {"section", s_change_section, 0},
1636   {"short", s_cons, 1},
1637   {"single", s_float_cons, 'f'},
1638   {"stabd", s_mips_stab, 'd'},
1639   {"stabn", s_mips_stab, 'n'},
1640   {"stabs", s_mips_stab, 's'},
1641   {"text", s_change_sec, 't'},
1642   {"word", s_cons, 2},
1643
1644   { "extern", ecoff_directive_extern, 0},
1645
1646   { NULL, NULL, 0 },
1647 };
1648
1649 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1650 {
1651   /* These pseudo-ops should be defined by the object file format.
1652      However, a.out doesn't support them, so we have versions here.  */
1653   {"aent", s_mips_ent, 1},
1654   {"bgnb", s_ignore, 0},
1655   {"end", s_mips_end, 0},
1656   {"endb", s_ignore, 0},
1657   {"ent", s_mips_ent, 0},
1658   {"file", s_mips_file, 0},
1659   {"fmask", s_mips_mask, 'F'},
1660   {"frame", s_mips_frame, 0},
1661   {"loc", s_mips_loc, 0},
1662   {"mask", s_mips_mask, 'R'},
1663   {"verstamp", s_ignore, 0},
1664   { NULL, NULL, 0 },
1665 };
1666
1667 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1668    purpose of the `.dc.a' internal pseudo-op.  */
1669
1670 int
1671 mips_address_bytes (void)
1672 {
1673   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1674 }
1675
1676 extern void pop_insert (const pseudo_typeS *);
1677
1678 void
1679 mips_pop_insert (void)
1680 {
1681   pop_insert (mips_pseudo_table);
1682   if (! ECOFF_DEBUGGING)
1683     pop_insert (mips_nonecoff_pseudo_table);
1684 }
1685 \f
1686 /* Symbols labelling the current insn.  */
1687
1688 struct insn_label_list
1689 {
1690   struct insn_label_list *next;
1691   symbolS *label;
1692 };
1693
1694 static struct insn_label_list *free_insn_labels;
1695 #define label_list tc_segment_info_data.labels
1696
1697 static void mips_clear_insn_labels (void);
1698 static void mips_mark_labels (void);
1699 static void mips_compressed_mark_labels (void);
1700
1701 static inline void
1702 mips_clear_insn_labels (void)
1703 {
1704   register struct insn_label_list **pl;
1705   segment_info_type *si;
1706
1707   if (now_seg)
1708     {
1709       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1710         ;
1711       
1712       si = seg_info (now_seg);
1713       *pl = si->label_list;
1714       si->label_list = NULL;
1715     }
1716 }
1717
1718 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1719
1720 static inline void
1721 mips_mark_labels (void)
1722 {
1723   if (HAVE_CODE_COMPRESSION)
1724     mips_compressed_mark_labels ();
1725 }
1726 \f
1727 static char *expr_end;
1728
1729 /* Expressions which appear in macro instructions.  These are set by
1730    mips_ip and read by macro.  */
1731
1732 static expressionS imm_expr;
1733 static expressionS imm2_expr;
1734
1735 /* The relocatable field in an instruction and the relocs associated
1736    with it.  These variables are used for instructions like LUI and
1737    JAL as well as true offsets.  They are also used for address
1738    operands in macros.  */
1739
1740 static expressionS offset_expr;
1741 static bfd_reloc_code_real_type offset_reloc[3]
1742   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1743
1744 /* This is set to the resulting size of the instruction to be produced
1745    by mips16_ip if an explicit extension is used or by mips_ip if an
1746    explicit size is supplied.  */
1747
1748 static unsigned int forced_insn_length;
1749
1750 /* True if we are assembling an instruction.  All dot symbols defined during
1751    this time should be treated as code labels.  */
1752
1753 static bfd_boolean mips_assembling_insn;
1754
1755 /* The pdr segment for per procedure frame/regmask info.  Not used for
1756    ECOFF debugging.  */
1757
1758 static segT pdr_seg;
1759
1760 /* The default target format to use.  */
1761
1762 #if defined (TE_FreeBSD)
1763 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1764 #elif defined (TE_TMIPS)
1765 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1766 #else
1767 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1768 #endif
1769
1770 const char *
1771 mips_target_format (void)
1772 {
1773   switch (OUTPUT_FLAVOR)
1774     {
1775     case bfd_target_elf_flavour:
1776 #ifdef TE_VXWORKS
1777       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1778         return (target_big_endian
1779                 ? "elf32-bigmips-vxworks"
1780                 : "elf32-littlemips-vxworks");
1781 #endif
1782       return (target_big_endian
1783               ? (HAVE_64BIT_OBJECTS
1784                  ? ELF_TARGET ("elf64-", "big")
1785                  : (HAVE_NEWABI
1786                     ? ELF_TARGET ("elf32-n", "big")
1787                     : ELF_TARGET ("elf32-", "big")))
1788               : (HAVE_64BIT_OBJECTS
1789                  ? ELF_TARGET ("elf64-", "little")
1790                  : (HAVE_NEWABI
1791                     ? ELF_TARGET ("elf32-n", "little")
1792                     : ELF_TARGET ("elf32-", "little"))));
1793     default:
1794       abort ();
1795       return NULL;
1796     }
1797 }
1798
1799 /* Return the ISA revision that is currently in use, or 0 if we are
1800    generating code for MIPS V or below.  */
1801
1802 static int
1803 mips_isa_rev (void)
1804 {
1805   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
1806     return 2;
1807
1808   /* microMIPS implies revision 2 or above.  */
1809   if (mips_opts.micromips)
1810     return 2;
1811
1812   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
1813     return 1;
1814
1815   return 0;
1816 }
1817
1818 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
1819
1820 static unsigned int
1821 mips_ase_mask (unsigned int flags)
1822 {
1823   unsigned int i;
1824
1825   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
1826     if (flags & mips_ase_groups[i])
1827       flags |= mips_ase_groups[i];
1828   return flags;
1829 }
1830
1831 /* Check whether the current ISA supports ASE.  Issue a warning if
1832    appropriate.  */
1833
1834 static void
1835 mips_check_isa_supports_ase (const struct mips_ase *ase)
1836 {
1837   const char *base;
1838   int min_rev, size;
1839   static unsigned int warned_isa;
1840   static unsigned int warned_fp32;
1841
1842   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
1843     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
1844   else
1845     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
1846   if ((min_rev < 0 || mips_isa_rev () < min_rev)
1847       && (warned_isa & ase->flags) != ase->flags)
1848     {
1849       warned_isa |= ase->flags;
1850       base = mips_opts.micromips ? "microMIPS" : "MIPS";
1851       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
1852       if (min_rev < 0)
1853         as_warn (_("The %d-bit %s architecture does not support the"
1854                    " `%s' extension"), size, base, ase->name);
1855       else
1856         as_warn (_("The `%s' extension requires %s%d revision %d or greater"),
1857                  ase->name, base, size, min_rev);
1858     }
1859   if ((ase->flags & FP64_ASES)
1860       && mips_opts.fp32
1861       && (warned_fp32 & ase->flags) != ase->flags)
1862     {
1863       warned_fp32 |= ase->flags;
1864       as_warn (_("The `%s' extension requires 64-bit FPRs"), ase->name);
1865     }
1866 }
1867
1868 /* Check all enabled ASEs to see whether they are supported by the
1869    chosen architecture.  */
1870
1871 static void
1872 mips_check_isa_supports_ases (void)
1873 {
1874   unsigned int i, mask;
1875
1876   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1877     {
1878       mask = mips_ase_mask (mips_ases[i].flags);
1879       if ((mips_opts.ase & mask) == mips_ases[i].flags)
1880         mips_check_isa_supports_ase (&mips_ases[i]);
1881     }
1882 }
1883
1884 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
1885    that were affected.  */
1886
1887 static unsigned int
1888 mips_set_ase (const struct mips_ase *ase, bfd_boolean enabled_p)
1889 {
1890   unsigned int mask;
1891
1892   mask = mips_ase_mask (ase->flags);
1893   mips_opts.ase &= ~mask;
1894   if (enabled_p)
1895     mips_opts.ase |= ase->flags;
1896   return mask;
1897 }
1898
1899 /* Return the ASE called NAME, or null if none.  */
1900
1901 static const struct mips_ase *
1902 mips_lookup_ase (const char *name)
1903 {
1904   unsigned int i;
1905
1906   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1907     if (strcmp (name, mips_ases[i].name) == 0)
1908       return &mips_ases[i];
1909   return NULL;
1910 }
1911
1912 /* Return the length of a microMIPS instruction in bytes.  If bits of
1913    the mask beyond the low 16 are 0, then it is a 16-bit instruction.
1914    Otherwise assume a 32-bit instruction; 48-bit instructions (0x1f
1915    major opcode) will require further modifications to the opcode
1916    table.  */
1917
1918 static inline unsigned int
1919 micromips_insn_length (const struct mips_opcode *mo)
1920 {
1921   return (mo->mask >> 16) == 0 ? 2 : 4;
1922 }
1923
1924 /* Return the length of MIPS16 instruction OPCODE.  */
1925
1926 static inline unsigned int
1927 mips16_opcode_length (unsigned long opcode)
1928 {
1929   return (opcode >> 16) == 0 ? 2 : 4;
1930 }
1931
1932 /* Return the length of instruction INSN.  */
1933
1934 static inline unsigned int
1935 insn_length (const struct mips_cl_insn *insn)
1936 {
1937   if (mips_opts.micromips)
1938     return micromips_insn_length (insn->insn_mo);
1939   else if (mips_opts.mips16)
1940     return mips16_opcode_length (insn->insn_opcode);
1941   else
1942     return 4;
1943 }
1944
1945 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
1946
1947 static void
1948 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
1949 {
1950   size_t i;
1951
1952   insn->insn_mo = mo;
1953   insn->insn_opcode = mo->match;
1954   insn->frag = NULL;
1955   insn->where = 0;
1956   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
1957     insn->fixp[i] = NULL;
1958   insn->fixed_p = (mips_opts.noreorder > 0);
1959   insn->noreorder_p = (mips_opts.noreorder > 0);
1960   insn->mips16_absolute_jump_p = 0;
1961   insn->complete_p = 0;
1962   insn->cleared_p = 0;
1963 }
1964
1965 /* Get a list of all the operands in INSN.  */
1966
1967 static const struct mips_operand_array *
1968 insn_operands (const struct mips_cl_insn *insn)
1969 {
1970   if (insn->insn_mo >= &mips_opcodes[0]
1971       && insn->insn_mo < &mips_opcodes[NUMOPCODES])
1972     return &mips_operands[insn->insn_mo - &mips_opcodes[0]];
1973
1974   if (insn->insn_mo >= &mips16_opcodes[0]
1975       && insn->insn_mo < &mips16_opcodes[bfd_mips16_num_opcodes])
1976     return &mips16_operands[insn->insn_mo - &mips16_opcodes[0]];
1977
1978   if (insn->insn_mo >= &micromips_opcodes[0]
1979       && insn->insn_mo < &micromips_opcodes[bfd_micromips_num_opcodes])
1980     return &micromips_operands[insn->insn_mo - &micromips_opcodes[0]];
1981
1982   abort ();
1983 }
1984
1985 /* Get a description of operand OPNO of INSN.  */
1986
1987 static const struct mips_operand *
1988 insn_opno (const struct mips_cl_insn *insn, unsigned opno)
1989 {
1990   const struct mips_operand_array *operands;
1991
1992   operands = insn_operands (insn);
1993   if (opno >= MAX_OPERANDS || !operands->operand[opno])
1994     abort ();
1995   return operands->operand[opno];
1996 }
1997
1998 /* Install UVAL as the value of OPERAND in INSN.  */
1999
2000 static inline void
2001 insn_insert_operand (struct mips_cl_insn *insn,
2002                      const struct mips_operand *operand, unsigned int uval)
2003 {
2004   insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
2005 }
2006
2007 /* Extract the value of OPERAND from INSN.  */
2008
2009 static inline unsigned
2010 insn_extract_operand (const struct mips_cl_insn *insn,
2011                       const struct mips_operand *operand)
2012 {
2013   return mips_extract_operand (operand, insn->insn_opcode);
2014 }
2015
2016 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2017
2018 static void
2019 mips_record_compressed_mode (void)
2020 {
2021   segment_info_type *si;
2022
2023   si = seg_info (now_seg);
2024   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2025     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2026   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2027     si->tc_segment_info_data.micromips = mips_opts.micromips;
2028 }
2029
2030 /* Read a standard MIPS instruction from BUF.  */
2031
2032 static unsigned long
2033 read_insn (char *buf)
2034 {
2035   if (target_big_endian)
2036     return bfd_getb32 ((bfd_byte *) buf);
2037   else
2038     return bfd_getl32 ((bfd_byte *) buf);
2039 }
2040
2041 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2042    the next byte.  */
2043
2044 static char *
2045 write_insn (char *buf, unsigned int insn)
2046 {
2047   md_number_to_chars (buf, insn, 4);
2048   return buf + 4;
2049 }
2050
2051 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2052    has length LENGTH.  */
2053
2054 static unsigned long
2055 read_compressed_insn (char *buf, unsigned int length)
2056 {
2057   unsigned long insn;
2058   unsigned int i;
2059
2060   insn = 0;
2061   for (i = 0; i < length; i += 2)
2062     {
2063       insn <<= 16;
2064       if (target_big_endian)
2065         insn |= bfd_getb16 ((char *) buf);
2066       else
2067         insn |= bfd_getl16 ((char *) buf);
2068       buf += 2;
2069     }
2070   return insn;
2071 }
2072
2073 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2074    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2075
2076 static char *
2077 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2078 {
2079   unsigned int i;
2080
2081   for (i = 0; i < length; i += 2)
2082     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2083   return buf + length;
2084 }
2085
2086 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2087
2088 static void
2089 install_insn (const struct mips_cl_insn *insn)
2090 {
2091   char *f = insn->frag->fr_literal + insn->where;
2092   if (HAVE_CODE_COMPRESSION)
2093     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2094   else
2095     write_insn (f, insn->insn_opcode);
2096   mips_record_compressed_mode ();
2097 }
2098
2099 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2100    and install the opcode in the new location.  */
2101
2102 static void
2103 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2104 {
2105   size_t i;
2106
2107   insn->frag = frag;
2108   insn->where = where;
2109   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2110     if (insn->fixp[i] != NULL)
2111       {
2112         insn->fixp[i]->fx_frag = frag;
2113         insn->fixp[i]->fx_where = where;
2114       }
2115   install_insn (insn);
2116 }
2117
2118 /* Add INSN to the end of the output.  */
2119
2120 static void
2121 add_fixed_insn (struct mips_cl_insn *insn)
2122 {
2123   char *f = frag_more (insn_length (insn));
2124   move_insn (insn, frag_now, f - frag_now->fr_literal);
2125 }
2126
2127 /* Start a variant frag and move INSN to the start of the variant part,
2128    marking it as fixed.  The other arguments are as for frag_var.  */
2129
2130 static void
2131 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2132                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2133 {
2134   frag_grow (max_chars);
2135   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2136   insn->fixed_p = 1;
2137   frag_var (rs_machine_dependent, max_chars, var,
2138             subtype, symbol, offset, NULL);
2139 }
2140
2141 /* Insert N copies of INSN into the history buffer, starting at
2142    position FIRST.  Neither FIRST nor N need to be clipped.  */
2143
2144 static void
2145 insert_into_history (unsigned int first, unsigned int n,
2146                      const struct mips_cl_insn *insn)
2147 {
2148   if (mips_relax.sequence != 2)
2149     {
2150       unsigned int i;
2151
2152       for (i = ARRAY_SIZE (history); i-- > first;)
2153         if (i >= first + n)
2154           history[i] = history[i - n];
2155         else
2156           history[i] = *insn;
2157     }
2158 }
2159
2160 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2161    the idea is to make it obvious at a glance that each errata is
2162    included.  */
2163
2164 static void
2165 init_vr4120_conflicts (void)
2166 {
2167 #define CONFLICT(FIRST, SECOND) \
2168     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2169
2170   /* Errata 21 - [D]DIV[U] after [D]MACC */
2171   CONFLICT (MACC, DIV);
2172   CONFLICT (DMACC, DIV);
2173
2174   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2175   CONFLICT (DMULT, DMULT);
2176   CONFLICT (DMULT, DMACC);
2177   CONFLICT (DMACC, DMULT);
2178   CONFLICT (DMACC, DMACC);
2179
2180   /* Errata 24 - MT{LO,HI} after [D]MACC */
2181   CONFLICT (MACC, MTHILO);
2182   CONFLICT (DMACC, MTHILO);
2183
2184   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2185      instruction is executed immediately after a MACC or DMACC
2186      instruction, the result of [either instruction] is incorrect."  */
2187   CONFLICT (MACC, MULT);
2188   CONFLICT (MACC, DMULT);
2189   CONFLICT (DMACC, MULT);
2190   CONFLICT (DMACC, DMULT);
2191
2192   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2193      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2194      DDIV or DDIVU instruction, the result of the MACC or
2195      DMACC instruction is incorrect.".  */
2196   CONFLICT (DMULT, MACC);
2197   CONFLICT (DMULT, DMACC);
2198   CONFLICT (DIV, MACC);
2199   CONFLICT (DIV, DMACC);
2200
2201 #undef CONFLICT
2202 }
2203
2204 struct regname {
2205   const char *name;
2206   unsigned int num;
2207 };
2208
2209 #define RNUM_MASK       0x00000ff
2210 #define RTYPE_MASK      0x0efff00
2211 #define RTYPE_NUM       0x0000100
2212 #define RTYPE_FPU       0x0000200
2213 #define RTYPE_FCC       0x0000400
2214 #define RTYPE_VEC       0x0000800
2215 #define RTYPE_GP        0x0001000
2216 #define RTYPE_CP0       0x0002000
2217 #define RTYPE_PC        0x0004000
2218 #define RTYPE_ACC       0x0008000
2219 #define RTYPE_CCC       0x0010000
2220 #define RTYPE_VI        0x0020000
2221 #define RTYPE_VF        0x0040000
2222 #define RTYPE_R5900_I   0x0080000
2223 #define RTYPE_R5900_Q   0x0100000
2224 #define RTYPE_R5900_R   0x0200000
2225 #define RTYPE_R5900_ACC 0x0400000
2226 #define RWARN           0x8000000
2227
2228 #define GENERIC_REGISTER_NUMBERS \
2229     {"$0",      RTYPE_NUM | 0},  \
2230     {"$1",      RTYPE_NUM | 1},  \
2231     {"$2",      RTYPE_NUM | 2},  \
2232     {"$3",      RTYPE_NUM | 3},  \
2233     {"$4",      RTYPE_NUM | 4},  \
2234     {"$5",      RTYPE_NUM | 5},  \
2235     {"$6",      RTYPE_NUM | 6},  \
2236     {"$7",      RTYPE_NUM | 7},  \
2237     {"$8",      RTYPE_NUM | 8},  \
2238     {"$9",      RTYPE_NUM | 9},  \
2239     {"$10",     RTYPE_NUM | 10}, \
2240     {"$11",     RTYPE_NUM | 11}, \
2241     {"$12",     RTYPE_NUM | 12}, \
2242     {"$13",     RTYPE_NUM | 13}, \
2243     {"$14",     RTYPE_NUM | 14}, \
2244     {"$15",     RTYPE_NUM | 15}, \
2245     {"$16",     RTYPE_NUM | 16}, \
2246     {"$17",     RTYPE_NUM | 17}, \
2247     {"$18",     RTYPE_NUM | 18}, \
2248     {"$19",     RTYPE_NUM | 19}, \
2249     {"$20",     RTYPE_NUM | 20}, \
2250     {"$21",     RTYPE_NUM | 21}, \
2251     {"$22",     RTYPE_NUM | 22}, \
2252     {"$23",     RTYPE_NUM | 23}, \
2253     {"$24",     RTYPE_NUM | 24}, \
2254     {"$25",     RTYPE_NUM | 25}, \
2255     {"$26",     RTYPE_NUM | 26}, \
2256     {"$27",     RTYPE_NUM | 27}, \
2257     {"$28",     RTYPE_NUM | 28}, \
2258     {"$29",     RTYPE_NUM | 29}, \
2259     {"$30",     RTYPE_NUM | 30}, \
2260     {"$31",     RTYPE_NUM | 31} 
2261
2262 #define FPU_REGISTER_NAMES       \
2263     {"$f0",     RTYPE_FPU | 0},  \
2264     {"$f1",     RTYPE_FPU | 1},  \
2265     {"$f2",     RTYPE_FPU | 2},  \
2266     {"$f3",     RTYPE_FPU | 3},  \
2267     {"$f4",     RTYPE_FPU | 4},  \
2268     {"$f5",     RTYPE_FPU | 5},  \
2269     {"$f6",     RTYPE_FPU | 6},  \
2270     {"$f7",     RTYPE_FPU | 7},  \
2271     {"$f8",     RTYPE_FPU | 8},  \
2272     {"$f9",     RTYPE_FPU | 9},  \
2273     {"$f10",    RTYPE_FPU | 10}, \
2274     {"$f11",    RTYPE_FPU | 11}, \
2275     {"$f12",    RTYPE_FPU | 12}, \
2276     {"$f13",    RTYPE_FPU | 13}, \
2277     {"$f14",    RTYPE_FPU | 14}, \
2278     {"$f15",    RTYPE_FPU | 15}, \
2279     {"$f16",    RTYPE_FPU | 16}, \
2280     {"$f17",    RTYPE_FPU | 17}, \
2281     {"$f18",    RTYPE_FPU | 18}, \
2282     {"$f19",    RTYPE_FPU | 19}, \
2283     {"$f20",    RTYPE_FPU | 20}, \
2284     {"$f21",    RTYPE_FPU | 21}, \
2285     {"$f22",    RTYPE_FPU | 22}, \
2286     {"$f23",    RTYPE_FPU | 23}, \
2287     {"$f24",    RTYPE_FPU | 24}, \
2288     {"$f25",    RTYPE_FPU | 25}, \
2289     {"$f26",    RTYPE_FPU | 26}, \
2290     {"$f27",    RTYPE_FPU | 27}, \
2291     {"$f28",    RTYPE_FPU | 28}, \
2292     {"$f29",    RTYPE_FPU | 29}, \
2293     {"$f30",    RTYPE_FPU | 30}, \
2294     {"$f31",    RTYPE_FPU | 31}
2295
2296 #define FPU_CONDITION_CODE_NAMES \
2297     {"$fcc0",   RTYPE_FCC | 0},  \
2298     {"$fcc1",   RTYPE_FCC | 1},  \
2299     {"$fcc2",   RTYPE_FCC | 2},  \
2300     {"$fcc3",   RTYPE_FCC | 3},  \
2301     {"$fcc4",   RTYPE_FCC | 4},  \
2302     {"$fcc5",   RTYPE_FCC | 5},  \
2303     {"$fcc6",   RTYPE_FCC | 6},  \
2304     {"$fcc7",   RTYPE_FCC | 7}
2305
2306 #define COPROC_CONDITION_CODE_NAMES         \
2307     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2308     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2309     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2310     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2311     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2312     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2313     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2314     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2315
2316 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2317     {"$a4",     RTYPE_GP | 8},  \
2318     {"$a5",     RTYPE_GP | 9},  \
2319     {"$a6",     RTYPE_GP | 10}, \
2320     {"$a7",     RTYPE_GP | 11}, \
2321     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2322     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2323     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2324     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2325     {"$t0",     RTYPE_GP | 12}, \
2326     {"$t1",     RTYPE_GP | 13}, \
2327     {"$t2",     RTYPE_GP | 14}, \
2328     {"$t3",     RTYPE_GP | 15}
2329
2330 #define O32_SYMBOLIC_REGISTER_NAMES \
2331     {"$t0",     RTYPE_GP | 8},  \
2332     {"$t1",     RTYPE_GP | 9},  \
2333     {"$t2",     RTYPE_GP | 10}, \
2334     {"$t3",     RTYPE_GP | 11}, \
2335     {"$t4",     RTYPE_GP | 12}, \
2336     {"$t5",     RTYPE_GP | 13}, \
2337     {"$t6",     RTYPE_GP | 14}, \
2338     {"$t7",     RTYPE_GP | 15}, \
2339     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2340     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2341     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2342     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */ 
2343
2344 /* Remaining symbolic register names */
2345 #define SYMBOLIC_REGISTER_NAMES \
2346     {"$zero",   RTYPE_GP | 0},  \
2347     {"$at",     RTYPE_GP | 1},  \
2348     {"$AT",     RTYPE_GP | 1},  \
2349     {"$v0",     RTYPE_GP | 2},  \
2350     {"$v1",     RTYPE_GP | 3},  \
2351     {"$a0",     RTYPE_GP | 4},  \
2352     {"$a1",     RTYPE_GP | 5},  \
2353     {"$a2",     RTYPE_GP | 6},  \
2354     {"$a3",     RTYPE_GP | 7},  \
2355     {"$s0",     RTYPE_GP | 16}, \
2356     {"$s1",     RTYPE_GP | 17}, \
2357     {"$s2",     RTYPE_GP | 18}, \
2358     {"$s3",     RTYPE_GP | 19}, \
2359     {"$s4",     RTYPE_GP | 20}, \
2360     {"$s5",     RTYPE_GP | 21}, \
2361     {"$s6",     RTYPE_GP | 22}, \
2362     {"$s7",     RTYPE_GP | 23}, \
2363     {"$t8",     RTYPE_GP | 24}, \
2364     {"$t9",     RTYPE_GP | 25}, \
2365     {"$k0",     RTYPE_GP | 26}, \
2366     {"$kt0",    RTYPE_GP | 26}, \
2367     {"$k1",     RTYPE_GP | 27}, \
2368     {"$kt1",    RTYPE_GP | 27}, \
2369     {"$gp",     RTYPE_GP | 28}, \
2370     {"$sp",     RTYPE_GP | 29}, \
2371     {"$s8",     RTYPE_GP | 30}, \
2372     {"$fp",     RTYPE_GP | 30}, \
2373     {"$ra",     RTYPE_GP | 31}
2374
2375 #define MIPS16_SPECIAL_REGISTER_NAMES \
2376     {"$pc",     RTYPE_PC | 0}
2377
2378 #define MDMX_VECTOR_REGISTER_NAMES \
2379     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2380     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2381     {"$v2",     RTYPE_VEC | 2},  \
2382     {"$v3",     RTYPE_VEC | 3},  \
2383     {"$v4",     RTYPE_VEC | 4},  \
2384     {"$v5",     RTYPE_VEC | 5},  \
2385     {"$v6",     RTYPE_VEC | 6},  \
2386     {"$v7",     RTYPE_VEC | 7},  \
2387     {"$v8",     RTYPE_VEC | 8},  \
2388     {"$v9",     RTYPE_VEC | 9},  \
2389     {"$v10",    RTYPE_VEC | 10}, \
2390     {"$v11",    RTYPE_VEC | 11}, \
2391     {"$v12",    RTYPE_VEC | 12}, \
2392     {"$v13",    RTYPE_VEC | 13}, \
2393     {"$v14",    RTYPE_VEC | 14}, \
2394     {"$v15",    RTYPE_VEC | 15}, \
2395     {"$v16",    RTYPE_VEC | 16}, \
2396     {"$v17",    RTYPE_VEC | 17}, \
2397     {"$v18",    RTYPE_VEC | 18}, \
2398     {"$v19",    RTYPE_VEC | 19}, \
2399     {"$v20",    RTYPE_VEC | 20}, \
2400     {"$v21",    RTYPE_VEC | 21}, \
2401     {"$v22",    RTYPE_VEC | 22}, \
2402     {"$v23",    RTYPE_VEC | 23}, \
2403     {"$v24",    RTYPE_VEC | 24}, \
2404     {"$v25",    RTYPE_VEC | 25}, \
2405     {"$v26",    RTYPE_VEC | 26}, \
2406     {"$v27",    RTYPE_VEC | 27}, \
2407     {"$v28",    RTYPE_VEC | 28}, \
2408     {"$v29",    RTYPE_VEC | 29}, \
2409     {"$v30",    RTYPE_VEC | 30}, \
2410     {"$v31",    RTYPE_VEC | 31}
2411
2412 #define R5900_I_NAMES \
2413     {"$I",      RTYPE_R5900_I | 0}
2414
2415 #define R5900_Q_NAMES \
2416     {"$Q",      RTYPE_R5900_Q | 0}
2417
2418 #define R5900_R_NAMES \
2419     {"$R",      RTYPE_R5900_R | 0}
2420
2421 #define R5900_ACC_NAMES \
2422     {"$ACC",    RTYPE_R5900_ACC | 0 }
2423
2424 #define MIPS_DSP_ACCUMULATOR_NAMES \
2425     {"$ac0",    RTYPE_ACC | 0}, \
2426     {"$ac1",    RTYPE_ACC | 1}, \
2427     {"$ac2",    RTYPE_ACC | 2}, \
2428     {"$ac3",    RTYPE_ACC | 3}
2429
2430 static const struct regname reg_names[] = {
2431   GENERIC_REGISTER_NUMBERS,
2432   FPU_REGISTER_NAMES,
2433   FPU_CONDITION_CODE_NAMES,
2434   COPROC_CONDITION_CODE_NAMES,
2435
2436   /* The $txx registers depends on the abi,
2437      these will be added later into the symbol table from
2438      one of the tables below once mips_abi is set after 
2439      parsing of arguments from the command line. */
2440   SYMBOLIC_REGISTER_NAMES,
2441
2442   MIPS16_SPECIAL_REGISTER_NAMES,
2443   MDMX_VECTOR_REGISTER_NAMES,
2444   R5900_I_NAMES,
2445   R5900_Q_NAMES,
2446   R5900_R_NAMES,
2447   R5900_ACC_NAMES,
2448   MIPS_DSP_ACCUMULATOR_NAMES,
2449   {0, 0}
2450 };
2451
2452 static const struct regname reg_names_o32[] = {
2453   O32_SYMBOLIC_REGISTER_NAMES,
2454   {0, 0}
2455 };
2456
2457 static const struct regname reg_names_n32n64[] = {
2458   N32N64_SYMBOLIC_REGISTER_NAMES,
2459   {0, 0}
2460 };
2461
2462 /* Register symbols $v0 and $v1 map to GPRs 2 and 3, but they can also be
2463    interpreted as vector registers 0 and 1.  If SYMVAL is the value of one
2464    of these register symbols, return the associated vector register,
2465    otherwise return SYMVAL itself.  */
2466
2467 static unsigned int
2468 mips_prefer_vec_regno (unsigned int symval)
2469 {
2470   if ((symval & -2) == (RTYPE_GP | 2))
2471     return RTYPE_VEC | (symval & 1);
2472   return symval;
2473 }
2474
2475 /* Return true if string [S, E) is a valid register name, storing its
2476    symbol value in *SYMVAL_PTR if so.  */
2477
2478 static bfd_boolean
2479 mips_parse_register_1 (char *s, char *e, unsigned int *symval_ptr)
2480 {
2481   char save_c;
2482   symbolS *symbol;
2483
2484   /* Terminate name.  */
2485   save_c = *e;
2486   *e = '\0';
2487
2488   /* Look up the name.  */
2489   symbol = symbol_find (s);
2490   *e = save_c;
2491
2492   if (!symbol || S_GET_SEGMENT (symbol) != reg_section)
2493     return FALSE;
2494
2495   *symval_ptr = S_GET_VALUE (symbol);
2496   return TRUE;
2497 }
2498
2499 /* Return true if the string at *SPTR is a valid register name.  Allow it
2500    to have a VU0-style channel suffix of the form x?y?z?w? if CHANNELS_PTR
2501    is nonnull.
2502
2503    When returning true, move *SPTR past the register, store the
2504    register's symbol value in *SYMVAL_PTR and the channel mask in
2505    *CHANNELS_PTR (if nonnull).  The symbol value includes the register
2506    number (RNUM_MASK) and register type (RTYPE_MASK).  The channel mask
2507    is a 4-bit value of the form XYZW and is 0 if no suffix was given.  */
2508
2509 static bfd_boolean
2510 mips_parse_register (char **sptr, unsigned int *symval_ptr,
2511                      unsigned int *channels_ptr)
2512 {
2513   char *s, *e, *m;
2514   const char *q;
2515   unsigned int channels, symval, bit;
2516
2517   /* Find end of name.  */
2518   s = e = *sptr;
2519   if (is_name_beginner (*e))
2520     ++e;
2521   while (is_part_of_name (*e))
2522     ++e;
2523
2524   channels = 0;
2525   if (!mips_parse_register_1 (s, e, &symval))
2526     {
2527       if (!channels_ptr)
2528         return FALSE;
2529
2530       /* Eat characters from the end of the string that are valid
2531          channel suffixes.  The preceding register must be $ACC or
2532          end with a digit, so there is no ambiguity.  */
2533       bit = 1;
2534       m = e;
2535       for (q = "wzyx"; *q; q++, bit <<= 1)
2536         if (m > s && m[-1] == *q)
2537           {
2538             --m;
2539             channels |= bit;
2540           }
2541
2542       if (channels == 0
2543           || !mips_parse_register_1 (s, m, &symval)
2544           || (symval & (RTYPE_VI | RTYPE_VF | RTYPE_R5900_ACC)) == 0)
2545         return FALSE;
2546     }
2547
2548   *sptr = e;
2549   *symval_ptr = symval;
2550   if (channels_ptr)
2551     *channels_ptr = channels;
2552   return TRUE;
2553 }
2554
2555 /* Check if SPTR points at a valid register specifier according to TYPES.
2556    If so, then return 1, advance S to consume the specifier and store
2557    the register's number in REGNOP, otherwise return 0.  */
2558
2559 static int
2560 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2561 {
2562   unsigned int regno;
2563
2564   if (mips_parse_register (s, &regno, NULL))
2565     {
2566       if (types & RTYPE_VEC)
2567         regno = mips_prefer_vec_regno (regno);
2568       if (regno & types)
2569         regno &= RNUM_MASK;
2570       else
2571         regno = ~0;
2572     }
2573   else
2574     {
2575       if (types & RWARN)
2576         as_warn (_("Unrecognized register name `%s'"), *s);
2577       regno = ~0;
2578     }
2579   if (regnop)
2580     *regnop = regno;
2581   return regno <= RNUM_MASK;
2582 }
2583
2584 /* Parse a VU0 "x?y?z?w?" channel mask at S and store the associated
2585    mask in *CHANNELS.  Return a pointer to the first unconsumed character.  */
2586
2587 static char *
2588 mips_parse_vu0_channels (char *s, unsigned int *channels)
2589 {
2590   unsigned int i;
2591
2592   *channels = 0;
2593   for (i = 0; i < 4; i++)
2594     if (*s == "xyzw"[i])
2595       {
2596         *channels |= 1 << (3 - i);
2597         ++s;
2598       }
2599   return s;
2600 }
2601
2602 /* Token types for parsed operand lists.  */
2603 enum mips_operand_token_type {
2604   /* A plain register, e.g. $f2.  */
2605   OT_REG,
2606
2607   /* A 4-bit XYZW channel mask.  */
2608   OT_CHANNELS,
2609
2610   /* An element of a vector, e.g. $v0[1].  */
2611   OT_REG_ELEMENT,
2612
2613   /* A continuous range of registers, e.g. $s0-$s4.  */
2614   OT_REG_RANGE,
2615
2616   /* A (possibly relocated) expression.  */
2617   OT_INTEGER,
2618
2619   /* A floating-point value.  */
2620   OT_FLOAT,
2621
2622   /* A single character.  This can be '(', ')' or ',', but '(' only appears
2623      before OT_REGs.  */
2624   OT_CHAR,
2625
2626   /* A doubled character, either "--" or "++".  */
2627   OT_DOUBLE_CHAR,
2628
2629   /* The end of the operand list.  */
2630   OT_END
2631 };
2632
2633 /* A parsed operand token.  */
2634 struct mips_operand_token
2635 {
2636   /* The type of token.  */
2637   enum mips_operand_token_type type;
2638   union
2639   {
2640     /* The register symbol value for an OT_REG.  */
2641     unsigned int regno;
2642
2643     /* The 4-bit channel mask for an OT_CHANNEL_SUFFIX.  */
2644     unsigned int channels;
2645
2646     /* The register symbol value and index for an OT_REG_ELEMENT.  */
2647     struct {
2648       unsigned int regno;
2649       addressT index;
2650     } reg_element;
2651
2652     /* The two register symbol values involved in an OT_REG_RANGE.  */
2653     struct {
2654       unsigned int regno1;
2655       unsigned int regno2;
2656     } reg_range;
2657
2658     /* The value of an OT_INTEGER.  The value is represented as an
2659        expression and the relocation operators that were applied to
2660        that expression.  The reloc entries are BFD_RELOC_UNUSED if no
2661        relocation operators were used.  */
2662     struct {
2663       expressionS value;
2664       bfd_reloc_code_real_type relocs[3];
2665     } integer;
2666
2667     /* The binary data for an OT_FLOAT constant, and the number of bytes
2668        in the constant.  */
2669     struct {
2670       unsigned char data[8];
2671       int length;
2672     } flt;
2673
2674     /* The character represented by an OT_CHAR or OT_DOUBLE_CHAR.  */
2675     char ch;
2676   } u;
2677 };
2678
2679 /* An obstack used to construct lists of mips_operand_tokens.  */
2680 static struct obstack mips_operand_tokens;
2681
2682 /* Give TOKEN type TYPE and add it to mips_operand_tokens.  */
2683
2684 static void
2685 mips_add_token (struct mips_operand_token *token,
2686                 enum mips_operand_token_type type)
2687 {
2688   token->type = type;
2689   obstack_grow (&mips_operand_tokens, token, sizeof (*token));
2690 }
2691
2692 /* Check whether S is '(' followed by a register name.  Add OT_CHAR
2693    and OT_REG tokens for them if so, and return a pointer to the first
2694    unconsumed character.  Return null otherwise.  */
2695
2696 static char *
2697 mips_parse_base_start (char *s)
2698 {
2699   struct mips_operand_token token;
2700   unsigned int regno, channels;
2701   bfd_boolean decrement_p;
2702
2703   if (*s != '(')
2704     return 0;
2705
2706   ++s;
2707   SKIP_SPACE_TABS (s);
2708
2709   /* Only match "--" as part of a base expression.  In other contexts "--X"
2710      is a double negative.  */
2711   decrement_p = (s[0] == '-' && s[1] == '-');
2712   if (decrement_p)
2713     {
2714       s += 2;
2715       SKIP_SPACE_TABS (s);
2716     }
2717
2718   /* Allow a channel specifier because that leads to better error messages
2719      than treating something like "$vf0x++" as an expression.  */
2720   if (!mips_parse_register (&s, &regno, &channels))
2721     return 0;
2722
2723   token.u.ch = '(';
2724   mips_add_token (&token, OT_CHAR);
2725
2726   if (decrement_p)
2727     {
2728       token.u.ch = '-';
2729       mips_add_token (&token, OT_DOUBLE_CHAR);
2730     }
2731
2732   token.u.regno = regno;
2733   mips_add_token (&token, OT_REG);
2734
2735   if (channels)
2736     {
2737       token.u.channels = channels;
2738       mips_add_token (&token, OT_CHANNELS);
2739     }
2740
2741   /* For consistency, only match "++" as part of base expressions too.  */
2742   SKIP_SPACE_TABS (s);
2743   if (s[0] == '+' && s[1] == '+')
2744     {
2745       s += 2;
2746       token.u.ch = '+';
2747       mips_add_token (&token, OT_DOUBLE_CHAR);
2748     }
2749
2750   return s;
2751 }
2752
2753 /* Parse one or more tokens from S.  Return a pointer to the first
2754    unconsumed character on success.  Return null if an error was found
2755    and store the error text in insn_error.  FLOAT_FORMAT is as for
2756    mips_parse_arguments.  */
2757
2758 static char *
2759 mips_parse_argument_token (char *s, char float_format)
2760 {
2761   char *end, *save_in, *err;
2762   unsigned int regno1, regno2, channels;
2763   struct mips_operand_token token;
2764
2765   /* First look for "($reg", since we want to treat that as an
2766      OT_CHAR and OT_REG rather than an expression.  */
2767   end = mips_parse_base_start (s);
2768   if (end)
2769     return end;
2770
2771   /* Handle other characters that end up as OT_CHARs.  */
2772   if (*s == ')' || *s == ',')
2773     {
2774       token.u.ch = *s;
2775       mips_add_token (&token, OT_CHAR);
2776       ++s;
2777       return s;
2778     }
2779
2780   /* Handle tokens that start with a register.  */
2781   if (mips_parse_register (&s, &regno1, &channels))
2782     {
2783       if (channels)
2784         {
2785           /* A register and a VU0 channel suffix.  */
2786           token.u.regno = regno1;
2787           mips_add_token (&token, OT_REG);
2788
2789           token.u.channels = channels;
2790           mips_add_token (&token, OT_CHANNELS);
2791           return s;
2792         }
2793
2794       SKIP_SPACE_TABS (s);
2795       if (*s == '-')
2796         {
2797           /* A register range.  */
2798           ++s;
2799           SKIP_SPACE_TABS (s);
2800           if (!mips_parse_register (&s, &regno2, NULL))
2801             {
2802               insn_error = _("Invalid register range");
2803               return 0;
2804             }
2805
2806           token.u.reg_range.regno1 = regno1;
2807           token.u.reg_range.regno2 = regno2;
2808           mips_add_token (&token, OT_REG_RANGE);
2809           return s;
2810         }
2811       else if (*s == '[')
2812         {
2813           /* A vector element.  */
2814           expressionS element;
2815
2816           ++s;
2817           SKIP_SPACE_TABS (s);
2818           my_getExpression (&element, s);
2819           if (element.X_op != O_constant)
2820             {
2821               insn_error = _("Vector element must be constant");
2822               return 0;
2823             }
2824           s = expr_end;
2825           SKIP_SPACE_TABS (s);
2826           if (*s != ']')
2827             {
2828               insn_error = _("Missing `]'");
2829               return 0;
2830             }
2831           ++s;
2832
2833           token.u.reg_element.regno = regno1;
2834           token.u.reg_element.index = element.X_add_number;
2835           mips_add_token (&token, OT_REG_ELEMENT);
2836           return s;
2837         }
2838
2839       /* Looks like just a plain register.  */
2840       token.u.regno = regno1;
2841       mips_add_token (&token, OT_REG);
2842       return s;
2843     }
2844
2845   if (float_format)
2846     {
2847       /* First try to treat expressions as floats.  */
2848       save_in = input_line_pointer;
2849       input_line_pointer = s;
2850       err = md_atof (float_format, (char *) token.u.flt.data,
2851                      &token.u.flt.length);
2852       end = input_line_pointer;
2853       input_line_pointer = save_in;
2854       if (err && *err)
2855         {
2856           insn_error = err;
2857           return 0;
2858         }
2859       if (s != end)
2860         {
2861           mips_add_token (&token, OT_FLOAT);
2862           return end;
2863         }
2864     }
2865
2866   /* Treat everything else as an integer expression.  */
2867   token.u.integer.relocs[0] = BFD_RELOC_UNUSED;
2868   token.u.integer.relocs[1] = BFD_RELOC_UNUSED;
2869   token.u.integer.relocs[2] = BFD_RELOC_UNUSED;
2870   my_getSmallExpression (&token.u.integer.value, token.u.integer.relocs, s);
2871   s = expr_end;
2872   mips_add_token (&token, OT_INTEGER);
2873   return s;
2874 }
2875
2876 /* S points to the operand list for an instruction.  FLOAT_FORMAT is 'f'
2877    if expressions should be treated as 32-bit floating-point constants,
2878    'd' if they should be treated as 64-bit floating-point constants,
2879    or 0 if they should be treated as integer expressions (the usual case).
2880
2881    Return a list of tokens on success, otherwise return 0.  The caller
2882    must obstack_free the list after use.  */
2883
2884 static struct mips_operand_token *
2885 mips_parse_arguments (char *s, char float_format)
2886 {
2887   struct mips_operand_token token;
2888
2889   SKIP_SPACE_TABS (s);
2890   while (*s)
2891     {
2892       s = mips_parse_argument_token (s, float_format);
2893       if (!s)
2894         {
2895           obstack_free (&mips_operand_tokens,
2896                         obstack_finish (&mips_operand_tokens));
2897           return 0;
2898         }
2899       SKIP_SPACE_TABS (s);
2900     }
2901   mips_add_token (&token, OT_END);
2902   return (struct mips_operand_token *) obstack_finish (&mips_operand_tokens);
2903 }
2904
2905 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
2906    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
2907
2908 static bfd_boolean
2909 is_opcode_valid (const struct mips_opcode *mo)
2910 {
2911   int isa = mips_opts.isa;
2912   int ase = mips_opts.ase;
2913   int fp_s, fp_d;
2914   unsigned int i;
2915
2916   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
2917     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2918       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
2919         ase |= mips_ases[i].flags64;
2920
2921   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
2922     return FALSE;
2923
2924   /* Check whether the instruction or macro requires single-precision or
2925      double-precision floating-point support.  Note that this information is
2926      stored differently in the opcode table for insns and macros.  */
2927   if (mo->pinfo == INSN_MACRO)
2928     {
2929       fp_s = mo->pinfo2 & INSN2_M_FP_S;
2930       fp_d = mo->pinfo2 & INSN2_M_FP_D;
2931     }
2932   else
2933     {
2934       fp_s = mo->pinfo & FP_S;
2935       fp_d = mo->pinfo & FP_D;
2936     }
2937
2938   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
2939     return FALSE;
2940
2941   if (fp_s && mips_opts.soft_float)
2942     return FALSE;
2943
2944   return TRUE;
2945 }
2946
2947 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
2948    selected ISA and architecture.  */
2949
2950 static bfd_boolean
2951 is_opcode_valid_16 (const struct mips_opcode *mo)
2952 {
2953   return opcode_is_member (mo, mips_opts.isa, 0, mips_opts.arch);
2954 }
2955
2956 /* Return TRUE if the size of the microMIPS opcode MO matches one
2957    explicitly requested.  Always TRUE in the standard MIPS mode.  */
2958
2959 static bfd_boolean
2960 is_size_valid (const struct mips_opcode *mo)
2961 {
2962   if (!mips_opts.micromips)
2963     return TRUE;
2964
2965   if (mips_opts.insn32)
2966     {
2967       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
2968         return FALSE;
2969       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
2970         return FALSE;
2971     }
2972   if (!forced_insn_length)
2973     return TRUE;
2974   if (mo->pinfo == INSN_MACRO)
2975     return FALSE;
2976   return forced_insn_length == micromips_insn_length (mo);
2977 }
2978
2979 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
2980    of the preceding instruction.  Always TRUE in the standard MIPS mode.
2981
2982    We don't accept macros in 16-bit delay slots to avoid a case where
2983    a macro expansion fails because it relies on a preceding 32-bit real
2984    instruction to have matched and does not handle the operands correctly.
2985    The only macros that may expand to 16-bit instructions are JAL that
2986    cannot be placed in a delay slot anyway, and corner cases of BALIGN
2987    and BGT (that likewise cannot be placed in a delay slot) that decay to
2988    a NOP.  In all these cases the macros precede any corresponding real
2989    instruction definitions in the opcode table, so they will match in the
2990    second pass where the size of the delay slot is ignored and therefore
2991    produce correct code.  */
2992
2993 static bfd_boolean
2994 is_delay_slot_valid (const struct mips_opcode *mo)
2995 {
2996   if (!mips_opts.micromips)
2997     return TRUE;
2998
2999   if (mo->pinfo == INSN_MACRO)
3000     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
3001   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
3002       && micromips_insn_length (mo) != 4)
3003     return FALSE;
3004   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
3005       && micromips_insn_length (mo) != 2)
3006     return FALSE;
3007
3008   return TRUE;
3009 }
3010
3011 /* For consistency checking, verify that all bits of OPCODE are specified
3012    either by the match/mask part of the instruction definition, or by the
3013    operand list.  Also build up a list of operands in OPERANDS.
3014
3015    INSN_BITS says which bits of the instruction are significant.
3016    If OPCODE is a standard or microMIPS instruction, DECODE_OPERAND
3017    provides the mips_operand description of each operand.  DECODE_OPERAND
3018    is null for MIPS16 instructions.  */
3019
3020 static int
3021 validate_mips_insn (const struct mips_opcode *opcode,
3022                     unsigned long insn_bits,
3023                     const struct mips_operand *(*decode_operand) (const char *),
3024                     struct mips_operand_array *operands)
3025 {
3026   const char *s;
3027   unsigned long used_bits, doubled, undefined, opno, mask;
3028   const struct mips_operand *operand;
3029
3030   mask = (opcode->pinfo == INSN_MACRO ? 0 : opcode->mask);
3031   if ((mask & opcode->match) != opcode->match)
3032     {
3033       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
3034               opcode->name, opcode->args);
3035       return 0;
3036     }
3037   used_bits = 0;
3038   opno = 0;
3039   if (opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX)
3040     used_bits = mips_insert_operand (&mips_vu0_channel_mask, used_bits, -1);
3041   for (s = opcode->args; *s; ++s)
3042     switch (*s)
3043       {
3044       case ',':
3045       case '(':
3046       case ')':
3047         break;
3048
3049       case '#':
3050         s++;
3051         break;
3052
3053       default:
3054         if (!decode_operand)
3055           operand = decode_mips16_operand (*s, FALSE);
3056         else
3057           operand = decode_operand (s);
3058         if (!operand && opcode->pinfo != INSN_MACRO)
3059           {
3060             as_bad (_("internal: unknown operand type: %s %s"),
3061                     opcode->name, opcode->args);
3062             return 0;
3063           }
3064         gas_assert (opno < MAX_OPERANDS);
3065         operands->operand[opno] = operand;
3066         if (operand && operand->type != OP_VU0_MATCH_SUFFIX)
3067           {
3068             used_bits = mips_insert_operand (operand, used_bits, -1);
3069             if (operand->type == OP_MDMX_IMM_REG)
3070               /* Bit 5 is the format selector (OB vs QH).  The opcode table
3071                  has separate entries for each format.  */
3072               used_bits &= ~(1 << (operand->lsb + 5));
3073             if (operand->type == OP_ENTRY_EXIT_LIST)
3074               used_bits &= ~(mask & 0x700);
3075           }
3076         /* Skip prefix characters.  */
3077         if (decode_operand && (*s == '+' || *s == 'm'))
3078           ++s;
3079         opno += 1;
3080         break;
3081       }
3082   doubled = used_bits & mask & insn_bits;
3083   if (doubled)
3084     {
3085       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
3086                 " %s %s"), doubled, opcode->name, opcode->args);
3087       return 0;
3088     }
3089   used_bits |= mask;
3090   undefined = ~used_bits & insn_bits;
3091   if (opcode->pinfo != INSN_MACRO && undefined)
3092     {
3093       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
3094               undefined, opcode->name, opcode->args);
3095       return 0;
3096     }
3097   used_bits &= ~insn_bits;
3098   if (used_bits)
3099     {
3100       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
3101               used_bits, opcode->name, opcode->args);
3102       return 0;
3103     }
3104   return 1;
3105 }
3106
3107 /* The MIPS16 version of validate_mips_insn.  */
3108
3109 static int
3110 validate_mips16_insn (const struct mips_opcode *opcode,
3111                       struct mips_operand_array *operands)
3112 {
3113   if (opcode->args[0] == 'a' || opcode->args[0] == 'i')
3114     {
3115       /* In this case OPCODE defines the first 16 bits in a 32-bit jump
3116          instruction.  Use TMP to describe the full instruction.  */
3117       struct mips_opcode tmp;
3118
3119       tmp = *opcode;
3120       tmp.match <<= 16;
3121       tmp.mask <<= 16;
3122       return validate_mips_insn (&tmp, 0xffffffff, 0, operands);
3123     }
3124   return validate_mips_insn (opcode, 0xffff, 0, operands);
3125 }
3126
3127 /* The microMIPS version of validate_mips_insn.  */
3128
3129 static int
3130 validate_micromips_insn (const struct mips_opcode *opc,
3131                          struct mips_operand_array *operands)
3132 {
3133   unsigned long insn_bits;
3134   unsigned long major;
3135   unsigned int length;
3136
3137   if (opc->pinfo == INSN_MACRO)
3138     return validate_mips_insn (opc, 0xffffffff, decode_micromips_operand,
3139                                operands);
3140
3141   length = micromips_insn_length (opc);
3142   if (length != 2 && length != 4)
3143     {
3144       as_bad (_("Internal error: bad microMIPS opcode (incorrect length: %u): "
3145                 "%s %s"), length, opc->name, opc->args);
3146       return 0;
3147     }
3148   major = opc->match >> (10 + 8 * (length - 2));
3149   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
3150       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
3151     {
3152       as_bad (_("Internal error: bad microMIPS opcode "
3153                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
3154       return 0;
3155     }
3156
3157   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
3158   insn_bits = 1 << 4 * length;
3159   insn_bits <<= 4 * length;
3160   insn_bits -= 1;
3161   return validate_mips_insn (opc, insn_bits, decode_micromips_operand,
3162                              operands);
3163 }
3164
3165 /* This function is called once, at assembler startup time.  It should set up
3166    all the tables, etc. that the MD part of the assembler will need.  */
3167
3168 void
3169 md_begin (void)
3170 {
3171   const char *retval = NULL;
3172   int i = 0;
3173   int broken = 0;
3174
3175   if (mips_pic != NO_PIC)
3176     {
3177       if (g_switch_seen && g_switch_value != 0)
3178         as_bad (_("-G may not be used in position-independent code"));
3179       g_switch_value = 0;
3180     }
3181
3182   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_arch))
3183     as_warn (_("Could not set architecture and machine"));
3184
3185   op_hash = hash_new ();
3186
3187   mips_operands = XCNEWVEC (struct mips_operand_array, NUMOPCODES);
3188   for (i = 0; i < NUMOPCODES;)
3189     {
3190       const char *name = mips_opcodes[i].name;
3191
3192       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
3193       if (retval != NULL)
3194         {
3195           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
3196                    mips_opcodes[i].name, retval);
3197           /* Probably a memory allocation problem?  Give up now.  */
3198           as_fatal (_("Broken assembler.  No assembly attempted."));
3199         }
3200       do
3201         {
3202           if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
3203                                    decode_mips_operand, &mips_operands[i]))
3204             broken = 1;
3205           if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3206             {
3207               create_insn (&nop_insn, mips_opcodes + i);
3208               if (mips_fix_loongson2f_nop)
3209                 nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
3210               nop_insn.fixed_p = 1;
3211             }
3212           ++i;
3213         }
3214       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
3215     }
3216
3217   mips16_op_hash = hash_new ();
3218   mips16_operands = XCNEWVEC (struct mips_operand_array,
3219                               bfd_mips16_num_opcodes);
3220
3221   i = 0;
3222   while (i < bfd_mips16_num_opcodes)
3223     {
3224       const char *name = mips16_opcodes[i].name;
3225
3226       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
3227       if (retval != NULL)
3228         as_fatal (_("internal: can't hash `%s': %s"),
3229                   mips16_opcodes[i].name, retval);
3230       do
3231         {
3232           if (!validate_mips16_insn (&mips16_opcodes[i], &mips16_operands[i]))
3233             broken = 1;
3234           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3235             {
3236               create_insn (&mips16_nop_insn, mips16_opcodes + i);
3237               mips16_nop_insn.fixed_p = 1;
3238             }
3239           ++i;
3240         }
3241       while (i < bfd_mips16_num_opcodes
3242              && strcmp (mips16_opcodes[i].name, name) == 0);
3243     }
3244
3245   micromips_op_hash = hash_new ();
3246   micromips_operands = XCNEWVEC (struct mips_operand_array,
3247                                  bfd_micromips_num_opcodes);
3248
3249   i = 0;
3250   while (i < bfd_micromips_num_opcodes)
3251     {
3252       const char *name = micromips_opcodes[i].name;
3253
3254       retval = hash_insert (micromips_op_hash, name,
3255                             (void *) &micromips_opcodes[i]);
3256       if (retval != NULL)
3257         as_fatal (_("internal: can't hash `%s': %s"),
3258                   micromips_opcodes[i].name, retval);
3259       do
3260         {
3261           struct mips_cl_insn *micromips_nop_insn;
3262
3263           if (!validate_micromips_insn (&micromips_opcodes[i],
3264                                         &micromips_operands[i]))
3265             broken = 1;
3266
3267           if (micromips_opcodes[i].pinfo != INSN_MACRO)
3268             {
3269               if (micromips_insn_length (micromips_opcodes + i) == 2)
3270                 micromips_nop_insn = &micromips_nop16_insn;
3271               else if (micromips_insn_length (micromips_opcodes + i) == 4)
3272                 micromips_nop_insn = &micromips_nop32_insn;
3273               else
3274                 continue;
3275
3276               if (micromips_nop_insn->insn_mo == NULL
3277                   && strcmp (name, "nop") == 0)
3278                 {
3279                   create_insn (micromips_nop_insn, micromips_opcodes + i);
3280                   micromips_nop_insn->fixed_p = 1;
3281                 }
3282             }
3283         }
3284       while (++i < bfd_micromips_num_opcodes
3285              && strcmp (micromips_opcodes[i].name, name) == 0);
3286     }
3287
3288   if (broken)
3289     as_fatal (_("Broken assembler.  No assembly attempted."));
3290
3291   /* We add all the general register names to the symbol table.  This
3292      helps us detect invalid uses of them.  */
3293   for (i = 0; reg_names[i].name; i++) 
3294     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
3295                                      reg_names[i].num, /* & RNUM_MASK, */
3296                                      &zero_address_frag));
3297   if (HAVE_NEWABI)
3298     for (i = 0; reg_names_n32n64[i].name; i++) 
3299       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
3300                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
3301                                        &zero_address_frag));
3302   else
3303     for (i = 0; reg_names_o32[i].name; i++) 
3304       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
3305                                        reg_names_o32[i].num, /* & RNUM_MASK, */
3306                                        &zero_address_frag));
3307
3308   for (i = 0; i < 32; i++)
3309     {
3310       char regname[7];
3311
3312       /* R5900 VU0 floating-point register.  */
3313       regname[sizeof (rename) - 1] = 0;
3314       snprintf (regname, sizeof (regname) - 1, "$vf%d", i);
3315       symbol_table_insert (symbol_new (regname, reg_section,
3316                                        RTYPE_VF | i, &zero_address_frag));
3317
3318       /* R5900 VU0 integer register.  */
3319       snprintf (regname, sizeof (regname) - 1, "$vi%d", i);
3320       symbol_table_insert (symbol_new (regname, reg_section,
3321                                        RTYPE_VI | i, &zero_address_frag));
3322
3323     }
3324
3325   obstack_init (&mips_operand_tokens);
3326
3327   mips_no_prev_insn ();
3328
3329   mips_gprmask = 0;
3330   mips_cprmask[0] = 0;
3331   mips_cprmask[1] = 0;
3332   mips_cprmask[2] = 0;
3333   mips_cprmask[3] = 0;
3334
3335   /* set the default alignment for the text section (2**2) */
3336   record_alignment (text_section, 2);
3337
3338   bfd_set_gp_size (stdoutput, g_switch_value);
3339
3340   /* On a native system other than VxWorks, sections must be aligned
3341      to 16 byte boundaries.  When configured for an embedded ELF
3342      target, we don't bother.  */
3343   if (strncmp (TARGET_OS, "elf", 3) != 0
3344       && strncmp (TARGET_OS, "vxworks", 7) != 0)
3345     {
3346       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
3347       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
3348       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
3349     }
3350
3351   /* Create a .reginfo section for register masks and a .mdebug
3352      section for debugging information.  */
3353   {
3354     segT seg;
3355     subsegT subseg;
3356     flagword flags;
3357     segT sec;
3358
3359     seg = now_seg;
3360     subseg = now_subseg;
3361
3362     /* The ABI says this section should be loaded so that the
3363        running program can access it.  However, we don't load it
3364        if we are configured for an embedded target */
3365     flags = SEC_READONLY | SEC_DATA;
3366     if (strncmp (TARGET_OS, "elf", 3) != 0)
3367       flags |= SEC_ALLOC | SEC_LOAD;
3368
3369     if (mips_abi != N64_ABI)
3370       {
3371         sec = subseg_new (".reginfo", (subsegT) 0);
3372
3373         bfd_set_section_flags (stdoutput, sec, flags);
3374         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
3375
3376         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
3377       }
3378     else
3379       {
3380         /* The 64-bit ABI uses a .MIPS.options section rather than
3381            .reginfo section.  */
3382         sec = subseg_new (".MIPS.options", (subsegT) 0);
3383         bfd_set_section_flags (stdoutput, sec, flags);
3384         bfd_set_section_alignment (stdoutput, sec, 3);
3385
3386         /* Set up the option header.  */
3387         {
3388           Elf_Internal_Options opthdr;
3389           char *f;
3390
3391           opthdr.kind = ODK_REGINFO;
3392           opthdr.size = (sizeof (Elf_External_Options)
3393                          + sizeof (Elf64_External_RegInfo));
3394           opthdr.section = 0;
3395           opthdr.info = 0;
3396           f = frag_more (sizeof (Elf_External_Options));
3397           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
3398                                          (Elf_External_Options *) f);
3399
3400           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
3401         }
3402       }
3403
3404     if (ECOFF_DEBUGGING)
3405       {
3406         sec = subseg_new (".mdebug", (subsegT) 0);
3407         (void) bfd_set_section_flags (stdoutput, sec,
3408                                       SEC_HAS_CONTENTS | SEC_READONLY);
3409         (void) bfd_set_section_alignment (stdoutput, sec, 2);
3410       }
3411     else if (mips_flag_pdr)
3412       {
3413         pdr_seg = subseg_new (".pdr", (subsegT) 0);
3414         (void) bfd_set_section_flags (stdoutput, pdr_seg,
3415                                       SEC_READONLY | SEC_RELOC
3416                                       | SEC_DEBUGGING);
3417         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
3418       }
3419
3420     subseg_set (seg, subseg);
3421   }
3422
3423   if (! ECOFF_DEBUGGING)
3424     md_obj_begin ();
3425
3426   if (mips_fix_vr4120)
3427     init_vr4120_conflicts ();
3428 }
3429
3430 void
3431 md_mips_end (void)
3432 {
3433   mips_emit_delays ();
3434   if (! ECOFF_DEBUGGING)
3435     md_obj_end ();
3436 }
3437
3438 void
3439 md_assemble (char *str)
3440 {
3441   struct mips_cl_insn insn;
3442   bfd_reloc_code_real_type unused_reloc[3]
3443     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
3444
3445   imm_expr.X_op = O_absent;
3446   imm2_expr.X_op = O_absent;
3447   offset_expr.X_op = O_absent;
3448   offset_reloc[0] = BFD_RELOC_UNUSED;
3449   offset_reloc[1] = BFD_RELOC_UNUSED;
3450   offset_reloc[2] = BFD_RELOC_UNUSED;
3451
3452   mips_mark_labels ();
3453   mips_assembling_insn = TRUE;
3454
3455   if (mips_opts.mips16)
3456     mips16_ip (str, &insn);
3457   else
3458     {
3459       mips_ip (str, &insn);
3460       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
3461             str, insn.insn_opcode));
3462     }
3463
3464   if (insn_error)
3465     as_bad ("%s `%s'", insn_error, str);
3466   else if (insn.insn_mo->pinfo == INSN_MACRO)
3467     {
3468       macro_start ();
3469       if (mips_opts.mips16)
3470         mips16_macro (&insn);
3471       else
3472         macro (&insn, str);
3473       macro_end ();
3474     }
3475   else
3476     {
3477       if (offset_expr.X_op != O_absent)
3478         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
3479       else
3480         append_insn (&insn, NULL, unused_reloc, FALSE);
3481     }
3482
3483   mips_assembling_insn = FALSE;
3484 }
3485
3486 /* Convenience functions for abstracting away the differences between
3487    MIPS16 and non-MIPS16 relocations.  */
3488
3489 static inline bfd_boolean
3490 mips16_reloc_p (bfd_reloc_code_real_type reloc)
3491 {
3492   switch (reloc)
3493     {
3494     case BFD_RELOC_MIPS16_JMP:
3495     case BFD_RELOC_MIPS16_GPREL:
3496     case BFD_RELOC_MIPS16_GOT16:
3497     case BFD_RELOC_MIPS16_CALL16:
3498     case BFD_RELOC_MIPS16_HI16_S:
3499     case BFD_RELOC_MIPS16_HI16:
3500     case BFD_RELOC_MIPS16_LO16:
3501       return TRUE;
3502
3503     default:
3504       return FALSE;
3505     }
3506 }
3507
3508 static inline bfd_boolean
3509 micromips_reloc_p (bfd_reloc_code_real_type reloc)
3510 {
3511   switch (reloc)
3512     {
3513     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3514     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3515     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3516     case BFD_RELOC_MICROMIPS_GPREL16:
3517     case BFD_RELOC_MICROMIPS_JMP:
3518     case BFD_RELOC_MICROMIPS_HI16:
3519     case BFD_RELOC_MICROMIPS_HI16_S:
3520     case BFD_RELOC_MICROMIPS_LO16:
3521     case BFD_RELOC_MICROMIPS_LITERAL:
3522     case BFD_RELOC_MICROMIPS_GOT16:
3523     case BFD_RELOC_MICROMIPS_CALL16:
3524     case BFD_RELOC_MICROMIPS_GOT_HI16:
3525     case BFD_RELOC_MICROMIPS_GOT_LO16:
3526     case BFD_RELOC_MICROMIPS_CALL_HI16:
3527     case BFD_RELOC_MICROMIPS_CALL_LO16:
3528     case BFD_RELOC_MICROMIPS_SUB:
3529     case BFD_RELOC_MICROMIPS_GOT_PAGE:
3530     case BFD_RELOC_MICROMIPS_GOT_OFST:
3531     case BFD_RELOC_MICROMIPS_GOT_DISP:
3532     case BFD_RELOC_MICROMIPS_HIGHEST:
3533     case BFD_RELOC_MICROMIPS_HIGHER:
3534     case BFD_RELOC_MICROMIPS_SCN_DISP:
3535     case BFD_RELOC_MICROMIPS_JALR:
3536       return TRUE;
3537
3538     default:
3539       return FALSE;
3540     }
3541 }
3542
3543 static inline bfd_boolean
3544 jmp_reloc_p (bfd_reloc_code_real_type reloc)
3545 {
3546   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
3547 }
3548
3549 static inline bfd_boolean
3550 got16_reloc_p (bfd_reloc_code_real_type reloc)
3551 {
3552   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
3553           || reloc == BFD_RELOC_MICROMIPS_GOT16);
3554 }
3555
3556 static inline bfd_boolean
3557 hi16_reloc_p (bfd_reloc_code_real_type reloc)
3558 {
3559   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
3560           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
3561 }
3562
3563 static inline bfd_boolean
3564 lo16_reloc_p (bfd_reloc_code_real_type reloc)
3565 {
3566   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
3567           || reloc == BFD_RELOC_MICROMIPS_LO16);
3568 }
3569
3570 static inline bfd_boolean
3571 jalr_reloc_p (bfd_reloc_code_real_type reloc)
3572 {
3573   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
3574 }
3575
3576 static inline bfd_boolean
3577 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
3578 {
3579   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
3580           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
3581 }
3582
3583 /* Return true if RELOC is a PC-relative relocation that does not have
3584    full address range.  */
3585
3586 static inline bfd_boolean
3587 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
3588 {
3589   switch (reloc)
3590     {
3591     case BFD_RELOC_16_PCREL_S2:
3592     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3593     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3594     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3595       return TRUE;
3596
3597     case BFD_RELOC_32_PCREL:
3598       return HAVE_64BIT_ADDRESSES;
3599
3600     default:
3601       return FALSE;
3602     }
3603 }
3604
3605 /* Return true if the given relocation might need a matching %lo().
3606    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
3607    need a matching %lo() when applied to local symbols.  */
3608
3609 static inline bfd_boolean
3610 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
3611 {
3612   return (HAVE_IN_PLACE_ADDENDS
3613           && (hi16_reloc_p (reloc)
3614               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
3615                  all GOT16 relocations evaluate to "G".  */
3616               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
3617 }
3618
3619 /* Return the type of %lo() reloc needed by RELOC, given that
3620    reloc_needs_lo_p.  */
3621
3622 static inline bfd_reloc_code_real_type
3623 matching_lo_reloc (bfd_reloc_code_real_type reloc)
3624 {
3625   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
3626           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
3627              : BFD_RELOC_LO16));
3628 }
3629
3630 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
3631    relocation.  */
3632
3633 static inline bfd_boolean
3634 fixup_has_matching_lo_p (fixS *fixp)
3635 {
3636   return (fixp->fx_next != NULL
3637           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
3638           && fixp->fx_addsy == fixp->fx_next->fx_addsy
3639           && fixp->fx_offset == fixp->fx_next->fx_offset);
3640 }
3641
3642 /* Move all labels in LABELS to the current insertion point.  TEXT_P
3643    says whether the labels refer to text or data.  */
3644
3645 static void
3646 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
3647 {
3648   struct insn_label_list *l;
3649   valueT val;
3650
3651   for (l = labels; l != NULL; l = l->next)
3652     {
3653       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
3654       symbol_set_frag (l->label, frag_now);
3655       val = (valueT) frag_now_fix ();
3656       /* MIPS16/microMIPS text labels are stored as odd.  */
3657       if (text_p && HAVE_CODE_COMPRESSION)
3658         ++val;
3659       S_SET_VALUE (l->label, val);
3660     }
3661 }
3662
3663 /* Move all labels in insn_labels to the current insertion point
3664    and treat them as text labels.  */
3665
3666 static void
3667 mips_move_text_labels (void)
3668 {
3669   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
3670 }
3671
3672 static bfd_boolean
3673 s_is_linkonce (symbolS *sym, segT from_seg)
3674 {
3675   bfd_boolean linkonce = FALSE;
3676   segT symseg = S_GET_SEGMENT (sym);
3677
3678   if (symseg != from_seg && !S_IS_LOCAL (sym))
3679     {
3680       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
3681         linkonce = TRUE;
3682       /* The GNU toolchain uses an extension for ELF: a section
3683          beginning with the magic string .gnu.linkonce is a
3684          linkonce section.  */
3685       if (strncmp (segment_name (symseg), ".gnu.linkonce",
3686                    sizeof ".gnu.linkonce" - 1) == 0)
3687         linkonce = TRUE;
3688     }
3689   return linkonce;
3690 }
3691
3692 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
3693    linker to handle them specially, such as generating jalx instructions
3694    when needed.  We also make them odd for the duration of the assembly,
3695    in order to generate the right sort of code.  We will make them even
3696    in the adjust_symtab routine, while leaving them marked.  This is
3697    convenient for the debugger and the disassembler.  The linker knows
3698    to make them odd again.  */
3699
3700 static void
3701 mips_compressed_mark_label (symbolS *label)
3702 {
3703   gas_assert (HAVE_CODE_COMPRESSION);
3704
3705   if (mips_opts.mips16)
3706     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
3707   else
3708     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
3709   if ((S_GET_VALUE (label) & 1) == 0
3710       /* Don't adjust the address if the label is global or weak, or
3711          in a link-once section, since we'll be emitting symbol reloc
3712          references to it which will be patched up by the linker, and
3713          the final value of the symbol may or may not be MIPS16/microMIPS.  */
3714       && !S_IS_WEAK (label)
3715       && !S_IS_EXTERNAL (label)
3716       && !s_is_linkonce (label, now_seg))
3717     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
3718 }
3719
3720 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
3721
3722 static void
3723 mips_compressed_mark_labels (void)
3724 {
3725   struct insn_label_list *l;
3726
3727   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
3728     mips_compressed_mark_label (l->label);
3729 }
3730
3731 /* End the current frag.  Make it a variant frag and record the
3732    relaxation info.  */
3733
3734 static void
3735 relax_close_frag (void)
3736 {
3737   mips_macro_warning.first_frag = frag_now;
3738   frag_var (rs_machine_dependent, 0, 0,
3739             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
3740             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
3741
3742   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
3743   mips_relax.first_fixup = 0;
3744 }
3745
3746 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
3747    See the comment above RELAX_ENCODE for more details.  */
3748
3749 static void
3750 relax_start (symbolS *symbol)
3751 {
3752   gas_assert (mips_relax.sequence == 0);
3753   mips_relax.sequence = 1;
3754   mips_relax.symbol = symbol;
3755 }
3756
3757 /* Start generating the second version of a relaxable sequence.
3758    See the comment above RELAX_ENCODE for more details.  */
3759
3760 static void
3761 relax_switch (void)
3762 {
3763   gas_assert (mips_relax.sequence == 1);
3764   mips_relax.sequence = 2;
3765 }
3766
3767 /* End the current relaxable sequence.  */
3768
3769 static void
3770 relax_end (void)
3771 {
3772   gas_assert (mips_relax.sequence == 2);
3773   relax_close_frag ();
3774   mips_relax.sequence = 0;
3775 }
3776
3777 /* Return true if IP is a delayed branch or jump.  */
3778
3779 static inline bfd_boolean
3780 delayed_branch_p (const struct mips_cl_insn *ip)
3781 {
3782   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
3783                                 | INSN_COND_BRANCH_DELAY
3784                                 | INSN_COND_BRANCH_LIKELY)) != 0;
3785 }
3786
3787 /* Return true if IP is a compact branch or jump.  */
3788
3789 static inline bfd_boolean
3790 compact_branch_p (const struct mips_cl_insn *ip)
3791 {
3792   return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
3793                                  | INSN2_COND_BRANCH)) != 0;
3794 }
3795
3796 /* Return true if IP is an unconditional branch or jump.  */
3797
3798 static inline bfd_boolean
3799 uncond_branch_p (const struct mips_cl_insn *ip)
3800 {
3801   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
3802           || (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0);
3803 }
3804
3805 /* Return true if IP is a branch-likely instruction.  */
3806
3807 static inline bfd_boolean
3808 branch_likely_p (const struct mips_cl_insn *ip)
3809 {
3810   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
3811 }
3812
3813 /* Return the type of nop that should be used to fill the delay slot
3814    of delayed branch IP.  */
3815
3816 static struct mips_cl_insn *
3817 get_delay_slot_nop (const struct mips_cl_insn *ip)
3818 {
3819   if (mips_opts.micromips
3820       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
3821     return &micromips_nop32_insn;
3822   return NOP_INSN;
3823 }
3824
3825 /* Return a mask that has bit N set if OPCODE reads the register(s)
3826    in operand N.  */
3827
3828 static unsigned int
3829 insn_read_mask (const struct mips_opcode *opcode)
3830 {
3831   return (opcode->pinfo & INSN_READ_ALL) >> INSN_READ_SHIFT;
3832 }
3833
3834 /* Return a mask that has bit N set if OPCODE writes to the register(s)
3835    in operand N.  */
3836
3837 static unsigned int
3838 insn_write_mask (const struct mips_opcode *opcode)
3839 {
3840   return (opcode->pinfo & INSN_WRITE_ALL) >> INSN_WRITE_SHIFT;
3841 }
3842
3843 /* Return a mask of the registers specified by operand OPERAND of INSN.
3844    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
3845    is set.  */
3846
3847 static unsigned int
3848 operand_reg_mask (const struct mips_cl_insn *insn,
3849                   const struct mips_operand *operand,
3850                   unsigned int type_mask)
3851 {
3852   unsigned int uval, vsel;
3853
3854   switch (operand->type)
3855     {
3856     case OP_INT:
3857     case OP_MAPPED_INT:
3858     case OP_MSB:
3859     case OP_PCREL:
3860     case OP_PERF_REG:
3861     case OP_ADDIUSP_INT:
3862     case OP_ENTRY_EXIT_LIST:
3863     case OP_REPEAT_DEST_REG:
3864     case OP_REPEAT_PREV_REG:
3865     case OP_PC:
3866     case OP_VU0_SUFFIX:
3867     case OP_VU0_MATCH_SUFFIX:
3868       abort ();
3869
3870     case OP_REG:
3871     case OP_OPTIONAL_REG:
3872       {
3873         const struct mips_reg_operand *reg_op;
3874
3875         reg_op = (const struct mips_reg_operand *) operand;
3876         if (!(type_mask & (1 << reg_op->reg_type)))
3877           return 0;
3878         uval = insn_extract_operand (insn, operand);
3879         return 1 << mips_decode_reg_operand (reg_op, uval);
3880       }
3881
3882     case OP_REG_PAIR:
3883       {
3884         const struct mips_reg_pair_operand *pair_op;
3885
3886         pair_op = (const struct mips_reg_pair_operand *) operand;
3887         if (!(type_mask & (1 << pair_op->reg_type)))
3888           return 0;
3889         uval = insn_extract_operand (insn, operand);
3890         return (1 << pair_op->reg1_map[uval]) | (1 << pair_op->reg2_map[uval]);
3891       }
3892
3893     case OP_CLO_CLZ_DEST:
3894       if (!(type_mask & (1 << OP_REG_GP)))
3895         return 0;
3896       uval = insn_extract_operand (insn, operand);
3897       return (1 << (uval & 31)) | (1 << (uval >> 5));
3898
3899     case OP_LWM_SWM_LIST:
3900       abort ();
3901
3902     case OP_SAVE_RESTORE_LIST:
3903       abort ();
3904
3905     case OP_MDMX_IMM_REG:
3906       if (!(type_mask & (1 << OP_REG_VEC)))
3907         return 0;
3908       uval = insn_extract_operand (insn, operand);
3909       vsel = uval >> 5;
3910       if ((vsel & 0x18) == 0x18)
3911         return 0;
3912       return 1 << (uval & 31);
3913     }
3914   abort ();
3915 }
3916
3917 /* Return a mask of the registers specified by operands OPNO_MASK of INSN,
3918    where bit N of OPNO_MASK is set if operand N should be included.
3919    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
3920    is set.  */
3921
3922 static unsigned int
3923 insn_reg_mask (const struct mips_cl_insn *insn,
3924                unsigned int type_mask, unsigned int opno_mask)
3925 {
3926   unsigned int opno, reg_mask;
3927
3928   opno = 0;
3929   reg_mask = 0;
3930   while (opno_mask != 0)
3931     {
3932       if (opno_mask & 1)
3933         reg_mask |= operand_reg_mask (insn, insn_opno (insn, opno), type_mask);
3934       opno_mask >>= 1;
3935       opno += 1;
3936     }
3937   return reg_mask;
3938 }
3939
3940 /* Return the mask of core registers that IP reads.  */
3941
3942 static unsigned int
3943 gpr_read_mask (const struct mips_cl_insn *ip)
3944 {
3945   unsigned long pinfo, pinfo2;
3946   unsigned int mask;
3947
3948   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_read_mask (ip->insn_mo));
3949   pinfo = ip->insn_mo->pinfo;
3950   pinfo2 = ip->insn_mo->pinfo2;
3951   if (pinfo & INSN_UDI)
3952     {
3953       /* UDI instructions have traditionally been assumed to read RS
3954          and RT.  */
3955       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
3956       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
3957     }
3958   if (pinfo & INSN_READ_GPR_24)
3959     mask |= 1 << 24;
3960   if (pinfo2 & INSN2_READ_GPR_16)
3961     mask |= 1 << 16;
3962   if (pinfo2 & INSN2_READ_SP)
3963     mask |= 1 << SP;
3964   if (pinfo2 & INSN2_READ_GPR_31)
3965     mask |= 1 << 31;
3966   /* Don't include register 0.  */
3967   return mask & ~1;
3968 }
3969
3970 /* Return the mask of core registers that IP writes.  */
3971
3972 static unsigned int
3973 gpr_write_mask (const struct mips_cl_insn *ip)
3974 {
3975   unsigned long pinfo, pinfo2;
3976   unsigned int mask;
3977
3978   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_write_mask (ip->insn_mo));
3979   pinfo = ip->insn_mo->pinfo;
3980   pinfo2 = ip->insn_mo->pinfo2;
3981   if (pinfo & INSN_WRITE_GPR_24)
3982     mask |= 1 << 24;
3983   if (pinfo & INSN_WRITE_GPR_31)
3984     mask |= 1 << 31;
3985   if (pinfo & INSN_UDI)
3986     /* UDI instructions have traditionally been assumed to write to RD.  */
3987     mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
3988   if (pinfo2 & INSN2_WRITE_SP)
3989     mask |= 1 << SP;
3990   /* Don't include register 0.  */
3991   return mask & ~1;
3992 }
3993
3994 /* Return the mask of floating-point registers that IP reads.  */
3995
3996 static unsigned int
3997 fpr_read_mask (const struct mips_cl_insn *ip)
3998 {
3999   unsigned long pinfo;
4000   unsigned int mask;
4001
4002   mask = insn_reg_mask (ip, (1 << OP_REG_FP) | (1 << OP_REG_VEC),
4003                         insn_read_mask (ip->insn_mo));
4004   pinfo = ip->insn_mo->pinfo;
4005   /* Conservatively treat all operands to an FP_D instruction are doubles.
4006      (This is overly pessimistic for things like cvt.d.s.)  */
4007   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
4008     mask |= mask << 1;
4009   return mask;
4010 }
4011
4012 /* Return the mask of floating-point registers that IP writes.  */
4013
4014 static unsigned int
4015 fpr_write_mask (const struct mips_cl_insn *ip)
4016 {
4017   unsigned long pinfo;
4018   unsigned int mask;
4019
4020   mask = insn_reg_mask (ip, (1 << OP_REG_FP) | (1 << OP_REG_VEC),
4021                         insn_write_mask (ip->insn_mo));
4022   pinfo = ip->insn_mo->pinfo;
4023   /* Conservatively treat all operands to an FP_D instruction are doubles.
4024      (This is overly pessimistic for things like cvt.s.d.)  */
4025   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
4026     mask |= mask << 1;
4027   return mask;
4028 }
4029
4030 /* Operand OPNUM of INSN is an odd-numbered floating-point register.
4031    Check whether that is allowed.  */
4032
4033 static bfd_boolean
4034 mips_oddfpreg_ok (const struct mips_opcode *insn, int opnum)
4035 {
4036   const char *s = insn->name;
4037
4038   if (insn->pinfo == INSN_MACRO)
4039     /* Let a macro pass, we'll catch it later when it is expanded.  */
4040     return TRUE;
4041
4042   if (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa) || mips_opts.arch == CPU_R5900)
4043     {
4044       /* Allow odd registers for single-precision ops.  */
4045       switch (insn->pinfo & (FP_S | FP_D))
4046         {
4047         case FP_S:
4048         case 0:
4049           return TRUE;
4050         case FP_D:
4051           return FALSE;
4052         default:
4053           break;
4054         }
4055
4056       /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
4057       s = strchr (insn->name, '.');
4058       if (s != NULL && opnum == 2)
4059         s = strchr (s + 1, '.');
4060       return (s != NULL && (s[1] == 'w' || s[1] == 's'));
4061     }
4062
4063   /* Single-precision coprocessor loads and moves are OK too.  */
4064   if ((insn->pinfo & FP_S)
4065       && (insn->pinfo & (INSN_COPROC_MEMORY_DELAY | INSN_STORE_MEMORY
4066                          | INSN_LOAD_COPROC_DELAY | INSN_COPROC_MOVE_DELAY)))
4067     return TRUE;
4068
4069   return FALSE;
4070 }
4071
4072 /* Report that user-supplied argument ARGNUM for INSN was VAL, but should
4073    have been in the range [MIN_VAL, MAX_VAL].  PRINT_HEX says whether
4074    this operand is normally printed in hex or decimal.  */
4075
4076 static void
4077 report_bad_range (struct mips_cl_insn *insn, int argnum,
4078                   offsetT val, int min_val, int max_val,
4079                   bfd_boolean print_hex)
4080 {
4081   if (print_hex && val >= 0)
4082     as_bad (_("Operand %d of `%s' must be in the range [0x%x, 0x%x],"
4083               " was 0x%lx."),
4084             argnum, insn->insn_mo->name, min_val, max_val, (unsigned long) val);
4085   else if (print_hex)
4086     as_bad (_("Operand %d of `%s' must be in the range [0x%x, 0x%x],"
4087               " was %ld."),
4088             argnum, insn->insn_mo->name, min_val, max_val, (unsigned long) val);
4089   else
4090     as_bad (_("Operand %d of `%s' must be in the range [%d, %d],"
4091               " was %ld."),
4092             argnum, insn->insn_mo->name, min_val, max_val, (unsigned long) val);
4093 }
4094
4095 /* Report an invalid combination of position and size operands for a bitfield
4096    operation.  POS and SIZE are the values that were given.  */
4097
4098 static void
4099 report_bad_field (offsetT pos, offsetT size)
4100 {
4101   as_bad (_("Invalid field specification (position %ld, size %ld)"),
4102           (unsigned long) pos, (unsigned long) size);
4103 }
4104
4105 /* Information about an instruction argument that we're trying to match.  */
4106 struct mips_arg_info
4107 {
4108   /* The instruction so far.  */
4109   struct mips_cl_insn *insn;
4110
4111   /* The first unconsumed operand token.  */
4112   struct mips_operand_token *token;
4113
4114   /* The 1-based operand number, in terms of insn->insn_mo->args.  */
4115   int opnum;
4116
4117   /* The 1-based argument number, for error reporting.  This does not
4118      count elided optional registers, etc..  */
4119   int argnum;
4120
4121   /* The last OP_REG operand seen, or ILLEGAL_REG if none.  */
4122   unsigned int last_regno;
4123
4124   /* If the first operand was an OP_REG, this is the register that it
4125      specified, otherwise it is ILLEGAL_REG.  */
4126   unsigned int dest_regno;
4127
4128   /* The value of the last OP_INT operand.  Only used for OP_MSB,
4129      where it gives the lsb position.  */
4130   unsigned int last_op_int;
4131
4132   /* If true, match routines should silently reject invalid arguments.
4133      If false, match routines can accept invalid arguments as long as
4134      they report an appropriate error.  They still have the option of
4135      silently rejecting arguments, in which case a generic "Invalid operands"
4136      style of error will be used instead.  */
4137   bfd_boolean soft_match;
4138
4139   /* If true, the OP_INT match routine should treat plain symbolic operands
4140      as if a relocation operator like %lo(...) had been used.  This is only
4141      ever true if the operand can be relocated.  */
4142   bfd_boolean allow_nonconst;
4143
4144   /* When true, the OP_INT match routine should allow unsigned N-bit
4145      arguments to be used where a signed N-bit operand is expected.  */
4146   bfd_boolean lax_max;
4147
4148   /* True if a reference to the current AT register was seen.  */
4149   bfd_boolean seen_at;
4150 };
4151
4152 /* Try to match an OT_CHAR token for character CH.  Consume the token
4153    and return true on success, otherwise return false.  */
4154
4155 static bfd_boolean
4156 match_char (struct mips_arg_info *arg, char ch)
4157 {
4158   if (arg->token->type == OT_CHAR && arg->token->u.ch == ch)
4159     {
4160       ++arg->token;
4161       if (ch == ',')
4162         arg->argnum += 1;
4163       return TRUE;
4164     }
4165   return FALSE;
4166 }
4167
4168 /* Try to get an expression from the next tokens in ARG.  Consume the
4169    tokens and return true on success, storing the expression value in
4170    VALUE and relocation types in R.  */
4171
4172 static bfd_boolean
4173 match_expression (struct mips_arg_info *arg, expressionS *value,
4174                   bfd_reloc_code_real_type *r)
4175 {
4176   if (arg->token->type == OT_INTEGER)
4177     {
4178       *value = arg->token->u.integer.value;
4179       memcpy (r, arg->token->u.integer.relocs, 3 * sizeof (*r));
4180       ++arg->token;
4181       return TRUE;
4182     }
4183
4184   /* Error-reporting is more consistent if we treat registers as O_register
4185      rather than rejecting them outright.  "$1", "($1)" and "(($1))" are
4186      then handled in the same way.  */
4187   if (arg->token->type == OT_REG)
4188     {
4189       value->X_add_number = arg->token->u.regno;
4190       ++arg->token;
4191     }
4192   else if (arg->token[0].type == OT_CHAR
4193            && arg->token[0].u.ch == '('
4194            && arg->token[1].type == OT_REG
4195            && arg->token[2].type == OT_CHAR
4196            && arg->token[2].u.ch == ')')
4197     {
4198       value->X_add_number = arg->token[1].u.regno;
4199       arg->token += 3;
4200     }
4201   else
4202     return FALSE;
4203
4204   value->X_op = O_register;
4205   r[0] = r[1] = r[2] = BFD_RELOC_UNUSED;
4206   return TRUE;
4207 }
4208
4209 /* Try to get a constant expression from the next tokens in ARG.  Consume
4210    the tokens and return return true on success, storing the constant value
4211    in *VALUE.  Use FALLBACK as the value if the match succeeded with an
4212    error.  */
4213
4214 static bfd_boolean
4215 match_const_int (struct mips_arg_info *arg, offsetT *value, offsetT fallback)
4216 {
4217   expressionS ex;
4218   bfd_reloc_code_real_type r[3];
4219
4220   if (!match_expression (arg, &ex, r))
4221     return FALSE;
4222
4223   if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_constant)
4224     *value = ex.X_add_number;
4225   else
4226     {
4227       if (arg->soft_match)
4228         return FALSE;
4229       as_bad (_("Operand %d of `%s' must be constant"),
4230               arg->argnum, arg->insn->insn_mo->name);
4231       *value = fallback;
4232     }
4233   return TRUE;
4234 }
4235
4236 /* Return the RTYPE_* flags for a register operand of type TYPE that
4237    appears in instruction OPCODE.  */
4238
4239 static unsigned int
4240 convert_reg_type (const struct mips_opcode *opcode,
4241                   enum mips_reg_operand_type type)
4242 {
4243   switch (type)
4244     {
4245     case OP_REG_GP:
4246       return RTYPE_NUM | RTYPE_GP;
4247
4248     case OP_REG_FP:
4249       /* Allow vector register names for MDMX if the instruction is a 64-bit
4250          FPR load, store or move (including moves to and from GPRs).  */
4251       if ((mips_opts.ase & ASE_MDMX)
4252           && (opcode->pinfo & FP_D)
4253           && (opcode->pinfo & (INSN_COPROC_MOVE_DELAY
4254                                | INSN_COPROC_MEMORY_DELAY
4255                                | INSN_LOAD_COPROC_DELAY
4256                                | INSN_LOAD_MEMORY_DELAY
4257                                | INSN_STORE_MEMORY)))
4258         return RTYPE_FPU | RTYPE_VEC;
4259       return RTYPE_FPU;
4260
4261     case OP_REG_CCC:
4262       if (opcode->pinfo & (FP_D | FP_S))
4263         return RTYPE_CCC | RTYPE_FCC;
4264       return RTYPE_CCC;
4265
4266     case OP_REG_VEC:
4267       if (opcode->membership & INSN_5400)
4268         return RTYPE_FPU;
4269       return RTYPE_FPU | RTYPE_VEC;
4270
4271     case OP_REG_ACC:
4272       return RTYPE_ACC;
4273
4274     case OP_REG_COPRO:
4275       if (opcode->name[strlen (opcode->name) - 1] == '0')
4276         return RTYPE_NUM | RTYPE_CP0;
4277       return RTYPE_NUM;
4278
4279     case OP_REG_HW:
4280       return RTYPE_NUM;
4281
4282     case OP_REG_VI:
4283       return RTYPE_NUM | RTYPE_VI;
4284
4285     case OP_REG_VF:
4286       return RTYPE_NUM | RTYPE_VF;
4287
4288     case OP_REG_R5900_I:
4289       return RTYPE_R5900_I;
4290
4291     case OP_REG_R5900_Q:
4292       return RTYPE_R5900_Q;
4293
4294     case OP_REG_R5900_R:
4295       return RTYPE_R5900_R;
4296
4297     case OP_REG_R5900_ACC:
4298       return RTYPE_R5900_ACC;
4299     }
4300   abort ();
4301 }
4302
4303 /* ARG is register REGNO, of type TYPE.  Warn about any dubious registers.  */
4304
4305 static void
4306 check_regno (struct mips_arg_info *arg,
4307              enum mips_reg_operand_type type, unsigned int regno)
4308 {
4309   if (AT && type == OP_REG_GP && regno == AT)
4310     arg->seen_at = TRUE;
4311
4312   if (type == OP_REG_FP
4313       && (regno & 1) != 0
4314       && HAVE_32BIT_FPRS
4315       && !mips_oddfpreg_ok (arg->insn->insn_mo, arg->opnum))
4316     as_warn (_("Float register should be even, was %d"), regno);
4317
4318   if (type == OP_REG_CCC)
4319     {
4320       const char *name;
4321       size_t length;
4322
4323       name = arg->insn->insn_mo->name;
4324       length = strlen (name);
4325       if ((regno & 1) != 0
4326           && ((length >= 3 && strcmp (name + length - 3, ".ps") == 0)
4327               || (length >= 5 && strncmp (name + length - 5, "any2", 4) == 0)))
4328         as_warn (_("Condition code register should be even for %s, was %d"),
4329                  name, regno);
4330
4331       if ((regno & 3) != 0
4332           && (length >= 5 && strncmp (name + length - 5, "any4", 4) == 0))
4333         as_warn (_("Condition code register should be 0 or 4 for %s, was %d"),
4334                  name, regno);
4335     }
4336 }
4337
4338 /* ARG is a register with symbol value SYMVAL.  Try to interpret it as
4339    a register of type TYPE.  Return true on success, storing the register
4340    number in *REGNO and warning about any dubious uses.  */
4341
4342 static bfd_boolean
4343 match_regno (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4344              unsigned int symval, unsigned int *regno)
4345 {
4346   if (type == OP_REG_VEC)
4347     symval = mips_prefer_vec_regno (symval);
4348   if (!(symval & convert_reg_type (arg->insn->insn_mo, type)))
4349     return FALSE;
4350
4351   *regno = symval & RNUM_MASK;
4352   check_regno (arg, type, *regno);
4353   return TRUE;
4354 }
4355
4356 /* Try to interpret the next token in ARG as a register of type TYPE.
4357    Consume the token and return true on success, storing the register
4358    number in *REGNO.  Return false on failure.  */
4359
4360 static bfd_boolean
4361 match_reg (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4362            unsigned int *regno)
4363 {
4364   if (arg->token->type == OT_REG
4365       && match_regno (arg, type, arg->token->u.regno, regno))
4366     {
4367       ++arg->token;
4368       return TRUE;
4369     }
4370   return FALSE;
4371 }
4372
4373 /* Try to interpret the next token in ARG as a range of registers of type TYPE.
4374    Consume the token and return true on success, storing the register numbers
4375    in *REGNO1 and *REGNO2.  Return false on failure.  */
4376
4377 static bfd_boolean
4378 match_reg_range (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4379                  unsigned int *regno1, unsigned int *regno2)
4380 {
4381   if (match_reg (arg, type, regno1))
4382     {
4383       *regno2 = *regno1;
4384       return TRUE;
4385     }
4386   if (arg->token->type == OT_REG_RANGE
4387       && match_regno (arg, type, arg->token->u.reg_range.regno1, regno1)
4388       && match_regno (arg, type, arg->token->u.reg_range.regno2, regno2)
4389       && *regno1 <= *regno2)
4390     {
4391       ++arg->token;
4392       return TRUE;
4393     }
4394   return FALSE;
4395 }
4396
4397 /* OP_INT matcher.  */
4398
4399 static bfd_boolean
4400 match_int_operand (struct mips_arg_info *arg,
4401                    const struct mips_operand *operand_base)
4402 {
4403   const struct mips_int_operand *operand;
4404   unsigned int uval;
4405   int min_val, max_val, factor;
4406   offsetT sval;
4407   bfd_boolean print_hex;
4408
4409   operand = (const struct mips_int_operand *) operand_base;
4410   factor = 1 << operand->shift;
4411   min_val = mips_int_operand_min (operand);
4412   max_val = mips_int_operand_max (operand);
4413   if (arg->lax_max)
4414     max_val = ((1 << operand_base->size) - 1) << operand->shift;
4415
4416   if (arg->token->type == OT_CHAR && arg->token->u.ch == '(')
4417     /* Assume we have an elided offset.  The later match will fail
4418        if this turns out to be wrong.  */
4419     sval = 0;
4420   else if (operand_base->lsb == 0
4421            && operand_base->size == 16
4422            && operand->shift == 0
4423            && operand->bias == 0
4424            && (operand->max_val == 32767 || operand->max_val == 65535))
4425     {
4426       /* The operand can be relocated.  */
4427       if (!match_expression (arg, &offset_expr, offset_reloc))
4428         return FALSE;
4429
4430       if (offset_reloc[0] != BFD_RELOC_UNUSED)
4431         /* Relocation operators were used.  Accept the arguent and
4432            leave the relocation value in offset_expr and offset_relocs
4433            for the caller to process.  */
4434         return TRUE;
4435
4436       if (offset_expr.X_op != O_constant)
4437         {
4438           /* If non-constant operands are allowed then leave them for
4439              the caller to process, otherwise fail the match.  */
4440           if (!arg->allow_nonconst)
4441             return FALSE;
4442           offset_reloc[0] = BFD_RELOC_LO16;
4443           return TRUE;
4444         }
4445
4446       /* Clear the global state; we're going to install the operand
4447          ourselves.  */
4448       sval = offset_expr.X_add_number;
4449       offset_expr.X_op = O_absent;
4450     }
4451   else
4452     {
4453       if (!match_const_int (arg, &sval, min_val))
4454         return FALSE;
4455     }
4456
4457   arg->last_op_int = sval;
4458
4459   /* Check the range.  If there's a problem, record the lowest acceptable
4460      value in arg->last_op_int in order to prevent an unhelpful error
4461      from OP_MSB too.
4462
4463      Bit counts have traditionally been printed in hex by the disassembler
4464      but printed as decimal in error messages.  Only resort to hex if
4465      the operand is bigger than 6 bits.  */
4466   print_hex = operand->print_hex && operand_base->size > 6;
4467   if (sval < min_val || sval > max_val)
4468     {
4469       if (arg->soft_match)
4470         return FALSE;
4471       report_bad_range (arg->insn, arg->argnum, sval, min_val, max_val,
4472                         print_hex);
4473       arg->last_op_int = min_val;
4474     }
4475   else if (sval % factor)
4476     {
4477       if (arg->soft_match)
4478         return FALSE;
4479       as_bad (print_hex && sval >= 0
4480               ? _("Operand %d of `%s' must be a factor of %d, was 0x%lx.")
4481               : _("Operand %d of `%s' must be a factor of %d, was %ld."),
4482               arg->argnum, arg->insn->insn_mo->name, factor,
4483               (unsigned long) sval);
4484       arg->last_op_int = min_val;
4485     }
4486
4487   uval = (unsigned int) sval >> operand->shift;
4488   uval -= operand->bias;
4489
4490   /* Handle -mfix-cn63xxp1.  */
4491   if (arg->opnum == 1
4492       && mips_fix_cn63xxp1
4493       && !mips_opts.micromips
4494       && strcmp ("pref", arg->insn->insn_mo->name) == 0)
4495     switch (uval)
4496       {
4497       case 5:
4498       case 25:
4499       case 26:
4500       case 27:
4501       case 28:
4502       case 29:
4503       case 30:
4504       case 31:
4505         /* These are ok.  */
4506         break;
4507
4508       default:
4509         /* The rest must be changed to 28.  */
4510         uval = 28;
4511         break;
4512       }
4513
4514   insn_insert_operand (arg->insn, operand_base, uval);
4515   return TRUE;
4516 }
4517
4518 /* OP_MAPPED_INT matcher.  */
4519
4520 static bfd_boolean
4521 match_mapped_int_operand (struct mips_arg_info *arg,
4522                           const struct mips_operand *operand_base)
4523 {
4524   const struct mips_mapped_int_operand *operand;
4525   unsigned int uval, num_vals;
4526   offsetT sval;
4527
4528   operand = (const struct mips_mapped_int_operand *) operand_base;
4529   if (!match_const_int (arg, &sval, operand->int_map[0]))
4530     return FALSE;
4531
4532   num_vals = 1 << operand_base->size;
4533   for (uval = 0; uval < num_vals; uval++)
4534     if (operand->int_map[uval] == sval)
4535       break;
4536   if (uval == num_vals)
4537     return FALSE;
4538
4539   insn_insert_operand (arg->insn, operand_base, uval);
4540   return TRUE;
4541 }
4542
4543 /* OP_MSB matcher.  */
4544
4545 static bfd_boolean
4546 match_msb_operand (struct mips_arg_info *arg,
4547                    const struct mips_operand *operand_base)
4548 {
4549   const struct mips_msb_operand *operand;
4550   int min_val, max_val, max_high;
4551   offsetT size, sval, high;
4552
4553   operand = (const struct mips_msb_operand *) operand_base;
4554   min_val = operand->bias;
4555   max_val = min_val + (1 << operand_base->size) - 1;
4556   max_high = operand->opsize;
4557
4558   if (!match_const_int (arg, &size, 1))
4559     return FALSE;
4560
4561   high = size + arg->last_op_int;
4562   sval = operand->add_lsb ? high : size;
4563
4564   if (size < 0 || high > max_high || sval < min_val || sval > max_val)
4565     {
4566       if (arg->soft_match)
4567         return FALSE;
4568       report_bad_field (arg->last_op_int, size);
4569       sval = min_val;
4570     }
4571   insn_insert_operand (arg->insn, operand_base, sval - min_val);
4572   return TRUE;
4573 }
4574
4575 /* OP_REG matcher.  */
4576
4577 static bfd_boolean
4578 match_reg_operand (struct mips_arg_info *arg,
4579                    const struct mips_operand *operand_base)
4580 {
4581   const struct mips_reg_operand *operand;
4582   unsigned int regno, uval, num_vals;
4583
4584   operand = (const struct mips_reg_operand *) operand_base;
4585   if (!match_reg (arg, operand->reg_type, &regno))
4586     return FALSE;
4587
4588   if (operand->reg_map)
4589     {
4590       num_vals = 1 << operand->root.size;
4591       for (uval = 0; uval < num_vals; uval++)
4592         if (operand->reg_map[uval] == regno)
4593           break;
4594       if (num_vals == uval)
4595         return FALSE;
4596     }
4597   else
4598     uval = regno;
4599
4600   arg->last_regno = regno;
4601   if (arg->opnum == 1)
4602     arg->dest_regno = regno;
4603   insn_insert_operand (arg->insn, operand_base, uval);
4604   return TRUE;
4605 }
4606
4607 /* OP_REG_PAIR matcher.  */
4608
4609 static bfd_boolean
4610 match_reg_pair_operand (struct mips_arg_info *arg,
4611                         const struct mips_operand *operand_base)
4612 {
4613   const struct mips_reg_pair_operand *operand;
4614   unsigned int regno1, regno2, uval, num_vals;
4615
4616   operand = (const struct mips_reg_pair_operand *) operand_base;
4617   if (!match_reg (arg, operand->reg_type, &regno1)
4618       || !match_char (arg, ',')
4619       || !match_reg (arg, operand->reg_type, &regno2))
4620     return FALSE;
4621
4622   num_vals = 1 << operand_base->size;
4623   for (uval = 0; uval < num_vals; uval++)
4624     if (operand->reg1_map[uval] == regno1 && operand->reg2_map[uval] == regno2)
4625       break;
4626   if (uval == num_vals)
4627     return FALSE;
4628
4629   insn_insert_operand (arg->insn, operand_base, uval);
4630   return TRUE;
4631 }
4632
4633 /* OP_PCREL matcher.  The caller chooses the relocation type.  */
4634
4635 static bfd_boolean
4636 match_pcrel_operand (struct mips_arg_info *arg)
4637 {
4638   bfd_reloc_code_real_type r[3];
4639
4640   return match_expression (arg, &offset_expr, r) && r[0] == BFD_RELOC_UNUSED;
4641 }
4642
4643 /* OP_PERF_REG matcher.  */
4644
4645 static bfd_boolean
4646 match_perf_reg_operand (struct mips_arg_info *arg,
4647                         const struct mips_operand *operand)
4648 {
4649   offsetT sval;
4650
4651   if (!match_const_int (arg, &sval, 0))
4652     return FALSE;
4653
4654   if (sval != 0
4655       && (sval != 1
4656           || (mips_opts.arch == CPU_R5900
4657               && (strcmp (arg->insn->insn_mo->name, "mfps") == 0
4658                   || strcmp (arg->insn->insn_mo->name, "mtps") == 0))))
4659     {
4660       if (arg->soft_match)
4661         return FALSE;
4662       as_bad (_("Invalid performance register (%ld)"), (unsigned long) sval);
4663     }
4664
4665   insn_insert_operand (arg->insn, operand, sval);
4666   return TRUE;
4667 }
4668
4669 /* OP_ADDIUSP matcher.  */
4670
4671 static bfd_boolean
4672 match_addiusp_operand (struct mips_arg_info *arg,
4673                        const struct mips_operand *operand)
4674 {
4675   offsetT sval;
4676   unsigned int uval;
4677
4678   if (!match_const_int (arg, &sval, -256))
4679     return FALSE;
4680
4681   if (sval % 4)
4682     return FALSE;
4683
4684   sval /= 4;
4685   if (!(sval >= -258 && sval <= 257) || (sval >= -2 && sval <= 1))
4686     return FALSE;
4687
4688   uval = (unsigned int) sval;
4689   uval = ((uval >> 1) & ~0xff) | (uval & 0xff);
4690   insn_insert_operand (arg->insn, operand, uval);
4691   return TRUE;
4692 }
4693
4694 /* OP_CLO_CLZ_DEST matcher.  */
4695
4696 static bfd_boolean
4697 match_clo_clz_dest_operand (struct mips_arg_info *arg,
4698                             const struct mips_operand *operand)
4699 {
4700   unsigned int regno;
4701
4702   if (!match_reg (arg, OP_REG_GP, &regno))
4703     return FALSE;
4704
4705   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
4706   return TRUE;
4707 }
4708
4709 /* OP_LWM_SWM_LIST matcher.  */
4710
4711 static bfd_boolean
4712 match_lwm_swm_list_operand (struct mips_arg_info *arg,
4713                             const struct mips_operand *operand)
4714 {
4715   unsigned int reglist, sregs, ra, regno1, regno2;
4716   struct mips_arg_info reset;
4717
4718   reglist = 0;
4719   if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4720     return FALSE;
4721   do
4722     {
4723       if (regno2 == FP && regno1 >= S0 && regno1 <= S7)
4724         {
4725           reglist |= 1 << FP;
4726           regno2 = S7;
4727         }
4728       reglist |= ((1U << regno2 << 1) - 1) & -(1U << regno1);
4729       reset = *arg;
4730     }
4731   while (match_char (arg, ',')
4732          && match_reg_range (arg, OP_REG_GP, &regno1, &regno2));
4733   *arg = reset;
4734
4735   if (operand->size == 2)
4736     {
4737       /* The list must include both ra and s0-sN, for 0 <= N <= 3.  E.g.:
4738
4739          s0, ra
4740          s0, s1, ra, s2, s3
4741          s0-s2, ra
4742
4743          and any permutations of these.  */
4744       if ((reglist & 0xfff1ffff) != 0x80010000)
4745         return FALSE;
4746
4747       sregs = (reglist >> 17) & 7;
4748       ra = 0;
4749     }
4750   else
4751     {
4752       /* The list must include at least one of ra and s0-sN,
4753          for 0 <= N <= 8.  (Note that there is a gap between s7 and s8,
4754          which are $23 and $30 respectively.)  E.g.:
4755
4756          ra
4757          s0
4758          ra, s0, s1, s2
4759          s0-s8
4760          s0-s5, ra
4761
4762          and any permutations of these.  */
4763       if ((reglist & 0x3f00ffff) != 0)
4764         return FALSE;
4765
4766       ra = (reglist >> 27) & 0x10;
4767       sregs = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
4768     }
4769   sregs += 1;
4770   if ((sregs & -sregs) != sregs)
4771     return FALSE;
4772
4773   insn_insert_operand (arg->insn, operand, (ffs (sregs) - 1) | ra);
4774   return TRUE;
4775 }
4776
4777 /* OP_ENTRY_EXIT_LIST matcher.  */
4778
4779 static unsigned int
4780 match_entry_exit_operand (struct mips_arg_info *arg,
4781                           const struct mips_operand *operand)
4782 {
4783   unsigned int mask;
4784   bfd_boolean is_exit;
4785
4786   /* The format is the same for both ENTRY and EXIT, but the constraints
4787      are different.  */
4788   is_exit = strcmp (arg->insn->insn_mo->name, "exit") == 0;
4789   mask = (is_exit ? 7 << 3 : 0);
4790   do
4791     {
4792       unsigned int regno1, regno2;
4793       bfd_boolean is_freg;
4794
4795       if (match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4796         is_freg = FALSE;
4797       else if (match_reg_range (arg, OP_REG_FP, &regno1, &regno2))
4798         is_freg = TRUE;
4799       else
4800         return FALSE;
4801
4802       if (is_exit && is_freg && regno1 == 0 && regno2 < 2)
4803         {
4804           mask &= ~(7 << 3);
4805           mask |= (5 + regno2) << 3;
4806         }
4807       else if (!is_exit && regno1 == 4 && regno2 >= 4 && regno2 <= 7)
4808         mask |= (regno2 - 3) << 3;
4809       else if (regno1 == 16 && regno2 >= 16 && regno2 <= 17)
4810         mask |= (regno2 - 15) << 1;
4811       else if (regno1 == RA && regno2 == RA)
4812         mask |= 1;
4813       else
4814         return FALSE;
4815     }
4816   while (match_char (arg, ','));
4817
4818   insn_insert_operand (arg->insn, operand, mask);
4819   return TRUE;
4820 }
4821
4822 /* OP_SAVE_RESTORE_LIST matcher.  */
4823
4824 static bfd_boolean
4825 match_save_restore_list_operand (struct mips_arg_info *arg)
4826 {
4827   unsigned int opcode, args, statics, sregs;
4828   unsigned int num_frame_sizes, num_args, num_statics, num_sregs;
4829   offsetT frame_size;
4830   const char *error;
4831
4832   error = 0;
4833   opcode = arg->insn->insn_opcode;
4834   frame_size = 0;
4835   num_frame_sizes = 0;
4836   args = 0;
4837   statics = 0;
4838   sregs = 0;
4839   do
4840     {
4841       unsigned int regno1, regno2;
4842
4843       if (arg->token->type == OT_INTEGER)
4844         {
4845           /* Handle the frame size.  */
4846           if (!match_const_int (arg, &frame_size, 0))
4847             return FALSE;
4848           num_frame_sizes += 1;
4849         }
4850       else
4851         {
4852           if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4853             return FALSE;
4854
4855           while (regno1 <= regno2)
4856             {
4857               if (regno1 >= 4 && regno1 <= 7)
4858                 {
4859                   if (num_frame_sizes == 0)
4860                     /* args $a0-$a3 */
4861                     args |= 1 << (regno1 - 4);
4862                   else
4863                     /* statics $a0-$a3 */
4864                     statics |= 1 << (regno1 - 4);
4865                 }
4866               else if (regno1 >= 16 && regno1 <= 23)
4867                 /* $s0-$s7 */
4868                 sregs |= 1 << (regno1 - 16);
4869               else if (regno1 == 30)
4870                 /* $s8 */
4871                 sregs |= 1 << 8;
4872               else if (regno1 == 31)
4873                 /* Add $ra to insn.  */
4874                 opcode |= 0x40;
4875               else
4876                 return FALSE;
4877               regno1 += 1;
4878               if (regno1 == 24)
4879                 regno1 = 30;
4880             }
4881         }
4882     }
4883   while (match_char (arg, ','));
4884
4885   /* Encode args/statics combination.  */
4886   if (args & statics)
4887     return FALSE;
4888   else if (args == 0xf)
4889     /* All $a0-$a3 are args.  */
4890     opcode |= MIPS16_ALL_ARGS << 16;
4891   else if (statics == 0xf)
4892     /* All $a0-$a3 are statics.  */
4893     opcode |= MIPS16_ALL_STATICS << 16;
4894   else
4895     {
4896       /* Count arg registers.  */
4897       num_args = 0;
4898       while (args & 0x1)
4899         {
4900           args >>= 1;
4901           num_args += 1;
4902         }
4903       if (args != 0)
4904         return FALSE;
4905
4906       /* Count static registers.  */
4907       num_statics = 0;
4908       while (statics & 0x8)
4909         {
4910           statics = (statics << 1) & 0xf;
4911           num_statics += 1;
4912         }
4913       if (statics != 0)
4914         return FALSE;
4915
4916       /* Encode args/statics.  */
4917       opcode |= ((num_args << 2) | num_statics) << 16;
4918     }
4919
4920   /* Encode $s0/$s1.  */
4921   if (sregs & (1 << 0))         /* $s0 */
4922     opcode |= 0x20;
4923   if (sregs & (1 << 1))         /* $s1 */
4924     opcode |= 0x10;
4925   sregs >>= 2;
4926
4927   /* Encode $s2-$s8. */
4928   num_sregs = 0;
4929   while (sregs & 1)
4930     {
4931       sregs >>= 1;
4932       num_sregs += 1;
4933     }
4934   if (sregs != 0)
4935     return FALSE;
4936   opcode |= num_sregs << 24;
4937
4938   /* Encode frame size.  */
4939   if (num_frame_sizes == 0)
4940     error = _("Missing frame size");
4941   else if (num_frame_sizes > 1)
4942     error = _("Frame size specified twice");
4943   else if ((frame_size & 7) != 0 || frame_size < 0 || frame_size > 0xff * 8)
4944     error = _("Invalid frame size");
4945   else if (frame_size != 128 || (opcode >> 16) != 0)
4946     {
4947       frame_size /= 8;
4948       opcode |= (((frame_size & 0xf0) << 16)
4949                  | (frame_size & 0x0f));
4950     }
4951
4952   if (error)
4953     {
4954       if (arg->soft_match)
4955         return FALSE;
4956       as_bad ("%s", error);
4957     }
4958
4959   /* Finally build the instruction.  */
4960   if ((opcode >> 16) != 0 || frame_size == 0)
4961     opcode |= MIPS16_EXTEND;
4962   arg->insn->insn_opcode = opcode;
4963   return TRUE;
4964 }
4965
4966 /* OP_MDMX_IMM_REG matcher.  */
4967
4968 static bfd_boolean
4969 match_mdmx_imm_reg_operand (struct mips_arg_info *arg,
4970                             const struct mips_operand *operand)
4971 {
4972   unsigned int regno, uval;
4973   bfd_boolean is_qh;
4974   const struct mips_opcode *opcode;
4975
4976   /* The mips_opcode records whether this is an octobyte or quadhalf
4977      instruction.  Start out with that bit in place.  */
4978   opcode = arg->insn->insn_mo;
4979   uval = mips_extract_operand (operand, opcode->match);
4980   is_qh = (uval != 0);
4981
4982   if (arg->token->type == OT_REG || arg->token->type == OT_REG_ELEMENT)
4983     {
4984       if ((opcode->membership & INSN_5400)
4985           && strcmp (opcode->name, "rzu.ob") == 0)
4986         {
4987           if (arg->soft_match)
4988             return FALSE;
4989           as_bad (_("Operand %d of `%s' must be an immediate"),
4990                   arg->argnum, opcode->name);
4991         }
4992
4993       /* Check whether this is a vector register or a broadcast of
4994          a single element.  */
4995       if (arg->token->type == OT_REG_ELEMENT)
4996         {
4997           if (!match_regno (arg, OP_REG_VEC, arg->token->u.reg_element.regno,
4998                             &regno))
4999             return FALSE;
5000           if (arg->token->u.reg_element.index > (is_qh ? 3 : 7))
5001             {
5002               if (arg->soft_match)
5003                 return FALSE;
5004               as_bad (_("Invalid element selector"));
5005             }
5006           else
5007             uval |= arg->token->u.reg_element.index << (is_qh ? 2 : 1) << 5;
5008         }
5009       else
5010         {
5011           /* A full vector.  */
5012           if ((opcode->membership & INSN_5400)
5013               && (strcmp (opcode->name, "sll.ob") == 0
5014                   || strcmp (opcode->name, "srl.ob") == 0))
5015             {
5016               if (arg->soft_match)
5017                 return FALSE;
5018               as_bad (_("Operand %d of `%s' must be scalar"),
5019                       arg->argnum, opcode->name);
5020             }
5021
5022           if (!match_regno (arg, OP_REG_VEC, arg->token->u.regno, &regno))
5023             return FALSE;
5024           if (is_qh)
5025             uval |= MDMX_FMTSEL_VEC_QH << 5;
5026           else
5027             uval |= MDMX_FMTSEL_VEC_OB << 5;
5028         }
5029       uval |= regno;
5030       ++arg->token;
5031     }
5032   else
5033     {
5034       offsetT sval;
5035
5036       if (!match_const_int (arg, &sval, 0))
5037         return FALSE;
5038       if (sval < 0 || sval > 31)
5039         {
5040           if (arg->soft_match)
5041             return FALSE;
5042           report_bad_range (arg->insn, arg->argnum, sval, 0, 31, FALSE);
5043         }
5044       uval |= (sval & 31);
5045       if (is_qh)
5046         uval |= MDMX_FMTSEL_IMM_QH << 5;
5047       else
5048         uval |= MDMX_FMTSEL_IMM_OB << 5;
5049     }
5050   insn_insert_operand (arg->insn, operand, uval);
5051   return TRUE;
5052 }
5053
5054 /* OP_PC matcher.  */
5055
5056 static bfd_boolean
5057 match_pc_operand (struct mips_arg_info *arg)
5058 {
5059   if (arg->token->type == OT_REG && (arg->token->u.regno & RTYPE_PC))
5060     {
5061       ++arg->token;
5062       return TRUE;
5063     }
5064   return FALSE;
5065 }
5066
5067 /* OP_REPEAT_DEST_REG and OP_REPEAT_PREV_REG matcher.  OTHER_REGNO is the
5068    register that we need to match.  */
5069
5070 static bfd_boolean
5071 match_tied_reg_operand (struct mips_arg_info *arg, unsigned int other_regno)
5072 {
5073   unsigned int regno;
5074
5075   return match_reg (arg, OP_REG_GP, &regno) && regno == other_regno;
5076 }
5077
5078 /* Read a floating-point constant from S for LI.S or LI.D.  LENGTH is
5079    the length of the value in bytes (4 for float, 8 for double) and
5080    USING_GPRS says whether the destination is a GPR rather than an FPR.
5081
5082    Return the constant in IMM and OFFSET as follows:
5083
5084    - If the constant should be loaded via memory, set IMM to O_absent and
5085      OFFSET to the memory address.
5086
5087    - Otherwise, if the constant should be loaded into two 32-bit registers,
5088      set IMM to the O_constant to load into the high register and OFFSET
5089      to the corresponding value for the low register.
5090
5091    - Otherwise, set IMM to the full O_constant and set OFFSET to O_absent.
5092
5093    These constants only appear as the last operand in an instruction,
5094    and every instruction that accepts them in any variant accepts them
5095    in all variants.  This means we don't have to worry about backing out
5096    any changes if the instruction does not match.  We just match
5097    unconditionally and report an error if the constant is invalid.  */
5098
5099 static bfd_boolean
5100 match_float_constant (struct mips_arg_info *arg, expressionS *imm,
5101                       expressionS *offset, int length, bfd_boolean using_gprs)
5102 {
5103   char *p;
5104   segT seg, new_seg;
5105   subsegT subseg;
5106   const char *newname;
5107   unsigned char *data;
5108
5109   /* Where the constant is placed is based on how the MIPS assembler
5110      does things:
5111
5112      length == 4 && using_gprs  -- immediate value only
5113      length == 8 && using_gprs  -- .rdata or immediate value
5114      length == 4 && !using_gprs -- .lit4 or immediate value
5115      length == 8 && !using_gprs -- .lit8 or immediate value
5116
5117      The .lit4 and .lit8 sections are only used if permitted by the
5118      -G argument.  */
5119   if (arg->token->type != OT_FLOAT)
5120     return FALSE;
5121
5122   gas_assert (arg->token->u.flt.length == length);
5123   data = arg->token->u.flt.data;
5124   ++arg->token;
5125
5126   /* Handle 32-bit constants for which an immediate value is best.  */
5127   if (length == 4
5128       && (using_gprs
5129           || g_switch_value < 4
5130           || (data[0] == 0 && data[1] == 0)
5131           || (data[2] == 0 && data[3] == 0)))
5132     {
5133       imm->X_op = O_constant;
5134       if (!target_big_endian)
5135         imm->X_add_number = bfd_getl32 (data);
5136       else
5137         imm->X_add_number = bfd_getb32 (data);
5138       offset->X_op = O_absent;
5139       return TRUE;
5140     }
5141
5142   /* Handle 64-bit constants for which an immediate value is best.  */
5143   if (length == 8
5144       && !mips_disable_float_construction
5145       /* Constants can only be constructed in GPRs and copied
5146          to FPRs if the GPRs are at least as wide as the FPRs.
5147          Force the constant into memory if we are using 64-bit FPRs
5148          but the GPRs are only 32 bits wide.  */
5149       /* ??? No longer true with the addition of MTHC1, but this
5150          is legacy code...  */
5151       && (using_gprs || !(HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
5152       && ((data[0] == 0 && data[1] == 0)
5153           || (data[2] == 0 && data[3] == 0))
5154       && ((data[4] == 0 && data[5] == 0)
5155           || (data[6] == 0 && data[7] == 0)))
5156     {
5157       /* The value is simple enough to load with a couple of instructions.
5158          If using 32-bit registers, set IMM to the high order 32 bits and
5159          OFFSET to the low order 32 bits.  Otherwise, set IMM to the entire
5160          64 bit constant.  */
5161       if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
5162         {
5163           imm->X_op = O_constant;
5164           offset->X_op = O_constant;
5165           if (!target_big_endian)
5166             {
5167               imm->X_add_number = bfd_getl32 (data + 4);
5168               offset->X_add_number = bfd_getl32 (data);
5169             }
5170           else
5171             {
5172               imm->X_add_number = bfd_getb32 (data);
5173               offset->X_add_number = bfd_getb32 (data + 4);
5174             }
5175           if (offset->X_add_number == 0)
5176             offset->X_op = O_absent;
5177         }
5178       else
5179         {
5180           imm->X_op = O_constant;
5181           if (!target_big_endian)
5182             imm->X_add_number = bfd_getl64 (data);
5183           else
5184             imm->X_add_number = bfd_getb64 (data);
5185           offset->X_op = O_absent;
5186         }
5187       return TRUE;
5188     }
5189
5190   /* Switch to the right section.  */
5191   seg = now_seg;
5192   subseg = now_subseg;
5193   if (length == 4)
5194     {
5195       gas_assert (!using_gprs && g_switch_value >= 4);
5196       newname = ".lit4";
5197     }
5198   else
5199     {
5200       if (using_gprs || g_switch_value < 8)
5201         newname = RDATA_SECTION_NAME;
5202       else
5203         newname = ".lit8";
5204     }
5205
5206   new_seg = subseg_new (newname, (subsegT) 0);
5207   bfd_set_section_flags (stdoutput, new_seg,
5208                          SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA);
5209   frag_align (length == 4 ? 2 : 3, 0, 0);
5210   if (strncmp (TARGET_OS, "elf", 3) != 0)
5211     record_alignment (new_seg, 4);
5212   else
5213     record_alignment (new_seg, length == 4 ? 2 : 3);
5214   if (seg == now_seg)
5215     as_bad (_("Can't use floating point insn in this section"));
5216
5217   /* Set the argument to the current address in the section.  */
5218   imm->X_op = O_absent;
5219   offset->X_op = O_symbol;
5220   offset->X_add_symbol = symbol_temp_new_now ();
5221   offset->X_add_number = 0;
5222
5223   /* Put the floating point number into the section.  */
5224   p = frag_more (length);
5225   memcpy (p, data, length);
5226
5227   /* Switch back to the original section.  */
5228   subseg_set (seg, subseg);
5229   return TRUE;
5230 }
5231
5232 /* OP_VU0_SUFFIX and OP_VU0_MATCH_SUFFIX matcher; MATCH_P selects between
5233    them.  */
5234
5235 static bfd_boolean
5236 match_vu0_suffix_operand (struct mips_arg_info *arg,
5237                           const struct mips_operand *operand,
5238                           bfd_boolean match_p)
5239 {
5240   unsigned int uval;
5241
5242   /* The operand can be an XYZW mask or a single 2-bit channel index
5243      (with X being 0).  */
5244   gas_assert (operand->size == 2 || operand->size == 4);
5245
5246   /* The suffix can be omitted when it is already part of the opcode.  */
5247   if (arg->token->type != OT_CHANNELS)
5248     return match_p;
5249
5250   uval = arg->token->u.channels;
5251   if (operand->size == 2)
5252     {
5253       /* Check that a single bit is set and convert it into a 2-bit index.  */
5254       if ((uval & -uval) != uval)
5255         return FALSE;
5256       uval = 4 - ffs (uval);
5257     }
5258
5259   if (match_p && insn_extract_operand (arg->insn, operand) != uval)
5260     return FALSE;
5261
5262   ++arg->token;
5263   if (!match_p)
5264     insn_insert_operand (arg->insn, operand, uval);
5265   return TRUE;
5266 }
5267
5268 /* S is the text seen for ARG.  Match it against OPERAND.  Return the end
5269    of the argument text if the match is successful, otherwise return null.  */
5270
5271 static bfd_boolean
5272 match_operand (struct mips_arg_info *arg,
5273                const struct mips_operand *operand)
5274 {
5275   switch (operand->type)
5276     {
5277     case OP_INT:
5278       return match_int_operand (arg, operand);
5279
5280     case OP_MAPPED_INT:
5281       return match_mapped_int_operand (arg, operand);
5282
5283     case OP_MSB:
5284       return match_msb_operand (arg, operand);
5285
5286     case OP_REG:
5287     case OP_OPTIONAL_REG:
5288       return match_reg_operand (arg, operand);
5289
5290     case OP_REG_PAIR:
5291       return match_reg_pair_operand (arg, operand);
5292
5293     case OP_PCREL:
5294       return match_pcrel_operand (arg);
5295
5296     case OP_PERF_REG:
5297       return match_perf_reg_operand (arg, operand);
5298
5299     case OP_ADDIUSP_INT:
5300       return match_addiusp_operand (arg, operand);
5301
5302     case OP_CLO_CLZ_DEST:
5303       return match_clo_clz_dest_operand (arg, operand);
5304
5305     case OP_LWM_SWM_LIST:
5306       return match_lwm_swm_list_operand (arg, operand);
5307
5308     case OP_ENTRY_EXIT_LIST:
5309       return match_entry_exit_operand (arg, operand);
5310
5311     case OP_SAVE_RESTORE_LIST:
5312       return match_save_restore_list_operand (arg);
5313
5314     case OP_MDMX_IMM_REG:
5315       return match_mdmx_imm_reg_operand (arg, operand);
5316
5317     case OP_REPEAT_DEST_REG:
5318       return match_tied_reg_operand (arg, arg->dest_regno);
5319
5320     case OP_REPEAT_PREV_REG:
5321       return match_tied_reg_operand (arg, arg->last_regno);
5322
5323     case OP_PC:
5324       return match_pc_operand (arg);
5325
5326     case OP_VU0_SUFFIX:
5327       return match_vu0_suffix_operand (arg, operand, FALSE);
5328
5329     case OP_VU0_MATCH_SUFFIX:
5330       return match_vu0_suffix_operand (arg, operand, TRUE);
5331     }
5332   abort ();
5333 }
5334
5335 /* ARG is the state after successfully matching an instruction.
5336    Issue any queued-up warnings.  */
5337
5338 static void
5339 check_completed_insn (struct mips_arg_info *arg)
5340 {
5341   if (arg->seen_at)
5342     {
5343       if (AT == ATREG)
5344         as_warn (_("Used $at without \".set noat\""));
5345       else
5346         as_warn (_("Used $%u with \".set at=$%u\""), AT, AT);
5347     }
5348 }
5349
5350 /* Return true if modifying general-purpose register REG needs a delay.  */
5351
5352 static bfd_boolean
5353 reg_needs_delay (unsigned int reg)
5354 {
5355   unsigned long prev_pinfo;
5356
5357   prev_pinfo = history[0].insn_mo->pinfo;
5358   if (!mips_opts.noreorder
5359       && (((prev_pinfo & INSN_LOAD_MEMORY_DELAY) && !gpr_interlocks)
5360           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY) && !cop_interlocks))
5361       && (gpr_write_mask (&history[0]) & (1 << reg)))
5362     return TRUE;
5363
5364   return FALSE;
5365 }
5366
5367 /* Classify an instruction according to the FIX_VR4120_* enumeration.
5368    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
5369    by VR4120 errata.  */
5370
5371 static unsigned int
5372 classify_vr4120_insn (const char *name)
5373 {
5374   if (strncmp (name, "macc", 4) == 0)
5375     return FIX_VR4120_MACC;
5376   if (strncmp (name, "dmacc", 5) == 0)
5377     return FIX_VR4120_DMACC;
5378   if (strncmp (name, "mult", 4) == 0)
5379     return FIX_VR4120_MULT;
5380   if (strncmp (name, "dmult", 5) == 0)
5381     return FIX_VR4120_DMULT;
5382   if (strstr (name, "div"))
5383     return FIX_VR4120_DIV;
5384   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
5385     return FIX_VR4120_MTHILO;
5386   return NUM_FIX_VR4120_CLASSES;
5387 }
5388
5389 #define INSN_ERET  0x42000018
5390 #define INSN_DERET 0x4200001f
5391
5392 /* Return the number of instructions that must separate INSN1 and INSN2,
5393    where INSN1 is the earlier instruction.  Return the worst-case value
5394    for any INSN2 if INSN2 is null.  */
5395
5396 static unsigned int
5397 insns_between (const struct mips_cl_insn *insn1,
5398                const struct mips_cl_insn *insn2)
5399 {
5400   unsigned long pinfo1, pinfo2;
5401   unsigned int mask;
5402
5403   /* If INFO2 is null, pessimistically assume that all flags are set for
5404      the second instruction.  */
5405   pinfo1 = insn1->insn_mo->pinfo;
5406   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
5407
5408   /* For most targets, write-after-read dependencies on the HI and LO
5409      registers must be separated by at least two instructions.  */
5410   if (!hilo_interlocks)
5411     {
5412       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
5413         return 2;
5414       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
5415         return 2;
5416     }
5417
5418   /* If we're working around r7000 errata, there must be two instructions
5419      between an mfhi or mflo and any instruction that uses the result.  */
5420   if (mips_7000_hilo_fix
5421       && !mips_opts.micromips
5422       && MF_HILO_INSN (pinfo1)
5423       && (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1))))
5424     return 2;
5425
5426   /* If we're working around 24K errata, one instruction is required
5427      if an ERET or DERET is followed by a branch instruction.  */
5428   if (mips_fix_24k && !mips_opts.micromips)
5429     {
5430       if (insn1->insn_opcode == INSN_ERET
5431           || insn1->insn_opcode == INSN_DERET)
5432         {
5433           if (insn2 == NULL
5434               || insn2->insn_opcode == INSN_ERET
5435               || insn2->insn_opcode == INSN_DERET
5436               || delayed_branch_p (insn2))
5437             return 1;
5438         }
5439     }
5440
5441   /* If working around VR4120 errata, check for combinations that need
5442      a single intervening instruction.  */
5443   if (mips_fix_vr4120 && !mips_opts.micromips)
5444     {
5445       unsigned int class1, class2;
5446
5447       class1 = classify_vr4120_insn (insn1->insn_mo->name);
5448       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
5449         {
5450           if (insn2 == NULL)
5451             return 1;
5452           class2 = classify_vr4120_insn (insn2->insn_mo->name);
5453           if (vr4120_conflicts[class1] & (1 << class2))
5454             return 1;
5455         }
5456     }
5457
5458   if (!HAVE_CODE_COMPRESSION)
5459     {
5460       /* Check for GPR or coprocessor load delays.  All such delays
5461          are on the RT register.  */
5462       /* Itbl support may require additional care here.  */
5463       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY_DELAY))
5464           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
5465         {
5466           if (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1)))
5467             return 1;
5468         }
5469
5470       /* Check for generic coprocessor hazards.
5471
5472          This case is not handled very well.  There is no special
5473          knowledge of CP0 handling, and the coprocessors other than
5474          the floating point unit are not distinguished at all.  */
5475       /* Itbl support may require additional care here. FIXME!
5476          Need to modify this to include knowledge about
5477          user specified delays!  */
5478       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
5479                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
5480         {
5481           /* Handle cases where INSN1 writes to a known general coprocessor
5482              register.  There must be a one instruction delay before INSN2
5483              if INSN2 reads that register, otherwise no delay is needed.  */
5484           mask = fpr_write_mask (insn1);
5485           if (mask != 0)
5486             {
5487               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
5488                 return 1;
5489             }
5490           else
5491             {
5492               /* Read-after-write dependencies on the control registers
5493                  require a two-instruction gap.  */
5494               if ((pinfo1 & INSN_WRITE_COND_CODE)
5495                   && (pinfo2 & INSN_READ_COND_CODE))
5496                 return 2;
5497
5498               /* We don't know exactly what INSN1 does.  If INSN2 is
5499                  also a coprocessor instruction, assume there must be
5500                  a one instruction gap.  */
5501               if (pinfo2 & INSN_COP)
5502                 return 1;
5503             }
5504         }
5505
5506       /* Check for read-after-write dependencies on the coprocessor
5507          control registers in cases where INSN1 does not need a general
5508          coprocessor delay.  This means that INSN1 is a floating point
5509          comparison instruction.  */
5510       /* Itbl support may require additional care here.  */
5511       else if (!cop_interlocks
5512                && (pinfo1 & INSN_WRITE_COND_CODE)
5513                && (pinfo2 & INSN_READ_COND_CODE))
5514         return 1;
5515     }
5516
5517   return 0;
5518 }
5519
5520 /* Return the number of nops that would be needed to work around the
5521    VR4130 mflo/mfhi errata if instruction INSN immediately followed
5522    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
5523    that are contained within the first IGNORE instructions of HIST.  */
5524
5525 static int
5526 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
5527                  const struct mips_cl_insn *insn)
5528 {
5529   int i, j;
5530   unsigned int mask;
5531
5532   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
5533      are not affected by the errata.  */
5534   if (insn != 0
5535       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
5536           || strcmp (insn->insn_mo->name, "mtlo") == 0
5537           || strcmp (insn->insn_mo->name, "mthi") == 0))
5538     return 0;
5539
5540   /* Search for the first MFLO or MFHI.  */
5541   for (i = 0; i < MAX_VR4130_NOPS; i++)
5542     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
5543       {
5544         /* Extract the destination register.  */
5545         mask = gpr_write_mask (&hist[i]);
5546
5547         /* No nops are needed if INSN reads that register.  */
5548         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
5549           return 0;
5550
5551         /* ...or if any of the intervening instructions do.  */
5552         for (j = 0; j < i; j++)
5553           if (gpr_read_mask (&hist[j]) & mask)
5554             return 0;
5555
5556         if (i >= ignore)
5557           return MAX_VR4130_NOPS - i;
5558       }
5559   return 0;
5560 }
5561
5562 #define BASE_REG_EQ(INSN1, INSN2)       \
5563   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
5564       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
5565
5566 /* Return the minimum alignment for this store instruction.  */
5567
5568 static int
5569 fix_24k_align_to (const struct mips_opcode *mo)
5570 {
5571   if (strcmp (mo->name, "sh") == 0)
5572     return 2;
5573
5574   if (strcmp (mo->name, "swc1") == 0
5575       || strcmp (mo->name, "swc2") == 0
5576       || strcmp (mo->name, "sw") == 0
5577       || strcmp (mo->name, "sc") == 0
5578       || strcmp (mo->name, "s.s") == 0)
5579     return 4;
5580
5581   if (strcmp (mo->name, "sdc1") == 0
5582       || strcmp (mo->name, "sdc2") == 0
5583       || strcmp (mo->name, "s.d") == 0)
5584     return 8;
5585
5586   /* sb, swl, swr */
5587   return 1;
5588 }
5589
5590 struct fix_24k_store_info
5591   {
5592     /* Immediate offset, if any, for this store instruction.  */
5593     short off;
5594     /* Alignment required by this store instruction.  */
5595     int align_to;
5596     /* True for register offsets.  */
5597     int register_offset;
5598   };
5599
5600 /* Comparison function used by qsort.  */
5601
5602 static int
5603 fix_24k_sort (const void *a, const void *b)
5604 {
5605   const struct fix_24k_store_info *pos1 = a;
5606   const struct fix_24k_store_info *pos2 = b;
5607
5608   return (pos1->off - pos2->off);
5609 }
5610
5611 /* INSN is a store instruction.  Try to record the store information
5612    in STINFO.  Return false if the information isn't known.  */
5613
5614 static bfd_boolean
5615 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
5616                            const struct mips_cl_insn *insn)
5617 {
5618   /* The instruction must have a known offset.  */
5619   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
5620     return FALSE;
5621
5622   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
5623   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
5624   return TRUE;
5625 }
5626
5627 /* Return the number of nops that would be needed to work around the 24k
5628    "lost data on stores during refill" errata if instruction INSN
5629    immediately followed the 2 instructions described by HIST.
5630    Ignore hazards that are contained within the first IGNORE
5631    instructions of HIST.
5632
5633    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
5634    for the data cache refills and store data. The following describes
5635    the scenario where the store data could be lost.
5636
5637    * A data cache miss, due to either a load or a store, causing fill
5638      data to be supplied by the memory subsystem
5639    * The first three doublewords of fill data are returned and written
5640      into the cache
5641    * A sequence of four stores occurs in consecutive cycles around the
5642      final doubleword of the fill:
5643    * Store A
5644    * Store B
5645    * Store C
5646    * Zero, One or more instructions
5647    * Store D
5648
5649    The four stores A-D must be to different doublewords of the line that
5650    is being filled. The fourth instruction in the sequence above permits
5651    the fill of the final doubleword to be transferred from the FSB into
5652    the cache. In the sequence above, the stores may be either integer
5653    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
5654    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
5655    different doublewords on the line. If the floating point unit is
5656    running in 1:2 mode, it is not possible to create the sequence above
5657    using only floating point store instructions.
5658
5659    In this case, the cache line being filled is incorrectly marked
5660    invalid, thereby losing the data from any store to the line that
5661    occurs between the original miss and the completion of the five
5662    cycle sequence shown above.
5663
5664    The workarounds are:
5665
5666    * Run the data cache in write-through mode.
5667    * Insert a non-store instruction between
5668      Store A and Store B or Store B and Store C.  */
5669   
5670 static int
5671 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
5672               const struct mips_cl_insn *insn)
5673 {
5674   struct fix_24k_store_info pos[3];
5675   int align, i, base_offset;
5676
5677   if (ignore >= 2)
5678     return 0;
5679
5680   /* If the previous instruction wasn't a store, there's nothing to
5681      worry about.  */
5682   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5683     return 0;
5684
5685   /* If the instructions after the previous one are unknown, we have
5686      to assume the worst.  */
5687   if (!insn)
5688     return 1;
5689
5690   /* Check whether we are dealing with three consecutive stores.  */
5691   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
5692       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5693     return 0;
5694
5695   /* If we don't know the relationship between the store addresses,
5696      assume the worst.  */
5697   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
5698       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
5699     return 1;
5700
5701   if (!fix_24k_record_store_info (&pos[0], insn)
5702       || !fix_24k_record_store_info (&pos[1], &hist[0])
5703       || !fix_24k_record_store_info (&pos[2], &hist[1]))
5704     return 1;
5705
5706   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
5707
5708   /* Pick a value of ALIGN and X such that all offsets are adjusted by
5709      X bytes and such that the base register + X is known to be aligned
5710      to align bytes.  */
5711
5712   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
5713     align = 8;
5714   else
5715     {
5716       align = pos[0].align_to;
5717       base_offset = pos[0].off;
5718       for (i = 1; i < 3; i++)
5719         if (align < pos[i].align_to)
5720           {
5721             align = pos[i].align_to;
5722             base_offset = pos[i].off;
5723           }
5724       for (i = 0; i < 3; i++)
5725         pos[i].off -= base_offset;
5726     }
5727
5728   pos[0].off &= ~align + 1;
5729   pos[1].off &= ~align + 1;
5730   pos[2].off &= ~align + 1;
5731
5732   /* If any two stores write to the same chunk, they also write to the
5733      same doubleword.  The offsets are still sorted at this point.  */
5734   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
5735     return 0;
5736
5737   /* A range of at least 9 bytes is needed for the stores to be in
5738      non-overlapping doublewords.  */
5739   if (pos[2].off - pos[0].off <= 8)
5740     return 0;
5741
5742   if (pos[2].off - pos[1].off >= 24
5743       || pos[1].off - pos[0].off >= 24
5744       || pos[2].off - pos[0].off >= 32)
5745     return 0;
5746
5747   return 1;
5748 }
5749
5750 /* Return the number of nops that would be needed if instruction INSN
5751    immediately followed the MAX_NOPS instructions given by HIST,
5752    where HIST[0] is the most recent instruction.  Ignore hazards
5753    between INSN and the first IGNORE instructions in HIST.
5754
5755    If INSN is null, return the worse-case number of nops for any
5756    instruction.  */
5757
5758 static int
5759 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
5760                const struct mips_cl_insn *insn)
5761 {
5762   int i, nops, tmp_nops;
5763
5764   nops = 0;
5765   for (i = ignore; i < MAX_DELAY_NOPS; i++)
5766     {
5767       tmp_nops = insns_between (hist + i, insn) - i;
5768       if (tmp_nops > nops)
5769         nops = tmp_nops;
5770     }
5771
5772   if (mips_fix_vr4130 && !mips_opts.micromips)
5773     {
5774       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
5775       if (tmp_nops > nops)
5776         nops = tmp_nops;
5777     }
5778
5779   if (mips_fix_24k && !mips_opts.micromips)
5780     {
5781       tmp_nops = nops_for_24k (ignore, hist, insn);
5782       if (tmp_nops > nops)
5783         nops = tmp_nops;
5784     }
5785
5786   return nops;
5787 }
5788
5789 /* The variable arguments provide NUM_INSNS extra instructions that
5790    might be added to HIST.  Return the largest number of nops that
5791    would be needed after the extended sequence, ignoring hazards
5792    in the first IGNORE instructions.  */
5793
5794 static int
5795 nops_for_sequence (int num_insns, int ignore,
5796                    const struct mips_cl_insn *hist, ...)
5797 {
5798   va_list args;
5799   struct mips_cl_insn buffer[MAX_NOPS];
5800   struct mips_cl_insn *cursor;
5801   int nops;
5802
5803   va_start (args, hist);
5804   cursor = buffer + num_insns;
5805   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
5806   while (cursor > buffer)
5807     *--cursor = *va_arg (args, const struct mips_cl_insn *);
5808
5809   nops = nops_for_insn (ignore, buffer, NULL);
5810   va_end (args);
5811   return nops;
5812 }
5813
5814 /* Like nops_for_insn, but if INSN is a branch, take into account the
5815    worst-case delay for the branch target.  */
5816
5817 static int
5818 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
5819                          const struct mips_cl_insn *insn)
5820 {
5821   int nops, tmp_nops;
5822
5823   nops = nops_for_insn (ignore, hist, insn);
5824   if (delayed_branch_p (insn))
5825     {
5826       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
5827                                     hist, insn, get_delay_slot_nop (insn));
5828       if (tmp_nops > nops)
5829         nops = tmp_nops;
5830     }
5831   else if (compact_branch_p (insn))
5832     {
5833       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
5834       if (tmp_nops > nops)
5835         nops = tmp_nops;
5836     }
5837   return nops;
5838 }
5839
5840 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
5841
5842 static void
5843 fix_loongson2f_nop (struct mips_cl_insn * ip)
5844 {
5845   gas_assert (!HAVE_CODE_COMPRESSION);
5846   if (strcmp (ip->insn_mo->name, "nop") == 0)
5847     ip->insn_opcode = LOONGSON2F_NOP_INSN;
5848 }
5849
5850 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
5851                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
5852
5853 static void
5854 fix_loongson2f_jump (struct mips_cl_insn * ip)
5855 {
5856   gas_assert (!HAVE_CODE_COMPRESSION);
5857   if (strcmp (ip->insn_mo->name, "j") == 0
5858       || strcmp (ip->insn_mo->name, "jr") == 0
5859       || strcmp (ip->insn_mo->name, "jalr") == 0)
5860     {
5861       int sreg;
5862       expressionS ep;
5863
5864       if (! mips_opts.at)
5865         return;
5866
5867       sreg = EXTRACT_OPERAND (0, RS, *ip);
5868       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
5869         return;
5870
5871       ep.X_op = O_constant;
5872       ep.X_add_number = 0xcfff0000;
5873       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
5874       ep.X_add_number = 0xffff;
5875       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
5876       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
5877     }
5878 }
5879
5880 static void
5881 fix_loongson2f (struct mips_cl_insn * ip)
5882 {
5883   if (mips_fix_loongson2f_nop)
5884     fix_loongson2f_nop (ip);
5885
5886   if (mips_fix_loongson2f_jump)
5887     fix_loongson2f_jump (ip);
5888 }
5889
5890 /* IP is a branch that has a delay slot, and we need to fill it
5891    automatically.   Return true if we can do that by swapping IP
5892    with the previous instruction.
5893    ADDRESS_EXPR is an operand of the instruction to be used with
5894    RELOC_TYPE.  */
5895
5896 static bfd_boolean
5897 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
5898                    bfd_reloc_code_real_type *reloc_type)
5899 {
5900   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
5901   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
5902
5903   /* -O2 and above is required for this optimization.  */
5904   if (mips_optimize < 2)
5905     return FALSE;
5906
5907   /* If we have seen .set volatile or .set nomove, don't optimize.  */
5908   if (mips_opts.nomove)
5909     return FALSE;
5910
5911   /* We can't swap if the previous instruction's position is fixed.  */
5912   if (history[0].fixed_p)
5913     return FALSE;
5914
5915   /* If the previous previous insn was in a .set noreorder, we can't
5916      swap.  Actually, the MIPS assembler will swap in this situation.
5917      However, gcc configured -with-gnu-as will generate code like
5918
5919         .set    noreorder
5920         lw      $4,XXX
5921         .set    reorder
5922         INSN
5923         bne     $4,$0,foo
5924
5925      in which we can not swap the bne and INSN.  If gcc is not configured
5926      -with-gnu-as, it does not output the .set pseudo-ops.  */
5927   if (history[1].noreorder_p)
5928     return FALSE;
5929
5930   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
5931      This means that the previous instruction was a 4-byte one anyhow.  */
5932   if (mips_opts.mips16 && history[0].fixp[0])
5933     return FALSE;
5934
5935   /* If the branch is itself the target of a branch, we can not swap.
5936      We cheat on this; all we check for is whether there is a label on
5937      this instruction.  If there are any branches to anything other than
5938      a label, users must use .set noreorder.  */
5939   if (seg_info (now_seg)->label_list)
5940     return FALSE;
5941
5942   /* If the previous instruction is in a variant frag other than this
5943      branch's one, we cannot do the swap.  This does not apply to
5944      MIPS16 code, which uses variant frags for different purposes.  */
5945   if (!mips_opts.mips16
5946       && history[0].frag
5947       && history[0].frag->fr_type == rs_machine_dependent)
5948     return FALSE;
5949
5950   /* We do not swap with instructions that cannot architecturally
5951      be placed in a branch delay slot, such as SYNC or ERET.  We
5952      also refrain from swapping with a trap instruction, since it
5953      complicates trap handlers to have the trap instruction be in
5954      a delay slot.  */
5955   prev_pinfo = history[0].insn_mo->pinfo;
5956   if (prev_pinfo & INSN_NO_DELAY_SLOT)
5957     return FALSE;
5958
5959   /* Check for conflicts between the branch and the instructions
5960      before the candidate delay slot.  */
5961   if (nops_for_insn (0, history + 1, ip) > 0)
5962     return FALSE;
5963
5964   /* Check for conflicts between the swapped sequence and the
5965      target of the branch.  */
5966   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
5967     return FALSE;
5968
5969   /* If the branch reads a register that the previous
5970      instruction sets, we can not swap.  */
5971   gpr_read = gpr_read_mask (ip);
5972   prev_gpr_write = gpr_write_mask (&history[0]);
5973   if (gpr_read & prev_gpr_write)
5974     return FALSE;
5975
5976   /* If the branch writes a register that the previous
5977      instruction sets, we can not swap.  */
5978   gpr_write = gpr_write_mask (ip);
5979   if (gpr_write & prev_gpr_write)
5980     return FALSE;
5981
5982   /* If the branch writes a register that the previous
5983      instruction reads, we can not swap.  */
5984   prev_gpr_read = gpr_read_mask (&history[0]);
5985   if (gpr_write & prev_gpr_read)
5986     return FALSE;
5987
5988   /* If one instruction sets a condition code and the
5989      other one uses a condition code, we can not swap.  */
5990   pinfo = ip->insn_mo->pinfo;
5991   if ((pinfo & INSN_READ_COND_CODE)
5992       && (prev_pinfo & INSN_WRITE_COND_CODE))
5993     return FALSE;
5994   if ((pinfo & INSN_WRITE_COND_CODE)
5995       && (prev_pinfo & INSN_READ_COND_CODE))
5996     return FALSE;
5997
5998   /* If the previous instruction uses the PC, we can not swap.  */
5999   prev_pinfo2 = history[0].insn_mo->pinfo2;
6000   if (prev_pinfo2 & INSN2_READ_PC)
6001     return FALSE;
6002
6003   /* If the previous instruction has an incorrect size for a fixed
6004      branch delay slot in microMIPS mode, we cannot swap.  */
6005   pinfo2 = ip->insn_mo->pinfo2;
6006   if (mips_opts.micromips
6007       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
6008       && insn_length (history) != 2)
6009     return FALSE;
6010   if (mips_opts.micromips
6011       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
6012       && insn_length (history) != 4)
6013     return FALSE;
6014
6015   /* On R5900 short loops need to be fixed by inserting a nop in
6016      the branch delay slots.
6017      A short loop can be terminated too early.  */
6018   if (mips_opts.arch == CPU_R5900
6019       /* Check if instruction has a parameter, ignore "j $31". */
6020       && (address_expr != NULL)
6021       /* Parameter must be 16 bit. */
6022       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
6023       /* Branch to same segment. */
6024       && (S_GET_SEGMENT(address_expr->X_add_symbol) == now_seg)
6025       /* Branch to same code fragment. */
6026       && (symbol_get_frag(address_expr->X_add_symbol) == frag_now)
6027       /* Can only calculate branch offset if value is known. */
6028       && symbol_constant_p(address_expr->X_add_symbol)
6029       /* Check if branch is really conditional. */
6030       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
6031         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
6032         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
6033     {
6034       int distance;
6035       /* Check if loop is shorter than 6 instructions including
6036          branch and delay slot.  */
6037       distance = frag_now_fix() - S_GET_VALUE(address_expr->X_add_symbol);
6038       if (distance <= 20)
6039         {
6040           int i;
6041           int rv;
6042
6043           rv = FALSE;
6044           /* When the loop includes branches or jumps,
6045              it is not a short loop. */
6046           for (i = 0; i < (distance / 4); i++)
6047             {
6048               if ((history[i].cleared_p)
6049                   || delayed_branch_p(&history[i]))
6050                 {
6051                   rv = TRUE;
6052                   break;
6053                 }
6054             }
6055           if (rv == FALSE)
6056             {
6057               /* Insert nop after branch to fix short loop. */
6058               return FALSE;
6059             }
6060         }
6061     }
6062
6063   return TRUE;
6064 }
6065
6066 /* Decide how we should add IP to the instruction stream.
6067    ADDRESS_EXPR is an operand of the instruction to be used with
6068    RELOC_TYPE.  */
6069
6070 static enum append_method
6071 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
6072                    bfd_reloc_code_real_type *reloc_type)
6073 {
6074   /* The relaxed version of a macro sequence must be inherently
6075      hazard-free.  */
6076   if (mips_relax.sequence == 2)
6077     return APPEND_ADD;
6078
6079   /* We must not dabble with instructions in a ".set norerorder" block.  */
6080   if (mips_opts.noreorder)
6081     return APPEND_ADD;
6082
6083   /* Otherwise, it's our responsibility to fill branch delay slots.  */
6084   if (delayed_branch_p (ip))
6085     {
6086       if (!branch_likely_p (ip)
6087           && can_swap_branch_p (ip, address_expr, reloc_type))
6088         return APPEND_SWAP;
6089
6090       if (mips_opts.mips16
6091           && ISA_SUPPORTS_MIPS16E
6092           && gpr_read_mask (ip) != 0)
6093         return APPEND_ADD_COMPACT;
6094
6095       return APPEND_ADD_WITH_NOP;
6096     }
6097
6098   return APPEND_ADD;
6099 }
6100
6101 /* IP is a MIPS16 instruction whose opcode we have just changed.
6102    Point IP->insn_mo to the new opcode's definition.  */
6103
6104 static void
6105 find_altered_mips16_opcode (struct mips_cl_insn *ip)
6106 {
6107   const struct mips_opcode *mo, *end;
6108
6109   end = &mips16_opcodes[bfd_mips16_num_opcodes];
6110   for (mo = ip->insn_mo; mo < end; mo++)
6111     if ((ip->insn_opcode & mo->mask) == mo->match)
6112       {
6113         ip->insn_mo = mo;
6114         return;
6115       }
6116   abort ();
6117 }
6118
6119 /* For microMIPS macros, we need to generate a local number label
6120    as the target of branches.  */
6121 #define MICROMIPS_LABEL_CHAR            '\037'
6122 static unsigned long micromips_target_label;
6123 static char micromips_target_name[32];
6124
6125 static char *
6126 micromips_label_name (void)
6127 {
6128   char *p = micromips_target_name;
6129   char symbol_name_temporary[24];
6130   unsigned long l;
6131   int i;
6132
6133   if (*p)
6134     return p;
6135
6136   i = 0;
6137   l = micromips_target_label;
6138 #ifdef LOCAL_LABEL_PREFIX
6139   *p++ = LOCAL_LABEL_PREFIX;
6140 #endif
6141   *p++ = 'L';
6142   *p++ = MICROMIPS_LABEL_CHAR;
6143   do
6144     {
6145       symbol_name_temporary[i++] = l % 10 + '0';
6146       l /= 10;
6147     }
6148   while (l != 0);
6149   while (i > 0)
6150     *p++ = symbol_name_temporary[--i];
6151   *p = '\0';
6152
6153   return micromips_target_name;
6154 }
6155
6156 static void
6157 micromips_label_expr (expressionS *label_expr)
6158 {
6159   label_expr->X_op = O_symbol;
6160   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
6161   label_expr->X_add_number = 0;
6162 }
6163
6164 static void
6165 micromips_label_inc (void)
6166 {
6167   micromips_target_label++;
6168   *micromips_target_name = '\0';
6169 }
6170
6171 static void
6172 micromips_add_label (void)
6173 {
6174   symbolS *s;
6175
6176   s = colon (micromips_label_name ());
6177   micromips_label_inc ();
6178   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
6179 }
6180
6181 /* If assembling microMIPS code, then return the microMIPS reloc
6182    corresponding to the requested one if any.  Otherwise return
6183    the reloc unchanged.  */
6184
6185 static bfd_reloc_code_real_type
6186 micromips_map_reloc (bfd_reloc_code_real_type reloc)
6187 {
6188   static const bfd_reloc_code_real_type relocs[][2] =
6189     {
6190       /* Keep sorted incrementally by the left-hand key.  */
6191       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
6192       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
6193       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
6194       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
6195       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
6196       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
6197       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
6198       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
6199       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
6200       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
6201       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
6202       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
6203       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
6204       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
6205       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
6206       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
6207       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
6208       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
6209       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
6210       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
6211       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
6212       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
6213       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
6214       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
6215       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
6216       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
6217       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
6218     };
6219   bfd_reloc_code_real_type r;
6220   size_t i;
6221
6222   if (!mips_opts.micromips)
6223     return reloc;
6224   for (i = 0; i < ARRAY_SIZE (relocs); i++)
6225     {
6226       r = relocs[i][0];
6227       if (r > reloc)
6228         return reloc;
6229       if (r == reloc)
6230         return relocs[i][1];
6231     }
6232   return reloc;
6233 }
6234
6235 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
6236    Return true on success, storing the resolved value in RESULT.  */
6237
6238 static bfd_boolean
6239 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
6240                  offsetT *result)
6241 {
6242   switch (reloc)
6243     {
6244     case BFD_RELOC_MIPS_HIGHEST:
6245     case BFD_RELOC_MICROMIPS_HIGHEST:
6246       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
6247       return TRUE;
6248
6249     case BFD_RELOC_MIPS_HIGHER:
6250     case BFD_RELOC_MICROMIPS_HIGHER:
6251       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
6252       return TRUE;
6253
6254     case BFD_RELOC_HI16_S:
6255     case BFD_RELOC_MICROMIPS_HI16_S:
6256     case BFD_RELOC_MIPS16_HI16_S:
6257       *result = ((operand + 0x8000) >> 16) & 0xffff;
6258       return TRUE;
6259
6260     case BFD_RELOC_HI16:
6261     case BFD_RELOC_MICROMIPS_HI16:
6262     case BFD_RELOC_MIPS16_HI16:
6263       *result = (operand >> 16) & 0xffff;
6264       return TRUE;
6265
6266     case BFD_RELOC_LO16:
6267     case BFD_RELOC_MICROMIPS_LO16:
6268     case BFD_RELOC_MIPS16_LO16:
6269       *result = operand & 0xffff;
6270       return TRUE;
6271
6272     case BFD_RELOC_UNUSED:
6273       *result = operand;
6274       return TRUE;
6275
6276     default:
6277       return FALSE;
6278     }
6279 }
6280
6281 /* Output an instruction.  IP is the instruction information.
6282    ADDRESS_EXPR is an operand of the instruction to be used with
6283    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
6284    a macro expansion.  */
6285
6286 static void
6287 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
6288              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
6289 {
6290   unsigned long prev_pinfo2, pinfo;
6291   bfd_boolean relaxed_branch = FALSE;
6292   enum append_method method;
6293   bfd_boolean relax32;
6294   int branch_disp;
6295
6296   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
6297     fix_loongson2f (ip);
6298
6299   file_ase_mips16 |= mips_opts.mips16;
6300   file_ase_micromips |= mips_opts.micromips;
6301
6302   prev_pinfo2 = history[0].insn_mo->pinfo2;
6303   pinfo = ip->insn_mo->pinfo;
6304
6305   if (mips_opts.micromips
6306       && !expansionp
6307       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
6308            && micromips_insn_length (ip->insn_mo) != 2)
6309           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
6310               && micromips_insn_length (ip->insn_mo) != 4)))
6311     as_warn (_("Wrong size instruction in a %u-bit branch delay slot"),
6312              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
6313
6314   if (address_expr == NULL)
6315     ip->complete_p = 1;
6316   else if (reloc_type[0] <= BFD_RELOC_UNUSED
6317            && reloc_type[1] == BFD_RELOC_UNUSED
6318            && reloc_type[2] == BFD_RELOC_UNUSED
6319            && address_expr->X_op == O_constant)
6320     {
6321       switch (*reloc_type)
6322         {
6323         case BFD_RELOC_MIPS_JMP:
6324           {
6325             int shift;
6326
6327             shift = mips_opts.micromips ? 1 : 2;
6328             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
6329               as_bad (_("jump to misaligned address (0x%lx)"),
6330                       (unsigned long) address_expr->X_add_number);
6331             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
6332                                 & 0x3ffffff);
6333             ip->complete_p = 1;
6334           }
6335           break;
6336
6337         case BFD_RELOC_MIPS16_JMP:
6338           if ((address_expr->X_add_number & 3) != 0)
6339             as_bad (_("jump to misaligned address (0x%lx)"),
6340                     (unsigned long) address_expr->X_add_number);
6341           ip->insn_opcode |=
6342             (((address_expr->X_add_number & 0x7c0000) << 3)
6343                | ((address_expr->X_add_number & 0xf800000) >> 7)
6344                | ((address_expr->X_add_number & 0x3fffc) >> 2));
6345           ip->complete_p = 1;
6346           break;
6347
6348         case BFD_RELOC_16_PCREL_S2:
6349           {
6350             int shift;
6351
6352             shift = mips_opts.micromips ? 1 : 2;
6353             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
6354               as_bad (_("branch to misaligned address (0x%lx)"),
6355                       (unsigned long) address_expr->X_add_number);
6356             if (!mips_relax_branch)
6357               {
6358                 if ((address_expr->X_add_number + (1 << (shift + 15)))
6359                     & ~((1 << (shift + 16)) - 1))
6360                   as_bad (_("branch address range overflow (0x%lx)"),
6361                           (unsigned long) address_expr->X_add_number);
6362                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
6363                                     & 0xffff);
6364               }
6365           }
6366           break;
6367
6368         default:
6369           {
6370             offsetT value;
6371
6372             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
6373                                  &value))
6374               {
6375                 ip->insn_opcode |= value & 0xffff;
6376                 ip->complete_p = 1;
6377               }
6378           }
6379           break;
6380         }
6381     }
6382
6383   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
6384     {
6385       /* There are a lot of optimizations we could do that we don't.
6386          In particular, we do not, in general, reorder instructions.
6387          If you use gcc with optimization, it will reorder
6388          instructions and generally do much more optimization then we
6389          do here; repeating all that work in the assembler would only
6390          benefit hand written assembly code, and does not seem worth
6391          it.  */
6392       int nops = (mips_optimize == 0
6393                   ? nops_for_insn (0, history, NULL)
6394                   : nops_for_insn_or_target (0, history, ip));
6395       if (nops > 0)
6396         {
6397           fragS *old_frag;
6398           unsigned long old_frag_offset;
6399           int i;
6400
6401           old_frag = frag_now;
6402           old_frag_offset = frag_now_fix ();
6403
6404           for (i = 0; i < nops; i++)
6405             add_fixed_insn (NOP_INSN);
6406           insert_into_history (0, nops, NOP_INSN);
6407
6408           if (listing)
6409             {
6410               listing_prev_line ();
6411               /* We may be at the start of a variant frag.  In case we
6412                  are, make sure there is enough space for the frag
6413                  after the frags created by listing_prev_line.  The
6414                  argument to frag_grow here must be at least as large
6415                  as the argument to all other calls to frag_grow in
6416                  this file.  We don't have to worry about being in the
6417                  middle of a variant frag, because the variants insert
6418                  all needed nop instructions themselves.  */
6419               frag_grow (40);
6420             }
6421
6422           mips_move_text_labels ();
6423
6424 #ifndef NO_ECOFF_DEBUGGING
6425           if (ECOFF_DEBUGGING)
6426             ecoff_fix_loc (old_frag, old_frag_offset);
6427 #endif
6428         }
6429     }
6430   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
6431     {
6432       int nops;
6433
6434       /* Work out how many nops in prev_nop_frag are needed by IP,
6435          ignoring hazards generated by the first prev_nop_frag_since
6436          instructions.  */
6437       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
6438       gas_assert (nops <= prev_nop_frag_holds);
6439
6440       /* Enforce NOPS as a minimum.  */
6441       if (nops > prev_nop_frag_required)
6442         prev_nop_frag_required = nops;
6443
6444       if (prev_nop_frag_holds == prev_nop_frag_required)
6445         {
6446           /* Settle for the current number of nops.  Update the history
6447              accordingly (for the benefit of any future .set reorder code).  */
6448           prev_nop_frag = NULL;
6449           insert_into_history (prev_nop_frag_since,
6450                                prev_nop_frag_holds, NOP_INSN);
6451         }
6452       else
6453         {
6454           /* Allow this instruction to replace one of the nops that was
6455              tentatively added to prev_nop_frag.  */
6456           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
6457           prev_nop_frag_holds--;
6458           prev_nop_frag_since++;
6459         }
6460     }
6461
6462   method = get_append_method (ip, address_expr, reloc_type);
6463   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
6464
6465   dwarf2_emit_insn (0);
6466   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
6467      so "move" the instruction address accordingly.
6468
6469      Also, it doesn't seem appropriate for the assembler to reorder .loc
6470      entries.  If this instruction is a branch that we are going to swap
6471      with the previous instruction, the two instructions should be
6472      treated as a unit, and the debug information for both instructions
6473      should refer to the start of the branch sequence.  Using the
6474      current position is certainly wrong when swapping a 32-bit branch
6475      and a 16-bit delay slot, since the current position would then be
6476      in the middle of a branch.  */
6477   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
6478
6479   relax32 = (mips_relax_branch
6480              /* Don't try branch relaxation within .set nomacro, or within
6481                 .set noat if we use $at for PIC computations.  If it turns
6482                 out that the branch was out-of-range, we'll get an error.  */
6483              && !mips_opts.warn_about_macros
6484              && (mips_opts.at || mips_pic == NO_PIC)
6485              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
6486                 as they have no complementing branches.  */
6487              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
6488
6489   if (!HAVE_CODE_COMPRESSION
6490       && address_expr
6491       && relax32
6492       && *reloc_type == BFD_RELOC_16_PCREL_S2
6493       && delayed_branch_p (ip))
6494     {
6495       relaxed_branch = TRUE;
6496       add_relaxed_insn (ip, (relaxed_branch_length
6497                              (NULL, NULL,
6498                               uncond_branch_p (ip) ? -1
6499                               : branch_likely_p (ip) ? 1
6500                               : 0)), 4,
6501                         RELAX_BRANCH_ENCODE
6502                         (AT,
6503                          uncond_branch_p (ip),
6504                          branch_likely_p (ip),
6505                          pinfo & INSN_WRITE_GPR_31,
6506                          0),
6507                         address_expr->X_add_symbol,
6508                         address_expr->X_add_number);
6509       *reloc_type = BFD_RELOC_UNUSED;
6510     }
6511   else if (mips_opts.micromips
6512            && address_expr
6513            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
6514                || *reloc_type > BFD_RELOC_UNUSED)
6515            && (delayed_branch_p (ip) || compact_branch_p (ip))
6516            /* Don't try branch relaxation when users specify
6517               16-bit/32-bit instructions.  */
6518            && !forced_insn_length)
6519     {
6520       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
6521       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
6522       int uncond = uncond_branch_p (ip) ? -1 : 0;
6523       int compact = compact_branch_p (ip);
6524       int al = pinfo & INSN_WRITE_GPR_31;
6525       int length32;
6526
6527       gas_assert (address_expr != NULL);
6528       gas_assert (!mips_relax.sequence);
6529
6530       relaxed_branch = TRUE;
6531       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
6532       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
6533                         RELAX_MICROMIPS_ENCODE (type, AT, uncond, compact, al,
6534                                                 relax32, 0, 0),
6535                         address_expr->X_add_symbol,
6536                         address_expr->X_add_number);
6537       *reloc_type = BFD_RELOC_UNUSED;
6538     }
6539   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
6540     {
6541       /* We need to set up a variant frag.  */
6542       gas_assert (address_expr != NULL);
6543       add_relaxed_insn (ip, 4, 0,
6544                         RELAX_MIPS16_ENCODE
6545                         (*reloc_type - BFD_RELOC_UNUSED,
6546                          forced_insn_length == 2, forced_insn_length == 4,
6547                          delayed_branch_p (&history[0]),
6548                          history[0].mips16_absolute_jump_p),
6549                         make_expr_symbol (address_expr), 0);
6550     }
6551   else if (mips_opts.mips16 && insn_length (ip) == 2)
6552     {
6553       if (!delayed_branch_p (ip))
6554         /* Make sure there is enough room to swap this instruction with
6555            a following jump instruction.  */
6556         frag_grow (6);
6557       add_fixed_insn (ip);
6558     }
6559   else
6560     {
6561       if (mips_opts.mips16
6562           && mips_opts.noreorder
6563           && delayed_branch_p (&history[0]))
6564         as_warn (_("extended instruction in delay slot"));
6565
6566       if (mips_relax.sequence)
6567         {
6568           /* If we've reached the end of this frag, turn it into a variant
6569              frag and record the information for the instructions we've
6570              written so far.  */
6571           if (frag_room () < 4)
6572             relax_close_frag ();
6573           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
6574         }
6575
6576       if (mips_relax.sequence != 2)
6577         {
6578           if (mips_macro_warning.first_insn_sizes[0] == 0)
6579             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
6580           mips_macro_warning.sizes[0] += insn_length (ip);
6581           mips_macro_warning.insns[0]++;
6582         }
6583       if (mips_relax.sequence != 1)
6584         {
6585           if (mips_macro_warning.first_insn_sizes[1] == 0)
6586             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
6587           mips_macro_warning.sizes[1] += insn_length (ip);
6588           mips_macro_warning.insns[1]++;
6589         }
6590
6591       if (mips_opts.mips16)
6592         {
6593           ip->fixed_p = 1;
6594           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
6595         }
6596       add_fixed_insn (ip);
6597     }
6598
6599   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
6600     {
6601       bfd_reloc_code_real_type final_type[3];
6602       reloc_howto_type *howto0;
6603       reloc_howto_type *howto;
6604       int i;
6605
6606       /* Perform any necessary conversion to microMIPS relocations
6607          and find out how many relocations there actually are.  */
6608       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
6609         final_type[i] = micromips_map_reloc (reloc_type[i]);
6610
6611       /* In a compound relocation, it is the final (outermost)
6612          operator that determines the relocated field.  */
6613       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
6614       if (!howto)
6615         abort ();
6616
6617       if (i > 1)
6618         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
6619       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
6620                                  bfd_get_reloc_size (howto),
6621                                  address_expr,
6622                                  howto0 && howto0->pc_relative,
6623                                  final_type[0]);
6624
6625       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
6626       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
6627         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
6628
6629       /* These relocations can have an addend that won't fit in
6630          4 octets for 64bit assembly.  */
6631       if (HAVE_64BIT_GPRS
6632           && ! howto->partial_inplace
6633           && (reloc_type[0] == BFD_RELOC_16
6634               || reloc_type[0] == BFD_RELOC_32
6635               || reloc_type[0] == BFD_RELOC_MIPS_JMP
6636               || reloc_type[0] == BFD_RELOC_GPREL16
6637               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
6638               || reloc_type[0] == BFD_RELOC_GPREL32
6639               || reloc_type[0] == BFD_RELOC_64
6640               || reloc_type[0] == BFD_RELOC_CTOR
6641               || reloc_type[0] == BFD_RELOC_MIPS_SUB
6642               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
6643               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
6644               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
6645               || reloc_type[0] == BFD_RELOC_MIPS_REL16
6646               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
6647               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
6648               || hi16_reloc_p (reloc_type[0])
6649               || lo16_reloc_p (reloc_type[0])))
6650         ip->fixp[0]->fx_no_overflow = 1;
6651
6652       /* These relocations can have an addend that won't fit in 2 octets.  */
6653       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
6654           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
6655         ip->fixp[0]->fx_no_overflow = 1;
6656
6657       if (mips_relax.sequence)
6658         {
6659           if (mips_relax.first_fixup == 0)
6660             mips_relax.first_fixup = ip->fixp[0];
6661         }
6662       else if (reloc_needs_lo_p (*reloc_type))
6663         {
6664           struct mips_hi_fixup *hi_fixup;
6665
6666           /* Reuse the last entry if it already has a matching %lo.  */
6667           hi_fixup = mips_hi_fixup_list;
6668           if (hi_fixup == 0
6669               || !fixup_has_matching_lo_p (hi_fixup->fixp))
6670             {
6671               hi_fixup = ((struct mips_hi_fixup *)
6672                           xmalloc (sizeof (struct mips_hi_fixup)));
6673               hi_fixup->next = mips_hi_fixup_list;
6674               mips_hi_fixup_list = hi_fixup;
6675             }
6676           hi_fixup->fixp = ip->fixp[0];
6677           hi_fixup->seg = now_seg;
6678         }
6679
6680       /* Add fixups for the second and third relocations, if given.
6681          Note that the ABI allows the second relocation to be
6682          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
6683          moment we only use RSS_UNDEF, but we could add support
6684          for the others if it ever becomes necessary.  */
6685       for (i = 1; i < 3; i++)
6686         if (reloc_type[i] != BFD_RELOC_UNUSED)
6687           {
6688             ip->fixp[i] = fix_new (ip->frag, ip->where,
6689                                    ip->fixp[0]->fx_size, NULL, 0,
6690                                    FALSE, final_type[i]);
6691
6692             /* Use fx_tcbit to mark compound relocs.  */
6693             ip->fixp[0]->fx_tcbit = 1;
6694             ip->fixp[i]->fx_tcbit = 1;
6695           }
6696     }
6697   install_insn (ip);
6698
6699   /* Update the register mask information.  */
6700   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
6701   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
6702
6703   switch (method)
6704     {
6705     case APPEND_ADD:
6706       insert_into_history (0, 1, ip);
6707       break;
6708
6709     case APPEND_ADD_WITH_NOP:
6710       {
6711         struct mips_cl_insn *nop;
6712
6713         insert_into_history (0, 1, ip);
6714         nop = get_delay_slot_nop (ip);
6715         add_fixed_insn (nop);
6716         insert_into_history (0, 1, nop);
6717         if (mips_relax.sequence)
6718           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
6719       }
6720       break;
6721
6722     case APPEND_ADD_COMPACT:
6723       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
6724       gas_assert (mips_opts.mips16);
6725       ip->insn_opcode |= 0x0080;
6726       find_altered_mips16_opcode (ip);
6727       install_insn (ip);
6728       insert_into_history (0, 1, ip);
6729       break;
6730
6731     case APPEND_SWAP:
6732       {
6733         struct mips_cl_insn delay = history[0];
6734         if (mips_opts.mips16)
6735           {
6736             know (delay.frag == ip->frag);
6737             move_insn (ip, delay.frag, delay.where);
6738             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
6739           }
6740         else if (relaxed_branch || delay.frag != ip->frag)
6741           {
6742             /* Add the delay slot instruction to the end of the
6743                current frag and shrink the fixed part of the
6744                original frag.  If the branch occupies the tail of
6745                the latter, move it backwards to cover the gap.  */
6746             delay.frag->fr_fix -= branch_disp;
6747             if (delay.frag == ip->frag)
6748               move_insn (ip, ip->frag, ip->where - branch_disp);
6749             add_fixed_insn (&delay);
6750           }
6751         else
6752           {
6753             move_insn (&delay, ip->frag,
6754                        ip->where - branch_disp + insn_length (ip));
6755             move_insn (ip, history[0].frag, history[0].where);
6756           }
6757         history[0] = *ip;
6758         delay.fixed_p = 1;
6759         insert_into_history (0, 1, &delay);
6760       }
6761       break;
6762     }
6763
6764   /* If we have just completed an unconditional branch, clear the history.  */
6765   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
6766       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
6767     {
6768       unsigned int i;
6769
6770       mips_no_prev_insn ();
6771
6772       for (i = 0; i < ARRAY_SIZE (history); i++)
6773         history[i].cleared_p = 1;
6774     }
6775
6776   /* We need to emit a label at the end of branch-likely macros.  */
6777   if (emit_branch_likely_macro)
6778     {
6779       emit_branch_likely_macro = FALSE;
6780       micromips_add_label ();
6781     }
6782
6783   /* We just output an insn, so the next one doesn't have a label.  */
6784   mips_clear_insn_labels ();
6785 }
6786
6787 /* Forget that there was any previous instruction or label.
6788    When BRANCH is true, the branch history is also flushed.  */
6789
6790 static void
6791 mips_no_prev_insn (void)
6792 {
6793   prev_nop_frag = NULL;
6794   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
6795   mips_clear_insn_labels ();
6796 }
6797
6798 /* This function must be called before we emit something other than
6799    instructions.  It is like mips_no_prev_insn except that it inserts
6800    any NOPS that might be needed by previous instructions.  */
6801
6802 void
6803 mips_emit_delays (void)
6804 {
6805   if (! mips_opts.noreorder)
6806     {
6807       int nops = nops_for_insn (0, history, NULL);
6808       if (nops > 0)
6809         {
6810           while (nops-- > 0)
6811             add_fixed_insn (NOP_INSN);
6812           mips_move_text_labels ();
6813         }
6814     }
6815   mips_no_prev_insn ();
6816 }
6817
6818 /* Start a (possibly nested) noreorder block.  */
6819
6820 static void
6821 start_noreorder (void)
6822 {
6823   if (mips_opts.noreorder == 0)
6824     {
6825       unsigned int i;
6826       int nops;
6827
6828       /* None of the instructions before the .set noreorder can be moved.  */
6829       for (i = 0; i < ARRAY_SIZE (history); i++)
6830         history[i].fixed_p = 1;
6831
6832       /* Insert any nops that might be needed between the .set noreorder
6833          block and the previous instructions.  We will later remove any
6834          nops that turn out not to be needed.  */
6835       nops = nops_for_insn (0, history, NULL);
6836       if (nops > 0)
6837         {
6838           if (mips_optimize != 0)
6839             {
6840               /* Record the frag which holds the nop instructions, so
6841                  that we can remove them if we don't need them.  */
6842               frag_grow (nops * NOP_INSN_SIZE);
6843               prev_nop_frag = frag_now;
6844               prev_nop_frag_holds = nops;
6845               prev_nop_frag_required = 0;
6846               prev_nop_frag_since = 0;
6847             }
6848
6849           for (; nops > 0; --nops)
6850             add_fixed_insn (NOP_INSN);
6851
6852           /* Move on to a new frag, so that it is safe to simply
6853              decrease the size of prev_nop_frag.  */
6854           frag_wane (frag_now);
6855           frag_new (0);
6856           mips_move_text_labels ();
6857         }
6858       mips_mark_labels ();
6859       mips_clear_insn_labels ();
6860     }
6861   mips_opts.noreorder++;
6862   mips_any_noreorder = 1;
6863 }
6864
6865 /* End a nested noreorder block.  */
6866
6867 static void
6868 end_noreorder (void)
6869 {
6870   mips_opts.noreorder--;
6871   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
6872     {
6873       /* Commit to inserting prev_nop_frag_required nops and go back to
6874          handling nop insertion the .set reorder way.  */
6875       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
6876                                 * NOP_INSN_SIZE);
6877       insert_into_history (prev_nop_frag_since,
6878                            prev_nop_frag_required, NOP_INSN);
6879       prev_nop_frag = NULL;
6880     }
6881 }
6882
6883 /* Set up global variables for the start of a new macro.  */
6884
6885 static void
6886 macro_start (void)
6887 {
6888   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
6889   memset (&mips_macro_warning.first_insn_sizes, 0,
6890           sizeof (mips_macro_warning.first_insn_sizes));
6891   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
6892   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
6893                                      && delayed_branch_p (&history[0]));
6894   switch (history[0].insn_mo->pinfo2
6895           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
6896     {
6897     case INSN2_BRANCH_DELAY_32BIT:
6898       mips_macro_warning.delay_slot_length = 4;
6899       break;
6900     case INSN2_BRANCH_DELAY_16BIT:
6901       mips_macro_warning.delay_slot_length = 2;
6902       break;
6903     default:
6904       mips_macro_warning.delay_slot_length = 0;
6905       break;
6906     }
6907   mips_macro_warning.first_frag = NULL;
6908 }
6909
6910 /* Given that a macro is longer than one instruction or of the wrong size,
6911    return the appropriate warning for it.  Return null if no warning is
6912    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
6913    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
6914    and RELAX_NOMACRO.  */
6915
6916 static const char *
6917 macro_warning (relax_substateT subtype)
6918 {
6919   if (subtype & RELAX_DELAY_SLOT)
6920     return _("Macro instruction expanded into multiple instructions"
6921              " in a branch delay slot");
6922   else if (subtype & RELAX_NOMACRO)
6923     return _("Macro instruction expanded into multiple instructions");
6924   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
6925                       | RELAX_DELAY_SLOT_SIZE_SECOND))
6926     return ((subtype & RELAX_DELAY_SLOT_16BIT)
6927             ? _("Macro instruction expanded into a wrong size instruction"
6928                 " in a 16-bit branch delay slot")
6929             : _("Macro instruction expanded into a wrong size instruction"
6930                 " in a 32-bit branch delay slot"));
6931   else
6932     return 0;
6933 }
6934
6935 /* Finish up a macro.  Emit warnings as appropriate.  */
6936
6937 static void
6938 macro_end (void)
6939 {
6940   /* Relaxation warning flags.  */
6941   relax_substateT subtype = 0;
6942
6943   /* Check delay slot size requirements.  */
6944   if (mips_macro_warning.delay_slot_length == 2)
6945     subtype |= RELAX_DELAY_SLOT_16BIT;
6946   if (mips_macro_warning.delay_slot_length != 0)
6947     {
6948       if (mips_macro_warning.delay_slot_length
6949           != mips_macro_warning.first_insn_sizes[0])
6950         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
6951       if (mips_macro_warning.delay_slot_length
6952           != mips_macro_warning.first_insn_sizes[1])
6953         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
6954     }
6955
6956   /* Check instruction count requirements.  */
6957   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
6958     {
6959       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
6960         subtype |= RELAX_SECOND_LONGER;
6961       if (mips_opts.warn_about_macros)
6962         subtype |= RELAX_NOMACRO;
6963       if (mips_macro_warning.delay_slot_p)
6964         subtype |= RELAX_DELAY_SLOT;
6965     }
6966
6967   /* If both alternatives fail to fill a delay slot correctly,
6968      emit the warning now.  */
6969   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
6970       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
6971     {
6972       relax_substateT s;
6973       const char *msg;
6974
6975       s = subtype & (RELAX_DELAY_SLOT_16BIT
6976                      | RELAX_DELAY_SLOT_SIZE_FIRST
6977                      | RELAX_DELAY_SLOT_SIZE_SECOND);
6978       msg = macro_warning (s);
6979       if (msg != NULL)
6980         as_warn ("%s", msg);
6981       subtype &= ~s;
6982     }
6983
6984   /* If both implementations are longer than 1 instruction, then emit the
6985      warning now.  */
6986   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
6987     {
6988       relax_substateT s;
6989       const char *msg;
6990
6991       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
6992       msg = macro_warning (s);
6993       if (msg != NULL)
6994         as_warn ("%s", msg);
6995       subtype &= ~s;
6996     }
6997
6998   /* If any flags still set, then one implementation might need a warning
6999      and the other either will need one of a different kind or none at all.
7000      Pass any remaining flags over to relaxation.  */
7001   if (mips_macro_warning.first_frag != NULL)
7002     mips_macro_warning.first_frag->fr_subtype |= subtype;
7003 }
7004
7005 /* Instruction operand formats used in macros that vary between
7006    standard MIPS and microMIPS code.  */
7007
7008 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
7009 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
7010 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
7011 static const char * const lui_fmt[2] = { "t,u", "s,u" };
7012 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
7013 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
7014 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
7015 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
7016
7017 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
7018 #define COP12_FMT (cop12_fmt[mips_opts.micromips])
7019 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
7020 #define LUI_FMT (lui_fmt[mips_opts.micromips])
7021 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
7022 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
7023 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
7024 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
7025
7026 /* Read a macro's relocation codes from *ARGS and store them in *R.
7027    The first argument in *ARGS will be either the code for a single
7028    relocation or -1 followed by the three codes that make up a
7029    composite relocation.  */
7030
7031 static void
7032 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
7033 {
7034   int i, next;
7035
7036   next = va_arg (*args, int);
7037   if (next >= 0)
7038     r[0] = (bfd_reloc_code_real_type) next;
7039   else
7040     {
7041       for (i = 0; i < 3; i++)
7042         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
7043       /* This function is only used for 16-bit relocation fields.
7044          To make the macro code simpler, treat an unrelocated value
7045          in the same way as BFD_RELOC_LO16.  */
7046       if (r[0] == BFD_RELOC_UNUSED)
7047         r[0] = BFD_RELOC_LO16;
7048     }
7049 }
7050
7051 /* Build an instruction created by a macro expansion.  This is passed
7052    a pointer to the count of instructions created so far, an
7053    expression, the name of the instruction to build, an operand format
7054    string, and corresponding arguments.  */
7055
7056 static void
7057 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
7058 {
7059   const struct mips_opcode *mo = NULL;
7060   bfd_reloc_code_real_type r[3];
7061   const struct mips_opcode *amo;
7062   const struct mips_operand *operand;
7063   struct hash_control *hash;
7064   struct mips_cl_insn insn;
7065   va_list args;
7066   unsigned int uval;
7067
7068   va_start (args, fmt);
7069
7070   if (mips_opts.mips16)
7071     {
7072       mips16_macro_build (ep, name, fmt, &args);
7073       va_end (args);
7074       return;
7075     }
7076
7077   r[0] = BFD_RELOC_UNUSED;
7078   r[1] = BFD_RELOC_UNUSED;
7079   r[2] = BFD_RELOC_UNUSED;
7080   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
7081   amo = (struct mips_opcode *) hash_find (hash, name);
7082   gas_assert (amo);
7083   gas_assert (strcmp (name, amo->name) == 0);
7084
7085   do
7086     {
7087       /* Search until we get a match for NAME.  It is assumed here that
7088          macros will never generate MDMX, MIPS-3D, or MT instructions.
7089          We try to match an instruction that fulfils the branch delay
7090          slot instruction length requirement (if any) of the previous
7091          instruction.  While doing this we record the first instruction
7092          seen that matches all the other conditions and use it anyway
7093          if the requirement cannot be met; we will issue an appropriate
7094          warning later on.  */
7095       if (strcmp (fmt, amo->args) == 0
7096           && amo->pinfo != INSN_MACRO
7097           && is_opcode_valid (amo)
7098           && is_size_valid (amo))
7099         {
7100           if (is_delay_slot_valid (amo))
7101             {
7102               mo = amo;
7103               break;
7104             }
7105           else if (!mo)
7106             mo = amo;
7107         }
7108
7109       ++amo;
7110       gas_assert (amo->name);
7111     }
7112   while (strcmp (name, amo->name) == 0);
7113
7114   gas_assert (mo);
7115   create_insn (&insn, mo);
7116   for (; *fmt; ++fmt)
7117     {
7118       switch (*fmt)
7119         {
7120         case ',':
7121         case '(':
7122         case ')':
7123         case 'z':
7124           break;
7125
7126         case 'i':
7127         case 'j':
7128           macro_read_relocs (&args, r);
7129           gas_assert (*r == BFD_RELOC_GPREL16
7130                       || *r == BFD_RELOC_MIPS_HIGHER
7131                       || *r == BFD_RELOC_HI16_S
7132                       || *r == BFD_RELOC_LO16
7133                       || *r == BFD_RELOC_MIPS_GOT_OFST);
7134           break;
7135
7136         case 'o':
7137           macro_read_relocs (&args, r);
7138           break;
7139
7140         case 'u':
7141           macro_read_relocs (&args, r);
7142           gas_assert (ep != NULL
7143                       && (ep->X_op == O_constant
7144                           || (ep->X_op == O_symbol
7145                               && (*r == BFD_RELOC_MIPS_HIGHEST
7146                                   || *r == BFD_RELOC_HI16_S
7147                                   || *r == BFD_RELOC_HI16
7148                                   || *r == BFD_RELOC_GPREL16
7149                                   || *r == BFD_RELOC_MIPS_GOT_HI16
7150                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
7151           break;
7152
7153         case 'p':
7154           gas_assert (ep != NULL);
7155
7156           /*
7157            * This allows macro() to pass an immediate expression for
7158            * creating short branches without creating a symbol.
7159            *
7160            * We don't allow branch relaxation for these branches, as
7161            * they should only appear in ".set nomacro" anyway.
7162            */
7163           if (ep->X_op == O_constant)
7164             {
7165               /* For microMIPS we always use relocations for branches.
7166                  So we should not resolve immediate values.  */
7167               gas_assert (!mips_opts.micromips);
7168
7169               if ((ep->X_add_number & 3) != 0)
7170                 as_bad (_("branch to misaligned address (0x%lx)"),
7171                         (unsigned long) ep->X_add_number);
7172               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
7173                 as_bad (_("branch address range overflow (0x%lx)"),
7174                         (unsigned long) ep->X_add_number);
7175               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
7176               ep = NULL;
7177             }
7178           else
7179             *r = BFD_RELOC_16_PCREL_S2;
7180           break;
7181
7182         case 'a':
7183           gas_assert (ep != NULL);
7184           *r = BFD_RELOC_MIPS_JMP;
7185           break;
7186
7187         default:
7188           operand = (mips_opts.micromips
7189                      ? decode_micromips_operand (fmt)
7190                      : decode_mips_operand (fmt));
7191           if (!operand)
7192             abort ();
7193
7194           uval = va_arg (args, int);
7195           if (operand->type == OP_CLO_CLZ_DEST)
7196             uval |= (uval << 5);
7197           insn_insert_operand (&insn, operand, uval);
7198
7199           if (*fmt == '+' || *fmt == 'm')
7200             ++fmt;
7201           break;
7202         }
7203     }
7204   va_end (args);
7205   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
7206
7207   append_insn (&insn, ep, r, TRUE);
7208 }
7209
7210 static void
7211 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
7212                     va_list *args)
7213 {
7214   struct mips_opcode *mo;
7215   struct mips_cl_insn insn;
7216   const struct mips_operand *operand;
7217   bfd_reloc_code_real_type r[3]
7218     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
7219
7220   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
7221   gas_assert (mo);
7222   gas_assert (strcmp (name, mo->name) == 0);
7223
7224   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
7225     {
7226       ++mo;
7227       gas_assert (mo->name);
7228       gas_assert (strcmp (name, mo->name) == 0);
7229     }
7230
7231   create_insn (&insn, mo);
7232   for (; *fmt; ++fmt)
7233     {
7234       int c;
7235
7236       c = *fmt;
7237       switch (c)
7238         {
7239         case ',':
7240         case '(':
7241         case ')':
7242           break;
7243
7244         case '0':
7245         case 'S':
7246         case 'P':
7247         case 'R':
7248           break;
7249
7250         case '<':
7251         case '>':
7252         case '4':
7253         case '5':
7254         case 'H':
7255         case 'W':
7256         case 'D':
7257         case 'j':
7258         case '8':
7259         case 'V':
7260         case 'C':
7261         case 'U':
7262         case 'k':
7263         case 'K':
7264         case 'p':
7265         case 'q':
7266           {
7267             offsetT value;
7268
7269             gas_assert (ep != NULL);
7270
7271             if (ep->X_op != O_constant)
7272               *r = (int) BFD_RELOC_UNUSED + c;
7273             else if (calculate_reloc (*r, ep->X_add_number, &value))
7274               {
7275                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
7276                 ep = NULL;
7277                 *r = BFD_RELOC_UNUSED;
7278               }
7279           }
7280           break;
7281
7282         default:
7283           operand = decode_mips16_operand (c, FALSE);
7284           if (!operand)
7285             abort ();
7286
7287           insn_insert_operand (&insn, operand, va_arg (*args, int));
7288           break;
7289         }
7290     }
7291
7292   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
7293
7294   append_insn (&insn, ep, r, TRUE);
7295 }
7296
7297 /*
7298  * Sign-extend 32-bit mode constants that have bit 31 set and all
7299  * higher bits unset.
7300  */
7301 static void
7302 normalize_constant_expr (expressionS *ex)
7303 {
7304   if (ex->X_op == O_constant
7305       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7306     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7307                         - 0x80000000);
7308 }
7309
7310 /*
7311  * Sign-extend 32-bit mode address offsets that have bit 31 set and
7312  * all higher bits unset.
7313  */
7314 static void
7315 normalize_address_expr (expressionS *ex)
7316 {
7317   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
7318         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
7319       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7320     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7321                         - 0x80000000);
7322 }
7323
7324 /*
7325  * Generate a "jalr" instruction with a relocation hint to the called
7326  * function.  This occurs in NewABI PIC code.
7327  */
7328 static void
7329 macro_build_jalr (expressionS *ep, int cprestore)
7330 {
7331   static const bfd_reloc_code_real_type jalr_relocs[2]
7332     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
7333   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
7334   const char *jalr;
7335   char *f = NULL;
7336
7337   if (MIPS_JALR_HINT_P (ep))
7338     {
7339       frag_grow (8);
7340       f = frag_more (0);
7341     }
7342   if (mips_opts.micromips)
7343     {
7344       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
7345               ? "jalr" : "jalrs");
7346       if (MIPS_JALR_HINT_P (ep)
7347           || mips_opts.insn32
7348           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
7349         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
7350       else
7351         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
7352     }
7353   else
7354     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
7355   if (MIPS_JALR_HINT_P (ep))
7356     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
7357 }
7358
7359 /*
7360  * Generate a "lui" instruction.
7361  */
7362 static void
7363 macro_build_lui (expressionS *ep, int regnum)
7364 {
7365   gas_assert (! mips_opts.mips16);
7366
7367   if (ep->X_op != O_constant)
7368     {
7369       gas_assert (ep->X_op == O_symbol);
7370       /* _gp_disp is a special case, used from s_cpload.
7371          __gnu_local_gp is used if mips_no_shared.  */
7372       gas_assert (mips_pic == NO_PIC
7373               || (! HAVE_NEWABI
7374                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
7375               || (! mips_in_shared
7376                   && strcmp (S_GET_NAME (ep->X_add_symbol),
7377                              "__gnu_local_gp") == 0));
7378     }
7379
7380   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
7381 }
7382
7383 /* Generate a sequence of instructions to do a load or store from a constant
7384    offset off of a base register (breg) into/from a target register (treg),
7385    using AT if necessary.  */
7386 static void
7387 macro_build_ldst_constoffset (expressionS *ep, const char *op,
7388                               int treg, int breg, int dbl)
7389 {
7390   gas_assert (ep->X_op == O_constant);
7391
7392   /* Sign-extending 32-bit constants makes their handling easier.  */
7393   if (!dbl)
7394     normalize_constant_expr (ep);
7395
7396   /* Right now, this routine can only handle signed 32-bit constants.  */
7397   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
7398     as_warn (_("operand overflow"));
7399
7400   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
7401     {
7402       /* Signed 16-bit offset will fit in the op.  Easy!  */
7403       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
7404     }
7405   else
7406     {
7407       /* 32-bit offset, need multiple instructions and AT, like:
7408            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
7409            addu     $tempreg,$tempreg,$breg
7410            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
7411          to handle the complete offset.  */
7412       macro_build_lui (ep, AT);
7413       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
7414       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
7415
7416       if (!mips_opts.at)
7417         as_bad (_("Macro used $at after \".set noat\""));
7418     }
7419 }
7420
7421 /*                      set_at()
7422  * Generates code to set the $at register to true (one)
7423  * if reg is less than the immediate expression.
7424  */
7425 static void
7426 set_at (int reg, int unsignedp)
7427 {
7428   if (imm_expr.X_op == O_constant
7429       && imm_expr.X_add_number >= -0x8000
7430       && imm_expr.X_add_number < 0x8000)
7431     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
7432                  AT, reg, BFD_RELOC_LO16);
7433   else
7434     {
7435       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7436       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
7437     }
7438 }
7439
7440 /* Count the leading zeroes by performing a binary chop. This is a
7441    bulky bit of source, but performance is a LOT better for the
7442    majority of values than a simple loop to count the bits:
7443        for (lcnt = 0; (lcnt < 32); lcnt++)
7444          if ((v) & (1 << (31 - lcnt)))
7445            break;
7446   However it is not code size friendly, and the gain will drop a bit
7447   on certain cached systems.
7448 */
7449 #define COUNT_TOP_ZEROES(v)             \
7450   (((v) & ~0xffff) == 0                 \
7451    ? ((v) & ~0xff) == 0                 \
7452      ? ((v) & ~0xf) == 0                \
7453        ? ((v) & ~0x3) == 0              \
7454          ? ((v) & ~0x1) == 0            \
7455            ? !(v)                       \
7456              ? 32                       \
7457              : 31                       \
7458            : 30                         \
7459          : ((v) & ~0x7) == 0            \
7460            ? 29                         \
7461            : 28                         \
7462        : ((v) & ~0x3f) == 0             \
7463          ? ((v) & ~0x1f) == 0           \
7464            ? 27                         \
7465            : 26                         \
7466          : ((v) & ~0x7f) == 0           \
7467            ? 25                         \
7468            : 24                         \
7469      : ((v) & ~0xfff) == 0              \
7470        ? ((v) & ~0x3ff) == 0            \
7471          ? ((v) & ~0x1ff) == 0          \
7472            ? 23                         \
7473            : 22                         \
7474          : ((v) & ~0x7ff) == 0          \
7475            ? 21                         \
7476            : 20                         \
7477        : ((v) & ~0x3fff) == 0           \
7478          ? ((v) & ~0x1fff) == 0         \
7479            ? 19                         \
7480            : 18                         \
7481          : ((v) & ~0x7fff) == 0         \
7482            ? 17                         \
7483            : 16                         \
7484    : ((v) & ~0xffffff) == 0             \
7485      ? ((v) & ~0xfffff) == 0            \
7486        ? ((v) & ~0x3ffff) == 0          \
7487          ? ((v) & ~0x1ffff) == 0        \
7488            ? 15                         \
7489            : 14                         \
7490          : ((v) & ~0x7ffff) == 0        \
7491            ? 13                         \
7492            : 12                         \
7493        : ((v) & ~0x3fffff) == 0         \
7494          ? ((v) & ~0x1fffff) == 0       \
7495            ? 11                         \
7496            : 10                         \
7497          : ((v) & ~0x7fffff) == 0       \
7498            ? 9                          \
7499            : 8                          \
7500      : ((v) & ~0xfffffff) == 0          \
7501        ? ((v) & ~0x3ffffff) == 0        \
7502          ? ((v) & ~0x1ffffff) == 0      \
7503            ? 7                          \
7504            : 6                          \
7505          : ((v) & ~0x7ffffff) == 0      \
7506            ? 5                          \
7507            : 4                          \
7508        : ((v) & ~0x3fffffff) == 0       \
7509          ? ((v) & ~0x1fffffff) == 0     \
7510            ? 3                          \
7511            : 2                          \
7512          : ((v) & ~0x7fffffff) == 0     \
7513            ? 1                          \
7514            : 0)
7515
7516 /*                      load_register()
7517  *  This routine generates the least number of instructions necessary to load
7518  *  an absolute expression value into a register.
7519  */
7520 static void
7521 load_register (int reg, expressionS *ep, int dbl)
7522 {
7523   int freg;
7524   expressionS hi32, lo32;
7525
7526   if (ep->X_op != O_big)
7527     {
7528       gas_assert (ep->X_op == O_constant);
7529
7530       /* Sign-extending 32-bit constants makes their handling easier.  */
7531       if (!dbl)
7532         normalize_constant_expr (ep);
7533
7534       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
7535         {
7536           /* We can handle 16 bit signed values with an addiu to
7537              $zero.  No need to ever use daddiu here, since $zero and
7538              the result are always correct in 32 bit mode.  */
7539           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
7540           return;
7541         }
7542       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
7543         {
7544           /* We can handle 16 bit unsigned values with an ori to
7545              $zero.  */
7546           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
7547           return;
7548         }
7549       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
7550         {
7551           /* 32 bit values require an lui.  */
7552           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
7553           if ((ep->X_add_number & 0xffff) != 0)
7554             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
7555           return;
7556         }
7557     }
7558
7559   /* The value is larger than 32 bits.  */
7560
7561   if (!dbl || HAVE_32BIT_GPRS)
7562     {
7563       char value[32];
7564
7565       sprintf_vma (value, ep->X_add_number);
7566       as_bad (_("Number (0x%s) larger than 32 bits"), value);
7567       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
7568       return;
7569     }
7570
7571   if (ep->X_op != O_big)
7572     {
7573       hi32 = *ep;
7574       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
7575       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
7576       hi32.X_add_number &= 0xffffffff;
7577       lo32 = *ep;
7578       lo32.X_add_number &= 0xffffffff;
7579     }
7580   else
7581     {
7582       gas_assert (ep->X_add_number > 2);
7583       if (ep->X_add_number == 3)
7584         generic_bignum[3] = 0;
7585       else if (ep->X_add_number > 4)
7586         as_bad (_("Number larger than 64 bits"));
7587       lo32.X_op = O_constant;
7588       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
7589       hi32.X_op = O_constant;
7590       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
7591     }
7592
7593   if (hi32.X_add_number == 0)
7594     freg = 0;
7595   else
7596     {
7597       int shift, bit;
7598       unsigned long hi, lo;
7599
7600       if (hi32.X_add_number == (offsetT) 0xffffffff)
7601         {
7602           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
7603             {
7604               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
7605               return;
7606             }
7607           if (lo32.X_add_number & 0x80000000)
7608             {
7609               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
7610               if (lo32.X_add_number & 0xffff)
7611                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
7612               return;
7613             }
7614         }
7615
7616       /* Check for 16bit shifted constant.  We know that hi32 is
7617          non-zero, so start the mask on the first bit of the hi32
7618          value.  */
7619       shift = 17;
7620       do
7621         {
7622           unsigned long himask, lomask;
7623
7624           if (shift < 32)
7625             {
7626               himask = 0xffff >> (32 - shift);
7627               lomask = (0xffff << shift) & 0xffffffff;
7628             }
7629           else
7630             {
7631               himask = 0xffff << (shift - 32);
7632               lomask = 0;
7633             }
7634           if ((hi32.X_add_number & ~(offsetT) himask) == 0
7635               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
7636             {
7637               expressionS tmp;
7638
7639               tmp.X_op = O_constant;
7640               if (shift < 32)
7641                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
7642                                     | (lo32.X_add_number >> shift));
7643               else
7644                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
7645               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
7646               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
7647                            reg, reg, (shift >= 32) ? shift - 32 : shift);
7648               return;
7649             }
7650           ++shift;
7651         }
7652       while (shift <= (64 - 16));
7653
7654       /* Find the bit number of the lowest one bit, and store the
7655          shifted value in hi/lo.  */
7656       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
7657       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
7658       if (lo != 0)
7659         {
7660           bit = 0;
7661           while ((lo & 1) == 0)
7662             {
7663               lo >>= 1;
7664               ++bit;
7665             }
7666           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
7667           hi >>= bit;
7668         }
7669       else
7670         {
7671           bit = 32;
7672           while ((hi & 1) == 0)
7673             {
7674               hi >>= 1;
7675               ++bit;
7676             }
7677           lo = hi;
7678           hi = 0;
7679         }
7680
7681       /* Optimize if the shifted value is a (power of 2) - 1.  */
7682       if ((hi == 0 && ((lo + 1) & lo) == 0)
7683           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
7684         {
7685           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
7686           if (shift != 0)
7687             {
7688               expressionS tmp;
7689
7690               /* This instruction will set the register to be all
7691                  ones.  */
7692               tmp.X_op = O_constant;
7693               tmp.X_add_number = (offsetT) -1;
7694               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
7695               if (bit != 0)
7696                 {
7697                   bit += shift;
7698                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
7699                                reg, reg, (bit >= 32) ? bit - 32 : bit);
7700                 }
7701               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
7702                            reg, reg, (shift >= 32) ? shift - 32 : shift);
7703               return;
7704             }
7705         }
7706
7707       /* Sign extend hi32 before calling load_register, because we can
7708          generally get better code when we load a sign extended value.  */
7709       if ((hi32.X_add_number & 0x80000000) != 0)
7710         hi32.X_add_number |= ~(offsetT) 0xffffffff;
7711       load_register (reg, &hi32, 0);
7712       freg = reg;
7713     }
7714   if ((lo32.X_add_number & 0xffff0000) == 0)
7715     {
7716       if (freg != 0)
7717         {
7718           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
7719           freg = reg;
7720         }
7721     }
7722   else
7723     {
7724       expressionS mid16;
7725
7726       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
7727         {
7728           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
7729           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
7730           return;
7731         }
7732
7733       if (freg != 0)
7734         {
7735           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
7736           freg = reg;
7737         }
7738       mid16 = lo32;
7739       mid16.X_add_number >>= 16;
7740       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
7741       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
7742       freg = reg;
7743     }
7744   if ((lo32.X_add_number & 0xffff) != 0)
7745     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
7746 }
7747
7748 static inline void
7749 load_delay_nop (void)
7750 {
7751   if (!gpr_interlocks)
7752     macro_build (NULL, "nop", "");
7753 }
7754
7755 /* Load an address into a register.  */
7756
7757 static void
7758 load_address (int reg, expressionS *ep, int *used_at)
7759 {
7760   if (ep->X_op != O_constant
7761       && ep->X_op != O_symbol)
7762     {
7763       as_bad (_("expression too complex"));
7764       ep->X_op = O_constant;
7765     }
7766
7767   if (ep->X_op == O_constant)
7768     {
7769       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
7770       return;
7771     }
7772
7773   if (mips_pic == NO_PIC)
7774     {
7775       /* If this is a reference to a GP relative symbol, we want
7776            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
7777          Otherwise we want
7778            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
7779            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
7780          If we have an addend, we always use the latter form.
7781
7782          With 64bit address space and a usable $at we want
7783            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
7784            lui          $at,<sym>               (BFD_RELOC_HI16_S)
7785            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
7786            daddiu       $at,<sym>               (BFD_RELOC_LO16)
7787            dsll32       $reg,0
7788            daddu        $reg,$reg,$at
7789
7790          If $at is already in use, we use a path which is suboptimal
7791          on superscalar processors.
7792            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
7793            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
7794            dsll         $reg,16
7795            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
7796            dsll         $reg,16
7797            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
7798
7799          For GP relative symbols in 64bit address space we can use
7800          the same sequence as in 32bit address space.  */
7801       if (HAVE_64BIT_SYMBOLS)
7802         {
7803           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
7804               && !nopic_need_relax (ep->X_add_symbol, 1))
7805             {
7806               relax_start (ep->X_add_symbol);
7807               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
7808                            mips_gp_register, BFD_RELOC_GPREL16);
7809               relax_switch ();
7810             }
7811
7812           if (*used_at == 0 && mips_opts.at)
7813             {
7814               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
7815               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
7816               macro_build (ep, "daddiu", "t,r,j", reg, reg,
7817                            BFD_RELOC_MIPS_HIGHER);
7818               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
7819               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
7820               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
7821               *used_at = 1;
7822             }
7823           else
7824             {
7825               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
7826               macro_build (ep, "daddiu", "t,r,j", reg, reg,
7827                            BFD_RELOC_MIPS_HIGHER);
7828               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
7829               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
7830               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
7831               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
7832             }
7833
7834           if (mips_relax.sequence)
7835             relax_end ();
7836         }
7837       else
7838         {
7839           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
7840               && !nopic_need_relax (ep->X_add_symbol, 1))
7841             {
7842               relax_start (ep->X_add_symbol);
7843               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
7844                            mips_gp_register, BFD_RELOC_GPREL16);
7845               relax_switch ();
7846             }
7847           macro_build_lui (ep, reg);
7848           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
7849                        reg, reg, BFD_RELOC_LO16);
7850           if (mips_relax.sequence)
7851             relax_end ();
7852         }
7853     }
7854   else if (!mips_big_got)
7855     {
7856       expressionS ex;
7857
7858       /* If this is a reference to an external symbol, we want
7859            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
7860          Otherwise we want
7861            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
7862            nop
7863            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
7864          If there is a constant, it must be added in after.
7865
7866          If we have NewABI, we want
7867            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7868          unless we're referencing a global symbol with a non-zero
7869          offset, in which case cst must be added separately.  */
7870       if (HAVE_NEWABI)
7871         {
7872           if (ep->X_add_number)
7873             {
7874               ex.X_add_number = ep->X_add_number;
7875               ep->X_add_number = 0;
7876               relax_start (ep->X_add_symbol);
7877               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7878                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7879               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
7880                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7881               ex.X_op = O_constant;
7882               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
7883                            reg, reg, BFD_RELOC_LO16);
7884               ep->X_add_number = ex.X_add_number;
7885               relax_switch ();
7886             }
7887           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7888                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7889           if (mips_relax.sequence)
7890             relax_end ();
7891         }
7892       else
7893         {
7894           ex.X_add_number = ep->X_add_number;
7895           ep->X_add_number = 0;
7896           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7897                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
7898           load_delay_nop ();
7899           relax_start (ep->X_add_symbol);
7900           relax_switch ();
7901           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7902                        BFD_RELOC_LO16);
7903           relax_end ();
7904
7905           if (ex.X_add_number != 0)
7906             {
7907               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
7908                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7909               ex.X_op = O_constant;
7910               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
7911                            reg, reg, BFD_RELOC_LO16);
7912             }
7913         }
7914     }
7915   else if (mips_big_got)
7916     {
7917       expressionS ex;
7918
7919       /* This is the large GOT case.  If this is a reference to an
7920          external symbol, we want
7921            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
7922            addu         $reg,$reg,$gp
7923            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
7924
7925          Otherwise, for a reference to a local symbol in old ABI, we want
7926            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
7927            nop
7928            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
7929          If there is a constant, it must be added in after.
7930
7931          In the NewABI, for local symbols, with or without offsets, we want:
7932            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
7933            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
7934       */
7935       if (HAVE_NEWABI)
7936         {
7937           ex.X_add_number = ep->X_add_number;
7938           ep->X_add_number = 0;
7939           relax_start (ep->X_add_symbol);
7940           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
7941           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7942                        reg, reg, mips_gp_register);
7943           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
7944                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
7945           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
7946             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7947           else if (ex.X_add_number)
7948             {
7949               ex.X_op = O_constant;
7950               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7951                            BFD_RELOC_LO16);
7952             }
7953
7954           ep->X_add_number = ex.X_add_number;
7955           relax_switch ();
7956           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7957                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
7958           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7959                        BFD_RELOC_MIPS_GOT_OFST);
7960           relax_end ();
7961         }
7962       else
7963         {
7964           ex.X_add_number = ep->X_add_number;
7965           ep->X_add_number = 0;
7966           relax_start (ep->X_add_symbol);
7967           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
7968           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7969                        reg, reg, mips_gp_register);
7970           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
7971                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
7972           relax_switch ();
7973           if (reg_needs_delay (mips_gp_register))
7974             {
7975               /* We need a nop before loading from $gp.  This special
7976                  check is required because the lui which starts the main
7977                  instruction stream does not refer to $gp, and so will not
7978                  insert the nop which may be required.  */
7979               macro_build (NULL, "nop", "");
7980             }
7981           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7982                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
7983           load_delay_nop ();
7984           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7985                        BFD_RELOC_LO16);
7986           relax_end ();
7987
7988           if (ex.X_add_number != 0)
7989             {
7990               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
7991                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7992               ex.X_op = O_constant;
7993               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7994                            BFD_RELOC_LO16);
7995             }
7996         }
7997     }
7998   else
7999     abort ();
8000
8001   if (!mips_opts.at && *used_at == 1)
8002     as_bad (_("Macro used $at after \".set noat\""));
8003 }
8004
8005 /* Move the contents of register SOURCE into register DEST.  */
8006
8007 static void
8008 move_register (int dest, int source)
8009 {
8010   /* Prefer to use a 16-bit microMIPS instruction unless the previous
8011      instruction specifically requires a 32-bit one.  */
8012   if (mips_opts.micromips
8013       && !mips_opts.insn32
8014       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8015     macro_build (NULL, "move", "mp,mj", dest, source);
8016   else
8017     macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
8018                  dest, source, 0);
8019 }
8020
8021 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
8022    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
8023    The two alternatives are:
8024
8025    Global symbol                Local sybmol
8026    -------------                ------------
8027    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
8028    ...                          ...
8029    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
8030
8031    load_got_offset emits the first instruction and add_got_offset
8032    emits the second for a 16-bit offset or add_got_offset_hilo emits
8033    a sequence to add a 32-bit offset using a scratch register.  */
8034
8035 static void
8036 load_got_offset (int dest, expressionS *local)
8037 {
8038   expressionS global;
8039
8040   global = *local;
8041   global.X_add_number = 0;
8042
8043   relax_start (local->X_add_symbol);
8044   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
8045                BFD_RELOC_MIPS_GOT16, mips_gp_register);
8046   relax_switch ();
8047   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
8048                BFD_RELOC_MIPS_GOT16, mips_gp_register);
8049   relax_end ();
8050 }
8051
8052 static void
8053 add_got_offset (int dest, expressionS *local)
8054 {
8055   expressionS global;
8056
8057   global.X_op = O_constant;
8058   global.X_op_symbol = NULL;
8059   global.X_add_symbol = NULL;
8060   global.X_add_number = local->X_add_number;
8061
8062   relax_start (local->X_add_symbol);
8063   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
8064                dest, dest, BFD_RELOC_LO16);
8065   relax_switch ();
8066   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
8067   relax_end ();
8068 }
8069
8070 static void
8071 add_got_offset_hilo (int dest, expressionS *local, int tmp)
8072 {
8073   expressionS global;
8074   int hold_mips_optimize;
8075
8076   global.X_op = O_constant;
8077   global.X_op_symbol = NULL;
8078   global.X_add_symbol = NULL;
8079   global.X_add_number = local->X_add_number;
8080
8081   relax_start (local->X_add_symbol);
8082   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
8083   relax_switch ();
8084   /* Set mips_optimize around the lui instruction to avoid
8085      inserting an unnecessary nop after the lw.  */
8086   hold_mips_optimize = mips_optimize;
8087   mips_optimize = 2;
8088   macro_build_lui (&global, tmp);
8089   mips_optimize = hold_mips_optimize;
8090   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
8091   relax_end ();
8092
8093   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
8094 }
8095
8096 /* Emit a sequence of instructions to emulate a branch likely operation.
8097    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
8098    is its complementing branch with the original condition negated.
8099    CALL is set if the original branch specified the link operation.
8100    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
8101
8102    Code like this is produced in the noreorder mode:
8103
8104         BRNEG   <args>, 1f
8105          nop
8106         b       <sym>
8107          delay slot (executed only if branch taken)
8108     1:
8109
8110    or, if CALL is set:
8111
8112         BRNEG   <args>, 1f
8113          nop
8114         bal     <sym>
8115          delay slot (executed only if branch taken)
8116     1:
8117
8118    In the reorder mode the delay slot would be filled with a nop anyway,
8119    so code produced is simply:
8120
8121         BR      <args>, <sym>
8122          nop
8123
8124    This function is used when producing code for the microMIPS ASE that
8125    does not implement branch likely instructions in hardware.  */
8126
8127 static void
8128 macro_build_branch_likely (const char *br, const char *brneg,
8129                            int call, expressionS *ep, const char *fmt,
8130                            unsigned int sreg, unsigned int treg)
8131 {
8132   int noreorder = mips_opts.noreorder;
8133   expressionS expr1;
8134
8135   gas_assert (mips_opts.micromips);
8136   start_noreorder ();
8137   if (noreorder)
8138     {
8139       micromips_label_expr (&expr1);
8140       macro_build (&expr1, brneg, fmt, sreg, treg);
8141       macro_build (NULL, "nop", "");
8142       macro_build (ep, call ? "bal" : "b", "p");
8143
8144       /* Set to true so that append_insn adds a label.  */
8145       emit_branch_likely_macro = TRUE;
8146     }
8147   else
8148     {
8149       macro_build (ep, br, fmt, sreg, treg);
8150       macro_build (NULL, "nop", "");
8151     }
8152   end_noreorder ();
8153 }
8154
8155 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
8156    the condition code tested.  EP specifies the branch target.  */
8157
8158 static void
8159 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
8160 {
8161   const int call = 0;
8162   const char *brneg;
8163   const char *br;
8164
8165   switch (type)
8166     {
8167     case M_BC1FL:
8168       br = "bc1f";
8169       brneg = "bc1t";
8170       break;
8171     case M_BC1TL:
8172       br = "bc1t";
8173       brneg = "bc1f";
8174       break;
8175     case M_BC2FL:
8176       br = "bc2f";
8177       brneg = "bc2t";
8178       break;
8179     case M_BC2TL:
8180       br = "bc2t";
8181       brneg = "bc2f";
8182       break;
8183     default:
8184       abort ();
8185     }
8186   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
8187 }
8188
8189 /* Emit a two-argument branch macro specified by TYPE, using SREG as
8190    the register tested.  EP specifies the branch target.  */
8191
8192 static void
8193 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
8194 {
8195   const char *brneg = NULL;
8196   const char *br;
8197   int call = 0;
8198
8199   switch (type)
8200     {
8201     case M_BGEZ:
8202       br = "bgez";
8203       break;
8204     case M_BGEZL:
8205       br = mips_opts.micromips ? "bgez" : "bgezl";
8206       brneg = "bltz";
8207       break;
8208     case M_BGEZALL:
8209       gas_assert (mips_opts.micromips);
8210       br = mips_opts.insn32 ? "bgezal" : "bgezals";
8211       brneg = "bltz";
8212       call = 1;
8213       break;
8214     case M_BGTZ:
8215       br = "bgtz";
8216       break;
8217     case M_BGTZL:
8218       br = mips_opts.micromips ? "bgtz" : "bgtzl";
8219       brneg = "blez";
8220       break;
8221     case M_BLEZ:
8222       br = "blez";
8223       break;
8224     case M_BLEZL:
8225       br = mips_opts.micromips ? "blez" : "blezl";
8226       brneg = "bgtz";
8227       break;
8228     case M_BLTZ:
8229       br = "bltz";
8230       break;
8231     case M_BLTZL:
8232       br = mips_opts.micromips ? "bltz" : "bltzl";
8233       brneg = "bgez";
8234       break;
8235     case M_BLTZALL:
8236       gas_assert (mips_opts.micromips);
8237       br = mips_opts.insn32 ? "bltzal" : "bltzals";
8238       brneg = "bgez";
8239       call = 1;
8240       break;
8241     default:
8242       abort ();
8243     }
8244   if (mips_opts.micromips && brneg)
8245     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
8246   else
8247     macro_build (ep, br, "s,p", sreg);
8248 }
8249
8250 /* Emit a three-argument branch macro specified by TYPE, using SREG and
8251    TREG as the registers tested.  EP specifies the branch target.  */
8252
8253 static void
8254 macro_build_branch_rsrt (int type, expressionS *ep,
8255                          unsigned int sreg, unsigned int treg)
8256 {
8257   const char *brneg = NULL;
8258   const int call = 0;
8259   const char *br;
8260
8261   switch (type)
8262     {
8263     case M_BEQ:
8264     case M_BEQ_I:
8265       br = "beq";
8266       break;
8267     case M_BEQL:
8268     case M_BEQL_I:
8269       br = mips_opts.micromips ? "beq" : "beql";
8270       brneg = "bne";
8271       break;
8272     case M_BNE:
8273     case M_BNE_I:
8274       br = "bne";
8275       break;
8276     case M_BNEL:
8277     case M_BNEL_I:
8278       br = mips_opts.micromips ? "bne" : "bnel";
8279       brneg = "beq";
8280       break;
8281     default:
8282       abort ();
8283     }
8284   if (mips_opts.micromips && brneg)
8285     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
8286   else
8287     macro_build (ep, br, "s,t,p", sreg, treg);
8288 }
8289
8290 /* Return the high part that should be loaded in order to make the low
8291    part of VALUE accessible using an offset of OFFBITS bits.  */
8292
8293 static offsetT
8294 offset_high_part (offsetT value, unsigned int offbits)
8295 {
8296   offsetT bias;
8297   addressT low_mask;
8298
8299   if (offbits == 0)
8300     return value;
8301   bias = 1 << (offbits - 1);
8302   low_mask = bias * 2 - 1;
8303   return (value + bias) & ~low_mask;
8304 }
8305
8306 /* Return true if the value stored in offset_expr and offset_reloc
8307    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
8308    amount that the caller wants to add without inducing overflow
8309    and ALIGN is the known alignment of the value in bytes.  */
8310
8311 static bfd_boolean
8312 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
8313 {
8314   if (offbits == 16)
8315     {
8316       /* Accept any relocation operator if overflow isn't a concern.  */
8317       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
8318         return TRUE;
8319
8320       /* These relocations are guaranteed not to overflow in correct links.  */
8321       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
8322           || gprel16_reloc_p (*offset_reloc))
8323         return TRUE;
8324     }
8325   if (offset_expr.X_op == O_constant
8326       && offset_high_part (offset_expr.X_add_number, offbits) == 0
8327       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
8328     return TRUE;
8329   return FALSE;
8330 }
8331
8332 /*
8333  *                      Build macros
8334  *   This routine implements the seemingly endless macro or synthesized
8335  * instructions and addressing modes in the mips assembly language. Many
8336  * of these macros are simple and are similar to each other. These could
8337  * probably be handled by some kind of table or grammar approach instead of
8338  * this verbose method. Others are not simple macros but are more like
8339  * optimizing code generation.
8340  *   One interesting optimization is when several store macros appear
8341  * consecutively that would load AT with the upper half of the same address.
8342  * The ensuing load upper instructions are ommited. This implies some kind
8343  * of global optimization. We currently only optimize within a single macro.
8344  *   For many of the load and store macros if the address is specified as a
8345  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
8346  * first load register 'at' with zero and use it as the base register. The
8347  * mips assembler simply uses register $zero. Just one tiny optimization
8348  * we're missing.
8349  */
8350 static void
8351 macro (struct mips_cl_insn *ip, char *str)
8352 {
8353   const struct mips_operand_array *operands;
8354   unsigned int breg, i;
8355   unsigned int tempreg;
8356   int mask;
8357   int used_at = 0;
8358   expressionS label_expr;
8359   expressionS expr1;
8360   expressionS *ep;
8361   const char *s;
8362   const char *s2;
8363   const char *fmt;
8364   int likely = 0;
8365   int coproc = 0;
8366   int offbits = 16;
8367   int call = 0;
8368   int jals = 0;
8369   int dbl = 0;
8370   int imm = 0;
8371   int ust = 0;
8372   int lp = 0;
8373   bfd_boolean large_offset;
8374   int off;
8375   int hold_mips_optimize;
8376   unsigned int align;
8377   unsigned int op[MAX_OPERANDS];
8378
8379   gas_assert (! mips_opts.mips16);
8380
8381   operands = insn_operands (ip);
8382   for (i = 0; i < MAX_OPERANDS; i++)
8383     if (operands->operand[i])
8384       op[i] = insn_extract_operand (ip, operands->operand[i]);
8385     else
8386       op[i] = -1;
8387
8388   mask = ip->insn_mo->mask;
8389
8390   label_expr.X_op = O_constant;
8391   label_expr.X_op_symbol = NULL;
8392   label_expr.X_add_symbol = NULL;
8393   label_expr.X_add_number = 0;
8394
8395   expr1.X_op = O_constant;
8396   expr1.X_op_symbol = NULL;
8397   expr1.X_add_symbol = NULL;
8398   expr1.X_add_number = 1;
8399   align = 1;
8400
8401   switch (mask)
8402     {
8403     case M_DABS:
8404       dbl = 1;
8405     case M_ABS:
8406       /*    bgez    $a0,1f
8407             move    v0,$a0
8408             sub     v0,$zero,$a0
8409          1:
8410        */
8411
8412       start_noreorder ();
8413
8414       if (mips_opts.micromips)
8415         micromips_label_expr (&label_expr);
8416       else
8417         label_expr.X_add_number = 8;
8418       macro_build (&label_expr, "bgez", "s,p", op[1]);
8419       if (op[0] == op[1])
8420         macro_build (NULL, "nop", "");
8421       else
8422         move_register (op[0], op[1]);
8423       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", op[0], 0, op[1]);
8424       if (mips_opts.micromips)
8425         micromips_add_label ();
8426
8427       end_noreorder ();
8428       break;
8429
8430     case M_ADD_I:
8431       s = "addi";
8432       s2 = "add";
8433       goto do_addi;
8434     case M_ADDU_I:
8435       s = "addiu";
8436       s2 = "addu";
8437       goto do_addi;
8438     case M_DADD_I:
8439       dbl = 1;
8440       s = "daddi";
8441       s2 = "dadd";
8442       if (!mips_opts.micromips)
8443         goto do_addi;
8444       if (imm_expr.X_op == O_constant
8445           && imm_expr.X_add_number >= -0x200
8446           && imm_expr.X_add_number < 0x200)
8447         {
8448           macro_build (NULL, s, "t,r,.", op[0], op[1], imm_expr.X_add_number);
8449           break;
8450         }
8451       goto do_addi_i;
8452     case M_DADDU_I:
8453       dbl = 1;
8454       s = "daddiu";
8455       s2 = "daddu";
8456     do_addi:
8457       if (imm_expr.X_op == O_constant
8458           && imm_expr.X_add_number >= -0x8000
8459           && imm_expr.X_add_number < 0x8000)
8460         {
8461           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
8462           break;
8463         }
8464     do_addi_i:
8465       used_at = 1;
8466       load_register (AT, &imm_expr, dbl);
8467       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
8468       break;
8469
8470     case M_AND_I:
8471       s = "andi";
8472       s2 = "and";
8473       goto do_bit;
8474     case M_OR_I:
8475       s = "ori";
8476       s2 = "or";
8477       goto do_bit;
8478     case M_NOR_I:
8479       s = "";
8480       s2 = "nor";
8481       goto do_bit;
8482     case M_XOR_I:
8483       s = "xori";
8484       s2 = "xor";
8485     do_bit:
8486       if (imm_expr.X_op == O_constant
8487           && imm_expr.X_add_number >= 0
8488           && imm_expr.X_add_number < 0x10000)
8489         {
8490           if (mask != M_NOR_I)
8491             macro_build (&imm_expr, s, "t,r,i", op[0], op[1], BFD_RELOC_LO16);
8492           else
8493             {
8494               macro_build (&imm_expr, "ori", "t,r,i",
8495                            op[0], op[1], BFD_RELOC_LO16);
8496               macro_build (NULL, "nor", "d,v,t", op[0], op[0], 0);
8497             }
8498           break;
8499         }
8500
8501       used_at = 1;
8502       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
8503       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
8504       break;
8505
8506     case M_BALIGN:
8507       switch (imm_expr.X_add_number)
8508         {
8509         case 0:
8510           macro_build (NULL, "nop", "");
8511           break;
8512         case 2:
8513           macro_build (NULL, "packrl.ph", "d,s,t", op[0], op[0], op[1]);
8514           break;
8515         case 1:
8516         case 3:
8517           macro_build (NULL, "balign", "t,s,2", op[0], op[1],
8518                        (int) imm_expr.X_add_number);
8519           break;
8520         default:
8521           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
8522                   (unsigned long) imm_expr.X_add_number);
8523           break;
8524         }
8525       break;
8526
8527     case M_BC1FL:
8528     case M_BC1TL:
8529     case M_BC2FL:
8530     case M_BC2TL:
8531       gas_assert (mips_opts.micromips);
8532       macro_build_branch_ccl (mask, &offset_expr,
8533                               EXTRACT_OPERAND (1, BCC, *ip));
8534       break;
8535
8536     case M_BEQ_I:
8537     case M_BEQL_I:
8538     case M_BNE_I:
8539     case M_BNEL_I:
8540       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
8541         op[1] = 0;
8542       else
8543         {
8544           op[1] = AT;
8545           used_at = 1;
8546           load_register (op[1], &imm_expr, HAVE_64BIT_GPRS);
8547         }
8548       /* Fall through.  */
8549     case M_BEQL:
8550     case M_BNEL:
8551       macro_build_branch_rsrt (mask, &offset_expr, op[0], op[1]);
8552       break;
8553
8554     case M_BGEL:
8555       likely = 1;
8556     case M_BGE:
8557       if (op[1] == 0)
8558         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[0]);
8559       else if (op[0] == 0)
8560         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[1]);
8561       else
8562         {
8563           used_at = 1;
8564           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
8565           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8566                                    &offset_expr, AT, ZERO);
8567         }
8568       break;
8569
8570     case M_BGEZL:
8571     case M_BGEZALL:
8572     case M_BGTZL:
8573     case M_BLEZL:
8574     case M_BLTZL:
8575     case M_BLTZALL:
8576       macro_build_branch_rs (mask, &offset_expr, op[0]);
8577       break;
8578
8579     case M_BGTL_I:
8580       likely = 1;
8581     case M_BGT_I:
8582       /* Check for > max integer.  */
8583       if (imm_expr.X_op == O_constant && imm_expr.X_add_number >= GPR_SMAX)
8584         {
8585         do_false:
8586           /* Result is always false.  */
8587           if (! likely)
8588             macro_build (NULL, "nop", "");
8589           else
8590             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
8591           break;
8592         }
8593       if (imm_expr.X_op != O_constant)
8594         as_bad (_("Unsupported large constant"));
8595       ++imm_expr.X_add_number;
8596       /* FALLTHROUGH */
8597     case M_BGE_I:
8598     case M_BGEL_I:
8599       if (mask == M_BGEL_I)
8600         likely = 1;
8601       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
8602         {
8603           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
8604                                  &offset_expr, op[0]);
8605           break;
8606         }
8607       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
8608         {
8609           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
8610                                  &offset_expr, op[0]);
8611           break;
8612         }
8613       if (imm_expr.X_op == O_constant && imm_expr.X_add_number <= GPR_SMIN)
8614         {
8615         do_true:
8616           /* result is always true */
8617           as_warn (_("Branch %s is always true"), ip->insn_mo->name);
8618           macro_build (&offset_expr, "b", "p");
8619           break;
8620         }
8621       used_at = 1;
8622       set_at (op[0], 0);
8623       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8624                                &offset_expr, AT, ZERO);
8625       break;
8626
8627     case M_BGEUL:
8628       likely = 1;
8629     case M_BGEU:
8630       if (op[1] == 0)
8631         goto do_true;
8632       else if (op[0] == 0)
8633         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8634                                  &offset_expr, ZERO, op[1]);
8635       else
8636         {
8637           used_at = 1;
8638           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
8639           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8640                                    &offset_expr, AT, ZERO);
8641         }
8642       break;
8643
8644     case M_BGTUL_I:
8645       likely = 1;
8646     case M_BGTU_I:
8647       if (op[0] == 0
8648           || (HAVE_32BIT_GPRS
8649               && imm_expr.X_op == O_constant
8650               && imm_expr.X_add_number == -1))
8651         goto do_false;
8652       if (imm_expr.X_op != O_constant)
8653         as_bad (_("Unsupported large constant"));
8654       ++imm_expr.X_add_number;
8655       /* FALLTHROUGH */
8656     case M_BGEU_I:
8657     case M_BGEUL_I:
8658       if (mask == M_BGEUL_I)
8659         likely = 1;
8660       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
8661         goto do_true;
8662       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
8663         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8664                                  &offset_expr, op[0], ZERO);
8665       else
8666         {
8667           used_at = 1;
8668           set_at (op[0], 1);
8669           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8670                                    &offset_expr, AT, ZERO);
8671         }
8672       break;
8673
8674     case M_BGTL:
8675       likely = 1;
8676     case M_BGT:
8677       if (op[1] == 0)
8678         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[0]);
8679       else if (op[0] == 0)
8680         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[1]);
8681       else
8682         {
8683           used_at = 1;
8684           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
8685           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8686                                    &offset_expr, AT, ZERO);
8687         }
8688       break;
8689
8690     case M_BGTUL:
8691       likely = 1;
8692     case M_BGTU:
8693       if (op[1] == 0)
8694         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8695                                  &offset_expr, op[0], ZERO);
8696       else if (op[0] == 0)
8697         goto do_false;
8698       else
8699         {
8700           used_at = 1;
8701           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
8702           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8703                                    &offset_expr, AT, ZERO);
8704         }
8705       break;
8706
8707     case M_BLEL:
8708       likely = 1;
8709     case M_BLE:
8710       if (op[1] == 0)
8711         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
8712       else if (op[0] == 0)
8713         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[1]);
8714       else
8715         {
8716           used_at = 1;
8717           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
8718           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8719                                    &offset_expr, AT, ZERO);
8720         }
8721       break;
8722
8723     case M_BLEL_I:
8724       likely = 1;
8725     case M_BLE_I:
8726       if (imm_expr.X_op == O_constant && imm_expr.X_add_number >= GPR_SMAX)
8727         goto do_true;
8728       if (imm_expr.X_op != O_constant)
8729         as_bad (_("Unsupported large constant"));
8730       ++imm_expr.X_add_number;
8731       /* FALLTHROUGH */
8732     case M_BLT_I:
8733     case M_BLTL_I:
8734       if (mask == M_BLTL_I)
8735         likely = 1;
8736       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
8737         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
8738       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
8739         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
8740       else
8741         {
8742           used_at = 1;
8743           set_at (op[0], 0);
8744           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8745                                    &offset_expr, AT, ZERO);
8746         }
8747       break;
8748
8749     case M_BLEUL:
8750       likely = 1;
8751     case M_BLEU:
8752       if (op[1] == 0)
8753         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8754                                  &offset_expr, op[0], ZERO);
8755       else if (op[0] == 0)
8756         goto do_true;
8757       else
8758         {
8759           used_at = 1;
8760           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
8761           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8762                                    &offset_expr, AT, ZERO);
8763         }
8764       break;
8765
8766     case M_BLEUL_I:
8767       likely = 1;
8768     case M_BLEU_I:
8769       if (op[0] == 0
8770           || (HAVE_32BIT_GPRS
8771               && imm_expr.X_op == O_constant
8772               && imm_expr.X_add_number == -1))
8773         goto do_true;
8774       if (imm_expr.X_op != O_constant)
8775         as_bad (_("Unsupported large constant"));
8776       ++imm_expr.X_add_number;
8777       /* FALLTHROUGH */
8778     case M_BLTU_I:
8779     case M_BLTUL_I:
8780       if (mask == M_BLTUL_I)
8781         likely = 1;
8782       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
8783         goto do_false;
8784       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
8785         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
8786                                  &offset_expr, op[0], ZERO);
8787       else
8788         {
8789           used_at = 1;
8790           set_at (op[0], 1);
8791           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8792                                    &offset_expr, AT, ZERO);
8793         }
8794       break;
8795
8796     case M_BLTL:
8797       likely = 1;
8798     case M_BLT:
8799       if (op[1] == 0)
8800         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
8801       else if (op[0] == 0)
8802         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[1]);
8803       else
8804         {
8805           used_at = 1;
8806           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
8807           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8808                                    &offset_expr, AT, ZERO);
8809         }
8810       break;
8811
8812     case M_BLTUL:
8813       likely = 1;
8814     case M_BLTU:
8815       if (op[1] == 0)
8816         goto do_false;
8817       else if (op[0] == 0)
8818         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8819                                  &offset_expr, ZERO, op[1]);
8820       else
8821         {
8822           used_at = 1;
8823           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
8824           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8825                                    &offset_expr, AT, ZERO);
8826         }
8827       break;
8828
8829     case M_DEXT:
8830       {
8831         /* Use unsigned arithmetic.  */
8832         addressT pos;
8833         addressT size;
8834
8835         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
8836           {
8837             as_bad (_("Unsupported large constant"));
8838             pos = size = 1;
8839           }
8840         else
8841           {
8842             pos = imm_expr.X_add_number;
8843             size = imm2_expr.X_add_number;
8844           }
8845
8846         if (pos > 63)
8847           {
8848             report_bad_range (ip, 3, pos, 0, 63, FALSE);
8849             pos = 1;
8850           }
8851         if (size == 0 || size > 64 || (pos + size - 1) > 63)
8852           {
8853             report_bad_field (pos, size);
8854             size = 1;
8855           }
8856
8857         if (size <= 32 && pos < 32)
8858           {
8859             s = "dext";
8860             fmt = "t,r,+A,+C";
8861           }
8862         else if (size <= 32)
8863           {
8864             s = "dextu";
8865             fmt = "t,r,+E,+H";
8866           }
8867         else
8868           {
8869             s = "dextm";
8870             fmt = "t,r,+A,+G";
8871           }
8872         macro_build ((expressionS *) NULL, s, fmt, op[0], op[1], (int) pos,
8873                      (int) (size - 1));
8874       }
8875       break;
8876
8877     case M_DINS:
8878       {
8879         /* Use unsigned arithmetic.  */
8880         addressT pos;
8881         addressT size;
8882
8883         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
8884           {
8885             as_bad (_("Unsupported large constant"));
8886             pos = size = 1;
8887           }
8888         else
8889           {
8890             pos = imm_expr.X_add_number;
8891             size = imm2_expr.X_add_number;
8892           }
8893
8894         if (pos > 63)
8895           {
8896             report_bad_range (ip, 3, pos, 0, 63, FALSE);
8897             pos = 1;
8898           }
8899         if (size == 0 || size > 64 || (pos + size - 1) > 63)
8900           {
8901             report_bad_field (pos, size);
8902             size = 1;
8903           }
8904
8905         if (pos < 32 && (pos + size - 1) < 32)
8906           {
8907             s = "dins";
8908             fmt = "t,r,+A,+B";
8909           }
8910         else if (pos >= 32)
8911           {
8912             s = "dinsu";
8913             fmt = "t,r,+E,+F";
8914           }
8915         else
8916           {
8917             s = "dinsm";
8918             fmt = "t,r,+A,+F";
8919           }
8920         macro_build ((expressionS *) NULL, s, fmt, op[0], op[1], (int) pos,
8921                      (int) (pos + size - 1));
8922       }
8923       break;
8924
8925     case M_DDIV_3:
8926       dbl = 1;
8927     case M_DIV_3:
8928       s = "mflo";
8929       goto do_div3;
8930     case M_DREM_3:
8931       dbl = 1;
8932     case M_REM_3:
8933       s = "mfhi";
8934     do_div3:
8935       if (op[2] == 0)
8936         {
8937           as_warn (_("Divide by zero."));
8938           if (mips_trap)
8939             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
8940           else
8941             macro_build (NULL, "break", BRK_FMT, 7);
8942           break;
8943         }
8944
8945       start_noreorder ();
8946       if (mips_trap)
8947         {
8948           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
8949           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
8950         }
8951       else
8952         {
8953           if (mips_opts.micromips)
8954             micromips_label_expr (&label_expr);
8955           else
8956             label_expr.X_add_number = 8;
8957           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
8958           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
8959           macro_build (NULL, "break", BRK_FMT, 7);
8960           if (mips_opts.micromips)
8961             micromips_add_label ();
8962         }
8963       expr1.X_add_number = -1;
8964       used_at = 1;
8965       load_register (AT, &expr1, dbl);
8966       if (mips_opts.micromips)
8967         micromips_label_expr (&label_expr);
8968       else
8969         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
8970       macro_build (&label_expr, "bne", "s,t,p", op[2], AT);
8971       if (dbl)
8972         {
8973           expr1.X_add_number = 1;
8974           load_register (AT, &expr1, dbl);
8975           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
8976         }
8977       else
8978         {
8979           expr1.X_add_number = 0x80000000;
8980           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
8981         }
8982       if (mips_trap)
8983         {
8984           macro_build (NULL, "teq", TRAP_FMT, op[1], AT, 6);
8985           /* We want to close the noreorder block as soon as possible, so
8986              that later insns are available for delay slot filling.  */
8987           end_noreorder ();
8988         }
8989       else
8990         {
8991           if (mips_opts.micromips)
8992             micromips_label_expr (&label_expr);
8993           else
8994             label_expr.X_add_number = 8;
8995           macro_build (&label_expr, "bne", "s,t,p", op[1], AT);
8996           macro_build (NULL, "nop", "");
8997
8998           /* We want to close the noreorder block as soon as possible, so
8999              that later insns are available for delay slot filling.  */
9000           end_noreorder ();
9001
9002           macro_build (NULL, "break", BRK_FMT, 6);
9003         }
9004       if (mips_opts.micromips)
9005         micromips_add_label ();
9006       macro_build (NULL, s, MFHL_FMT, op[0]);
9007       break;
9008
9009     case M_DIV_3I:
9010       s = "div";
9011       s2 = "mflo";
9012       goto do_divi;
9013     case M_DIVU_3I:
9014       s = "divu";
9015       s2 = "mflo";
9016       goto do_divi;
9017     case M_REM_3I:
9018       s = "div";
9019       s2 = "mfhi";
9020       goto do_divi;
9021     case M_REMU_3I:
9022       s = "divu";
9023       s2 = "mfhi";
9024       goto do_divi;
9025     case M_DDIV_3I:
9026       dbl = 1;
9027       s = "ddiv";
9028       s2 = "mflo";
9029       goto do_divi;
9030     case M_DDIVU_3I:
9031       dbl = 1;
9032       s = "ddivu";
9033       s2 = "mflo";
9034       goto do_divi;
9035     case M_DREM_3I:
9036       dbl = 1;
9037       s = "ddiv";
9038       s2 = "mfhi";
9039       goto do_divi;
9040     case M_DREMU_3I:
9041       dbl = 1;
9042       s = "ddivu";
9043       s2 = "mfhi";
9044     do_divi:
9045       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
9046         {
9047           as_warn (_("Divide by zero."));
9048           if (mips_trap)
9049             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
9050           else
9051             macro_build (NULL, "break", BRK_FMT, 7);
9052           break;
9053         }
9054       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
9055         {
9056           if (strcmp (s2, "mflo") == 0)
9057             move_register (op[0], op[1]);
9058           else
9059             move_register (op[0], ZERO);
9060           break;
9061         }
9062       if (imm_expr.X_op == O_constant
9063           && imm_expr.X_add_number == -1
9064           && s[strlen (s) - 1] != 'u')
9065         {
9066           if (strcmp (s2, "mflo") == 0)
9067             macro_build (NULL, dbl ? "dneg" : "neg", "d,w", op[0], op[1]);
9068           else
9069             move_register (op[0], ZERO);
9070           break;
9071         }
9072
9073       used_at = 1;
9074       load_register (AT, &imm_expr, dbl);
9075       macro_build (NULL, s, "z,s,t", op[1], AT);
9076       macro_build (NULL, s2, MFHL_FMT, op[0]);
9077       break;
9078
9079     case M_DIVU_3:
9080       s = "divu";
9081       s2 = "mflo";
9082       goto do_divu3;
9083     case M_REMU_3:
9084       s = "divu";
9085       s2 = "mfhi";
9086       goto do_divu3;
9087     case M_DDIVU_3:
9088       s = "ddivu";
9089       s2 = "mflo";
9090       goto do_divu3;
9091     case M_DREMU_3:
9092       s = "ddivu";
9093       s2 = "mfhi";
9094     do_divu3:
9095       start_noreorder ();
9096       if (mips_trap)
9097         {
9098           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
9099           macro_build (NULL, s, "z,s,t", op[1], op[2]);
9100           /* We want to close the noreorder block as soon as possible, so
9101              that later insns are available for delay slot filling.  */
9102           end_noreorder ();
9103         }
9104       else
9105         {
9106           if (mips_opts.micromips)
9107             micromips_label_expr (&label_expr);
9108           else
9109             label_expr.X_add_number = 8;
9110           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
9111           macro_build (NULL, s, "z,s,t", op[1], op[2]);
9112
9113           /* We want to close the noreorder block as soon as possible, so
9114              that later insns are available for delay slot filling.  */
9115           end_noreorder ();
9116           macro_build (NULL, "break", BRK_FMT, 7);
9117           if (mips_opts.micromips)
9118             micromips_add_label ();
9119         }
9120       macro_build (NULL, s2, MFHL_FMT, op[0]);
9121       break;
9122
9123     case M_DLCA_AB:
9124       dbl = 1;
9125     case M_LCA_AB:
9126       call = 1;
9127       goto do_la;
9128     case M_DLA_AB:
9129       dbl = 1;
9130     case M_LA_AB:
9131     do_la:
9132       /* Load the address of a symbol into a register.  If breg is not
9133          zero, we then add a base register to it.  */
9134
9135       breg = op[2];
9136       if (dbl && HAVE_32BIT_GPRS)
9137         as_warn (_("dla used to load 32-bit register"));
9138
9139       if (!dbl && HAVE_64BIT_OBJECTS)
9140         as_warn (_("la used to load 64-bit address"));
9141
9142       if (small_offset_p (0, align, 16))
9143         {
9144           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", op[0], breg,
9145                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
9146           break;
9147         }
9148
9149       if (mips_opts.at && (op[0] == breg))
9150         {
9151           tempreg = AT;
9152           used_at = 1;
9153         }
9154       else
9155         tempreg = op[0];
9156
9157       if (offset_expr.X_op != O_symbol
9158           && offset_expr.X_op != O_constant)
9159         {
9160           as_bad (_("Expression too complex"));
9161           offset_expr.X_op = O_constant;
9162         }
9163
9164       if (offset_expr.X_op == O_constant)
9165         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
9166       else if (mips_pic == NO_PIC)
9167         {
9168           /* If this is a reference to a GP relative symbol, we want
9169                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
9170              Otherwise we want
9171                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
9172                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9173              If we have a constant, we need two instructions anyhow,
9174              so we may as well always use the latter form.
9175
9176              With 64bit address space and a usable $at we want
9177                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9178                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9179                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9180                daddiu   $at,<sym>               (BFD_RELOC_LO16)
9181                dsll32   $tempreg,0
9182                daddu    $tempreg,$tempreg,$at
9183
9184              If $at is already in use, we use a path which is suboptimal
9185              on superscalar processors.
9186                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9187                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9188                dsll     $tempreg,16
9189                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9190                dsll     $tempreg,16
9191                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
9192
9193              For GP relative symbols in 64bit address space we can use
9194              the same sequence as in 32bit address space.  */
9195           if (HAVE_64BIT_SYMBOLS)
9196             {
9197               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9198                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9199                 {
9200                   relax_start (offset_expr.X_add_symbol);
9201                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9202                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
9203                   relax_switch ();
9204                 }
9205
9206               if (used_at == 0 && mips_opts.at)
9207                 {
9208                   macro_build (&offset_expr, "lui", LUI_FMT,
9209                                tempreg, BFD_RELOC_MIPS_HIGHEST);
9210                   macro_build (&offset_expr, "lui", LUI_FMT,
9211                                AT, BFD_RELOC_HI16_S);
9212                   macro_build (&offset_expr, "daddiu", "t,r,j",
9213                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
9214                   macro_build (&offset_expr, "daddiu", "t,r,j",
9215                                AT, AT, BFD_RELOC_LO16);
9216                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
9217                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
9218                   used_at = 1;
9219                 }
9220               else
9221                 {
9222                   macro_build (&offset_expr, "lui", LUI_FMT,
9223                                tempreg, BFD_RELOC_MIPS_HIGHEST);
9224                   macro_build (&offset_expr, "daddiu", "t,r,j",
9225                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
9226                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9227                   macro_build (&offset_expr, "daddiu", "t,r,j",
9228                                tempreg, tempreg, BFD_RELOC_HI16_S);
9229                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9230                   macro_build (&offset_expr, "daddiu", "t,r,j",
9231                                tempreg, tempreg, BFD_RELOC_LO16);
9232                 }
9233
9234               if (mips_relax.sequence)
9235                 relax_end ();
9236             }
9237           else
9238             {
9239               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9240                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9241                 {
9242                   relax_start (offset_expr.X_add_symbol);
9243                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9244                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
9245                   relax_switch ();
9246                 }
9247               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
9248                 as_bad (_("Offset too large"));
9249               macro_build_lui (&offset_expr, tempreg);
9250               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9251                            tempreg, tempreg, BFD_RELOC_LO16);
9252               if (mips_relax.sequence)
9253                 relax_end ();
9254             }
9255         }
9256       else if (!mips_big_got && !HAVE_NEWABI)
9257         {
9258           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
9259
9260           /* If this is a reference to an external symbol, and there
9261              is no constant, we want
9262                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9263              or for lca or if tempreg is PIC_CALL_REG
9264                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
9265              For a local symbol, we want
9266                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9267                nop
9268                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9269
9270              If we have a small constant, and this is a reference to
9271              an external symbol, we want
9272                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9273                nop
9274                addiu    $tempreg,$tempreg,<constant>
9275              For a local symbol, we want the same instruction
9276              sequence, but we output a BFD_RELOC_LO16 reloc on the
9277              addiu instruction.
9278
9279              If we have a large constant, and this is a reference to
9280              an external symbol, we want
9281                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9282                lui      $at,<hiconstant>
9283                addiu    $at,$at,<loconstant>
9284                addu     $tempreg,$tempreg,$at
9285              For a local symbol, we want the same instruction
9286              sequence, but we output a BFD_RELOC_LO16 reloc on the
9287              addiu instruction.
9288            */
9289
9290           if (offset_expr.X_add_number == 0)
9291             {
9292               if (mips_pic == SVR4_PIC
9293                   && breg == 0
9294                   && (call || tempreg == PIC_CALL_REG))
9295                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
9296
9297               relax_start (offset_expr.X_add_symbol);
9298               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9299                            lw_reloc_type, mips_gp_register);
9300               if (breg != 0)
9301                 {
9302                   /* We're going to put in an addu instruction using
9303                      tempreg, so we may as well insert the nop right
9304                      now.  */
9305                   load_delay_nop ();
9306                 }
9307               relax_switch ();
9308               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9309                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
9310               load_delay_nop ();
9311               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9312                            tempreg, tempreg, BFD_RELOC_LO16);
9313               relax_end ();
9314               /* FIXME: If breg == 0, and the next instruction uses
9315                  $tempreg, then if this variant case is used an extra
9316                  nop will be generated.  */
9317             }
9318           else if (offset_expr.X_add_number >= -0x8000
9319                    && offset_expr.X_add_number < 0x8000)
9320             {
9321               load_got_offset (tempreg, &offset_expr);
9322               load_delay_nop ();
9323               add_got_offset (tempreg, &offset_expr);
9324             }
9325           else
9326             {
9327               expr1.X_add_number = offset_expr.X_add_number;
9328               offset_expr.X_add_number =
9329                 SEXT_16BIT (offset_expr.X_add_number);
9330               load_got_offset (tempreg, &offset_expr);
9331               offset_expr.X_add_number = expr1.X_add_number;
9332               /* If we are going to add in a base register, and the
9333                  target register and the base register are the same,
9334                  then we are using AT as a temporary register.  Since
9335                  we want to load the constant into AT, we add our
9336                  current AT (from the global offset table) and the
9337                  register into the register now, and pretend we were
9338                  not using a base register.  */
9339               if (breg == op[0])
9340                 {
9341                   load_delay_nop ();
9342                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9343                                op[0], AT, breg);
9344                   breg = 0;
9345                   tempreg = op[0];
9346                 }
9347               add_got_offset_hilo (tempreg, &offset_expr, AT);
9348               used_at = 1;
9349             }
9350         }
9351       else if (!mips_big_got && HAVE_NEWABI)
9352         {
9353           int add_breg_early = 0;
9354
9355           /* If this is a reference to an external, and there is no
9356              constant, or local symbol (*), with or without a
9357              constant, we want
9358                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
9359              or for lca or if tempreg is PIC_CALL_REG
9360                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
9361
9362              If we have a small constant, and this is a reference to
9363              an external symbol, we want
9364                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
9365                addiu    $tempreg,$tempreg,<constant>
9366
9367              If we have a large constant, and this is a reference to
9368              an external symbol, we want
9369                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
9370                lui      $at,<hiconstant>
9371                addiu    $at,$at,<loconstant>
9372                addu     $tempreg,$tempreg,$at
9373
9374              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
9375              local symbols, even though it introduces an additional
9376              instruction.  */
9377
9378           if (offset_expr.X_add_number)
9379             {
9380               expr1.X_add_number = offset_expr.X_add_number;
9381               offset_expr.X_add_number = 0;
9382
9383               relax_start (offset_expr.X_add_symbol);
9384               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9385                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9386
9387               if (expr1.X_add_number >= -0x8000
9388                   && expr1.X_add_number < 0x8000)
9389                 {
9390                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
9391                                tempreg, tempreg, BFD_RELOC_LO16);
9392                 }
9393               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
9394                 {
9395                   unsigned int dreg;
9396
9397                   /* If we are going to add in a base register, and the
9398                      target register and the base register are the same,
9399                      then we are using AT as a temporary register.  Since
9400                      we want to load the constant into AT, we add our
9401                      current AT (from the global offset table) and the
9402                      register into the register now, and pretend we were
9403                      not using a base register.  */
9404                   if (breg != op[0])
9405                     dreg = tempreg;
9406                   else
9407                     {
9408                       gas_assert (tempreg == AT);
9409                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9410                                    op[0], AT, breg);
9411                       dreg = op[0];
9412                       add_breg_early = 1;
9413                     }
9414
9415                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
9416                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9417                                dreg, dreg, AT);
9418
9419                   used_at = 1;
9420                 }
9421               else
9422                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
9423
9424               relax_switch ();
9425               offset_expr.X_add_number = expr1.X_add_number;
9426
9427               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9428                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9429               if (add_breg_early)
9430                 {
9431                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9432                                op[0], tempreg, breg);
9433                   breg = 0;
9434                   tempreg = op[0];
9435                 }
9436               relax_end ();
9437             }
9438           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
9439             {
9440               relax_start (offset_expr.X_add_symbol);
9441               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9442                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
9443               relax_switch ();
9444               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9445                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9446               relax_end ();
9447             }
9448           else
9449             {
9450               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9451                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9452             }
9453         }
9454       else if (mips_big_got && !HAVE_NEWABI)
9455         {
9456           int gpdelay;
9457           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
9458           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
9459           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
9460
9461           /* This is the large GOT case.  If this is a reference to an
9462              external symbol, and there is no constant, we want
9463                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
9464                addu     $tempreg,$tempreg,$gp
9465                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
9466              or for lca or if tempreg is PIC_CALL_REG
9467                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
9468                addu     $tempreg,$tempreg,$gp
9469                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
9470              For a local symbol, we want
9471                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9472                nop
9473                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9474
9475              If we have a small constant, and this is a reference to
9476              an external symbol, we want
9477                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
9478                addu     $tempreg,$tempreg,$gp
9479                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
9480                nop
9481                addiu    $tempreg,$tempreg,<constant>
9482              For a local symbol, we want
9483                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9484                nop
9485                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
9486
9487              If we have a large constant, and this is a reference to
9488              an external symbol, we want
9489                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
9490                addu     $tempreg,$tempreg,$gp
9491                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
9492                lui      $at,<hiconstant>
9493                addiu    $at,$at,<loconstant>
9494                addu     $tempreg,$tempreg,$at
9495              For a local symbol, we want
9496                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9497                lui      $at,<hiconstant>
9498                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
9499                addu     $tempreg,$tempreg,$at
9500           */
9501
9502           expr1.X_add_number = offset_expr.X_add_number;
9503           offset_expr.X_add_number = 0;
9504           relax_start (offset_expr.X_add_symbol);
9505           gpdelay = reg_needs_delay (mips_gp_register);
9506           if (expr1.X_add_number == 0 && breg == 0
9507               && (call || tempreg == PIC_CALL_REG))
9508             {
9509               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
9510               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
9511             }
9512           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
9513           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9514                        tempreg, tempreg, mips_gp_register);
9515           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9516                        tempreg, lw_reloc_type, tempreg);
9517           if (expr1.X_add_number == 0)
9518             {
9519               if (breg != 0)
9520                 {
9521                   /* We're going to put in an addu instruction using
9522                      tempreg, so we may as well insert the nop right
9523                      now.  */
9524                   load_delay_nop ();
9525                 }
9526             }
9527           else if (expr1.X_add_number >= -0x8000
9528                    && expr1.X_add_number < 0x8000)
9529             {
9530               load_delay_nop ();
9531               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
9532                            tempreg, tempreg, BFD_RELOC_LO16);
9533             }
9534           else
9535             {
9536               unsigned int dreg;
9537
9538               /* If we are going to add in a base register, and the
9539                  target register and the base register are the same,
9540                  then we are using AT as a temporary register.  Since
9541                  we want to load the constant into AT, we add our
9542                  current AT (from the global offset table) and the
9543                  register into the register now, and pretend we were
9544                  not using a base register.  */
9545               if (breg != op[0])
9546                 dreg = tempreg;
9547               else
9548                 {
9549                   gas_assert (tempreg == AT);
9550                   load_delay_nop ();
9551                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9552                                op[0], AT, breg);
9553                   dreg = op[0];
9554                 }
9555
9556               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
9557               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
9558
9559               used_at = 1;
9560             }
9561           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
9562           relax_switch ();
9563
9564           if (gpdelay)
9565             {
9566               /* This is needed because this instruction uses $gp, but
9567                  the first instruction on the main stream does not.  */
9568               macro_build (NULL, "nop", "");
9569             }
9570
9571           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9572                        local_reloc_type, mips_gp_register);
9573           if (expr1.X_add_number >= -0x8000
9574               && expr1.X_add_number < 0x8000)
9575             {
9576               load_delay_nop ();
9577               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9578                            tempreg, tempreg, BFD_RELOC_LO16);
9579               /* FIXME: If add_number is 0, and there was no base
9580                  register, the external symbol case ended with a load,
9581                  so if the symbol turns out to not be external, and
9582                  the next instruction uses tempreg, an unnecessary nop
9583                  will be inserted.  */
9584             }
9585           else
9586             {
9587               if (breg == op[0])
9588                 {
9589                   /* We must add in the base register now, as in the
9590                      external symbol case.  */
9591                   gas_assert (tempreg == AT);
9592                   load_delay_nop ();
9593                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9594                                op[0], AT, breg);
9595                   tempreg = op[0];
9596                   /* We set breg to 0 because we have arranged to add
9597                      it in in both cases.  */
9598                   breg = 0;
9599                 }
9600
9601               macro_build_lui (&expr1, AT);
9602               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9603                            AT, AT, BFD_RELOC_LO16);
9604               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9605                            tempreg, tempreg, AT);
9606               used_at = 1;
9607             }
9608           relax_end ();
9609         }
9610       else if (mips_big_got && HAVE_NEWABI)
9611         {
9612           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
9613           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
9614           int add_breg_early = 0;
9615
9616           /* This is the large GOT case.  If this is a reference to an
9617              external symbol, and there is no constant, we want
9618                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
9619                add      $tempreg,$tempreg,$gp
9620                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
9621              or for lca or if tempreg is PIC_CALL_REG
9622                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
9623                add      $tempreg,$tempreg,$gp
9624                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
9625
9626              If we have a small constant, and this is a reference to
9627              an external symbol, we want
9628                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
9629                add      $tempreg,$tempreg,$gp
9630                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
9631                addi     $tempreg,$tempreg,<constant>
9632
9633              If we have a large constant, and this is a reference to
9634              an external symbol, we want
9635                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
9636                addu     $tempreg,$tempreg,$gp
9637                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
9638                lui      $at,<hiconstant>
9639                addi     $at,$at,<loconstant>
9640                add      $tempreg,$tempreg,$at
9641
9642              If we have NewABI, and we know it's a local symbol, we want
9643                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
9644                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
9645              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
9646
9647           relax_start (offset_expr.X_add_symbol);
9648
9649           expr1.X_add_number = offset_expr.X_add_number;
9650           offset_expr.X_add_number = 0;
9651
9652           if (expr1.X_add_number == 0 && breg == 0
9653               && (call || tempreg == PIC_CALL_REG))
9654             {
9655               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
9656               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
9657             }
9658           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
9659           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9660                        tempreg, tempreg, mips_gp_register);
9661           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9662                        tempreg, lw_reloc_type, tempreg);
9663
9664           if (expr1.X_add_number == 0)
9665             ;
9666           else if (expr1.X_add_number >= -0x8000
9667                    && expr1.X_add_number < 0x8000)
9668             {
9669               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
9670                            tempreg, tempreg, BFD_RELOC_LO16);
9671             }
9672           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
9673             {
9674               unsigned int dreg;
9675
9676               /* If we are going to add in a base register, and the
9677                  target register and the base register are the same,
9678                  then we are using AT as a temporary register.  Since
9679                  we want to load the constant into AT, we add our
9680                  current AT (from the global offset table) and the
9681                  register into the register now, and pretend we were
9682                  not using a base register.  */
9683               if (breg != op[0])
9684                 dreg = tempreg;
9685               else
9686                 {
9687                   gas_assert (tempreg == AT);
9688                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9689                                op[0], AT, breg);
9690                   dreg = op[0];
9691                   add_breg_early = 1;
9692                 }
9693
9694               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
9695               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
9696
9697               used_at = 1;
9698             }
9699           else
9700             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
9701
9702           relax_switch ();
9703           offset_expr.X_add_number = expr1.X_add_number;
9704           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9705                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9706           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
9707                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
9708           if (add_breg_early)
9709             {
9710               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9711                            op[0], tempreg, breg);
9712               breg = 0;
9713               tempreg = op[0];
9714             }
9715           relax_end ();
9716         }
9717       else
9718         abort ();
9719
9720       if (breg != 0)
9721         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", op[0], tempreg, breg);
9722       break;
9723
9724     case M_MSGSND:
9725       gas_assert (!mips_opts.micromips);
9726       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x01);
9727       break;
9728
9729     case M_MSGLD:
9730       gas_assert (!mips_opts.micromips);
9731       macro_build (NULL, "c2", "C", 0x02);
9732       break;
9733
9734     case M_MSGLD_T:
9735       gas_assert (!mips_opts.micromips);
9736       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x02);
9737       break;
9738
9739     case M_MSGWAIT:
9740       gas_assert (!mips_opts.micromips);
9741       macro_build (NULL, "c2", "C", 3);
9742       break;
9743
9744     case M_MSGWAIT_T:
9745       gas_assert (!mips_opts.micromips);
9746       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x03);
9747       break;
9748
9749     case M_J_A:
9750       /* The j instruction may not be used in PIC code, since it
9751          requires an absolute address.  We convert it to a b
9752          instruction.  */
9753       if (mips_pic == NO_PIC)
9754         macro_build (&offset_expr, "j", "a");
9755       else
9756         macro_build (&offset_expr, "b", "p");
9757       break;
9758
9759       /* The jal instructions must be handled as macros because when
9760          generating PIC code they expand to multi-instruction
9761          sequences.  Normally they are simple instructions.  */
9762     case M_JALS_1:
9763       op[1] = op[0];
9764       op[0] = RA;
9765       /* Fall through.  */
9766     case M_JALS_2:
9767       gas_assert (mips_opts.micromips);
9768       if (mips_opts.insn32)
9769         {
9770           as_bad (_("Opcode not supported in the `insn32' mode `%s'"), str);
9771           break;
9772         }
9773       jals = 1;
9774       goto jal;
9775     case M_JAL_1:
9776       op[1] = op[0];
9777       op[0] = RA;
9778       /* Fall through.  */
9779     case M_JAL_2:
9780     jal:
9781       if (mips_pic == NO_PIC)
9782         {
9783           s = jals ? "jalrs" : "jalr";
9784           if (mips_opts.micromips
9785               && !mips_opts.insn32
9786               && op[0] == RA
9787               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
9788             macro_build (NULL, s, "mj", op[1]);
9789           else
9790             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
9791         }
9792       else
9793         {
9794           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
9795                            && mips_cprestore_offset >= 0);
9796
9797           if (op[1] != PIC_CALL_REG)
9798             as_warn (_("MIPS PIC call to register other than $25"));
9799
9800           s = ((mips_opts.micromips
9801                 && !mips_opts.insn32
9802                 && (!mips_opts.noreorder || cprestore))
9803                ? "jalrs" : "jalr");
9804           if (mips_opts.micromips
9805               && !mips_opts.insn32
9806               && op[0] == RA
9807               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
9808             macro_build (NULL, s, "mj", op[1]);
9809           else
9810             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
9811           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
9812             {
9813               if (mips_cprestore_offset < 0)
9814                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
9815               else
9816                 {
9817                   if (!mips_frame_reg_valid)
9818                     {
9819                       as_warn (_("No .frame pseudo-op used in PIC code"));
9820                       /* Quiet this warning.  */
9821                       mips_frame_reg_valid = 1;
9822                     }
9823                   if (!mips_cprestore_valid)
9824                     {
9825                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
9826                       /* Quiet this warning.  */
9827                       mips_cprestore_valid = 1;
9828                     }
9829                   if (mips_opts.noreorder)
9830                     macro_build (NULL, "nop", "");
9831                   expr1.X_add_number = mips_cprestore_offset;
9832                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
9833                                                 mips_gp_register,
9834                                                 mips_frame_reg,
9835                                                 HAVE_64BIT_ADDRESSES);
9836                 }
9837             }
9838         }
9839
9840       break;
9841
9842     case M_JALS_A:
9843       gas_assert (mips_opts.micromips);
9844       if (mips_opts.insn32)
9845         {
9846           as_bad (_("Opcode not supported in the `insn32' mode `%s'"), str);
9847           break;
9848         }
9849       jals = 1;
9850       /* Fall through.  */
9851     case M_JAL_A:
9852       if (mips_pic == NO_PIC)
9853         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
9854       else if (mips_pic == SVR4_PIC)
9855         {
9856           /* If this is a reference to an external symbol, and we are
9857              using a small GOT, we want
9858                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
9859                nop
9860                jalr     $ra,$25
9861                nop
9862                lw       $gp,cprestore($sp)
9863              The cprestore value is set using the .cprestore
9864              pseudo-op.  If we are using a big GOT, we want
9865                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
9866                addu     $25,$25,$gp
9867                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
9868                nop
9869                jalr     $ra,$25
9870                nop
9871                lw       $gp,cprestore($sp)
9872              If the symbol is not external, we want
9873                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
9874                nop
9875                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
9876                jalr     $ra,$25
9877                nop
9878                lw $gp,cprestore($sp)
9879
9880              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
9881              sequences above, minus nops, unless the symbol is local,
9882              which enables us to use GOT_PAGE/GOT_OFST (big got) or
9883              GOT_DISP.  */
9884           if (HAVE_NEWABI)
9885             {
9886               if (!mips_big_got)
9887                 {
9888                   relax_start (offset_expr.X_add_symbol);
9889                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9890                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
9891                                mips_gp_register);
9892                   relax_switch ();
9893                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9894                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
9895                                mips_gp_register);
9896                   relax_end ();
9897                 }
9898               else
9899                 {
9900                   relax_start (offset_expr.X_add_symbol);
9901                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
9902                                BFD_RELOC_MIPS_CALL_HI16);
9903                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
9904                                PIC_CALL_REG, mips_gp_register);
9905                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9906                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
9907                                PIC_CALL_REG);
9908                   relax_switch ();
9909                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9910                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
9911                                mips_gp_register);
9912                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9913                                PIC_CALL_REG, PIC_CALL_REG,
9914                                BFD_RELOC_MIPS_GOT_OFST);
9915                   relax_end ();
9916                 }
9917
9918               macro_build_jalr (&offset_expr, 0);
9919             }
9920           else
9921             {
9922               relax_start (offset_expr.X_add_symbol);
9923               if (!mips_big_got)
9924                 {
9925                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9926                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
9927                                mips_gp_register);
9928                   load_delay_nop ();
9929                   relax_switch ();
9930                 }
9931               else
9932                 {
9933                   int gpdelay;
9934
9935                   gpdelay = reg_needs_delay (mips_gp_register);
9936                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
9937                                BFD_RELOC_MIPS_CALL_HI16);
9938                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
9939                                PIC_CALL_REG, mips_gp_register);
9940                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9941                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
9942                                PIC_CALL_REG);
9943                   load_delay_nop ();
9944                   relax_switch ();
9945                   if (gpdelay)
9946                     macro_build (NULL, "nop", "");
9947                 }
9948               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9949                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
9950                            mips_gp_register);
9951               load_delay_nop ();
9952               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9953                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
9954               relax_end ();
9955               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
9956
9957               if (mips_cprestore_offset < 0)
9958                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
9959               else
9960                 {
9961                   if (!mips_frame_reg_valid)
9962                     {
9963                       as_warn (_("No .frame pseudo-op used in PIC code"));
9964                       /* Quiet this warning.  */
9965                       mips_frame_reg_valid = 1;
9966                     }
9967                   if (!mips_cprestore_valid)
9968                     {
9969                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
9970                       /* Quiet this warning.  */
9971                       mips_cprestore_valid = 1;
9972                     }
9973                   if (mips_opts.noreorder)
9974                     macro_build (NULL, "nop", "");
9975                   expr1.X_add_number = mips_cprestore_offset;
9976                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
9977                                                 mips_gp_register,
9978                                                 mips_frame_reg,
9979                                                 HAVE_64BIT_ADDRESSES);
9980                 }
9981             }
9982         }
9983       else if (mips_pic == VXWORKS_PIC)
9984         as_bad (_("Non-PIC jump used in PIC library"));
9985       else
9986         abort ();
9987
9988       break;
9989
9990     case M_LBUE_AB:
9991       s = "lbue";
9992       fmt = "t,+j(b)";
9993       offbits = 9;
9994       goto ld_st;
9995     case M_LHUE_AB:
9996       s = "lhue";
9997       fmt = "t,+j(b)";
9998       offbits = 9;
9999       goto ld_st;
10000     case M_LBE_AB:
10001       s = "lbe";
10002       fmt = "t,+j(b)";
10003       offbits = 9;
10004       goto ld_st;
10005     case M_LHE_AB:
10006       s = "lhe";
10007       fmt = "t,+j(b)";
10008       offbits = 9;
10009       goto ld_st;
10010     case M_LLE_AB:
10011       s = "lle";
10012       fmt = "t,+j(b)";
10013       offbits = 9;
10014       goto ld_st;
10015     case M_LWE_AB:
10016       s = "lwe";
10017       fmt = "t,+j(b)";
10018       offbits = 9;
10019       goto ld_st;
10020     case M_LWLE_AB:
10021       s = "lwle";
10022       fmt = "t,+j(b)";
10023       offbits = 9;
10024       goto ld_st;
10025     case M_LWRE_AB:
10026       s = "lwre";
10027       fmt = "t,+j(b)";
10028       offbits = 9;
10029       goto ld_st;
10030     case M_SBE_AB:
10031       s = "sbe";
10032       fmt = "t,+j(b)";
10033       offbits = 9;
10034       goto ld_st;
10035     case M_SCE_AB:
10036       s = "sce";
10037       fmt = "t,+j(b)";
10038       offbits = 9;
10039       goto ld_st;
10040     case M_SHE_AB:
10041       s = "she";
10042       fmt = "t,+j(b)";
10043       offbits = 9;
10044       goto ld_st;
10045     case M_SWE_AB:
10046       s = "swe";
10047       fmt = "t,+j(b)";
10048       offbits = 9;
10049       goto ld_st;
10050     case M_SWLE_AB:
10051       s = "swle";
10052       fmt = "t,+j(b)";
10053       offbits = 9;
10054       goto ld_st;
10055     case M_SWRE_AB:
10056       s = "swre";
10057       fmt = "t,+j(b)";
10058       offbits = 9;
10059       goto ld_st;
10060     case M_ACLR_AB:
10061       s = "aclr";
10062       fmt = "\\,~(b)";
10063       offbits = 12;
10064       goto ld_st;
10065     case M_ASET_AB:
10066       s = "aset";
10067       fmt = "\\,~(b)";
10068       offbits = 12;
10069       goto ld_st;
10070     case M_LB_AB:
10071       s = "lb";
10072       fmt = "t,o(b)";
10073       goto ld;
10074     case M_LBU_AB:
10075       s = "lbu";
10076       fmt = "t,o(b)";
10077       goto ld;
10078     case M_LH_AB:
10079       s = "lh";
10080       fmt = "t,o(b)";
10081       goto ld;
10082     case M_LHU_AB:
10083       s = "lhu";
10084       fmt = "t,o(b)";
10085       goto ld;
10086     case M_LW_AB:
10087       s = "lw";
10088       fmt = "t,o(b)";
10089       goto ld;
10090     case M_LWC0_AB:
10091       gas_assert (!mips_opts.micromips);
10092       s = "lwc0";
10093       fmt = "E,o(b)";
10094       /* Itbl support may require additional care here.  */
10095       coproc = 1;
10096       goto ld_st;
10097     case M_LWC1_AB:
10098       s = "lwc1";
10099       fmt = "T,o(b)";
10100       /* Itbl support may require additional care here.  */
10101       coproc = 1;
10102       goto ld_st;
10103     case M_LWC2_AB:
10104       s = "lwc2";
10105       fmt = COP12_FMT;
10106       offbits = (mips_opts.micromips ? 12 : 16);
10107       /* Itbl support may require additional care here.  */
10108       coproc = 1;
10109       goto ld_st;
10110     case M_LWC3_AB:
10111       gas_assert (!mips_opts.micromips);
10112       s = "lwc3";
10113       fmt = "E,o(b)";
10114       /* Itbl support may require additional care here.  */
10115       coproc = 1;
10116       goto ld_st;
10117     case M_LWL_AB:
10118       s = "lwl";
10119       fmt = MEM12_FMT;
10120       offbits = (mips_opts.micromips ? 12 : 16);
10121       goto ld_st;
10122     case M_LWR_AB:
10123       s = "lwr";
10124       fmt = MEM12_FMT;
10125       offbits = (mips_opts.micromips ? 12 : 16);
10126       goto ld_st;
10127     case M_LDC1_AB:
10128       s = "ldc1";
10129       fmt = "T,o(b)";
10130       /* Itbl support may require additional care here.  */
10131       coproc = 1;
10132       goto ld_st;
10133     case M_LDC2_AB:
10134       s = "ldc2";
10135       fmt = COP12_FMT;
10136       offbits = (mips_opts.micromips ? 12 : 16);
10137       /* Itbl support may require additional care here.  */
10138       coproc = 1;
10139       goto ld_st;
10140     case M_LQC2_AB:
10141       s = "lqc2";
10142       fmt = "+7,o(b)";
10143       /* Itbl support may require additional care here.  */
10144       coproc = 1;
10145       goto ld_st;
10146     case M_LDC3_AB:
10147       s = "ldc3";
10148       fmt = "E,o(b)";
10149       /* Itbl support may require additional care here.  */
10150       coproc = 1;
10151       goto ld_st;
10152     case M_LDL_AB:
10153       s = "ldl";
10154       fmt = MEM12_FMT;
10155       offbits = (mips_opts.micromips ? 12 : 16);
10156       goto ld_st;
10157     case M_LDR_AB:
10158       s = "ldr";
10159       fmt = MEM12_FMT;
10160       offbits = (mips_opts.micromips ? 12 : 16);
10161       goto ld_st;
10162     case M_LL_AB:
10163       s = "ll";
10164       fmt = MEM12_FMT;
10165       offbits = (mips_opts.micromips ? 12 : 16);
10166       goto ld;
10167     case M_LLD_AB:
10168       s = "lld";
10169       fmt = MEM12_FMT;
10170       offbits = (mips_opts.micromips ? 12 : 16);
10171       goto ld;
10172     case M_LWU_AB:
10173       s = "lwu";
10174       fmt = MEM12_FMT;
10175       offbits = (mips_opts.micromips ? 12 : 16);
10176       goto ld;
10177     case M_LWP_AB:
10178       gas_assert (mips_opts.micromips);
10179       s = "lwp";
10180       fmt = "t,~(b)";
10181       offbits = 12;
10182       lp = 1;
10183       goto ld;
10184     case M_LDP_AB:
10185       gas_assert (mips_opts.micromips);
10186       s = "ldp";
10187       fmt = "t,~(b)";
10188       offbits = 12;
10189       lp = 1;
10190       goto ld;
10191     case M_LWM_AB:
10192       gas_assert (mips_opts.micromips);
10193       s = "lwm";
10194       fmt = "n,~(b)";
10195       offbits = 12;
10196       goto ld_st;
10197     case M_LDM_AB:
10198       gas_assert (mips_opts.micromips);
10199       s = "ldm";
10200       fmt = "n,~(b)";
10201       offbits = 12;
10202       goto ld_st;
10203
10204     ld:
10205       /* We don't want to use $0 as tempreg.  */
10206       if (op[2] == op[0] + lp || op[0] + lp == ZERO)
10207         goto ld_st;
10208       else
10209         tempreg = op[0] + lp;
10210       goto ld_noat;
10211
10212     case M_SB_AB:
10213       s = "sb";
10214       fmt = "t,o(b)";
10215       goto ld_st;
10216     case M_SH_AB:
10217       s = "sh";
10218       fmt = "t,o(b)";
10219       goto ld_st;
10220     case M_SW_AB:
10221       s = "sw";
10222       fmt = "t,o(b)";
10223       goto ld_st;
10224     case M_SWC0_AB:
10225       gas_assert (!mips_opts.micromips);
10226       s = "swc0";
10227       fmt = "E,o(b)";
10228       /* Itbl support may require additional care here.  */
10229       coproc = 1;
10230       goto ld_st;
10231     case M_SWC1_AB:
10232       s = "swc1";
10233       fmt = "T,o(b)";
10234       /* Itbl support may require additional care here.  */
10235       coproc = 1;
10236       goto ld_st;
10237     case M_SWC2_AB:
10238       s = "swc2";
10239       fmt = COP12_FMT;
10240       offbits = (mips_opts.micromips ? 12 : 16);
10241       /* Itbl support may require additional care here.  */
10242       coproc = 1;
10243       goto ld_st;
10244     case M_SWC3_AB:
10245       gas_assert (!mips_opts.micromips);
10246       s = "swc3";
10247       fmt = "E,o(b)";
10248       /* Itbl support may require additional care here.  */
10249       coproc = 1;
10250       goto ld_st;
10251     case M_SWL_AB:
10252       s = "swl";
10253       fmt = MEM12_FMT;
10254       offbits = (mips_opts.micromips ? 12 : 16);
10255       goto ld_st;
10256     case M_SWR_AB:
10257       s = "swr";
10258       fmt = MEM12_FMT;
10259       offbits = (mips_opts.micromips ? 12 : 16);
10260       goto ld_st;
10261     case M_SC_AB:
10262       s = "sc";
10263       fmt = MEM12_FMT;
10264       offbits = (mips_opts.micromips ? 12 : 16);
10265       goto ld_st;
10266     case M_SCD_AB:
10267       s = "scd";
10268       fmt = MEM12_FMT;
10269       offbits = (mips_opts.micromips ? 12 : 16);
10270       goto ld_st;
10271     case M_CACHE_AB:
10272       s = "cache";
10273       fmt = mips_opts.micromips ? "k,~(b)" : "k,o(b)";
10274       offbits = (mips_opts.micromips ? 12 : 16);
10275       goto ld_st;
10276     case M_CACHEE_AB:
10277       s = "cachee";
10278       fmt = "k,+j(b)";
10279       offbits = 9;
10280       goto ld_st;
10281     case M_PREF_AB:
10282       s = "pref";
10283       fmt = !mips_opts.micromips ? "k,o(b)" : "k,~(b)";
10284       offbits = (mips_opts.micromips ? 12 : 16);
10285       goto ld_st;
10286     case M_PREFE_AB:
10287       s = "prefe";
10288       fmt = "k,+j(b)";
10289       offbits = 9;
10290       goto ld_st;
10291     case M_SDC1_AB:
10292       s = "sdc1";
10293       fmt = "T,o(b)";
10294       coproc = 1;
10295       /* Itbl support may require additional care here.  */
10296       goto ld_st;
10297     case M_SDC2_AB:
10298       s = "sdc2";
10299       fmt = COP12_FMT;
10300       offbits = (mips_opts.micromips ? 12 : 16);
10301       /* Itbl support may require additional care here.  */
10302       coproc = 1;
10303       goto ld_st;
10304     case M_SQC2_AB:
10305       s = "sqc2";
10306       fmt = "+7,o(b)";
10307       /* Itbl support may require additional care here.  */
10308       coproc = 1;
10309       goto ld_st;
10310     case M_SDC3_AB:
10311       gas_assert (!mips_opts.micromips);
10312       s = "sdc3";
10313       fmt = "E,o(b)";
10314       /* Itbl support may require additional care here.  */
10315       coproc = 1;
10316       goto ld_st;
10317     case M_SDL_AB:
10318       s = "sdl";
10319       fmt = MEM12_FMT;
10320       offbits = (mips_opts.micromips ? 12 : 16);
10321       goto ld_st;
10322     case M_SDR_AB:
10323       s = "sdr";
10324       fmt = MEM12_FMT;
10325       offbits = (mips_opts.micromips ? 12 : 16);
10326       goto ld_st;
10327     case M_SWP_AB:
10328       gas_assert (mips_opts.micromips);
10329       s = "swp";
10330       fmt = "t,~(b)";
10331       offbits = 12;
10332       goto ld_st;
10333     case M_SDP_AB:
10334       gas_assert (mips_opts.micromips);
10335       s = "sdp";
10336       fmt = "t,~(b)";
10337       offbits = 12;
10338       goto ld_st;
10339     case M_SWM_AB:
10340       gas_assert (mips_opts.micromips);
10341       s = "swm";
10342       fmt = "n,~(b)";
10343       offbits = 12;
10344       goto ld_st;
10345     case M_SDM_AB:
10346       gas_assert (mips_opts.micromips);
10347       s = "sdm";
10348       fmt = "n,~(b)";
10349       offbits = 12;
10350
10351     ld_st:
10352       tempreg = AT;
10353     ld_noat:
10354       breg = op[2];
10355       if (small_offset_p (0, align, 16))
10356         {
10357           /* The first case exists for M_LD_AB and M_SD_AB, which are
10358              macros for o32 but which should act like normal instructions
10359              otherwise.  */
10360           if (offbits == 16)
10361             macro_build (&offset_expr, s, fmt, op[0], -1, offset_reloc[0],
10362                          offset_reloc[1], offset_reloc[2], breg);
10363           else if (small_offset_p (0, align, offbits))
10364             {
10365               if (offbits == 0)
10366                 macro_build (NULL, s, fmt, op[0], breg);
10367               else
10368                 macro_build (NULL, s, fmt, op[0],
10369                              (int) offset_expr.X_add_number, breg);
10370             }
10371           else
10372             {
10373               if (tempreg == AT)
10374                 used_at = 1;
10375               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10376                            tempreg, breg, -1, offset_reloc[0],
10377                            offset_reloc[1], offset_reloc[2]);
10378               if (offbits == 0)
10379                 macro_build (NULL, s, fmt, op[0], tempreg);
10380               else
10381                 macro_build (NULL, s, fmt, op[0], 0, tempreg);
10382             }
10383           break;
10384         }
10385
10386       if (tempreg == AT)
10387         used_at = 1;
10388
10389       if (offset_expr.X_op != O_constant
10390           && offset_expr.X_op != O_symbol)
10391         {
10392           as_bad (_("Expression too complex"));
10393           offset_expr.X_op = O_constant;
10394         }
10395
10396       if (HAVE_32BIT_ADDRESSES
10397           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
10398         {
10399           char value [32];
10400
10401           sprintf_vma (value, offset_expr.X_add_number);
10402           as_bad (_("Number (0x%s) larger than 32 bits"), value);
10403         }
10404
10405       /* A constant expression in PIC code can be handled just as it
10406          is in non PIC code.  */
10407       if (offset_expr.X_op == O_constant)
10408         {
10409           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
10410                                                  offbits == 0 ? 16 : offbits);
10411           offset_expr.X_add_number -= expr1.X_add_number;
10412
10413           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
10414           if (breg != 0)
10415             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10416                          tempreg, tempreg, breg);
10417           if (offbits == 0)
10418             {
10419               if (offset_expr.X_add_number != 0)
10420                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
10421                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
10422               macro_build (NULL, s, fmt, op[0], tempreg);
10423             }
10424           else if (offbits == 16)
10425             macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
10426           else
10427             macro_build (NULL, s, fmt, op[0],
10428                          (int) offset_expr.X_add_number, tempreg);
10429         }
10430       else if (offbits != 16)
10431         {
10432           /* The offset field is too narrow to be used for a low-part
10433              relocation, so load the whole address into the auxillary
10434              register.  */
10435           load_address (tempreg, &offset_expr, &used_at);
10436           if (breg != 0)
10437             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10438                          tempreg, tempreg, breg);
10439           if (offbits == 0)
10440             macro_build (NULL, s, fmt, op[0], tempreg);
10441           else
10442             macro_build (NULL, s, fmt, op[0], 0, tempreg);
10443         }
10444       else if (mips_pic == NO_PIC)
10445         {
10446           /* If this is a reference to a GP relative symbol, and there
10447              is no base register, we want
10448                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
10449              Otherwise, if there is no base register, we want
10450                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
10451                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
10452              If we have a constant, we need two instructions anyhow,
10453              so we always use the latter form.
10454
10455              If we have a base register, and this is a reference to a
10456              GP relative symbol, we want
10457                addu     $tempreg,$breg,$gp
10458                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_GPREL16)
10459              Otherwise we want
10460                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
10461                addu     $tempreg,$tempreg,$breg
10462                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
10463              With a constant we always use the latter case.
10464
10465              With 64bit address space and no base register and $at usable,
10466              we want
10467                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
10468                lui      $at,<sym>               (BFD_RELOC_HI16_S)
10469                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
10470                dsll32   $tempreg,0
10471                daddu    $tempreg,$at
10472                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
10473              If we have a base register, we want
10474                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
10475                lui      $at,<sym>               (BFD_RELOC_HI16_S)
10476                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
10477                daddu    $at,$breg
10478                dsll32   $tempreg,0
10479                daddu    $tempreg,$at
10480                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
10481
10482              Without $at we can't generate the optimal path for superscalar
10483              processors here since this would require two temporary registers.
10484                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
10485                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
10486                dsll     $tempreg,16
10487                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
10488                dsll     $tempreg,16
10489                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
10490              If we have a base register, we want
10491                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
10492                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
10493                dsll     $tempreg,16
10494                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
10495                dsll     $tempreg,16
10496                daddu    $tempreg,$tempreg,$breg
10497                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
10498
10499              For GP relative symbols in 64bit address space we can use
10500              the same sequence as in 32bit address space.  */
10501           if (HAVE_64BIT_SYMBOLS)
10502             {
10503               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10504                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10505                 {
10506                   relax_start (offset_expr.X_add_symbol);
10507                   if (breg == 0)
10508                     {
10509                       macro_build (&offset_expr, s, fmt, op[0],
10510                                    BFD_RELOC_GPREL16, mips_gp_register);
10511                     }
10512                   else
10513                     {
10514                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10515                                    tempreg, breg, mips_gp_register);
10516                       macro_build (&offset_expr, s, fmt, op[0],
10517                                    BFD_RELOC_GPREL16, tempreg);
10518                     }
10519                   relax_switch ();
10520                 }
10521
10522               if (used_at == 0 && mips_opts.at)
10523                 {
10524                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
10525                                BFD_RELOC_MIPS_HIGHEST);
10526                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
10527                                BFD_RELOC_HI16_S);
10528                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
10529                                tempreg, BFD_RELOC_MIPS_HIGHER);
10530                   if (breg != 0)
10531                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
10532                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
10533                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
10534                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16,
10535                                tempreg);
10536                   used_at = 1;
10537                 }
10538               else
10539                 {
10540                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
10541                                BFD_RELOC_MIPS_HIGHEST);
10542                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
10543                                tempreg, BFD_RELOC_MIPS_HIGHER);
10544                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
10545                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
10546                                tempreg, BFD_RELOC_HI16_S);
10547                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
10548                   if (breg != 0)
10549                     macro_build (NULL, "daddu", "d,v,t",
10550                                  tempreg, tempreg, breg);
10551                   macro_build (&offset_expr, s, fmt, op[0],
10552                                BFD_RELOC_LO16, tempreg);
10553                 }
10554
10555               if (mips_relax.sequence)
10556                 relax_end ();
10557               break;
10558             }
10559
10560           if (breg == 0)
10561             {
10562               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10563                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10564                 {
10565                   relax_start (offset_expr.X_add_symbol);
10566                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_GPREL16,
10567                                mips_gp_register);
10568                   relax_switch ();
10569                 }
10570               macro_build_lui (&offset_expr, tempreg);
10571               macro_build (&offset_expr, s, fmt, op[0],
10572                            BFD_RELOC_LO16, tempreg);
10573               if (mips_relax.sequence)
10574                 relax_end ();
10575             }
10576           else
10577             {
10578               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10579                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10580                 {
10581                   relax_start (offset_expr.X_add_symbol);
10582                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10583                                tempreg, breg, mips_gp_register);
10584                   macro_build (&offset_expr, s, fmt, op[0],
10585                                BFD_RELOC_GPREL16, tempreg);
10586                   relax_switch ();
10587                 }
10588               macro_build_lui (&offset_expr, tempreg);
10589               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10590                            tempreg, tempreg, breg);
10591               macro_build (&offset_expr, s, fmt, op[0],
10592                            BFD_RELOC_LO16, tempreg);
10593               if (mips_relax.sequence)
10594                 relax_end ();
10595             }
10596         }
10597       else if (!mips_big_got)
10598         {
10599           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10600
10601           /* If this is a reference to an external symbol, we want
10602                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10603                nop
10604                <op>     op[0],0($tempreg)
10605              Otherwise we want
10606                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10607                nop
10608                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10609                <op>     op[0],0($tempreg)
10610
10611              For NewABI, we want
10612                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
10613                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
10614
10615              If there is a base register, we add it to $tempreg before
10616              the <op>.  If there is a constant, we stick it in the
10617              <op> instruction.  We don't handle constants larger than
10618              16 bits, because we have no way to load the upper 16 bits
10619              (actually, we could handle them for the subset of cases
10620              in which we are not using $at).  */
10621           gas_assert (offset_expr.X_op == O_symbol);
10622           if (HAVE_NEWABI)
10623             {
10624               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10625                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
10626               if (breg != 0)
10627                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10628                              tempreg, tempreg, breg);
10629               macro_build (&offset_expr, s, fmt, op[0],
10630                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
10631               break;
10632             }
10633           expr1.X_add_number = offset_expr.X_add_number;
10634           offset_expr.X_add_number = 0;
10635           if (expr1.X_add_number < -0x8000
10636               || expr1.X_add_number >= 0x8000)
10637             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
10638           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10639                        lw_reloc_type, mips_gp_register);
10640           load_delay_nop ();
10641           relax_start (offset_expr.X_add_symbol);
10642           relax_switch ();
10643           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
10644                        tempreg, BFD_RELOC_LO16);
10645           relax_end ();
10646           if (breg != 0)
10647             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10648                          tempreg, tempreg, breg);
10649           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
10650         }
10651       else if (mips_big_got && !HAVE_NEWABI)
10652         {
10653           int gpdelay;
10654
10655           /* If this is a reference to an external symbol, we want
10656                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10657                addu     $tempreg,$tempreg,$gp
10658                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10659                <op>     op[0],0($tempreg)
10660              Otherwise we want
10661                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10662                nop
10663                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10664                <op>     op[0],0($tempreg)
10665              If there is a base register, we add it to $tempreg before
10666              the <op>.  If there is a constant, we stick it in the
10667              <op> instruction.  We don't handle constants larger than
10668              16 bits, because we have no way to load the upper 16 bits
10669              (actually, we could handle them for the subset of cases
10670              in which we are not using $at).  */
10671           gas_assert (offset_expr.X_op == O_symbol);
10672           expr1.X_add_number = offset_expr.X_add_number;
10673           offset_expr.X_add_number = 0;
10674           if (expr1.X_add_number < -0x8000
10675               || expr1.X_add_number >= 0x8000)
10676             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
10677           gpdelay = reg_needs_delay (mips_gp_register);
10678           relax_start (offset_expr.X_add_symbol);
10679           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
10680                        BFD_RELOC_MIPS_GOT_HI16);
10681           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
10682                        mips_gp_register);
10683           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10684                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
10685           relax_switch ();
10686           if (gpdelay)
10687             macro_build (NULL, "nop", "");
10688           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10689                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
10690           load_delay_nop ();
10691           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
10692                        tempreg, BFD_RELOC_LO16);
10693           relax_end ();
10694
10695           if (breg != 0)
10696             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10697                          tempreg, tempreg, breg);
10698           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
10699         }
10700       else if (mips_big_got && HAVE_NEWABI)
10701         {
10702           /* If this is a reference to an external symbol, we want
10703                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10704                add      $tempreg,$tempreg,$gp
10705                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10706                <op>     op[0],<ofst>($tempreg)
10707              Otherwise, for local symbols, we want:
10708                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
10709                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
10710           gas_assert (offset_expr.X_op == O_symbol);
10711           expr1.X_add_number = offset_expr.X_add_number;
10712           offset_expr.X_add_number = 0;
10713           if (expr1.X_add_number < -0x8000
10714               || expr1.X_add_number >= 0x8000)
10715             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
10716           relax_start (offset_expr.X_add_symbol);
10717           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
10718                        BFD_RELOC_MIPS_GOT_HI16);
10719           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
10720                        mips_gp_register);
10721           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10722                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
10723           if (breg != 0)
10724             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10725                          tempreg, tempreg, breg);
10726           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
10727
10728           relax_switch ();
10729           offset_expr.X_add_number = expr1.X_add_number;
10730           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10731                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
10732           if (breg != 0)
10733             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10734                          tempreg, tempreg, breg);
10735           macro_build (&offset_expr, s, fmt, op[0],
10736                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
10737           relax_end ();
10738         }
10739       else
10740         abort ();
10741
10742       break;
10743
10744     case M_JRADDIUSP:
10745       gas_assert (mips_opts.micromips);
10746       gas_assert (mips_opts.insn32);
10747       start_noreorder ();
10748       macro_build (NULL, "jr", "s", RA);
10749       expr1.X_add_number = op[0] << 2;
10750       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
10751       end_noreorder ();
10752       break;
10753
10754     case M_JRC:
10755       gas_assert (mips_opts.micromips);
10756       gas_assert (mips_opts.insn32);
10757       macro_build (NULL, "jr", "s", op[0]);
10758       if (mips_opts.noreorder)
10759         macro_build (NULL, "nop", "");
10760       break;
10761
10762     case M_LI:
10763     case M_LI_S:
10764       load_register (op[0], &imm_expr, 0);
10765       break;
10766
10767     case M_DLI:
10768       load_register (op[0], &imm_expr, 1);
10769       break;
10770
10771     case M_LI_SS:
10772       if (imm_expr.X_op == O_constant)
10773         {
10774           used_at = 1;
10775           load_register (AT, &imm_expr, 0);
10776           macro_build (NULL, "mtc1", "t,G", AT, op[0]);
10777           break;
10778         }
10779       else
10780         {
10781           gas_assert (offset_expr.X_op == O_symbol
10782                       && strcmp (segment_name (S_GET_SEGMENT
10783                                                (offset_expr.X_add_symbol)),
10784                                  ".lit4") == 0
10785                       && offset_expr.X_add_number == 0);
10786           macro_build (&offset_expr, "lwc1", "T,o(b)", op[0],
10787                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
10788           break;
10789         }
10790
10791     case M_LI_D:
10792       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
10793          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
10794          order 32 bits of the value and the low order 32 bits are either
10795          zero or in OFFSET_EXPR.  */
10796       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
10797         {
10798           if (HAVE_64BIT_GPRS)
10799             load_register (op[0], &imm_expr, 1);
10800           else
10801             {
10802               int hreg, lreg;
10803
10804               if (target_big_endian)
10805                 {
10806                   hreg = op[0];
10807                   lreg = op[0] + 1;
10808                 }
10809               else
10810                 {
10811                   hreg = op[0] + 1;
10812                   lreg = op[0];
10813                 }
10814
10815               if (hreg <= 31)
10816                 load_register (hreg, &imm_expr, 0);
10817               if (lreg <= 31)
10818                 {
10819                   if (offset_expr.X_op == O_absent)
10820                     move_register (lreg, 0);
10821                   else
10822                     {
10823                       gas_assert (offset_expr.X_op == O_constant);
10824                       load_register (lreg, &offset_expr, 0);
10825                     }
10826                 }
10827             }
10828           break;
10829         }
10830
10831       /* We know that sym is in the .rdata section.  First we get the
10832          upper 16 bits of the address.  */
10833       if (mips_pic == NO_PIC)
10834         {
10835           macro_build_lui (&offset_expr, AT);
10836           used_at = 1;
10837         }
10838       else
10839         {
10840           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
10841                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
10842           used_at = 1;
10843         }
10844
10845       /* Now we load the register(s).  */
10846       if (HAVE_64BIT_GPRS)
10847         {
10848           used_at = 1;
10849           macro_build (&offset_expr, "ld", "t,o(b)", op[0],
10850                        BFD_RELOC_LO16, AT);
10851         }
10852       else
10853         {
10854           used_at = 1;
10855           macro_build (&offset_expr, "lw", "t,o(b)", op[0],
10856                        BFD_RELOC_LO16, AT);
10857           if (op[0] != RA)
10858             {
10859               /* FIXME: How in the world do we deal with the possible
10860                  overflow here?  */
10861               offset_expr.X_add_number += 4;
10862               macro_build (&offset_expr, "lw", "t,o(b)",
10863                            op[0] + 1, BFD_RELOC_LO16, AT);
10864             }
10865         }
10866       break;
10867
10868     case M_LI_DD:
10869       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
10870          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
10871          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
10872          the value and the low order 32 bits are either zero or in
10873          OFFSET_EXPR.  */
10874       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
10875         {
10876           used_at = 1;
10877           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
10878           if (HAVE_64BIT_FPRS)
10879             {
10880               gas_assert (HAVE_64BIT_GPRS);
10881               macro_build (NULL, "dmtc1", "t,S", AT, op[0]);
10882             }
10883           else
10884             {
10885               macro_build (NULL, "mtc1", "t,G", AT, op[0] + 1);
10886               if (offset_expr.X_op == O_absent)
10887                 macro_build (NULL, "mtc1", "t,G", 0, op[0]);
10888               else
10889                 {
10890                   gas_assert (offset_expr.X_op == O_constant);
10891                   load_register (AT, &offset_expr, 0);
10892                   macro_build (NULL, "mtc1", "t,G", AT, op[0]);
10893                 }
10894             }
10895           break;
10896         }
10897
10898       gas_assert (offset_expr.X_op == O_symbol
10899                   && offset_expr.X_add_number == 0);
10900       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
10901       if (strcmp (s, ".lit8") == 0)
10902         {
10903           op[2] = mips_gp_register;
10904           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
10905           offset_reloc[1] = BFD_RELOC_UNUSED;
10906           offset_reloc[2] = BFD_RELOC_UNUSED;
10907         }
10908       else
10909         {
10910           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
10911           used_at = 1;
10912           if (mips_pic != NO_PIC)
10913             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
10914                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
10915           else
10916             {
10917               /* FIXME: This won't work for a 64 bit address.  */
10918               macro_build_lui (&offset_expr, AT);
10919             }
10920
10921           op[2] = AT;
10922           offset_reloc[0] = BFD_RELOC_LO16;
10923           offset_reloc[1] = BFD_RELOC_UNUSED;
10924           offset_reloc[2] = BFD_RELOC_UNUSED;
10925         }
10926       align = 8;
10927       /* Fall through */
10928
10929     case M_L_DAB:
10930       /*
10931        * The MIPS assembler seems to check for X_add_number not
10932        * being double aligned and generating:
10933        *        lui     at,%hi(foo+1)
10934        *        addu    at,at,v1
10935        *        addiu   at,at,%lo(foo+1)
10936        *        lwc1    f2,0(at)
10937        *        lwc1    f3,4(at)
10938        * But, the resulting address is the same after relocation so why
10939        * generate the extra instruction?
10940        */
10941       /* Itbl support may require additional care here.  */
10942       coproc = 1;
10943       fmt = "T,o(b)";
10944       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
10945         {
10946           s = "ldc1";
10947           goto ld_st;
10948         }
10949       s = "lwc1";
10950       goto ldd_std;
10951
10952     case M_S_DAB:
10953       gas_assert (!mips_opts.micromips);
10954       /* Itbl support may require additional care here.  */
10955       coproc = 1;
10956       fmt = "T,o(b)";
10957       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
10958         {
10959           s = "sdc1";
10960           goto ld_st;
10961         }
10962       s = "swc1";
10963       goto ldd_std;
10964
10965     case M_LQ_AB:
10966       fmt = "t,o(b)";
10967       s = "lq";
10968       goto ld;
10969
10970     case M_SQ_AB:
10971       fmt = "t,o(b)";
10972       s = "sq";
10973       goto ld_st;
10974
10975     case M_LD_AB:
10976       fmt = "t,o(b)";
10977       if (HAVE_64BIT_GPRS)
10978         {
10979           s = "ld";
10980           goto ld;
10981         }
10982       s = "lw";
10983       goto ldd_std;
10984
10985     case M_SD_AB:
10986       fmt = "t,o(b)";
10987       if (HAVE_64BIT_GPRS)
10988         {
10989           s = "sd";
10990           goto ld_st;
10991         }
10992       s = "sw";
10993
10994     ldd_std:
10995       /* Even on a big endian machine $fn comes before $fn+1.  We have
10996          to adjust when loading from memory.  We set coproc if we must
10997          load $fn+1 first.  */
10998       /* Itbl support may require additional care here.  */
10999       if (!target_big_endian)
11000         coproc = 0;
11001
11002       breg = op[2];
11003       if (small_offset_p (0, align, 16))
11004         {
11005           ep = &offset_expr;
11006           if (!small_offset_p (4, align, 16))
11007             {
11008               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
11009                            -1, offset_reloc[0], offset_reloc[1],
11010                            offset_reloc[2]);
11011               expr1.X_add_number = 0;
11012               ep = &expr1;
11013               breg = AT;
11014               used_at = 1;
11015               offset_reloc[0] = BFD_RELOC_LO16;
11016               offset_reloc[1] = BFD_RELOC_UNUSED;
11017               offset_reloc[2] = BFD_RELOC_UNUSED;
11018             }
11019           if (strcmp (s, "lw") == 0 && op[0] == breg)
11020             {
11021               ep->X_add_number += 4;
11022               macro_build (ep, s, fmt, op[0] + 1, -1, offset_reloc[0],
11023                            offset_reloc[1], offset_reloc[2], breg);
11024               ep->X_add_number -= 4;
11025               macro_build (ep, s, fmt, op[0], -1, offset_reloc[0],
11026                            offset_reloc[1], offset_reloc[2], breg);
11027             }
11028           else
11029             {
11030               macro_build (ep, s, fmt, coproc ? op[0] + 1 : op[0], -1,
11031                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
11032                            breg);
11033               ep->X_add_number += 4;
11034               macro_build (ep, s, fmt, coproc ? op[0] : op[0] + 1, -1,
11035                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
11036                            breg);
11037             }
11038           break;
11039         }
11040
11041       if (offset_expr.X_op != O_symbol
11042           && offset_expr.X_op != O_constant)
11043         {
11044           as_bad (_("Expression too complex"));
11045           offset_expr.X_op = O_constant;
11046         }
11047
11048       if (HAVE_32BIT_ADDRESSES
11049           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
11050         {
11051           char value [32];
11052
11053           sprintf_vma (value, offset_expr.X_add_number);
11054           as_bad (_("Number (0x%s) larger than 32 bits"), value);
11055         }
11056
11057       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
11058         {
11059           /* If this is a reference to a GP relative symbol, we want
11060                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
11061                <op>     op[0]+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
11062              If we have a base register, we use this
11063                addu     $at,$breg,$gp
11064                <op>     op[0],<sym>($at)        (BFD_RELOC_GPREL16)
11065                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
11066              If this is not a GP relative symbol, we want
11067                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11068                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11069                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11070              If there is a base register, we add it to $at after the
11071              lui instruction.  If there is a constant, we always use
11072              the last case.  */
11073           if (offset_expr.X_op == O_symbol
11074               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11075               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11076             {
11077               relax_start (offset_expr.X_add_symbol);
11078               if (breg == 0)
11079                 {
11080                   tempreg = mips_gp_register;
11081                 }
11082               else
11083                 {
11084                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11085                                AT, breg, mips_gp_register);
11086                   tempreg = AT;
11087                   used_at = 1;
11088                 }
11089
11090               /* Itbl support may require additional care here.  */
11091               macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11092                            BFD_RELOC_GPREL16, tempreg);
11093               offset_expr.X_add_number += 4;
11094
11095               /* Set mips_optimize to 2 to avoid inserting an
11096                  undesired nop.  */
11097               hold_mips_optimize = mips_optimize;
11098               mips_optimize = 2;
11099               /* Itbl support may require additional care here.  */
11100               macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11101                            BFD_RELOC_GPREL16, tempreg);
11102               mips_optimize = hold_mips_optimize;
11103
11104               relax_switch ();
11105
11106               offset_expr.X_add_number -= 4;
11107             }
11108           used_at = 1;
11109           if (offset_high_part (offset_expr.X_add_number, 16)
11110               != offset_high_part (offset_expr.X_add_number + 4, 16))
11111             {
11112               load_address (AT, &offset_expr, &used_at);
11113               offset_expr.X_op = O_constant;
11114               offset_expr.X_add_number = 0;
11115             }
11116           else
11117             macro_build_lui (&offset_expr, AT);
11118           if (breg != 0)
11119             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11120           /* Itbl support may require additional care here.  */
11121           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11122                        BFD_RELOC_LO16, AT);
11123           /* FIXME: How do we handle overflow here?  */
11124           offset_expr.X_add_number += 4;
11125           /* Itbl support may require additional care here.  */
11126           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11127                        BFD_RELOC_LO16, AT);
11128           if (mips_relax.sequence)
11129             relax_end ();
11130         }
11131       else if (!mips_big_got)
11132         {
11133           /* If this is a reference to an external symbol, we want
11134                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11135                nop
11136                <op>     op[0],0($at)
11137                <op>     op[0]+1,4($at)
11138              Otherwise we want
11139                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11140                nop
11141                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11142                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11143              If there is a base register we add it to $at before the
11144              lwc1 instructions.  If there is a constant we include it
11145              in the lwc1 instructions.  */
11146           used_at = 1;
11147           expr1.X_add_number = offset_expr.X_add_number;
11148           if (expr1.X_add_number < -0x8000
11149               || expr1.X_add_number >= 0x8000 - 4)
11150             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11151           load_got_offset (AT, &offset_expr);
11152           load_delay_nop ();
11153           if (breg != 0)
11154             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11155
11156           /* Set mips_optimize to 2 to avoid inserting an undesired
11157              nop.  */
11158           hold_mips_optimize = mips_optimize;
11159           mips_optimize = 2;
11160
11161           /* Itbl support may require additional care here.  */
11162           relax_start (offset_expr.X_add_symbol);
11163           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
11164                        BFD_RELOC_LO16, AT);
11165           expr1.X_add_number += 4;
11166           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
11167                        BFD_RELOC_LO16, AT);
11168           relax_switch ();
11169           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11170                        BFD_RELOC_LO16, AT);
11171           offset_expr.X_add_number += 4;
11172           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11173                        BFD_RELOC_LO16, AT);
11174           relax_end ();
11175
11176           mips_optimize = hold_mips_optimize;
11177         }
11178       else if (mips_big_got)
11179         {
11180           int gpdelay;
11181
11182           /* If this is a reference to an external symbol, we want
11183                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
11184                addu     $at,$at,$gp
11185                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
11186                nop
11187                <op>     op[0],0($at)
11188                <op>     op[0]+1,4($at)
11189              Otherwise we want
11190                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11191                nop
11192                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11193                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11194              If there is a base register we add it to $at before the
11195              lwc1 instructions.  If there is a constant we include it
11196              in the lwc1 instructions.  */
11197           used_at = 1;
11198           expr1.X_add_number = offset_expr.X_add_number;
11199           offset_expr.X_add_number = 0;
11200           if (expr1.X_add_number < -0x8000
11201               || expr1.X_add_number >= 0x8000 - 4)
11202             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11203           gpdelay = reg_needs_delay (mips_gp_register);
11204           relax_start (offset_expr.X_add_symbol);
11205           macro_build (&offset_expr, "lui", LUI_FMT,
11206                        AT, BFD_RELOC_MIPS_GOT_HI16);
11207           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11208                        AT, AT, mips_gp_register);
11209           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11210                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
11211           load_delay_nop ();
11212           if (breg != 0)
11213             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11214           /* Itbl support may require additional care here.  */
11215           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
11216                        BFD_RELOC_LO16, AT);
11217           expr1.X_add_number += 4;
11218
11219           /* Set mips_optimize to 2 to avoid inserting an undesired
11220              nop.  */
11221           hold_mips_optimize = mips_optimize;
11222           mips_optimize = 2;
11223           /* Itbl support may require additional care here.  */
11224           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
11225                        BFD_RELOC_LO16, AT);
11226           mips_optimize = hold_mips_optimize;
11227           expr1.X_add_number -= 4;
11228
11229           relax_switch ();
11230           offset_expr.X_add_number = expr1.X_add_number;
11231           if (gpdelay)
11232             macro_build (NULL, "nop", "");
11233           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11234                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11235           load_delay_nop ();
11236           if (breg != 0)
11237             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11238           /* Itbl support may require additional care here.  */
11239           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11240                        BFD_RELOC_LO16, AT);
11241           offset_expr.X_add_number += 4;
11242
11243           /* Set mips_optimize to 2 to avoid inserting an undesired
11244              nop.  */
11245           hold_mips_optimize = mips_optimize;
11246           mips_optimize = 2;
11247           /* Itbl support may require additional care here.  */
11248           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11249                        BFD_RELOC_LO16, AT);
11250           mips_optimize = hold_mips_optimize;
11251           relax_end ();
11252         }
11253       else
11254         abort ();
11255
11256       break;
11257         
11258     case M_SAA_AB:
11259       s = "saa";
11260       offbits = 0;
11261       fmt = "t,(b)";
11262       goto ld_st;
11263     case M_SAAD_AB:
11264       s = "saad";
11265       offbits = 0;
11266       fmt = "t,(b)";
11267       goto ld_st;
11268
11269    /* New code added to support COPZ instructions.
11270       This code builds table entries out of the macros in mip_opcodes.
11271       R4000 uses interlocks to handle coproc delays.
11272       Other chips (like the R3000) require nops to be inserted for delays.
11273
11274       FIXME: Currently, we require that the user handle delays.
11275       In order to fill delay slots for non-interlocked chips,
11276       we must have a way to specify delays based on the coprocessor.
11277       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
11278       What are the side-effects of the cop instruction?
11279       What cache support might we have and what are its effects?
11280       Both coprocessor & memory require delays. how long???
11281       What registers are read/set/modified?
11282
11283       If an itbl is provided to interpret cop instructions,
11284       this knowledge can be encoded in the itbl spec.  */
11285
11286     case M_COP0:
11287       s = "c0";
11288       goto copz;
11289     case M_COP1:
11290       s = "c1";
11291       goto copz;
11292     case M_COP2:
11293       s = "c2";
11294       goto copz;
11295     case M_COP3:
11296       s = "c3";
11297     copz:
11298       gas_assert (!mips_opts.micromips);
11299       /* For now we just do C (same as Cz).  The parameter will be
11300          stored in insn_opcode by mips_ip.  */
11301       macro_build (NULL, s, "C", (int) ip->insn_opcode);
11302       break;
11303
11304     case M_MOVE:
11305       move_register (op[0], op[1]);
11306       break;
11307
11308     case M_MOVEP:
11309       gas_assert (mips_opts.micromips);
11310       gas_assert (mips_opts.insn32);
11311       move_register (micromips_to_32_reg_h_map1[op[0]],
11312                      micromips_to_32_reg_m_map[op[1]]);
11313       move_register (micromips_to_32_reg_h_map2[op[0]],
11314                      micromips_to_32_reg_n_map[op[2]]);
11315       break;
11316
11317     case M_DMUL:
11318       dbl = 1;
11319     case M_MUL:
11320       if (mips_opts.arch == CPU_R5900)
11321         macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", op[0], op[1],
11322                      op[2]);
11323       else
11324         {
11325           macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", op[1], op[2]);
11326           macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11327         }
11328       break;
11329
11330     case M_DMUL_I:
11331       dbl = 1;
11332     case M_MUL_I:
11333       /* The MIPS assembler some times generates shifts and adds.  I'm
11334          not trying to be that fancy. GCC should do this for us
11335          anyway.  */
11336       used_at = 1;
11337       load_register (AT, &imm_expr, dbl);
11338       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", op[1], AT);
11339       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11340       break;
11341
11342     case M_DMULO_I:
11343       dbl = 1;
11344     case M_MULO_I:
11345       imm = 1;
11346       goto do_mulo;
11347
11348     case M_DMULO:
11349       dbl = 1;
11350     case M_MULO:
11351     do_mulo:
11352       start_noreorder ();
11353       used_at = 1;
11354       if (imm)
11355         load_register (AT, &imm_expr, dbl);
11356       macro_build (NULL, dbl ? "dmult" : "mult", "s,t",
11357                    op[1], imm ? AT : op[2]);
11358       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11359       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, op[0], op[0], 31);
11360       macro_build (NULL, "mfhi", MFHL_FMT, AT);
11361       if (mips_trap)
11362         macro_build (NULL, "tne", TRAP_FMT, op[0], AT, 6);
11363       else
11364         {
11365           if (mips_opts.micromips)
11366             micromips_label_expr (&label_expr);
11367           else
11368             label_expr.X_add_number = 8;
11369           macro_build (&label_expr, "beq", "s,t,p", op[0], AT);
11370           macro_build (NULL, "nop", "");
11371           macro_build (NULL, "break", BRK_FMT, 6);
11372           if (mips_opts.micromips)
11373             micromips_add_label ();
11374         }
11375       end_noreorder ();
11376       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11377       break;
11378
11379     case M_DMULOU_I:
11380       dbl = 1;
11381     case M_MULOU_I:
11382       imm = 1;
11383       goto do_mulou;
11384
11385     case M_DMULOU:
11386       dbl = 1;
11387     case M_MULOU:
11388     do_mulou:
11389       start_noreorder ();
11390       used_at = 1;
11391       if (imm)
11392         load_register (AT, &imm_expr, dbl);
11393       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
11394                    op[1], imm ? AT : op[2]);
11395       macro_build (NULL, "mfhi", MFHL_FMT, AT);
11396       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11397       if (mips_trap)
11398         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
11399       else
11400         {
11401           if (mips_opts.micromips)
11402             micromips_label_expr (&label_expr);
11403           else
11404             label_expr.X_add_number = 8;
11405           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
11406           macro_build (NULL, "nop", "");
11407           macro_build (NULL, "break", BRK_FMT, 6);
11408           if (mips_opts.micromips)
11409             micromips_add_label ();
11410         }
11411       end_noreorder ();
11412       break;
11413
11414     case M_DROL:
11415       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
11416         {
11417           if (op[0] == op[1])
11418             {
11419               tempreg = AT;
11420               used_at = 1;
11421             }
11422           else
11423             tempreg = op[0];
11424           macro_build (NULL, "dnegu", "d,w", tempreg, op[2]);
11425           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], tempreg);
11426           break;
11427         }
11428       used_at = 1;
11429       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
11430       macro_build (NULL, "dsrlv", "d,t,s", AT, op[1], AT);
11431       macro_build (NULL, "dsllv", "d,t,s", op[0], op[1], op[2]);
11432       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
11433       break;
11434
11435     case M_ROL:
11436       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
11437         {
11438           if (op[0] == op[1])
11439             {
11440               tempreg = AT;
11441               used_at = 1;
11442             }
11443           else
11444             tempreg = op[0];
11445           macro_build (NULL, "negu", "d,w", tempreg, op[2]);
11446           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], tempreg);
11447           break;
11448         }
11449       used_at = 1;
11450       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
11451       macro_build (NULL, "srlv", "d,t,s", AT, op[1], AT);
11452       macro_build (NULL, "sllv", "d,t,s", op[0], op[1], op[2]);
11453       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
11454       break;
11455
11456     case M_DROL_I:
11457       {
11458         unsigned int rot;
11459         char *l;
11460         char *rr;
11461
11462         if (imm_expr.X_op != O_constant)
11463           as_bad (_("Improper rotate count"));
11464         rot = imm_expr.X_add_number & 0x3f;
11465         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
11466           {
11467             rot = (64 - rot) & 0x3f;
11468             if (rot >= 32)
11469               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
11470             else
11471               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
11472             break;
11473           }
11474         if (rot == 0)
11475           {
11476             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
11477             break;
11478           }
11479         l = (rot < 0x20) ? "dsll" : "dsll32";
11480         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
11481         rot &= 0x1f;
11482         used_at = 1;
11483         macro_build (NULL, l, SHFT_FMT, AT, op[1], rot);
11484         macro_build (NULL, rr, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
11485         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
11486       }
11487       break;
11488
11489     case M_ROL_I:
11490       {
11491         unsigned int rot;
11492
11493         if (imm_expr.X_op != O_constant)
11494           as_bad (_("Improper rotate count"));
11495         rot = imm_expr.X_add_number & 0x1f;
11496         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
11497           {
11498             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1],
11499                          (32 - rot) & 0x1f);
11500             break;
11501           }
11502         if (rot == 0)
11503           {
11504             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
11505             break;
11506           }
11507         used_at = 1;
11508         macro_build (NULL, "sll", SHFT_FMT, AT, op[1], rot);
11509         macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
11510         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
11511       }
11512       break;
11513
11514     case M_DROR:
11515       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
11516         {
11517           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], op[2]);
11518           break;
11519         }
11520       used_at = 1;
11521       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
11522       macro_build (NULL, "dsllv", "d,t,s", AT, op[1], AT);
11523       macro_build (NULL, "dsrlv", "d,t,s", op[0], op[1], op[2]);
11524       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
11525       break;
11526
11527     case M_ROR:
11528       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
11529         {
11530           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], op[2]);
11531           break;
11532         }
11533       used_at = 1;
11534       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
11535       macro_build (NULL, "sllv", "d,t,s", AT, op[1], AT);
11536       macro_build (NULL, "srlv", "d,t,s", op[0], op[1], op[2]);
11537       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
11538       break;
11539
11540     case M_DROR_I:
11541       {
11542         unsigned int rot;
11543         char *l;
11544         char *rr;
11545
11546         if (imm_expr.X_op != O_constant)
11547           as_bad (_("Improper rotate count"));
11548         rot = imm_expr.X_add_number & 0x3f;
11549         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
11550           {
11551             if (rot >= 32)
11552               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
11553             else
11554               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
11555             break;
11556           }
11557         if (rot == 0)
11558           {
11559             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
11560             break;
11561           }
11562         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
11563         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
11564         rot &= 0x1f;
11565         used_at = 1;
11566         macro_build (NULL, rr, SHFT_FMT, AT, op[1], rot);
11567         macro_build (NULL, l, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
11568         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
11569       }
11570       break;
11571
11572     case M_ROR_I:
11573       {
11574         unsigned int rot;
11575
11576         if (imm_expr.X_op != O_constant)
11577           as_bad (_("Improper rotate count"));
11578         rot = imm_expr.X_add_number & 0x1f;
11579         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
11580           {
11581             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1], rot);
11582             break;
11583           }
11584         if (rot == 0)
11585           {
11586             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
11587             break;
11588           }
11589         used_at = 1;
11590         macro_build (NULL, "srl", SHFT_FMT, AT, op[1], rot);
11591         macro_build (NULL, "sll", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
11592         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
11593       }
11594       break;
11595
11596     case M_SEQ:
11597       if (op[1] == 0)
11598         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[2], BFD_RELOC_LO16);
11599       else if (op[2] == 0)
11600         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
11601       else
11602         {
11603           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
11604           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
11605         }
11606       break;
11607
11608     case M_SEQ_I:
11609       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
11610         {
11611           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
11612           break;
11613         }
11614       if (op[1] == 0)
11615         {
11616           as_warn (_("Instruction %s: result is always false"),
11617                    ip->insn_mo->name);
11618           move_register (op[0], 0);
11619           break;
11620         }
11621       if (CPU_HAS_SEQ (mips_opts.arch)
11622           && -512 <= imm_expr.X_add_number
11623           && imm_expr.X_add_number < 512)
11624         {
11625           macro_build (NULL, "seqi", "t,r,+Q", op[0], op[1],
11626                        (int) imm_expr.X_add_number);
11627           break;
11628         }
11629       if (imm_expr.X_op == O_constant
11630           && imm_expr.X_add_number >= 0
11631           && imm_expr.X_add_number < 0x10000)
11632         macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1], BFD_RELOC_LO16);
11633       else if (imm_expr.X_op == O_constant
11634                && imm_expr.X_add_number > -0x8000
11635                && imm_expr.X_add_number < 0)
11636         {
11637           imm_expr.X_add_number = -imm_expr.X_add_number;
11638           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
11639                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
11640         }
11641       else if (CPU_HAS_SEQ (mips_opts.arch))
11642         {
11643           used_at = 1;
11644           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11645           macro_build (NULL, "seq", "d,v,t", op[0], op[1], AT);
11646           break;
11647         }
11648       else
11649         {
11650           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11651           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
11652           used_at = 1;
11653         }
11654       macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
11655       break;
11656
11657     case M_SGE:         /* X >= Y  <==>  not (X < Y) */
11658       s = "slt";
11659       goto sge;
11660     case M_SGEU:
11661       s = "sltu";
11662     sge:
11663       macro_build (NULL, s, "d,v,t", op[0], op[1], op[2]);
11664       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
11665       break;
11666
11667     case M_SGE_I:       /* X >= I  <==>  not (X < I) */
11668     case M_SGEU_I:
11669       if (imm_expr.X_op == O_constant
11670           && imm_expr.X_add_number >= -0x8000
11671           && imm_expr.X_add_number < 0x8000)
11672         macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
11673                      op[0], op[1], BFD_RELOC_LO16);
11674       else
11675         {
11676           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11677           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
11678                        op[0], op[1], AT);
11679           used_at = 1;
11680         }
11681       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
11682       break;
11683
11684     case M_SGT:         /* X > Y  <==>  Y < X */
11685       s = "slt";
11686       goto sgt;
11687     case M_SGTU:
11688       s = "sltu";
11689     sgt:
11690       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
11691       break;
11692
11693     case M_SGT_I:       /* X > I  <==>  I < X */
11694       s = "slt";
11695       goto sgti;
11696     case M_SGTU_I:
11697       s = "sltu";
11698     sgti:
11699       used_at = 1;
11700       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11701       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
11702       break;
11703
11704     case M_SLE:         /* X <= Y  <==>  Y >= X  <==>  not (Y < X) */
11705       s = "slt";
11706       goto sle;
11707     case M_SLEU:
11708       s = "sltu";
11709     sle:
11710       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
11711       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
11712       break;
11713
11714     case M_SLE_I:       /* X <= I  <==>  I >= X  <==>  not (I < X) */
11715       s = "slt";
11716       goto slei;
11717     case M_SLEU_I:
11718       s = "sltu";
11719     slei:
11720       used_at = 1;
11721       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11722       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
11723       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
11724       break;
11725
11726     case M_SLT_I:
11727       if (imm_expr.X_op == O_constant
11728           && imm_expr.X_add_number >= -0x8000
11729           && imm_expr.X_add_number < 0x8000)
11730         {
11731           macro_build (&imm_expr, "slti", "t,r,j", op[0], op[1],
11732                        BFD_RELOC_LO16);
11733           break;
11734         }
11735       used_at = 1;
11736       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11737       macro_build (NULL, "slt", "d,v,t", op[0], op[1], AT);
11738       break;
11739
11740     case M_SLTU_I:
11741       if (imm_expr.X_op == O_constant
11742           && imm_expr.X_add_number >= -0x8000
11743           && imm_expr.X_add_number < 0x8000)
11744         {
11745           macro_build (&imm_expr, "sltiu", "t,r,j", op[0], op[1],
11746                        BFD_RELOC_LO16);
11747           break;
11748         }
11749       used_at = 1;
11750       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11751       macro_build (NULL, "sltu", "d,v,t", op[0], op[1], AT);
11752       break;
11753
11754     case M_SNE:
11755       if (op[1] == 0)
11756         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[2]);
11757       else if (op[2] == 0)
11758         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
11759       else
11760         {
11761           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
11762           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
11763         }
11764       break;
11765
11766     case M_SNE_I:
11767       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
11768         {
11769           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
11770           break;
11771         }
11772       if (op[1] == 0)
11773         {
11774           as_warn (_("Instruction %s: result is always true"),
11775                    ip->insn_mo->name);
11776           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
11777                        op[0], 0, BFD_RELOC_LO16);
11778           break;
11779         }
11780       if (CPU_HAS_SEQ (mips_opts.arch)
11781           && -512 <= imm_expr.X_add_number
11782           && imm_expr.X_add_number < 512)
11783         {
11784           macro_build (NULL, "snei", "t,r,+Q", op[0], op[1],
11785                        (int) imm_expr.X_add_number);
11786           break;
11787         }
11788       if (imm_expr.X_op == O_constant
11789           && imm_expr.X_add_number >= 0
11790           && imm_expr.X_add_number < 0x10000)
11791         {
11792           macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1],
11793                        BFD_RELOC_LO16);
11794         }
11795       else if (imm_expr.X_op == O_constant
11796                && imm_expr.X_add_number > -0x8000
11797                && imm_expr.X_add_number < 0)
11798         {
11799           imm_expr.X_add_number = -imm_expr.X_add_number;
11800           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
11801                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
11802         }
11803       else if (CPU_HAS_SEQ (mips_opts.arch))
11804         {
11805           used_at = 1;
11806           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11807           macro_build (NULL, "sne", "d,v,t", op[0], op[1], AT);
11808           break;
11809         }
11810       else
11811         {
11812           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11813           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
11814           used_at = 1;
11815         }
11816       macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
11817       break;
11818
11819     case M_SUB_I:
11820       s = "addi";
11821       s2 = "sub";
11822       goto do_subi;
11823     case M_SUBU_I:
11824       s = "addiu";
11825       s2 = "subu";
11826       goto do_subi;
11827     case M_DSUB_I:
11828       dbl = 1;
11829       s = "daddi";
11830       s2 = "dsub";
11831       if (!mips_opts.micromips)
11832         goto do_subi;
11833       if (imm_expr.X_op == O_constant
11834           && imm_expr.X_add_number > -0x200
11835           && imm_expr.X_add_number <= 0x200)
11836         {
11837           macro_build (NULL, s, "t,r,.", op[0], op[1], -imm_expr.X_add_number);
11838           break;
11839         }
11840       goto do_subi_i;
11841     case M_DSUBU_I:
11842       dbl = 1;
11843       s = "daddiu";
11844       s2 = "dsubu";
11845     do_subi:
11846       if (imm_expr.X_op == O_constant
11847           && imm_expr.X_add_number > -0x8000
11848           && imm_expr.X_add_number <= 0x8000)
11849         {
11850           imm_expr.X_add_number = -imm_expr.X_add_number;
11851           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
11852           break;
11853         }
11854     do_subi_i:
11855       used_at = 1;
11856       load_register (AT, &imm_expr, dbl);
11857       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
11858       break;
11859
11860     case M_TEQ_I:
11861       s = "teq";
11862       goto trap;
11863     case M_TGE_I:
11864       s = "tge";
11865       goto trap;
11866     case M_TGEU_I:
11867       s = "tgeu";
11868       goto trap;
11869     case M_TLT_I:
11870       s = "tlt";
11871       goto trap;
11872     case M_TLTU_I:
11873       s = "tltu";
11874       goto trap;
11875     case M_TNE_I:
11876       s = "tne";
11877     trap:
11878       used_at = 1;
11879       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11880       macro_build (NULL, s, "s,t", op[0], AT);
11881       break;
11882
11883     case M_TRUNCWS:
11884     case M_TRUNCWD:
11885       gas_assert (!mips_opts.micromips);
11886       gas_assert (mips_opts.isa == ISA_MIPS1);
11887       used_at = 1;
11888
11889       /*
11890        * Is the double cfc1 instruction a bug in the mips assembler;
11891        * or is there a reason for it?
11892        */
11893       start_noreorder ();
11894       macro_build (NULL, "cfc1", "t,G", op[2], RA);
11895       macro_build (NULL, "cfc1", "t,G", op[2], RA);
11896       macro_build (NULL, "nop", "");
11897       expr1.X_add_number = 3;
11898       macro_build (&expr1, "ori", "t,r,i", AT, op[2], BFD_RELOC_LO16);
11899       expr1.X_add_number = 2;
11900       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
11901       macro_build (NULL, "ctc1", "t,G", AT, RA);
11902       macro_build (NULL, "nop", "");
11903       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
11904                    op[0], op[1]);
11905       macro_build (NULL, "ctc1", "t,G", op[2], RA);
11906       macro_build (NULL, "nop", "");
11907       end_noreorder ();
11908       break;
11909
11910     case M_ULH_AB:
11911       s = "lb";
11912       s2 = "lbu";
11913       off = 1;
11914       goto uld_st;
11915     case M_ULHU_AB:
11916       s = "lbu";
11917       s2 = "lbu";
11918       off = 1;
11919       goto uld_st;
11920     case M_ULW_AB:
11921       s = "lwl";
11922       s2 = "lwr";
11923       offbits = (mips_opts.micromips ? 12 : 16);
11924       off = 3;
11925       goto uld_st;
11926     case M_ULD_AB:
11927       s = "ldl";
11928       s2 = "ldr";
11929       offbits = (mips_opts.micromips ? 12 : 16);
11930       off = 7;
11931       goto uld_st;
11932     case M_USH_AB:
11933       s = "sb";
11934       s2 = "sb";
11935       off = 1;
11936       ust = 1;
11937       goto uld_st;
11938     case M_USW_AB:
11939       s = "swl";
11940       s2 = "swr";
11941       offbits = (mips_opts.micromips ? 12 : 16);
11942       off = 3;
11943       ust = 1;
11944       goto uld_st;
11945     case M_USD_AB:
11946       s = "sdl";
11947       s2 = "sdr";
11948       offbits = (mips_opts.micromips ? 12 : 16);
11949       off = 7;
11950       ust = 1;
11951
11952     uld_st:
11953       breg = op[2];
11954       large_offset = !small_offset_p (off, align, offbits);
11955       ep = &offset_expr;
11956       expr1.X_add_number = 0;
11957       if (large_offset)
11958         {
11959           used_at = 1;
11960           tempreg = AT;
11961           if (small_offset_p (0, align, 16))
11962             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
11963                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
11964           else
11965             {
11966               load_address (tempreg, ep, &used_at);
11967               if (breg != 0)
11968                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11969                              tempreg, tempreg, breg);
11970             }
11971           offset_reloc[0] = BFD_RELOC_LO16;
11972           offset_reloc[1] = BFD_RELOC_UNUSED;
11973           offset_reloc[2] = BFD_RELOC_UNUSED;
11974           breg = tempreg;
11975           tempreg = op[0];
11976           ep = &expr1;
11977         }
11978       else if (!ust && op[0] == breg)
11979         {
11980           used_at = 1;
11981           tempreg = AT;
11982         }
11983       else
11984         tempreg = op[0];
11985
11986       if (off == 1)
11987         goto ulh_sh;
11988
11989       if (!target_big_endian)
11990         ep->X_add_number += off;
11991       if (offbits == 12)
11992         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
11993       else
11994         macro_build (ep, s, "t,o(b)", tempreg, -1,
11995                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
11996
11997       if (!target_big_endian)
11998         ep->X_add_number -= off;
11999       else
12000         ep->X_add_number += off;
12001       if (offbits == 12)
12002         macro_build (NULL, s2, "t,~(b)",
12003                      tempreg, (int) ep->X_add_number, breg);
12004       else
12005         macro_build (ep, s2, "t,o(b)", tempreg, -1,
12006                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12007
12008       /* If necessary, move the result in tempreg to the final destination.  */
12009       if (!ust && op[0] != tempreg)
12010         {
12011           /* Protect second load's delay slot.  */
12012           load_delay_nop ();
12013           move_register (op[0], tempreg);
12014         }
12015       break;
12016
12017     ulh_sh:
12018       used_at = 1;
12019       if (target_big_endian == ust)
12020         ep->X_add_number += off;
12021       tempreg = ust || large_offset ? op[0] : AT;
12022       macro_build (ep, s, "t,o(b)", tempreg, -1,
12023                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12024
12025       /* For halfword transfers we need a temporary register to shuffle
12026          bytes.  Unfortunately for M_USH_A we have none available before
12027          the next store as AT holds the base address.  We deal with this
12028          case by clobbering TREG and then restoring it as with ULH.  */
12029       tempreg = ust == large_offset ? op[0] : AT;
12030       if (ust)
12031         macro_build (NULL, "srl", SHFT_FMT, tempreg, op[0], 8);
12032
12033       if (target_big_endian == ust)
12034         ep->X_add_number -= off;
12035       else
12036         ep->X_add_number += off;
12037       macro_build (ep, s2, "t,o(b)", tempreg, -1,
12038                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12039
12040       /* For M_USH_A re-retrieve the LSB.  */
12041       if (ust && large_offset)
12042         {
12043           if (target_big_endian)
12044             ep->X_add_number += off;
12045           else
12046             ep->X_add_number -= off;
12047           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
12048                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
12049         }
12050       /* For ULH and M_USH_A OR the LSB in.  */
12051       if (!ust || large_offset)
12052         {
12053           tempreg = !large_offset ? AT : op[0];
12054           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
12055           macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12056         }
12057       break;
12058
12059     default:
12060       /* FIXME: Check if this is one of the itbl macros, since they
12061          are added dynamically.  */
12062       as_bad (_("Macro %s not implemented yet"), ip->insn_mo->name);
12063       break;
12064     }
12065   if (!mips_opts.at && used_at)
12066     as_bad (_("Macro used $at after \".set noat\""));
12067 }
12068
12069 /* Implement macros in mips16 mode.  */
12070
12071 static void
12072 mips16_macro (struct mips_cl_insn *ip)
12073 {
12074   const struct mips_operand_array *operands;
12075   int mask;
12076   int tmp;
12077   expressionS expr1;
12078   int dbl;
12079   const char *s, *s2, *s3;
12080   unsigned int op[MAX_OPERANDS];
12081   unsigned int i;
12082
12083   mask = ip->insn_mo->mask;
12084
12085   operands = insn_operands (ip);
12086   for (i = 0; i < MAX_OPERANDS; i++)
12087     if (operands->operand[i])
12088       op[i] = insn_extract_operand (ip, operands->operand[i]);
12089     else
12090       op[i] = -1;
12091
12092   expr1.X_op = O_constant;
12093   expr1.X_op_symbol = NULL;
12094   expr1.X_add_symbol = NULL;
12095   expr1.X_add_number = 1;
12096
12097   dbl = 0;
12098
12099   switch (mask)
12100     {
12101     default:
12102       abort ();
12103
12104     case M_DDIV_3:
12105       dbl = 1;
12106     case M_DIV_3:
12107       s = "mflo";
12108       goto do_div3;
12109     case M_DREM_3:
12110       dbl = 1;
12111     case M_REM_3:
12112       s = "mfhi";
12113     do_div3:
12114       start_noreorder ();
12115       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", op[1], op[2]);
12116       expr1.X_add_number = 2;
12117       macro_build (&expr1, "bnez", "x,p", op[2]);
12118       macro_build (NULL, "break", "6", 7);
12119
12120       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
12121          since that causes an overflow.  We should do that as well,
12122          but I don't see how to do the comparisons without a temporary
12123          register.  */
12124       end_noreorder ();
12125       macro_build (NULL, s, "x", op[0]);
12126       break;
12127
12128     case M_DIVU_3:
12129       s = "divu";
12130       s2 = "mflo";
12131       goto do_divu3;
12132     case M_REMU_3:
12133       s = "divu";
12134       s2 = "mfhi";
12135       goto do_divu3;
12136     case M_DDIVU_3:
12137       s = "ddivu";
12138       s2 = "mflo";
12139       goto do_divu3;
12140     case M_DREMU_3:
12141       s = "ddivu";
12142       s2 = "mfhi";
12143     do_divu3:
12144       start_noreorder ();
12145       macro_build (NULL, s, "0,x,y", op[1], op[2]);
12146       expr1.X_add_number = 2;
12147       macro_build (&expr1, "bnez", "x,p", op[2]);
12148       macro_build (NULL, "break", "6", 7);
12149       end_noreorder ();
12150       macro_build (NULL, s2, "x", op[0]);
12151       break;
12152
12153     case M_DMUL:
12154       dbl = 1;
12155     case M_MUL:
12156       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", op[1], op[2]);
12157       macro_build (NULL, "mflo", "x", op[0]);
12158       break;
12159
12160     case M_DSUBU_I:
12161       dbl = 1;
12162       goto do_subu;
12163     case M_SUBU_I:
12164     do_subu:
12165       if (imm_expr.X_op != O_constant)
12166         as_bad (_("Unsupported large constant"));
12167       imm_expr.X_add_number = -imm_expr.X_add_number;
12168       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", op[0], op[1]);
12169       break;
12170
12171     case M_SUBU_I_2:
12172       if (imm_expr.X_op != O_constant)
12173         as_bad (_("Unsupported large constant"));
12174       imm_expr.X_add_number = -imm_expr.X_add_number;
12175       macro_build (&imm_expr, "addiu", "x,k", op[0]);
12176       break;
12177
12178     case M_DSUBU_I_2:
12179       if (imm_expr.X_op != O_constant)
12180         as_bad (_("Unsupported large constant"));
12181       imm_expr.X_add_number = -imm_expr.X_add_number;
12182       macro_build (&imm_expr, "daddiu", "y,j", op[0]);
12183       break;
12184
12185     case M_BEQ:
12186       s = "cmp";
12187       s2 = "bteqz";
12188       goto do_branch;
12189     case M_BNE:
12190       s = "cmp";
12191       s2 = "btnez";
12192       goto do_branch;
12193     case M_BLT:
12194       s = "slt";
12195       s2 = "btnez";
12196       goto do_branch;
12197     case M_BLTU:
12198       s = "sltu";
12199       s2 = "btnez";
12200       goto do_branch;
12201     case M_BLE:
12202       s = "slt";
12203       s2 = "bteqz";
12204       goto do_reverse_branch;
12205     case M_BLEU:
12206       s = "sltu";
12207       s2 = "bteqz";
12208       goto do_reverse_branch;
12209     case M_BGE:
12210       s = "slt";
12211       s2 = "bteqz";
12212       goto do_branch;
12213     case M_BGEU:
12214       s = "sltu";
12215       s2 = "bteqz";
12216       goto do_branch;
12217     case M_BGT:
12218       s = "slt";
12219       s2 = "btnez";
12220       goto do_reverse_branch;
12221     case M_BGTU:
12222       s = "sltu";
12223       s2 = "btnez";
12224
12225     do_reverse_branch:
12226       tmp = op[1];
12227       op[1] = op[0];
12228       op[0] = tmp;
12229
12230     do_branch:
12231       macro_build (NULL, s, "x,y", op[0], op[1]);
12232       macro_build (&offset_expr, s2, "p");
12233       break;
12234
12235     case M_BEQ_I:
12236       s = "cmpi";
12237       s2 = "bteqz";
12238       s3 = "x,U";
12239       goto do_branch_i;
12240     case M_BNE_I:
12241       s = "cmpi";
12242       s2 = "btnez";
12243       s3 = "x,U";
12244       goto do_branch_i;
12245     case M_BLT_I:
12246       s = "slti";
12247       s2 = "btnez";
12248       s3 = "x,8";
12249       goto do_branch_i;
12250     case M_BLTU_I:
12251       s = "sltiu";
12252       s2 = "btnez";
12253       s3 = "x,8";
12254       goto do_branch_i;
12255     case M_BLE_I:
12256       s = "slti";
12257       s2 = "btnez";
12258       s3 = "x,8";
12259       goto do_addone_branch_i;
12260     case M_BLEU_I:
12261       s = "sltiu";
12262       s2 = "btnez";
12263       s3 = "x,8";
12264       goto do_addone_branch_i;
12265     case M_BGE_I:
12266       s = "slti";
12267       s2 = "bteqz";
12268       s3 = "x,8";
12269       goto do_branch_i;
12270     case M_BGEU_I:
12271       s = "sltiu";
12272       s2 = "bteqz";
12273       s3 = "x,8";
12274       goto do_branch_i;
12275     case M_BGT_I:
12276       s = "slti";
12277       s2 = "bteqz";
12278       s3 = "x,8";
12279       goto do_addone_branch_i;
12280     case M_BGTU_I:
12281       s = "sltiu";
12282       s2 = "bteqz";
12283       s3 = "x,8";
12284
12285     do_addone_branch_i:
12286       if (imm_expr.X_op != O_constant)
12287         as_bad (_("Unsupported large constant"));
12288       ++imm_expr.X_add_number;
12289
12290     do_branch_i:
12291       macro_build (&imm_expr, s, s3, op[0]);
12292       macro_build (&offset_expr, s2, "p");
12293       break;
12294
12295     case M_ABS:
12296       expr1.X_add_number = 0;
12297       macro_build (&expr1, "slti", "x,8", op[1]);
12298       if (op[0] != op[1])
12299         macro_build (NULL, "move", "y,X", op[0], mips16_to_32_reg_map[op[1]]);
12300       expr1.X_add_number = 2;
12301       macro_build (&expr1, "bteqz", "p");
12302       macro_build (NULL, "neg", "x,w", op[0], op[0]);
12303       break;
12304     }
12305 }
12306
12307 /* Look up instruction [START, START + LENGTH) in HASH.  Record any extra
12308    opcode bits in *OPCODE_EXTRA.  */
12309
12310 static struct mips_opcode *
12311 mips_lookup_insn (struct hash_control *hash, const char *start,
12312                   ssize_t length, unsigned int *opcode_extra)
12313 {
12314   char *name, *dot, *p;
12315   unsigned int mask, suffix;
12316   ssize_t opend;
12317   struct mips_opcode *insn;
12318
12319   /* Make a copy of the instruction so that we can fiddle with it.  */
12320   name = alloca (length + 1);
12321   memcpy (name, start, length);
12322   name[length] = '\0';
12323
12324   /* Look up the instruction as-is.  */
12325   insn = (struct mips_opcode *) hash_find (hash, name);
12326   if (insn)
12327     return insn;
12328
12329   dot = strchr (name, '.');
12330   if (dot && dot[1])
12331     {
12332       /* Try to interpret the text after the dot as a VU0 channel suffix.  */
12333       p = mips_parse_vu0_channels (dot + 1, &mask);
12334       if (*p == 0 && mask != 0)
12335         {
12336           *dot = 0;
12337           insn = (struct mips_opcode *) hash_find (hash, name);
12338           *dot = '.';
12339           if (insn && (insn->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0)
12340             {
12341               *opcode_extra |= mask << mips_vu0_channel_mask.lsb;
12342               return insn;
12343             }
12344         }
12345     }
12346
12347   if (mips_opts.micromips)
12348     {
12349       /* See if there's an instruction size override suffix,
12350          either `16' or `32', at the end of the mnemonic proper,
12351          that defines the operation, i.e. before the first `.'
12352          character if any.  Strip it and retry.  */
12353       opend = dot != NULL ? dot - name : length;
12354       if (opend >= 3 && name[opend - 2] == '1' && name[opend - 1] == '6')
12355         suffix = 2;
12356       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
12357         suffix = 4;
12358       else
12359         suffix = 0;
12360       if (suffix)
12361         {
12362           memcpy (name + opend - 2, name + opend, length - opend + 1);
12363           insn = (struct mips_opcode *) hash_find (hash, name);
12364           if (insn)
12365             {
12366               forced_insn_length = suffix;
12367               return insn;
12368             }
12369         }
12370     }
12371
12372   return NULL;
12373 }
12374
12375 /* Assemble an instruction into its binary format.  If the instruction
12376    is a macro, set imm_expr, imm2_expr and offset_expr to the values
12377    associated with "I", "+I" and "A" operands respectively.  Otherwise
12378    store the value of the relocatable field (if any) in offset_expr.
12379    In both cases set offset_reloc to the relocation operators applied
12380    to offset_expr.  */
12381
12382 static void
12383 mips_ip (char *str, struct mips_cl_insn *ip)
12384 {
12385   bfd_boolean wrong_delay_slot_insns = FALSE;
12386   bfd_boolean need_delay_slot_ok = TRUE;
12387   struct mips_opcode *firstinsn = NULL;
12388   const struct mips_opcode *past;
12389   struct hash_control *hash;
12390   const char *args;
12391   char c = 0;
12392   struct mips_opcode *first, *insn;
12393   char format;
12394   size_t end;
12395   const struct mips_operand *operand;
12396   struct mips_arg_info arg;
12397   struct mips_operand_token *tokens;
12398   unsigned int opcode_extra;
12399
12400   insn_error = NULL;
12401
12402   if (mips_opts.micromips)
12403     {
12404       hash = micromips_op_hash;
12405       past = &micromips_opcodes[bfd_micromips_num_opcodes];
12406     }
12407   else
12408     {
12409       hash = op_hash;
12410       past = &mips_opcodes[NUMOPCODES];
12411     }
12412   forced_insn_length = 0;
12413   insn = NULL;
12414   opcode_extra = 0;
12415
12416   /* We first try to match an instruction up to a space or to the end.  */
12417   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
12418     continue;
12419
12420   first = insn = mips_lookup_insn (hash, str, end, &opcode_extra);
12421   if (insn == NULL)
12422     {
12423       insn_error = _("Unrecognized opcode");
12424       return;
12425     }
12426   /* When no opcode suffix is specified, assume ".xyzw". */
12427   if ((insn->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0 && opcode_extra == 0)
12428     opcode_extra = 0xf << mips_vu0_channel_mask.lsb;
12429
12430   if (strcmp (insn->name, "li.s") == 0)
12431     format = 'f';
12432   else if (strcmp (insn->name, "li.d") == 0)
12433     format = 'd';
12434   else
12435     format = 0;
12436   tokens = mips_parse_arguments (str + end, format);
12437   if (!tokens)
12438     return;
12439
12440   /* For microMIPS instructions placed in a fixed-length branch delay slot
12441      we make up to two passes over the relevant fragment of the opcode
12442      table.  First we try instructions that meet the delay slot's length
12443      requirement.  If none matched, then we retry with the remaining ones
12444      and if one matches, then we use it and then issue an appropriate
12445      warning later on.  */
12446   for (;;)
12447     {
12448       bfd_boolean delay_slot_ok;
12449       bfd_boolean size_ok;
12450       bfd_boolean ok;
12451       bfd_boolean more_alts;
12452
12453       gas_assert (strcmp (insn->name, first->name) == 0);
12454
12455       ok = is_opcode_valid (insn);
12456       size_ok = is_size_valid (insn);
12457       delay_slot_ok = is_delay_slot_valid (insn);
12458       if (!delay_slot_ok && !wrong_delay_slot_insns)
12459         {
12460           firstinsn = insn;
12461           wrong_delay_slot_insns = TRUE;
12462         }
12463       more_alts = (insn + 1 < past
12464                    && strcmp (insn[0].name, insn[1].name) == 0);
12465       if (!ok || !size_ok || delay_slot_ok != need_delay_slot_ok)
12466         {
12467           static char buf[256];
12468
12469           if (more_alts)
12470             {
12471               ++insn;
12472               continue;
12473             }
12474           if (wrong_delay_slot_insns && need_delay_slot_ok)
12475             {
12476               gas_assert (firstinsn);
12477               need_delay_slot_ok = FALSE;
12478               past = insn + 1;
12479               insn = firstinsn;
12480               continue;
12481             }
12482
12483           obstack_free (&mips_operand_tokens, tokens);
12484           if (insn_error)
12485             return;
12486
12487           if (!ok)
12488             sprintf (buf, _("Opcode not supported on this processor: %s (%s)"),
12489                      mips_cpu_info_from_arch (mips_opts.arch)->name,
12490                      mips_cpu_info_from_isa (mips_opts.isa)->name);
12491           else if (mips_opts.insn32)
12492             sprintf (buf, _("Opcode not supported in the `insn32' mode"));
12493           else
12494             sprintf (buf, _("Unrecognized %u-bit version of microMIPS opcode"),
12495                      8 * forced_insn_length);
12496           insn_error = buf;
12497
12498           return;
12499         }
12500
12501       imm_expr.X_op = O_absent;
12502       imm2_expr.X_op = O_absent;
12503       offset_expr.X_op = O_absent;
12504       offset_reloc[0] = BFD_RELOC_UNUSED;
12505       offset_reloc[1] = BFD_RELOC_UNUSED;
12506       offset_reloc[2] = BFD_RELOC_UNUSED;
12507
12508       create_insn (ip, insn);
12509       ip->insn_opcode |= opcode_extra;
12510       insn_error = NULL;
12511       memset (&arg, 0, sizeof (arg));
12512       arg.insn = ip;
12513       arg.token = tokens;
12514       arg.argnum = 1;
12515       arg.last_regno = ILLEGAL_REG;
12516       arg.dest_regno = ILLEGAL_REG;
12517       arg.soft_match = (more_alts
12518                         || (wrong_delay_slot_insns && need_delay_slot_ok));
12519       for (args = insn->args;; ++args)
12520         {
12521           if (arg.token->type == OT_END)
12522             {
12523               /* Handle unary instructions in which only one operand is given.
12524                  The source is then the same as the destination.  */
12525               if (arg.opnum == 1 && *args == ',')
12526                 {
12527                   operand = (mips_opts.micromips
12528                              ? decode_micromips_operand (args + 1)
12529                              : decode_mips_operand (args + 1));
12530                   if (operand && mips_optional_operand_p (operand))
12531                     {
12532                       arg.token = tokens;
12533                       arg.argnum = 1;
12534                       continue;
12535                     }
12536                 }
12537
12538               /* Treat elided base registers as $0.  */
12539               if (strcmp (args, "(b)") == 0)
12540                 args += 3;
12541
12542               if (args[0] == '+')
12543                 switch (args[1])
12544                   {
12545                     case 'K':
12546                     case 'N':
12547                       /* The register suffix is optional. */
12548                       args += 2;
12549                       break;
12550                   }
12551
12552               /* Fail the match if there were too few operands.  */
12553               if (*args)
12554                 break;
12555
12556               /* Successful match.  */
12557               if (arg.dest_regno == arg.last_regno
12558                   && strncmp (ip->insn_mo->name, "jalr", 4) == 0)
12559                 {
12560                   if (arg.opnum == 2)
12561                     as_bad (_("Source and destination must be different"));
12562                   else if (arg.last_regno == 31)
12563                     as_bad (_("A destination register must be supplied"));
12564                 }
12565               check_completed_insn (&arg);
12566               obstack_free (&mips_operand_tokens, tokens);
12567               return;
12568             }
12569
12570           /* Fail the match if the line has too many operands.   */
12571           if (*args == 0)
12572             break;
12573
12574           /* Handle characters that need to match exactly.  */
12575           if (*args == '(' || *args == ')' || *args == ',')
12576             {
12577               if (match_char (&arg, *args))
12578                 continue;
12579               break;
12580             }
12581           if (*args == '#')
12582             {
12583               ++args;
12584               if (arg.token->type == OT_DOUBLE_CHAR
12585                   && arg.token->u.ch == *args)
12586                 {
12587                   ++arg.token;
12588                   continue;
12589                 }
12590               break;
12591             }
12592
12593           /* Handle special macro operands.  Work out the properties of
12594              other operands.  */
12595           arg.opnum += 1;
12596           arg.lax_max = FALSE;
12597           switch (*args)
12598             {
12599             case '+':
12600               switch (args[1])
12601                 {
12602                 case '1':
12603                 case '2':
12604                 case '3':
12605                 case '4':
12606                 case 'B':
12607                 case 'C':
12608                 case 'F':
12609                 case 'G':
12610                 case 'H':
12611                 case 'J':
12612                 case 'Q':
12613                 case 'S':
12614                 case 's':
12615                   /* If these integer forms come last, there is no other
12616                      form of the instruction that could match.  Prefer to
12617                      give detailed error messages where possible.  */
12618                   if (args[2] == 0)
12619                     arg.soft_match = FALSE;
12620                   break;
12621
12622                 case 'I':
12623                   /* "+I" is like "I", except that imm2_expr is used.  */
12624                   if (match_const_int (&arg, &imm2_expr.X_add_number, 0))
12625                     imm2_expr.X_op = O_constant;
12626                   else
12627                     insn_error = _("absolute expression required");
12628                   if (HAVE_32BIT_GPRS)
12629                     normalize_constant_expr (&imm2_expr);
12630                   ++args;
12631                   continue;
12632
12633                 case 'i':
12634                   *offset_reloc = BFD_RELOC_MIPS_JMP;
12635                   break;
12636                 }
12637               break;
12638
12639             case '\'':
12640             case ':':
12641             case '@':
12642             case '^':
12643             case '$':
12644             case '\\':
12645             case '%':
12646             case '|':
12647             case '0':
12648             case '1':
12649             case '2':
12650             case '3':
12651             case '4':
12652             case '5':
12653             case '6':
12654             case '8':
12655             case 'B':
12656             case 'C':
12657             case 'J':
12658             case 'O':
12659             case 'P':
12660             case 'Q':
12661             case 'c':
12662             case 'h':
12663             case 'q':
12664               /* If these integer forms come last, there is no other
12665                  form of the instruction that could match.  Prefer to
12666                  give detailed error messages where possible.  */
12667               if (args[1] == 0)
12668                 arg.soft_match = FALSE;
12669               break;
12670
12671             case 'I':
12672               if (match_const_int (&arg, &imm_expr.X_add_number, 0))
12673                 imm_expr.X_op = O_constant;
12674               else
12675                 insn_error = _("absolute expression required");
12676               if (HAVE_32BIT_GPRS)
12677                 normalize_constant_expr (&imm_expr);
12678               continue;
12679
12680             case 'A':
12681               if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
12682                 {
12683                   /* Assume that the offset has been elided and that what
12684                      we saw was a base register.  The match will fail later
12685                      if that assumption turns out to be wrong.  */
12686                   offset_expr.X_op = O_constant;
12687                   offset_expr.X_add_number = 0;
12688                 }
12689               else if (match_expression (&arg, &offset_expr, offset_reloc))
12690                 normalize_address_expr (&offset_expr);
12691               else
12692                 insn_error = _("absolute expression required");
12693               continue;
12694
12695             case 'F':
12696               if (!match_float_constant (&arg, &imm_expr, &offset_expr,
12697                                          8, TRUE))
12698                 insn_error = _("floating-point expression required");
12699               continue;
12700
12701             case 'L':
12702               if (!match_float_constant (&arg, &imm_expr, &offset_expr,
12703                                          8, FALSE))
12704                 insn_error = _("floating-point expression required");
12705               continue;
12706
12707             case 'f':
12708               if (!match_float_constant (&arg, &imm_expr, &offset_expr,
12709                                          4, TRUE))
12710                 insn_error = _("floating-point expression required");
12711               continue;
12712
12713             case 'l':
12714               if (!match_float_constant (&arg, &imm_expr, &offset_expr,
12715                                          4, FALSE))
12716                 insn_error = _("floating-point expression required");
12717               continue;
12718
12719               /* ??? This is the traditional behavior, but is flaky if
12720                  there are alternative versions of the same instruction
12721                  for different subarchitectures.  The next alternative
12722                  might not be suitable.  */
12723             case 'j':
12724               /* For compatibility with older assemblers, we accept
12725                  0x8000-0xffff as signed 16-bit numbers when only
12726                  signed numbers are allowed.  */
12727               arg.lax_max = !more_alts;
12728             case 'i':
12729               /* Only accept non-constant operands if this is the
12730                  final alternative.  Later alternatives might include
12731                  a macro implementation.  */
12732               arg.allow_nonconst = !more_alts;
12733               break;
12734
12735             case 'u':
12736               /* There are no macro implementations for out-of-range values.  */
12737               arg.allow_nonconst = TRUE;
12738               break;
12739
12740             case 'o':
12741               /* There should always be a macro implementation.  */
12742               arg.allow_nonconst = FALSE;
12743               break;
12744
12745             case 'p':
12746               *offset_reloc = BFD_RELOC_16_PCREL_S2;
12747               break;
12748
12749             case 'a':
12750               *offset_reloc = BFD_RELOC_MIPS_JMP;
12751               break;
12752
12753             case 'm':
12754               gas_assert (mips_opts.micromips);
12755               c = args[1];
12756               switch (c)
12757                 {
12758                 case 'D':
12759                 case 'E':
12760                   if (!forced_insn_length)
12761                     *offset_reloc = (int) BFD_RELOC_UNUSED + c;
12762                   else if (c == 'D')
12763                     *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
12764                   else
12765                     *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
12766                   break;
12767                 }
12768               break;
12769             }
12770
12771           operand = (mips_opts.micromips
12772                      ? decode_micromips_operand (args)
12773                      : decode_mips_operand (args));
12774           if (!operand)
12775             abort ();
12776
12777           /* Skip prefixes.  */
12778           if (*args == '+' || *args == 'm')
12779             args++;
12780
12781           if (mips_optional_operand_p (operand)
12782               && args[1] == ','
12783               && (arg.token[0].type != OT_REG
12784                   || arg.token[1].type == OT_END))
12785             {
12786               /* Assume that the register has been elided and is the
12787                  same as the first operand.  */
12788               arg.token = tokens;
12789               arg.argnum = 1;
12790             }
12791
12792           if (!match_operand (&arg, operand))
12793             break;
12794
12795           continue;
12796         }
12797       /* Args don't match.  */
12798       insn_error = _("Illegal operands");
12799       if (more_alts)
12800         {
12801           ++insn;
12802           continue;
12803         }
12804       if (wrong_delay_slot_insns && need_delay_slot_ok)
12805         {
12806           gas_assert (firstinsn);
12807           need_delay_slot_ok = FALSE;
12808           past = insn + 1;
12809           insn = firstinsn;
12810           continue;
12811         }
12812       obstack_free (&mips_operand_tokens, tokens);
12813       return;
12814     }
12815 }
12816
12817 /* As for mips_ip, but used when assembling MIPS16 code.
12818    Also set forced_insn_length to the resulting instruction size in
12819    bytes if the user explicitly requested a small or extended instruction.  */
12820
12821 static void
12822 mips16_ip (char *str, struct mips_cl_insn *ip)
12823 {
12824   char *s;
12825   const char *args;
12826   struct mips_opcode *insn;
12827   const struct mips_operand *operand;
12828   const struct mips_operand *ext_operand;
12829   struct mips_arg_info arg;
12830   struct mips_operand_token *tokens;
12831
12832   insn_error = NULL;
12833
12834   forced_insn_length = 0;
12835
12836   for (s = str; ISLOWER (*s); ++s)
12837     ;
12838   switch (*s)
12839     {
12840     case '\0':
12841       break;
12842
12843     case ' ':
12844       *s++ = '\0';
12845       break;
12846
12847     case '.':
12848       if (s[1] == 't' && s[2] == ' ')
12849         {
12850           *s = '\0';
12851           forced_insn_length = 2;
12852           s += 3;
12853           break;
12854         }
12855       else if (s[1] == 'e' && s[2] == ' ')
12856         {
12857           *s = '\0';
12858           forced_insn_length = 4;
12859           s += 3;
12860           break;
12861         }
12862       /* Fall through.  */
12863     default:
12864       insn_error = _("unknown opcode");
12865       return;
12866     }
12867
12868   if (mips_opts.noautoextend && !forced_insn_length)
12869     forced_insn_length = 2;
12870
12871   if ((insn = (struct mips_opcode *) hash_find (mips16_op_hash, str)) == NULL)
12872     {
12873       insn_error = _("unrecognized opcode");
12874       return;
12875     }
12876
12877   tokens = mips_parse_arguments (s, 0);
12878   if (!tokens)
12879     return;
12880
12881   for (;;)
12882     {
12883       bfd_boolean ok;
12884       bfd_boolean more_alts;
12885       char relax_char;
12886
12887       gas_assert (strcmp (insn->name, str) == 0);
12888
12889       ok = is_opcode_valid_16 (insn);
12890       more_alts = (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes]
12891                    && strcmp (insn[0].name, insn[1].name) == 0);
12892       if (! ok)
12893         {
12894           if (more_alts)
12895             {
12896               ++insn;
12897               continue;
12898             }
12899           else
12900             {
12901               if (!insn_error)
12902                 {
12903                   static char buf[100];
12904                   sprintf (buf,
12905                            _("Opcode not supported on this processor: %s (%s)"),
12906                            mips_cpu_info_from_arch (mips_opts.arch)->name,
12907                            mips_cpu_info_from_isa (mips_opts.isa)->name);
12908                   insn_error = buf;
12909                 }
12910               obstack_free (&mips_operand_tokens, tokens);
12911               return;
12912             }
12913         }
12914
12915       create_insn (ip, insn);
12916       imm_expr.X_op = O_absent;
12917       imm2_expr.X_op = O_absent;
12918       offset_expr.X_op = O_absent;
12919       offset_reloc[0] = BFD_RELOC_UNUSED;
12920       offset_reloc[1] = BFD_RELOC_UNUSED;
12921       offset_reloc[2] = BFD_RELOC_UNUSED;
12922       relax_char = 0;
12923
12924       memset (&arg, 0, sizeof (arg));
12925       arg.insn = ip;
12926       arg.token = tokens;
12927       arg.argnum = 1;
12928       arg.last_regno = ILLEGAL_REG;
12929       arg.dest_regno = ILLEGAL_REG;
12930       arg.soft_match = more_alts;
12931       relax_char = 0;
12932       for (args = insn->args; 1; ++args)
12933         {
12934           int c;
12935
12936           if (arg.token->type == OT_END)
12937             {
12938               offsetT value;
12939
12940               /* Handle unary instructions in which only one operand is given.
12941                  The source is then the same as the destination.  */
12942               if (arg.opnum == 1 && *args == ',')
12943                 {
12944                   operand = decode_mips16_operand (args[1], FALSE);
12945                   if (operand && mips_optional_operand_p (operand))
12946                     {
12947                       arg.token = tokens;
12948                       arg.argnum = 1;
12949                       continue;
12950                     }
12951                 }
12952
12953               /* Fail the match if there were too few operands.  */
12954               if (*args)
12955                 break;
12956
12957               /* Successful match.  Stuff the immediate value in now, if
12958                  we can.  */
12959               if (insn->pinfo == INSN_MACRO)
12960                 {
12961                   gas_assert (relax_char == 0 || relax_char == 'p');
12962                   gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
12963                 }
12964               else if (relax_char
12965                        && offset_expr.X_op == O_constant
12966                        && calculate_reloc (*offset_reloc,
12967                                            offset_expr.X_add_number,
12968                                            &value))
12969                 {
12970                   mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
12971                                 forced_insn_length, &ip->insn_opcode);
12972                   offset_expr.X_op = O_absent;
12973                   *offset_reloc = BFD_RELOC_UNUSED;
12974                 }
12975               else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
12976                 {
12977                   if (forced_insn_length == 2)
12978                     as_bad (_("invalid unextended operand value"));
12979                   forced_insn_length = 4;
12980                   ip->insn_opcode |= MIPS16_EXTEND;
12981                 }
12982               else if (relax_char)
12983                 *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
12984
12985               check_completed_insn (&arg);
12986               obstack_free (&mips_operand_tokens, tokens);
12987               return;
12988             }
12989
12990           /* Fail the match if the line has too many operands.   */
12991           if (*args == 0)
12992             break;
12993
12994           /* Handle characters that need to match exactly.  */
12995           if (*args == '(' || *args == ')' || *args == ',')
12996             {
12997               if (match_char (&arg, *args))
12998                 continue;
12999               break;
13000             }
13001
13002           arg.opnum += 1;
13003           c = *args;
13004           switch (c)
13005             {
13006             case 'p':
13007             case 'q':
13008             case 'A':
13009             case 'B':
13010             case 'E':
13011               relax_char = c;
13012               break;
13013
13014             case 'I':
13015               if (match_const_int (&arg, &imm_expr.X_add_number, 0))
13016                 imm_expr.X_op = O_constant;
13017               else
13018                 insn_error = _("absolute expression required");
13019               if (HAVE_32BIT_GPRS)
13020                 normalize_constant_expr (&imm_expr);
13021               continue;
13022
13023             case 'a':
13024             case 'i':
13025               *offset_reloc = BFD_RELOC_MIPS16_JMP;
13026               ip->insn_opcode <<= 16;
13027               break;
13028             }
13029
13030           operand = decode_mips16_operand (c, FALSE);
13031           if (!operand)
13032             abort ();
13033
13034           /* '6' is a special case.  It is used for BREAK and SDBBP,
13035              whose operands are only meaningful to the software that decodes
13036              them.  This means that there is no architectural reason why
13037              they cannot be prefixed by EXTEND, but in practice,
13038              exception handlers will only look at the instruction
13039              itself.  We therefore allow '6' to be extended when
13040              disassembling but not when assembling.  */
13041           if (operand->type != OP_PCREL && c != '6')
13042             {
13043               ext_operand = decode_mips16_operand (c, TRUE);
13044               if (operand != ext_operand)
13045                 {
13046                   if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
13047                     {
13048                       offset_expr.X_op = O_constant;
13049                       offset_expr.X_add_number = 0;
13050                       relax_char = c;
13051                       continue;
13052                     }
13053
13054                   /* We need the OT_INTEGER check because some MIPS16
13055                      immediate variants are listed before the register ones.  */
13056                   if (arg.token->type != OT_INTEGER
13057                       || !match_expression (&arg, &offset_expr, offset_reloc))
13058                     break;
13059
13060                   /* '8' is used for SLTI(U) and has traditionally not
13061                      been allowed to take relocation operators.  */
13062                   if (offset_reloc[0] != BFD_RELOC_UNUSED
13063                       && (ext_operand->size != 16 || c == '8'))
13064                     break;
13065
13066                   relax_char = c;
13067                   continue;
13068                 }
13069             }
13070
13071           if (mips_optional_operand_p (operand)
13072               && args[1] == ','
13073               && (arg.token[0].type != OT_REG
13074                   || arg.token[1].type == OT_END))
13075             {
13076               /* Assume that the register has been elided and is the
13077                  same as the first operand.  */
13078               arg.token = tokens;
13079               arg.argnum = 1;
13080             }
13081
13082           if (!match_operand (&arg, operand))
13083             break;
13084           continue;
13085         }
13086
13087       /* Args don't match.  */
13088       if (more_alts)
13089         {
13090           ++insn;
13091           continue;
13092         }
13093
13094       insn_error = _("illegal operands");
13095
13096       obstack_free (&mips_operand_tokens, tokens);
13097       return;
13098     }
13099 }
13100
13101 /* Marshal immediate value VAL for an extended MIPS16 instruction.
13102    NBITS is the number of significant bits in VAL.  */
13103
13104 static unsigned long
13105 mips16_immed_extend (offsetT val, unsigned int nbits)
13106 {
13107   int extval;
13108   if (nbits == 16)
13109     {
13110       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
13111       val &= 0x1f;
13112     }
13113   else if (nbits == 15)
13114     {
13115       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
13116       val &= 0xf;
13117     }
13118   else
13119     {
13120       extval = ((val & 0x1f) << 6) | (val & 0x20);
13121       val = 0;
13122     }
13123   return (extval << 16) | val;
13124 }
13125
13126 /* Like decode_mips16_operand, but require the operand to be defined and
13127    require it to be an integer.  */
13128
13129 static const struct mips_int_operand *
13130 mips16_immed_operand (int type, bfd_boolean extended_p)
13131 {
13132   const struct mips_operand *operand;
13133
13134   operand = decode_mips16_operand (type, extended_p);
13135   if (!operand || (operand->type != OP_INT && operand->type != OP_PCREL))
13136     abort ();
13137   return (const struct mips_int_operand *) operand;
13138 }
13139
13140 /* Return true if SVAL fits OPERAND.  RELOC is as for mips16_immed.  */
13141
13142 static bfd_boolean
13143 mips16_immed_in_range_p (const struct mips_int_operand *operand,
13144                          bfd_reloc_code_real_type reloc, offsetT sval)
13145 {
13146   int min_val, max_val;
13147
13148   min_val = mips_int_operand_min (operand);
13149   max_val = mips_int_operand_max (operand);
13150   if (reloc != BFD_RELOC_UNUSED)
13151     {
13152       if (min_val < 0)
13153         sval = SEXT_16BIT (sval);
13154       else
13155         sval &= 0xffff;
13156     }
13157
13158   return (sval >= min_val
13159           && sval <= max_val
13160           && (sval & ((1 << operand->shift) - 1)) == 0);
13161 }
13162
13163 /* Install immediate value VAL into MIPS16 instruction *INSN,
13164    extending it if necessary.  The instruction in *INSN may
13165    already be extended.
13166
13167    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
13168    if none.  In the former case, VAL is a 16-bit number with no
13169    defined signedness.
13170
13171    TYPE is the type of the immediate field.  USER_INSN_LENGTH
13172    is the length that the user requested, or 0 if none.  */
13173
13174 static void
13175 mips16_immed (char *file, unsigned int line, int type,
13176               bfd_reloc_code_real_type reloc, offsetT val,
13177               unsigned int user_insn_length, unsigned long *insn)
13178 {
13179   const struct mips_int_operand *operand;
13180   unsigned int uval, length;
13181
13182   operand = mips16_immed_operand (type, FALSE);
13183   if (!mips16_immed_in_range_p (operand, reloc, val))
13184     {
13185       /* We need an extended instruction.  */
13186       if (user_insn_length == 2)
13187         as_bad_where (file, line, _("invalid unextended operand value"));
13188       else
13189         *insn |= MIPS16_EXTEND;
13190     }
13191   else if (user_insn_length == 4)
13192     {
13193       /* The operand doesn't force an unextended instruction to be extended.
13194          Warn if the user wanted an extended instruction anyway.  */
13195       *insn |= MIPS16_EXTEND;
13196       as_warn_where (file, line,
13197                      _("extended operand requested but not required"));
13198     }
13199
13200   length = mips16_opcode_length (*insn);
13201   if (length == 4)
13202     {
13203       operand = mips16_immed_operand (type, TRUE);
13204       if (!mips16_immed_in_range_p (operand, reloc, val))
13205         as_bad_where (file, line,
13206                       _("operand value out of range for instruction"));
13207     }
13208   uval = ((unsigned int) val >> operand->shift) - operand->bias;
13209   if (length == 2)
13210     *insn = mips_insert_operand (&operand->root, *insn, uval);
13211   else
13212     *insn |= mips16_immed_extend (uval, operand->root.size);
13213 }
13214 \f
13215 struct percent_op_match
13216 {
13217   const char *str;
13218   bfd_reloc_code_real_type reloc;
13219 };
13220
13221 static const struct percent_op_match mips_percent_op[] =
13222 {
13223   {"%lo", BFD_RELOC_LO16},
13224   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
13225   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
13226   {"%call16", BFD_RELOC_MIPS_CALL16},
13227   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
13228   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
13229   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
13230   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
13231   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
13232   {"%got", BFD_RELOC_MIPS_GOT16},
13233   {"%gp_rel", BFD_RELOC_GPREL16},
13234   {"%half", BFD_RELOC_16},
13235   {"%highest", BFD_RELOC_MIPS_HIGHEST},
13236   {"%higher", BFD_RELOC_MIPS_HIGHER},
13237   {"%neg", BFD_RELOC_MIPS_SUB},
13238   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
13239   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
13240   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
13241   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
13242   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
13243   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
13244   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
13245   {"%hi", BFD_RELOC_HI16_S}
13246 };
13247
13248 static const struct percent_op_match mips16_percent_op[] =
13249 {
13250   {"%lo", BFD_RELOC_MIPS16_LO16},
13251   {"%gprel", BFD_RELOC_MIPS16_GPREL},
13252   {"%got", BFD_RELOC_MIPS16_GOT16},
13253   {"%call16", BFD_RELOC_MIPS16_CALL16},
13254   {"%hi", BFD_RELOC_MIPS16_HI16_S},
13255   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
13256   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
13257   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
13258   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
13259   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
13260   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
13261   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
13262 };
13263
13264
13265 /* Return true if *STR points to a relocation operator.  When returning true,
13266    move *STR over the operator and store its relocation code in *RELOC.
13267    Leave both *STR and *RELOC alone when returning false.  */
13268
13269 static bfd_boolean
13270 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
13271 {
13272   const struct percent_op_match *percent_op;
13273   size_t limit, i;
13274
13275   if (mips_opts.mips16)
13276     {
13277       percent_op = mips16_percent_op;
13278       limit = ARRAY_SIZE (mips16_percent_op);
13279     }
13280   else
13281     {
13282       percent_op = mips_percent_op;
13283       limit = ARRAY_SIZE (mips_percent_op);
13284     }
13285
13286   for (i = 0; i < limit; i++)
13287     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
13288       {
13289         int len = strlen (percent_op[i].str);
13290
13291         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
13292           continue;
13293
13294         *str += strlen (percent_op[i].str);
13295         *reloc = percent_op[i].reloc;
13296
13297         /* Check whether the output BFD supports this relocation.
13298            If not, issue an error and fall back on something safe.  */
13299         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
13300           {
13301             as_bad (_("relocation %s isn't supported by the current ABI"),
13302                     percent_op[i].str);
13303             *reloc = BFD_RELOC_UNUSED;
13304           }
13305         return TRUE;
13306       }
13307   return FALSE;
13308 }
13309
13310
13311 /* Parse string STR as a 16-bit relocatable operand.  Store the
13312    expression in *EP and the relocations in the array starting
13313    at RELOC.  Return the number of relocation operators used.
13314
13315    On exit, EXPR_END points to the first character after the expression.  */
13316
13317 static size_t
13318 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
13319                        char *str)
13320 {
13321   bfd_reloc_code_real_type reversed_reloc[3];
13322   size_t reloc_index, i;
13323   int crux_depth, str_depth;
13324   char *crux;
13325
13326   /* Search for the start of the main expression, recoding relocations
13327      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
13328      of the main expression and with CRUX_DEPTH containing the number
13329      of open brackets at that point.  */
13330   reloc_index = -1;
13331   str_depth = 0;
13332   do
13333     {
13334       reloc_index++;
13335       crux = str;
13336       crux_depth = str_depth;
13337
13338       /* Skip over whitespace and brackets, keeping count of the number
13339          of brackets.  */
13340       while (*str == ' ' || *str == '\t' || *str == '(')
13341         if (*str++ == '(')
13342           str_depth++;
13343     }
13344   while (*str == '%'
13345          && reloc_index < (HAVE_NEWABI ? 3 : 1)
13346          && parse_relocation (&str, &reversed_reloc[reloc_index]));
13347
13348   my_getExpression (ep, crux);
13349   str = expr_end;
13350
13351   /* Match every open bracket.  */
13352   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
13353     if (*str++ == ')')
13354       crux_depth--;
13355
13356   if (crux_depth > 0)
13357     as_bad (_("unclosed '('"));
13358
13359   expr_end = str;
13360
13361   if (reloc_index != 0)
13362     {
13363       prev_reloc_op_frag = frag_now;
13364       for (i = 0; i < reloc_index; i++)
13365         reloc[i] = reversed_reloc[reloc_index - 1 - i];
13366     }
13367
13368   return reloc_index;
13369 }
13370
13371 static void
13372 my_getExpression (expressionS *ep, char *str)
13373 {
13374   char *save_in;
13375
13376   save_in = input_line_pointer;
13377   input_line_pointer = str;
13378   expression (ep);
13379   expr_end = input_line_pointer;
13380   input_line_pointer = save_in;
13381 }
13382
13383 char *
13384 md_atof (int type, char *litP, int *sizeP)
13385 {
13386   return ieee_md_atof (type, litP, sizeP, target_big_endian);
13387 }
13388
13389 void
13390 md_number_to_chars (char *buf, valueT val, int n)
13391 {
13392   if (target_big_endian)
13393     number_to_chars_bigendian (buf, val, n);
13394   else
13395     number_to_chars_littleendian (buf, val, n);
13396 }
13397 \f
13398 static int support_64bit_objects(void)
13399 {
13400   const char **list, **l;
13401   int yes;
13402
13403   list = bfd_target_list ();
13404   for (l = list; *l != NULL; l++)
13405     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
13406         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
13407       break;
13408   yes = (*l != NULL);
13409   free (list);
13410   return yes;
13411 }
13412
13413 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
13414    NEW_VALUE.  Warn if another value was already specified.  Note:
13415    we have to defer parsing the -march and -mtune arguments in order
13416    to handle 'from-abi' correctly, since the ABI might be specified
13417    in a later argument.  */
13418
13419 static void
13420 mips_set_option_string (const char **string_ptr, const char *new_value)
13421 {
13422   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
13423     as_warn (_("A different %s was already specified, is now %s"),
13424              string_ptr == &mips_arch_string ? "-march" : "-mtune",
13425              new_value);
13426
13427   *string_ptr = new_value;
13428 }
13429
13430 int
13431 md_parse_option (int c, char *arg)
13432 {
13433   unsigned int i;
13434
13435   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
13436     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
13437       {
13438         file_ase_explicit |= mips_set_ase (&mips_ases[i],
13439                                            c == mips_ases[i].option_on);
13440         return 1;
13441       }
13442
13443   switch (c)
13444     {
13445     case OPTION_CONSTRUCT_FLOATS:
13446       mips_disable_float_construction = 0;
13447       break;
13448
13449     case OPTION_NO_CONSTRUCT_FLOATS:
13450       mips_disable_float_construction = 1;
13451       break;
13452
13453     case OPTION_TRAP:
13454       mips_trap = 1;
13455       break;
13456
13457     case OPTION_BREAK:
13458       mips_trap = 0;
13459       break;
13460
13461     case OPTION_EB:
13462       target_big_endian = 1;
13463       break;
13464
13465     case OPTION_EL:
13466       target_big_endian = 0;
13467       break;
13468
13469     case 'O':
13470       if (arg == NULL)
13471         mips_optimize = 1;
13472       else if (arg[0] == '0')
13473         mips_optimize = 0;
13474       else if (arg[0] == '1')
13475         mips_optimize = 1;
13476       else
13477         mips_optimize = 2;
13478       break;
13479
13480     case 'g':
13481       if (arg == NULL)
13482         mips_debug = 2;
13483       else
13484         mips_debug = atoi (arg);
13485       break;
13486
13487     case OPTION_MIPS1:
13488       file_mips_isa = ISA_MIPS1;
13489       break;
13490
13491     case OPTION_MIPS2:
13492       file_mips_isa = ISA_MIPS2;
13493       break;
13494
13495     case OPTION_MIPS3:
13496       file_mips_isa = ISA_MIPS3;
13497       break;
13498
13499     case OPTION_MIPS4:
13500       file_mips_isa = ISA_MIPS4;
13501       break;
13502
13503     case OPTION_MIPS5:
13504       file_mips_isa = ISA_MIPS5;
13505       break;
13506
13507     case OPTION_MIPS32:
13508       file_mips_isa = ISA_MIPS32;
13509       break;
13510
13511     case OPTION_MIPS32R2:
13512       file_mips_isa = ISA_MIPS32R2;
13513       break;
13514
13515     case OPTION_MIPS64R2:
13516       file_mips_isa = ISA_MIPS64R2;
13517       break;
13518
13519     case OPTION_MIPS64:
13520       file_mips_isa = ISA_MIPS64;
13521       break;
13522
13523     case OPTION_MTUNE:
13524       mips_set_option_string (&mips_tune_string, arg);
13525       break;
13526
13527     case OPTION_MARCH:
13528       mips_set_option_string (&mips_arch_string, arg);
13529       break;
13530
13531     case OPTION_M4650:
13532       mips_set_option_string (&mips_arch_string, "4650");
13533       mips_set_option_string (&mips_tune_string, "4650");
13534       break;
13535
13536     case OPTION_NO_M4650:
13537       break;
13538
13539     case OPTION_M4010:
13540       mips_set_option_string (&mips_arch_string, "4010");
13541       mips_set_option_string (&mips_tune_string, "4010");
13542       break;
13543
13544     case OPTION_NO_M4010:
13545       break;
13546
13547     case OPTION_M4100:
13548       mips_set_option_string (&mips_arch_string, "4100");
13549       mips_set_option_string (&mips_tune_string, "4100");
13550       break;
13551
13552     case OPTION_NO_M4100:
13553       break;
13554
13555     case OPTION_M3900:
13556       mips_set_option_string (&mips_arch_string, "3900");
13557       mips_set_option_string (&mips_tune_string, "3900");
13558       break;
13559
13560     case OPTION_NO_M3900:
13561       break;
13562
13563     case OPTION_MICROMIPS:
13564       if (mips_opts.mips16 == 1)
13565         {
13566           as_bad (_("-mmicromips cannot be used with -mips16"));
13567           return 0;
13568         }
13569       mips_opts.micromips = 1;
13570       mips_no_prev_insn ();
13571       break;
13572
13573     case OPTION_NO_MICROMIPS:
13574       mips_opts.micromips = 0;
13575       mips_no_prev_insn ();
13576       break;
13577
13578     case OPTION_MIPS16:
13579       if (mips_opts.micromips == 1)
13580         {
13581           as_bad (_("-mips16 cannot be used with -micromips"));
13582           return 0;
13583         }
13584       mips_opts.mips16 = 1;
13585       mips_no_prev_insn ();
13586       break;
13587
13588     case OPTION_NO_MIPS16:
13589       mips_opts.mips16 = 0;
13590       mips_no_prev_insn ();
13591       break;
13592
13593     case OPTION_FIX_24K:
13594       mips_fix_24k = 1;
13595       break;
13596
13597     case OPTION_NO_FIX_24K:
13598       mips_fix_24k = 0;
13599       break;
13600
13601     case OPTION_FIX_LOONGSON2F_JUMP:
13602       mips_fix_loongson2f_jump = TRUE;
13603       break;
13604
13605     case OPTION_NO_FIX_LOONGSON2F_JUMP:
13606       mips_fix_loongson2f_jump = FALSE;
13607       break;
13608
13609     case OPTION_FIX_LOONGSON2F_NOP:
13610       mips_fix_loongson2f_nop = TRUE;
13611       break;
13612
13613     case OPTION_NO_FIX_LOONGSON2F_NOP:
13614       mips_fix_loongson2f_nop = FALSE;
13615       break;
13616
13617     case OPTION_FIX_VR4120:
13618       mips_fix_vr4120 = 1;
13619       break;
13620
13621     case OPTION_NO_FIX_VR4120:
13622       mips_fix_vr4120 = 0;
13623       break;
13624
13625     case OPTION_FIX_VR4130:
13626       mips_fix_vr4130 = 1;
13627       break;
13628
13629     case OPTION_NO_FIX_VR4130:
13630       mips_fix_vr4130 = 0;
13631       break;
13632
13633     case OPTION_FIX_CN63XXP1:
13634       mips_fix_cn63xxp1 = TRUE;
13635       break;
13636
13637     case OPTION_NO_FIX_CN63XXP1:
13638       mips_fix_cn63xxp1 = FALSE;
13639       break;
13640
13641     case OPTION_RELAX_BRANCH:
13642       mips_relax_branch = 1;
13643       break;
13644
13645     case OPTION_NO_RELAX_BRANCH:
13646       mips_relax_branch = 0;
13647       break;
13648
13649     case OPTION_INSN32:
13650       mips_opts.insn32 = TRUE;
13651       break;
13652
13653     case OPTION_NO_INSN32:
13654       mips_opts.insn32 = FALSE;
13655       break;
13656
13657     case OPTION_MSHARED:
13658       mips_in_shared = TRUE;
13659       break;
13660
13661     case OPTION_MNO_SHARED:
13662       mips_in_shared = FALSE;
13663       break;
13664
13665     case OPTION_MSYM32:
13666       mips_opts.sym32 = TRUE;
13667       break;
13668
13669     case OPTION_MNO_SYM32:
13670       mips_opts.sym32 = FALSE;
13671       break;
13672
13673       /* When generating ELF code, we permit -KPIC and -call_shared to
13674          select SVR4_PIC, and -non_shared to select no PIC.  This is
13675          intended to be compatible with Irix 5.  */
13676     case OPTION_CALL_SHARED:
13677       mips_pic = SVR4_PIC;
13678       mips_abicalls = TRUE;
13679       break;
13680
13681     case OPTION_CALL_NONPIC:
13682       mips_pic = NO_PIC;
13683       mips_abicalls = TRUE;
13684       break;
13685
13686     case OPTION_NON_SHARED:
13687       mips_pic = NO_PIC;
13688       mips_abicalls = FALSE;
13689       break;
13690
13691       /* The -xgot option tells the assembler to use 32 bit offsets
13692          when accessing the got in SVR4_PIC mode.  It is for Irix
13693          compatibility.  */
13694     case OPTION_XGOT:
13695       mips_big_got = 1;
13696       break;
13697
13698     case 'G':
13699       g_switch_value = atoi (arg);
13700       g_switch_seen = 1;
13701       break;
13702
13703       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
13704          and -mabi=64.  */
13705     case OPTION_32:
13706       mips_abi = O32_ABI;
13707       break;
13708
13709     case OPTION_N32:
13710       mips_abi = N32_ABI;
13711       break;
13712
13713     case OPTION_64:
13714       mips_abi = N64_ABI;
13715       if (!support_64bit_objects())
13716         as_fatal (_("No compiled in support for 64 bit object file format"));
13717       break;
13718
13719     case OPTION_GP32:
13720       file_mips_gp32 = 1;
13721       break;
13722
13723     case OPTION_GP64:
13724       file_mips_gp32 = 0;
13725       break;
13726
13727     case OPTION_FP32:
13728       file_mips_fp32 = 1;
13729       break;
13730
13731     case OPTION_FP64:
13732       file_mips_fp32 = 0;
13733       break;
13734
13735     case OPTION_SINGLE_FLOAT:
13736       file_mips_single_float = 1;
13737       break;
13738
13739     case OPTION_DOUBLE_FLOAT:
13740       file_mips_single_float = 0;
13741       break;
13742
13743     case OPTION_SOFT_FLOAT:
13744       file_mips_soft_float = 1;
13745       break;
13746
13747     case OPTION_HARD_FLOAT:
13748       file_mips_soft_float = 0;
13749       break;
13750
13751     case OPTION_MABI:
13752       if (strcmp (arg, "32") == 0)
13753         mips_abi = O32_ABI;
13754       else if (strcmp (arg, "o64") == 0)
13755         mips_abi = O64_ABI;
13756       else if (strcmp (arg, "n32") == 0)
13757         mips_abi = N32_ABI;
13758       else if (strcmp (arg, "64") == 0)
13759         {
13760           mips_abi = N64_ABI;
13761           if (! support_64bit_objects())
13762             as_fatal (_("No compiled in support for 64 bit object file "
13763                         "format"));
13764         }
13765       else if (strcmp (arg, "eabi") == 0)
13766         mips_abi = EABI_ABI;
13767       else
13768         {
13769           as_fatal (_("invalid abi -mabi=%s"), arg);
13770           return 0;
13771         }
13772       break;
13773
13774     case OPTION_M7000_HILO_FIX:
13775       mips_7000_hilo_fix = TRUE;
13776       break;
13777
13778     case OPTION_MNO_7000_HILO_FIX:
13779       mips_7000_hilo_fix = FALSE;
13780       break;
13781
13782     case OPTION_MDEBUG:
13783       mips_flag_mdebug = TRUE;
13784       break;
13785
13786     case OPTION_NO_MDEBUG:
13787       mips_flag_mdebug = FALSE;
13788       break;
13789
13790     case OPTION_PDR:
13791       mips_flag_pdr = TRUE;
13792       break;
13793
13794     case OPTION_NO_PDR:
13795       mips_flag_pdr = FALSE;
13796       break;
13797
13798     case OPTION_MVXWORKS_PIC:
13799       mips_pic = VXWORKS_PIC;
13800       break;
13801
13802     case OPTION_NAN:
13803       if (strcmp (arg, "2008") == 0)
13804         mips_flag_nan2008 = TRUE;
13805       else if (strcmp (arg, "legacy") == 0)
13806         mips_flag_nan2008 = FALSE;
13807       else
13808         {
13809           as_fatal (_("Invalid NaN setting -mnan=%s"), arg);
13810           return 0;
13811         }
13812       break;
13813
13814     default:
13815       return 0;
13816     }
13817
13818     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
13819
13820   return 1;
13821 }
13822 \f
13823 /* Set up globals to generate code for the ISA or processor
13824    described by INFO.  */
13825
13826 static void
13827 mips_set_architecture (const struct mips_cpu_info *info)
13828 {
13829   if (info != 0)
13830     {
13831       file_mips_arch = info->cpu;
13832       mips_opts.arch = info->cpu;
13833       mips_opts.isa = info->isa;
13834     }
13835 }
13836
13837
13838 /* Likewise for tuning.  */
13839
13840 static void
13841 mips_set_tune (const struct mips_cpu_info *info)
13842 {
13843   if (info != 0)
13844     mips_tune = info->cpu;
13845 }
13846
13847
13848 void
13849 mips_after_parse_args (void)
13850 {
13851   const struct mips_cpu_info *arch_info = 0;
13852   const struct mips_cpu_info *tune_info = 0;
13853
13854   /* GP relative stuff not working for PE */
13855   if (strncmp (TARGET_OS, "pe", 2) == 0)
13856     {
13857       if (g_switch_seen && g_switch_value != 0)
13858         as_bad (_("-G not supported in this configuration."));
13859       g_switch_value = 0;
13860     }
13861
13862   if (mips_abi == NO_ABI)
13863     mips_abi = MIPS_DEFAULT_ABI;
13864
13865   /* The following code determines the architecture and register size.
13866      Similar code was added to GCC 3.3 (see override_options() in
13867      config/mips/mips.c).  The GAS and GCC code should be kept in sync
13868      as much as possible.  */
13869
13870   if (mips_arch_string != 0)
13871     arch_info = mips_parse_cpu ("-march", mips_arch_string);
13872
13873   if (file_mips_isa != ISA_UNKNOWN)
13874     {
13875       /* Handle -mipsN.  At this point, file_mips_isa contains the
13876          ISA level specified by -mipsN, while arch_info->isa contains
13877          the -march selection (if any).  */
13878       if (arch_info != 0)
13879         {
13880           /* -march takes precedence over -mipsN, since it is more descriptive.
13881              There's no harm in specifying both as long as the ISA levels
13882              are the same.  */
13883           if (file_mips_isa != arch_info->isa)
13884             as_bad (_("-%s conflicts with the other architecture options, which imply -%s"),
13885                     mips_cpu_info_from_isa (file_mips_isa)->name,
13886                     mips_cpu_info_from_isa (arch_info->isa)->name);
13887         }
13888       else
13889         arch_info = mips_cpu_info_from_isa (file_mips_isa);
13890     }
13891
13892   if (arch_info == 0)
13893     {
13894       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
13895       gas_assert (arch_info);
13896     }
13897
13898   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
13899     as_bad (_("-march=%s is not compatible with the selected ABI"),
13900             arch_info->name);
13901
13902   mips_set_architecture (arch_info);
13903
13904   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
13905   if (mips_tune_string != 0)
13906     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
13907
13908   if (tune_info == 0)
13909     mips_set_tune (arch_info);
13910   else
13911     mips_set_tune (tune_info);
13912
13913   if (file_mips_gp32 >= 0)
13914     {
13915       /* The user specified the size of the integer registers.  Make sure
13916          it agrees with the ABI and ISA.  */
13917       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
13918         as_bad (_("-mgp64 used with a 32-bit processor"));
13919       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
13920         as_bad (_("-mgp32 used with a 64-bit ABI"));
13921       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
13922         as_bad (_("-mgp64 used with a 32-bit ABI"));
13923     }
13924   else
13925     {
13926       /* Infer the integer register size from the ABI and processor.
13927          Restrict ourselves to 32-bit registers if that's all the
13928          processor has, or if the ABI cannot handle 64-bit registers.  */
13929       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
13930                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
13931     }
13932
13933   switch (file_mips_fp32)
13934     {
13935     default:
13936     case -1:
13937       /* No user specified float register size.
13938          ??? GAS treats single-float processors as though they had 64-bit
13939          float registers (although it complains when double-precision
13940          instructions are used).  As things stand, saying they have 32-bit
13941          registers would lead to spurious "register must be even" messages.
13942          So here we assume float registers are never smaller than the
13943          integer ones.  */
13944       if (file_mips_gp32 == 0)
13945         /* 64-bit integer registers implies 64-bit float registers.  */
13946         file_mips_fp32 = 0;
13947       else if ((mips_opts.ase & FP64_ASES)
13948                && ISA_HAS_64BIT_FPRS (mips_opts.isa))
13949         /* -mips3d and -mdmx imply 64-bit float registers, if possible.  */
13950         file_mips_fp32 = 0;
13951       else
13952         /* 32-bit float registers.  */
13953         file_mips_fp32 = 1;
13954       break;
13955
13956     /* The user specified the size of the float registers.  Check if it
13957        agrees with the ABI and ISA.  */
13958     case 0:
13959       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
13960         as_bad (_("-mfp64 used with a 32-bit fpu"));
13961       else if (ABI_NEEDS_32BIT_REGS (mips_abi)
13962                && !ISA_HAS_MXHC1 (mips_opts.isa))
13963         as_warn (_("-mfp64 used with a 32-bit ABI"));
13964       break;
13965     case 1:
13966       if (ABI_NEEDS_64BIT_REGS (mips_abi))
13967         as_warn (_("-mfp32 used with a 64-bit ABI"));
13968       break;
13969     }
13970
13971   /* End of GCC-shared inference code.  */
13972
13973   /* This flag is set when we have a 64-bit capable CPU but use only
13974      32-bit wide registers.  Note that EABI does not use it.  */
13975   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
13976       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
13977           || mips_abi == O32_ABI))
13978     mips_32bitmode = 1;
13979
13980   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
13981     as_bad (_("trap exception not supported at ISA 1"));
13982
13983   /* If the selected architecture includes support for ASEs, enable
13984      generation of code for them.  */
13985   if (mips_opts.mips16 == -1)
13986     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
13987   if (mips_opts.micromips == -1)
13988     mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_arch)) ? 1 : 0;
13989
13990   /* MIPS3D and MDMX require 64-bit FPRs, so -mfp32 should stop those
13991      ASEs from being selected implicitly.  */
13992   if (file_mips_fp32 == 1)
13993     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX;
13994
13995   /* If the user didn't explicitly select or deselect a particular ASE,
13996      use the default setting for the CPU.  */
13997   mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
13998
13999   file_mips_isa = mips_opts.isa;
14000   file_ase = mips_opts.ase;
14001   mips_opts.gp32 = file_mips_gp32;
14002   mips_opts.fp32 = file_mips_fp32;
14003   mips_opts.soft_float = file_mips_soft_float;
14004   mips_opts.single_float = file_mips_single_float;
14005
14006   mips_check_isa_supports_ases ();
14007
14008   if (mips_flag_mdebug < 0)
14009     mips_flag_mdebug = 0;
14010 }
14011 \f
14012 void
14013 mips_init_after_args (void)
14014 {
14015   /* initialize opcodes */
14016   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
14017   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
14018 }
14019
14020 long
14021 md_pcrel_from (fixS *fixP)
14022 {
14023   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
14024   switch (fixP->fx_r_type)
14025     {
14026     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14027     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14028       /* Return the address of the delay slot.  */
14029       return addr + 2;
14030
14031     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14032     case BFD_RELOC_MICROMIPS_JMP:
14033     case BFD_RELOC_16_PCREL_S2:
14034     case BFD_RELOC_MIPS_JMP:
14035       /* Return the address of the delay slot.  */
14036       return addr + 4;
14037
14038     case BFD_RELOC_32_PCREL:
14039       return addr;
14040
14041     default:
14042       /* We have no relocation type for PC relative MIPS16 instructions.  */
14043       if (fixP->fx_addsy && S_GET_SEGMENT (fixP->fx_addsy) != now_seg)
14044         as_bad_where (fixP->fx_file, fixP->fx_line,
14045                       _("PC relative MIPS16 instruction references a different section"));
14046       return addr;
14047     }
14048 }
14049
14050 /* This is called before the symbol table is processed.  In order to
14051    work with gcc when using mips-tfile, we must keep all local labels.
14052    However, in other cases, we want to discard them.  If we were
14053    called with -g, but we didn't see any debugging information, it may
14054    mean that gcc is smuggling debugging information through to
14055    mips-tfile, in which case we must generate all local labels.  */
14056
14057 void
14058 mips_frob_file_before_adjust (void)
14059 {
14060 #ifndef NO_ECOFF_DEBUGGING
14061   if (ECOFF_DEBUGGING
14062       && mips_debug != 0
14063       && ! ecoff_debugging_seen)
14064     flag_keep_locals = 1;
14065 #endif
14066 }
14067
14068 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
14069    the corresponding LO16 reloc.  This is called before md_apply_fix and
14070    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
14071    relocation operators.
14072
14073    For our purposes, a %lo() expression matches a %got() or %hi()
14074    expression if:
14075
14076       (a) it refers to the same symbol; and
14077       (b) the offset applied in the %lo() expression is no lower than
14078           the offset applied in the %got() or %hi().
14079
14080    (b) allows us to cope with code like:
14081
14082         lui     $4,%hi(foo)
14083         lh      $4,%lo(foo+2)($4)
14084
14085    ...which is legal on RELA targets, and has a well-defined behaviour
14086    if the user knows that adding 2 to "foo" will not induce a carry to
14087    the high 16 bits.
14088
14089    When several %lo()s match a particular %got() or %hi(), we use the
14090    following rules to distinguish them:
14091
14092      (1) %lo()s with smaller offsets are a better match than %lo()s with
14093          higher offsets.
14094
14095      (2) %lo()s with no matching %got() or %hi() are better than those
14096          that already have a matching %got() or %hi().
14097
14098      (3) later %lo()s are better than earlier %lo()s.
14099
14100    These rules are applied in order.
14101
14102    (1) means, among other things, that %lo()s with identical offsets are
14103    chosen if they exist.
14104
14105    (2) means that we won't associate several high-part relocations with
14106    the same low-part relocation unless there's no alternative.  Having
14107    several high parts for the same low part is a GNU extension; this rule
14108    allows careful users to avoid it.
14109
14110    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
14111    with the last high-part relocation being at the front of the list.
14112    It therefore makes sense to choose the last matching low-part
14113    relocation, all other things being equal.  It's also easier
14114    to code that way.  */
14115
14116 void
14117 mips_frob_file (void)
14118 {
14119   struct mips_hi_fixup *l;
14120   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
14121
14122   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
14123     {
14124       segment_info_type *seginfo;
14125       bfd_boolean matched_lo_p;
14126       fixS **hi_pos, **lo_pos, **pos;
14127
14128       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
14129
14130       /* If a GOT16 relocation turns out to be against a global symbol,
14131          there isn't supposed to be a matching LO.  Ignore %gots against
14132          constants; we'll report an error for those later.  */
14133       if (got16_reloc_p (l->fixp->fx_r_type)
14134           && !(l->fixp->fx_addsy
14135                && pic_need_relax (l->fixp->fx_addsy, l->seg)))
14136         continue;
14137
14138       /* Check quickly whether the next fixup happens to be a matching %lo.  */
14139       if (fixup_has_matching_lo_p (l->fixp))
14140         continue;
14141
14142       seginfo = seg_info (l->seg);
14143
14144       /* Set HI_POS to the position of this relocation in the chain.
14145          Set LO_POS to the position of the chosen low-part relocation.
14146          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
14147          relocation that matches an immediately-preceding high-part
14148          relocation.  */
14149       hi_pos = NULL;
14150       lo_pos = NULL;
14151       matched_lo_p = FALSE;
14152       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
14153
14154       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
14155         {
14156           if (*pos == l->fixp)
14157             hi_pos = pos;
14158
14159           if ((*pos)->fx_r_type == looking_for_rtype
14160               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
14161               && (*pos)->fx_offset >= l->fixp->fx_offset
14162               && (lo_pos == NULL
14163                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
14164                   || (!matched_lo_p
14165                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
14166             lo_pos = pos;
14167
14168           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
14169                           && fixup_has_matching_lo_p (*pos));
14170         }
14171
14172       /* If we found a match, remove the high-part relocation from its
14173          current position and insert it before the low-part relocation.
14174          Make the offsets match so that fixup_has_matching_lo_p()
14175          will return true.
14176
14177          We don't warn about unmatched high-part relocations since some
14178          versions of gcc have been known to emit dead "lui ...%hi(...)"
14179          instructions.  */
14180       if (lo_pos != NULL)
14181         {
14182           l->fixp->fx_offset = (*lo_pos)->fx_offset;
14183           if (l->fixp->fx_next != *lo_pos)
14184             {
14185               *hi_pos = l->fixp->fx_next;
14186               l->fixp->fx_next = *lo_pos;
14187               *lo_pos = l->fixp;
14188             }
14189         }
14190     }
14191 }
14192
14193 int
14194 mips_force_relocation (fixS *fixp)
14195 {
14196   if (generic_force_reloc (fixp))
14197     return 1;
14198
14199   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
14200      so that the linker relaxation can update targets.  */
14201   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
14202       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
14203       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
14204     return 1;
14205
14206   return 0;
14207 }
14208
14209 /* Read the instruction associated with RELOC from BUF.  */
14210
14211 static unsigned int
14212 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
14213 {
14214   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14215     return read_compressed_insn (buf, 4);
14216   else
14217     return read_insn (buf);
14218 }
14219
14220 /* Write instruction INSN to BUF, given that it has been relocated
14221    by RELOC.  */
14222
14223 static void
14224 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
14225                   unsigned long insn)
14226 {
14227   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14228     write_compressed_insn (buf, insn, 4);
14229   else
14230     write_insn (buf, insn);
14231 }
14232
14233 /* Apply a fixup to the object file.  */
14234
14235 void
14236 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
14237 {
14238   char *buf;
14239   unsigned long insn;
14240   reloc_howto_type *howto;
14241
14242   /* We ignore generic BFD relocations we don't know about.  */
14243   howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
14244   if (! howto)
14245     return;
14246
14247   gas_assert (fixP->fx_size == 2
14248               || fixP->fx_size == 4
14249               || fixP->fx_r_type == BFD_RELOC_16
14250               || fixP->fx_r_type == BFD_RELOC_64
14251               || fixP->fx_r_type == BFD_RELOC_CTOR
14252               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
14253               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
14254               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
14255               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
14256               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
14257
14258   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
14259
14260   gas_assert (!fixP->fx_pcrel || fixP->fx_r_type == BFD_RELOC_16_PCREL_S2
14261               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
14262               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
14263               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
14264               || fixP->fx_r_type == BFD_RELOC_32_PCREL);
14265
14266   /* Don't treat parts of a composite relocation as done.  There are two
14267      reasons for this:
14268
14269      (1) The second and third parts will be against 0 (RSS_UNDEF) but
14270          should nevertheless be emitted if the first part is.
14271
14272      (2) In normal usage, composite relocations are never assembly-time
14273          constants.  The easiest way of dealing with the pathological
14274          exceptions is to generate a relocation against STN_UNDEF and
14275          leave everything up to the linker.  */
14276   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
14277     fixP->fx_done = 1;
14278
14279   switch (fixP->fx_r_type)
14280     {
14281     case BFD_RELOC_MIPS_TLS_GD:
14282     case BFD_RELOC_MIPS_TLS_LDM:
14283     case BFD_RELOC_MIPS_TLS_DTPREL32:
14284     case BFD_RELOC_MIPS_TLS_DTPREL64:
14285     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
14286     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
14287     case BFD_RELOC_MIPS_TLS_GOTTPREL:
14288     case BFD_RELOC_MIPS_TLS_TPREL32:
14289     case BFD_RELOC_MIPS_TLS_TPREL64:
14290     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
14291     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
14292     case BFD_RELOC_MICROMIPS_TLS_GD:
14293     case BFD_RELOC_MICROMIPS_TLS_LDM:
14294     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
14295     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
14296     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
14297     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
14298     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
14299     case BFD_RELOC_MIPS16_TLS_GD:
14300     case BFD_RELOC_MIPS16_TLS_LDM:
14301     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
14302     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
14303     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
14304     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
14305     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
14306       if (!fixP->fx_addsy)
14307         {
14308           as_bad_where (fixP->fx_file, fixP->fx_line,
14309                         _("TLS relocation against a constant"));
14310           break;
14311         }
14312       S_SET_THREAD_LOCAL (fixP->fx_addsy);
14313       /* fall through */
14314
14315     case BFD_RELOC_MIPS_JMP:
14316     case BFD_RELOC_MIPS_SHIFT5:
14317     case BFD_RELOC_MIPS_SHIFT6:
14318     case BFD_RELOC_MIPS_GOT_DISP:
14319     case BFD_RELOC_MIPS_GOT_PAGE:
14320     case BFD_RELOC_MIPS_GOT_OFST:
14321     case BFD_RELOC_MIPS_SUB:
14322     case BFD_RELOC_MIPS_INSERT_A:
14323     case BFD_RELOC_MIPS_INSERT_B:
14324     case BFD_RELOC_MIPS_DELETE:
14325     case BFD_RELOC_MIPS_HIGHEST:
14326     case BFD_RELOC_MIPS_HIGHER:
14327     case BFD_RELOC_MIPS_SCN_DISP:
14328     case BFD_RELOC_MIPS_REL16:
14329     case BFD_RELOC_MIPS_RELGOT:
14330     case BFD_RELOC_MIPS_JALR:
14331     case BFD_RELOC_HI16:
14332     case BFD_RELOC_HI16_S:
14333     case BFD_RELOC_LO16:
14334     case BFD_RELOC_GPREL16:
14335     case BFD_RELOC_MIPS_LITERAL:
14336     case BFD_RELOC_MIPS_CALL16:
14337     case BFD_RELOC_MIPS_GOT16:
14338     case BFD_RELOC_GPREL32:
14339     case BFD_RELOC_MIPS_GOT_HI16:
14340     case BFD_RELOC_MIPS_GOT_LO16:
14341     case BFD_RELOC_MIPS_CALL_HI16:
14342     case BFD_RELOC_MIPS_CALL_LO16:
14343     case BFD_RELOC_MIPS16_GPREL:
14344     case BFD_RELOC_MIPS16_GOT16:
14345     case BFD_RELOC_MIPS16_CALL16:
14346     case BFD_RELOC_MIPS16_HI16:
14347     case BFD_RELOC_MIPS16_HI16_S:
14348     case BFD_RELOC_MIPS16_LO16:
14349     case BFD_RELOC_MIPS16_JMP:
14350     case BFD_RELOC_MICROMIPS_JMP:
14351     case BFD_RELOC_MICROMIPS_GOT_DISP:
14352     case BFD_RELOC_MICROMIPS_GOT_PAGE:
14353     case BFD_RELOC_MICROMIPS_GOT_OFST:
14354     case BFD_RELOC_MICROMIPS_SUB:
14355     case BFD_RELOC_MICROMIPS_HIGHEST:
14356     case BFD_RELOC_MICROMIPS_HIGHER:
14357     case BFD_RELOC_MICROMIPS_SCN_DISP:
14358     case BFD_RELOC_MICROMIPS_JALR:
14359     case BFD_RELOC_MICROMIPS_HI16:
14360     case BFD_RELOC_MICROMIPS_HI16_S:
14361     case BFD_RELOC_MICROMIPS_LO16:
14362     case BFD_RELOC_MICROMIPS_GPREL16:
14363     case BFD_RELOC_MICROMIPS_LITERAL:
14364     case BFD_RELOC_MICROMIPS_CALL16:
14365     case BFD_RELOC_MICROMIPS_GOT16:
14366     case BFD_RELOC_MICROMIPS_GOT_HI16:
14367     case BFD_RELOC_MICROMIPS_GOT_LO16:
14368     case BFD_RELOC_MICROMIPS_CALL_HI16:
14369     case BFD_RELOC_MICROMIPS_CALL_LO16:
14370     case BFD_RELOC_MIPS_EH:
14371       if (fixP->fx_done)
14372         {
14373           offsetT value;
14374
14375           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
14376             {
14377               insn = read_reloc_insn (buf, fixP->fx_r_type);
14378               if (mips16_reloc_p (fixP->fx_r_type))
14379                 insn |= mips16_immed_extend (value, 16);
14380               else
14381                 insn |= (value & 0xffff);
14382               write_reloc_insn (buf, fixP->fx_r_type, insn);
14383             }
14384           else
14385             as_bad_where (fixP->fx_file, fixP->fx_line,
14386                           _("Unsupported constant in relocation"));
14387         }
14388       break;
14389
14390     case BFD_RELOC_64:
14391       /* This is handled like BFD_RELOC_32, but we output a sign
14392          extended value if we are only 32 bits.  */
14393       if (fixP->fx_done)
14394         {
14395           if (8 <= sizeof (valueT))
14396             md_number_to_chars (buf, *valP, 8);
14397           else
14398             {
14399               valueT hiv;
14400
14401               if ((*valP & 0x80000000) != 0)
14402                 hiv = 0xffffffff;
14403               else
14404                 hiv = 0;
14405               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
14406               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
14407             }
14408         }
14409       break;
14410
14411     case BFD_RELOC_RVA:
14412     case BFD_RELOC_32:
14413     case BFD_RELOC_32_PCREL:
14414     case BFD_RELOC_16:
14415       /* If we are deleting this reloc entry, we must fill in the
14416          value now.  This can happen if we have a .word which is not
14417          resolved when it appears but is later defined.  */
14418       if (fixP->fx_done)
14419         md_number_to_chars (buf, *valP, fixP->fx_size);
14420       break;
14421
14422     case BFD_RELOC_16_PCREL_S2:
14423       if ((*valP & 0x3) != 0)
14424         as_bad_where (fixP->fx_file, fixP->fx_line,
14425                       _("Branch to misaligned address (%lx)"), (long) *valP);
14426
14427       /* We need to save the bits in the instruction since fixup_segment()
14428          might be deleting the relocation entry (i.e., a branch within
14429          the current segment).  */
14430       if (! fixP->fx_done)
14431         break;
14432
14433       /* Update old instruction data.  */
14434       insn = read_insn (buf);
14435
14436       if (*valP + 0x20000 <= 0x3ffff)
14437         {
14438           insn |= (*valP >> 2) & 0xffff;
14439           write_insn (buf, insn);
14440         }
14441       else if (mips_pic == NO_PIC
14442                && fixP->fx_done
14443                && fixP->fx_frag->fr_address >= text_section->vma
14444                && (fixP->fx_frag->fr_address
14445                    < text_section->vma + bfd_get_section_size (text_section))
14446                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
14447                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
14448                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
14449         {
14450           /* The branch offset is too large.  If this is an
14451              unconditional branch, and we are not generating PIC code,
14452              we can convert it to an absolute jump instruction.  */
14453           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
14454             insn = 0x0c000000;  /* jal */
14455           else
14456             insn = 0x08000000;  /* j */
14457           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
14458           fixP->fx_done = 0;
14459           fixP->fx_addsy = section_symbol (text_section);
14460           *valP += md_pcrel_from (fixP);
14461           write_insn (buf, insn);
14462         }
14463       else
14464         {
14465           /* If we got here, we have branch-relaxation disabled,
14466              and there's nothing we can do to fix this instruction
14467              without turning it into a longer sequence.  */
14468           as_bad_where (fixP->fx_file, fixP->fx_line,
14469                         _("Branch out of range"));
14470         }
14471       break;
14472
14473     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14474     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14475     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14476       /* We adjust the offset back to even.  */
14477       if ((*valP & 0x1) != 0)
14478         --(*valP);
14479
14480       if (! fixP->fx_done)
14481         break;
14482
14483       /* Should never visit here, because we keep the relocation.  */
14484       abort ();
14485       break;
14486
14487     case BFD_RELOC_VTABLE_INHERIT:
14488       fixP->fx_done = 0;
14489       if (fixP->fx_addsy
14490           && !S_IS_DEFINED (fixP->fx_addsy)
14491           && !S_IS_WEAK (fixP->fx_addsy))
14492         S_SET_WEAK (fixP->fx_addsy);
14493       break;
14494
14495     case BFD_RELOC_VTABLE_ENTRY:
14496       fixP->fx_done = 0;
14497       break;
14498
14499     default:
14500       abort ();
14501     }
14502
14503   /* Remember value for tc_gen_reloc.  */
14504   fixP->fx_addnumber = *valP;
14505 }
14506
14507 static symbolS *
14508 get_symbol (void)
14509 {
14510   int c;
14511   char *name;
14512   symbolS *p;
14513
14514   name = input_line_pointer;
14515   c = get_symbol_end ();
14516   p = (symbolS *) symbol_find_or_make (name);
14517   *input_line_pointer = c;
14518   return p;
14519 }
14520
14521 /* Align the current frag to a given power of two.  If a particular
14522    fill byte should be used, FILL points to an integer that contains
14523    that byte, otherwise FILL is null.
14524
14525    This function used to have the comment:
14526
14527       The MIPS assembler also automatically adjusts any preceding label.
14528
14529    The implementation therefore applied the adjustment to a maximum of
14530    one label.  However, other label adjustments are applied to batches
14531    of labels, and adjusting just one caused problems when new labels
14532    were added for the sake of debugging or unwind information.
14533    We therefore adjust all preceding labels (given as LABELS) instead.  */
14534
14535 static void
14536 mips_align (int to, int *fill, struct insn_label_list *labels)
14537 {
14538   mips_emit_delays ();
14539   mips_record_compressed_mode ();
14540   if (fill == NULL && subseg_text_p (now_seg))
14541     frag_align_code (to, 0);
14542   else
14543     frag_align (to, fill ? *fill : 0, 0);
14544   record_alignment (now_seg, to);
14545   mips_move_labels (labels, FALSE);
14546 }
14547
14548 /* Align to a given power of two.  .align 0 turns off the automatic
14549    alignment used by the data creating pseudo-ops.  */
14550
14551 static void
14552 s_align (int x ATTRIBUTE_UNUSED)
14553 {
14554   int temp, fill_value, *fill_ptr;
14555   long max_alignment = 28;
14556
14557   /* o Note that the assembler pulls down any immediately preceding label
14558        to the aligned address.
14559      o It's not documented but auto alignment is reinstated by
14560        a .align pseudo instruction.
14561      o Note also that after auto alignment is turned off the mips assembler
14562        issues an error on attempt to assemble an improperly aligned data item.
14563        We don't.  */
14564
14565   temp = get_absolute_expression ();
14566   if (temp > max_alignment)
14567     as_bad (_("Alignment too large: %d. assumed."), temp = max_alignment);
14568   else if (temp < 0)
14569     {
14570       as_warn (_("Alignment negative: 0 assumed."));
14571       temp = 0;
14572     }
14573   if (*input_line_pointer == ',')
14574     {
14575       ++input_line_pointer;
14576       fill_value = get_absolute_expression ();
14577       fill_ptr = &fill_value;
14578     }
14579   else
14580     fill_ptr = 0;
14581   if (temp)
14582     {
14583       segment_info_type *si = seg_info (now_seg);
14584       struct insn_label_list *l = si->label_list;
14585       /* Auto alignment should be switched on by next section change.  */
14586       auto_align = 1;
14587       mips_align (temp, fill_ptr, l);
14588     }
14589   else
14590     {
14591       auto_align = 0;
14592     }
14593
14594   demand_empty_rest_of_line ();
14595 }
14596
14597 static void
14598 s_change_sec (int sec)
14599 {
14600   segT seg;
14601
14602   /* The ELF backend needs to know that we are changing sections, so
14603      that .previous works correctly.  We could do something like check
14604      for an obj_section_change_hook macro, but that might be confusing
14605      as it would not be appropriate to use it in the section changing
14606      functions in read.c, since obj-elf.c intercepts those.  FIXME:
14607      This should be cleaner, somehow.  */
14608   obj_elf_section_change_hook ();
14609
14610   mips_emit_delays ();
14611
14612   switch (sec)
14613     {
14614     case 't':
14615       s_text (0);
14616       break;
14617     case 'd':
14618       s_data (0);
14619       break;
14620     case 'b':
14621       subseg_set (bss_section, (subsegT) get_absolute_expression ());
14622       demand_empty_rest_of_line ();
14623       break;
14624
14625     case 'r':
14626       seg = subseg_new (RDATA_SECTION_NAME,
14627                         (subsegT) get_absolute_expression ());
14628       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
14629                                               | SEC_READONLY | SEC_RELOC
14630                                               | SEC_DATA));
14631       if (strncmp (TARGET_OS, "elf", 3) != 0)
14632         record_alignment (seg, 4);
14633       demand_empty_rest_of_line ();
14634       break;
14635
14636     case 's':
14637       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
14638       bfd_set_section_flags (stdoutput, seg,
14639                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
14640       if (strncmp (TARGET_OS, "elf", 3) != 0)
14641         record_alignment (seg, 4);
14642       demand_empty_rest_of_line ();
14643       break;
14644
14645     case 'B':
14646       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
14647       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
14648       if (strncmp (TARGET_OS, "elf", 3) != 0)
14649         record_alignment (seg, 4);
14650       demand_empty_rest_of_line ();
14651       break;
14652     }
14653
14654   auto_align = 1;
14655 }
14656
14657 void
14658 s_change_section (int ignore ATTRIBUTE_UNUSED)
14659 {
14660   char *section_name;
14661   char c;
14662   char next_c = 0;
14663   int section_type;
14664   int section_flag;
14665   int section_entry_size;
14666   int section_alignment;
14667
14668   section_name = input_line_pointer;
14669   c = get_symbol_end ();
14670   if (c)
14671     next_c = *(input_line_pointer + 1);
14672
14673   /* Do we have .section Name<,"flags">?  */
14674   if (c != ',' || (c == ',' && next_c == '"'))
14675     {
14676       /* just after name is now '\0'.  */
14677       *input_line_pointer = c;
14678       input_line_pointer = section_name;
14679       obj_elf_section (ignore);
14680       return;
14681     }
14682   input_line_pointer++;
14683
14684   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
14685   if (c == ',')
14686     section_type = get_absolute_expression ();
14687   else
14688     section_type = 0;
14689   if (*input_line_pointer++ == ',')
14690     section_flag = get_absolute_expression ();
14691   else
14692     section_flag = 0;
14693   if (*input_line_pointer++ == ',')
14694     section_entry_size = get_absolute_expression ();
14695   else
14696     section_entry_size = 0;
14697   if (*input_line_pointer++ == ',')
14698     section_alignment = get_absolute_expression ();
14699   else
14700     section_alignment = 0;
14701   /* FIXME: really ignore?  */
14702   (void) section_alignment;
14703
14704   section_name = xstrdup (section_name);
14705
14706   /* When using the generic form of .section (as implemented by obj-elf.c),
14707      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
14708      traditionally had to fall back on the more common @progbits instead.
14709
14710      There's nothing really harmful in this, since bfd will correct
14711      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
14712      means that, for backwards compatibility, the special_section entries
14713      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
14714
14715      Even so, we shouldn't force users of the MIPS .section syntax to
14716      incorrectly label the sections as SHT_PROGBITS.  The best compromise
14717      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
14718      generic type-checking code.  */
14719   if (section_type == SHT_MIPS_DWARF)
14720     section_type = SHT_PROGBITS;
14721
14722   obj_elf_change_section (section_name, section_type, section_flag,
14723                           section_entry_size, 0, 0, 0);
14724
14725   if (now_seg->name != section_name)
14726     free (section_name);
14727 }
14728
14729 void
14730 mips_enable_auto_align (void)
14731 {
14732   auto_align = 1;
14733 }
14734
14735 static void
14736 s_cons (int log_size)
14737 {
14738   segment_info_type *si = seg_info (now_seg);
14739   struct insn_label_list *l = si->label_list;
14740
14741   mips_emit_delays ();
14742   if (log_size > 0 && auto_align)
14743     mips_align (log_size, 0, l);
14744   cons (1 << log_size);
14745   mips_clear_insn_labels ();
14746 }
14747
14748 static void
14749 s_float_cons (int type)
14750 {
14751   segment_info_type *si = seg_info (now_seg);
14752   struct insn_label_list *l = si->label_list;
14753
14754   mips_emit_delays ();
14755
14756   if (auto_align)
14757     {
14758       if (type == 'd')
14759         mips_align (3, 0, l);
14760       else
14761         mips_align (2, 0, l);
14762     }
14763
14764   float_cons (type);
14765   mips_clear_insn_labels ();
14766 }
14767
14768 /* Handle .globl.  We need to override it because on Irix 5 you are
14769    permitted to say
14770        .globl foo .text
14771    where foo is an undefined symbol, to mean that foo should be
14772    considered to be the address of a function.  */
14773
14774 static void
14775 s_mips_globl (int x ATTRIBUTE_UNUSED)
14776 {
14777   char *name;
14778   int c;
14779   symbolS *symbolP;
14780   flagword flag;
14781
14782   do
14783     {
14784       name = input_line_pointer;
14785       c = get_symbol_end ();
14786       symbolP = symbol_find_or_make (name);
14787       S_SET_EXTERNAL (symbolP);
14788
14789       *input_line_pointer = c;
14790       SKIP_WHITESPACE ();
14791
14792       /* On Irix 5, every global symbol that is not explicitly labelled as
14793          being a function is apparently labelled as being an object.  */
14794       flag = BSF_OBJECT;
14795
14796       if (!is_end_of_line[(unsigned char) *input_line_pointer]
14797           && (*input_line_pointer != ','))
14798         {
14799           char *secname;
14800           asection *sec;
14801
14802           secname = input_line_pointer;
14803           c = get_symbol_end ();
14804           sec = bfd_get_section_by_name (stdoutput, secname);
14805           if (sec == NULL)
14806             as_bad (_("%s: no such section"), secname);
14807           *input_line_pointer = c;
14808
14809           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
14810             flag = BSF_FUNCTION;
14811         }
14812
14813       symbol_get_bfdsym (symbolP)->flags |= flag;
14814
14815       c = *input_line_pointer;
14816       if (c == ',')
14817         {
14818           input_line_pointer++;
14819           SKIP_WHITESPACE ();
14820           if (is_end_of_line[(unsigned char) *input_line_pointer])
14821             c = '\n';
14822         }
14823     }
14824   while (c == ',');
14825
14826   demand_empty_rest_of_line ();
14827 }
14828
14829 static void
14830 s_option (int x ATTRIBUTE_UNUSED)
14831 {
14832   char *opt;
14833   char c;
14834
14835   opt = input_line_pointer;
14836   c = get_symbol_end ();
14837
14838   if (*opt == 'O')
14839     {
14840       /* FIXME: What does this mean?  */
14841     }
14842   else if (strncmp (opt, "pic", 3) == 0)
14843     {
14844       int i;
14845
14846       i = atoi (opt + 3);
14847       if (i == 0)
14848         mips_pic = NO_PIC;
14849       else if (i == 2)
14850         {
14851           mips_pic = SVR4_PIC;
14852           mips_abicalls = TRUE;
14853         }
14854       else
14855         as_bad (_(".option pic%d not supported"), i);
14856
14857       if (mips_pic == SVR4_PIC)
14858         {
14859           if (g_switch_seen && g_switch_value != 0)
14860             as_warn (_("-G may not be used with SVR4 PIC code"));
14861           g_switch_value = 0;
14862           bfd_set_gp_size (stdoutput, 0);
14863         }
14864     }
14865   else
14866     as_warn (_("Unrecognized option \"%s\""), opt);
14867
14868   *input_line_pointer = c;
14869   demand_empty_rest_of_line ();
14870 }
14871
14872 /* This structure is used to hold a stack of .set values.  */
14873
14874 struct mips_option_stack
14875 {
14876   struct mips_option_stack *next;
14877   struct mips_set_options options;
14878 };
14879
14880 static struct mips_option_stack *mips_opts_stack;
14881
14882 /* Handle the .set pseudo-op.  */
14883
14884 static void
14885 s_mipsset (int x ATTRIBUTE_UNUSED)
14886 {
14887   char *name = input_line_pointer, ch;
14888   const struct mips_ase *ase;
14889
14890   while (!is_end_of_line[(unsigned char) *input_line_pointer])
14891     ++input_line_pointer;
14892   ch = *input_line_pointer;
14893   *input_line_pointer = '\0';
14894
14895   if (strcmp (name, "reorder") == 0)
14896     {
14897       if (mips_opts.noreorder)
14898         end_noreorder ();
14899     }
14900   else if (strcmp (name, "noreorder") == 0)
14901     {
14902       if (!mips_opts.noreorder)
14903         start_noreorder ();
14904     }
14905   else if (strncmp (name, "at=", 3) == 0)
14906     {
14907       char *s = name + 3;
14908
14909       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
14910         as_bad (_("Unrecognized register name `%s'"), s);
14911     }
14912   else if (strcmp (name, "at") == 0)
14913     {
14914       mips_opts.at = ATREG;
14915     }
14916   else if (strcmp (name, "noat") == 0)
14917     {
14918       mips_opts.at = ZERO;
14919     }
14920   else if (strcmp (name, "macro") == 0)
14921     {
14922       mips_opts.warn_about_macros = 0;
14923     }
14924   else if (strcmp (name, "nomacro") == 0)
14925     {
14926       if (mips_opts.noreorder == 0)
14927         as_bad (_("`noreorder' must be set before `nomacro'"));
14928       mips_opts.warn_about_macros = 1;
14929     }
14930   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
14931     {
14932       mips_opts.nomove = 0;
14933     }
14934   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
14935     {
14936       mips_opts.nomove = 1;
14937     }
14938   else if (strcmp (name, "bopt") == 0)
14939     {
14940       mips_opts.nobopt = 0;
14941     }
14942   else if (strcmp (name, "nobopt") == 0)
14943     {
14944       mips_opts.nobopt = 1;
14945     }
14946   else if (strcmp (name, "gp=default") == 0)
14947     mips_opts.gp32 = file_mips_gp32;
14948   else if (strcmp (name, "gp=32") == 0)
14949     mips_opts.gp32 = 1;
14950   else if (strcmp (name, "gp=64") == 0)
14951     {
14952       if (!ISA_HAS_64BIT_REGS (mips_opts.isa))
14953         as_warn (_("%s isa does not support 64-bit registers"),
14954                  mips_cpu_info_from_isa (mips_opts.isa)->name);
14955       mips_opts.gp32 = 0;
14956     }
14957   else if (strcmp (name, "fp=default") == 0)
14958     mips_opts.fp32 = file_mips_fp32;
14959   else if (strcmp (name, "fp=32") == 0)
14960     mips_opts.fp32 = 1;
14961   else if (strcmp (name, "fp=64") == 0)
14962     {
14963       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
14964         as_warn (_("%s isa does not support 64-bit floating point registers"),
14965                  mips_cpu_info_from_isa (mips_opts.isa)->name);
14966       mips_opts.fp32 = 0;
14967     }
14968   else if (strcmp (name, "softfloat") == 0)
14969     mips_opts.soft_float = 1;
14970   else if (strcmp (name, "hardfloat") == 0)
14971     mips_opts.soft_float = 0;
14972   else if (strcmp (name, "singlefloat") == 0)
14973     mips_opts.single_float = 1;
14974   else if (strcmp (name, "doublefloat") == 0)
14975     mips_opts.single_float = 0;
14976   else if (strcmp (name, "mips16") == 0
14977            || strcmp (name, "MIPS-16") == 0)
14978     {
14979       if (mips_opts.micromips == 1)
14980         as_fatal (_("`mips16' cannot be used with `micromips'"));
14981       mips_opts.mips16 = 1;
14982     }
14983   else if (strcmp (name, "nomips16") == 0
14984            || strcmp (name, "noMIPS-16") == 0)
14985     mips_opts.mips16 = 0;
14986   else if (strcmp (name, "micromips") == 0)
14987     {
14988       if (mips_opts.mips16 == 1)
14989         as_fatal (_("`micromips' cannot be used with `mips16'"));
14990       mips_opts.micromips = 1;
14991     }
14992   else if (strcmp (name, "nomicromips") == 0)
14993     mips_opts.micromips = 0;
14994   else if (name[0] == 'n'
14995            && name[1] == 'o'
14996            && (ase = mips_lookup_ase (name + 2)))
14997     mips_set_ase (ase, FALSE);
14998   else if ((ase = mips_lookup_ase (name)))
14999     mips_set_ase (ase, TRUE);
15000   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
15001     {
15002       int reset = 0;
15003
15004       /* Permit the user to change the ISA and architecture on the fly.
15005          Needless to say, misuse can cause serious problems.  */
15006       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
15007         {
15008           reset = 1;
15009           mips_opts.isa = file_mips_isa;
15010           mips_opts.arch = file_mips_arch;
15011         }
15012       else if (strncmp (name, "arch=", 5) == 0)
15013         {
15014           const struct mips_cpu_info *p;
15015
15016           p = mips_parse_cpu("internal use", name + 5);
15017           if (!p)
15018             as_bad (_("unknown architecture %s"), name + 5);
15019           else
15020             {
15021               mips_opts.arch = p->cpu;
15022               mips_opts.isa = p->isa;
15023             }
15024         }
15025       else if (strncmp (name, "mips", 4) == 0)
15026         {
15027           const struct mips_cpu_info *p;
15028
15029           p = mips_parse_cpu("internal use", name);
15030           if (!p)
15031             as_bad (_("unknown ISA level %s"), name + 4);
15032           else
15033             {
15034               mips_opts.arch = p->cpu;
15035               mips_opts.isa = p->isa;
15036             }
15037         }
15038       else
15039         as_bad (_("unknown ISA or architecture %s"), name);
15040
15041       switch (mips_opts.isa)
15042         {
15043         case  0:
15044           break;
15045         case ISA_MIPS1:
15046         case ISA_MIPS2:
15047         case ISA_MIPS32:
15048         case ISA_MIPS32R2:
15049           mips_opts.gp32 = 1;
15050           mips_opts.fp32 = 1;
15051           break;
15052         case ISA_MIPS3:
15053         case ISA_MIPS4:
15054         case ISA_MIPS5:
15055         case ISA_MIPS64:
15056         case ISA_MIPS64R2:
15057           mips_opts.gp32 = 0;
15058           if (mips_opts.arch == CPU_R5900)
15059             {
15060                 mips_opts.fp32 = 1;
15061             }
15062           else
15063             {
15064           mips_opts.fp32 = 0;
15065             }
15066           break;
15067         default:
15068           as_bad (_("unknown ISA level %s"), name + 4);
15069           break;
15070         }
15071       if (reset)
15072         {
15073           mips_opts.gp32 = file_mips_gp32;
15074           mips_opts.fp32 = file_mips_fp32;
15075         }
15076     }
15077   else if (strcmp (name, "autoextend") == 0)
15078     mips_opts.noautoextend = 0;
15079   else if (strcmp (name, "noautoextend") == 0)
15080     mips_opts.noautoextend = 1;
15081   else if (strcmp (name, "insn32") == 0)
15082     mips_opts.insn32 = TRUE;
15083   else if (strcmp (name, "noinsn32") == 0)
15084     mips_opts.insn32 = FALSE;
15085   else if (strcmp (name, "push") == 0)
15086     {
15087       struct mips_option_stack *s;
15088
15089       s = (struct mips_option_stack *) xmalloc (sizeof *s);
15090       s->next = mips_opts_stack;
15091       s->options = mips_opts;
15092       mips_opts_stack = s;
15093     }
15094   else if (strcmp (name, "pop") == 0)
15095     {
15096       struct mips_option_stack *s;
15097
15098       s = mips_opts_stack;
15099       if (s == NULL)
15100         as_bad (_(".set pop with no .set push"));
15101       else
15102         {
15103           /* If we're changing the reorder mode we need to handle
15104              delay slots correctly.  */
15105           if (s->options.noreorder && ! mips_opts.noreorder)
15106             start_noreorder ();
15107           else if (! s->options.noreorder && mips_opts.noreorder)
15108             end_noreorder ();
15109
15110           mips_opts = s->options;
15111           mips_opts_stack = s->next;
15112           free (s);
15113         }
15114     }
15115   else if (strcmp (name, "sym32") == 0)
15116     mips_opts.sym32 = TRUE;
15117   else if (strcmp (name, "nosym32") == 0)
15118     mips_opts.sym32 = FALSE;
15119   else if (strchr (name, ','))
15120     {
15121       /* Generic ".set" directive; use the generic handler.  */
15122       *input_line_pointer = ch;
15123       input_line_pointer = name;
15124       s_set (0);
15125       return;
15126     }
15127   else
15128     {
15129       as_warn (_("Tried to set unrecognized symbol: %s\n"), name);
15130     }
15131   mips_check_isa_supports_ases ();
15132   *input_line_pointer = ch;
15133   demand_empty_rest_of_line ();
15134 }
15135
15136 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
15137    .option pic2.  It means to generate SVR4 PIC calls.  */
15138
15139 static void
15140 s_abicalls (int ignore ATTRIBUTE_UNUSED)
15141 {
15142   mips_pic = SVR4_PIC;
15143   mips_abicalls = TRUE;
15144
15145   if (g_switch_seen && g_switch_value != 0)
15146     as_warn (_("-G may not be used with SVR4 PIC code"));
15147   g_switch_value = 0;
15148
15149   bfd_set_gp_size (stdoutput, 0);
15150   demand_empty_rest_of_line ();
15151 }
15152
15153 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
15154    PIC code.  It sets the $gp register for the function based on the
15155    function address, which is in the register named in the argument.
15156    This uses a relocation against _gp_disp, which is handled specially
15157    by the linker.  The result is:
15158         lui     $gp,%hi(_gp_disp)
15159         addiu   $gp,$gp,%lo(_gp_disp)
15160         addu    $gp,$gp,.cpload argument
15161    The .cpload argument is normally $25 == $t9.
15162
15163    The -mno-shared option changes this to:
15164         lui     $gp,%hi(__gnu_local_gp)
15165         addiu   $gp,$gp,%lo(__gnu_local_gp)
15166    and the argument is ignored.  This saves an instruction, but the
15167    resulting code is not position independent; it uses an absolute
15168    address for __gnu_local_gp.  Thus code assembled with -mno-shared
15169    can go into an ordinary executable, but not into a shared library.  */
15170
15171 static void
15172 s_cpload (int ignore ATTRIBUTE_UNUSED)
15173 {
15174   expressionS ex;
15175   int reg;
15176   int in_shared;
15177
15178   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
15179      .cpload is ignored.  */
15180   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
15181     {
15182       s_ignore (0);
15183       return;
15184     }
15185
15186   if (mips_opts.mips16)
15187     {
15188       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
15189       ignore_rest_of_line ();
15190       return;
15191     }
15192
15193   /* .cpload should be in a .set noreorder section.  */
15194   if (mips_opts.noreorder == 0)
15195     as_warn (_(".cpload not in noreorder section"));
15196
15197   reg = tc_get_register (0);
15198
15199   /* If we need to produce a 64-bit address, we are better off using
15200      the default instruction sequence.  */
15201   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
15202
15203   ex.X_op = O_symbol;
15204   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
15205                                          "__gnu_local_gp");
15206   ex.X_op_symbol = NULL;
15207   ex.X_add_number = 0;
15208
15209   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
15210   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
15211
15212   mips_mark_labels ();
15213   mips_assembling_insn = TRUE;
15214
15215   macro_start ();
15216   macro_build_lui (&ex, mips_gp_register);
15217   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
15218                mips_gp_register, BFD_RELOC_LO16);
15219   if (in_shared)
15220     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
15221                  mips_gp_register, reg);
15222   macro_end ();
15223
15224   mips_assembling_insn = FALSE;
15225   demand_empty_rest_of_line ();
15226 }
15227
15228 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
15229      .cpsetup $reg1, offset|$reg2, label
15230
15231    If offset is given, this results in:
15232      sd         $gp, offset($sp)
15233      lui        $gp, %hi(%neg(%gp_rel(label)))
15234      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
15235      daddu      $gp, $gp, $reg1
15236
15237    If $reg2 is given, this results in:
15238      daddu      $reg2, $gp, $0
15239      lui        $gp, %hi(%neg(%gp_rel(label)))
15240      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
15241      daddu      $gp, $gp, $reg1
15242    $reg1 is normally $25 == $t9.
15243
15244    The -mno-shared option replaces the last three instructions with
15245         lui     $gp,%hi(_gp)
15246         addiu   $gp,$gp,%lo(_gp)  */
15247
15248 static void
15249 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
15250 {
15251   expressionS ex_off;
15252   expressionS ex_sym;
15253   int reg1;
15254
15255   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
15256      We also need NewABI support.  */
15257   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15258     {
15259       s_ignore (0);
15260       return;
15261     }
15262
15263   if (mips_opts.mips16)
15264     {
15265       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
15266       ignore_rest_of_line ();
15267       return;
15268     }
15269
15270   reg1 = tc_get_register (0);
15271   SKIP_WHITESPACE ();
15272   if (*input_line_pointer != ',')
15273     {
15274       as_bad (_("missing argument separator ',' for .cpsetup"));
15275       return;
15276     }
15277   else
15278     ++input_line_pointer;
15279   SKIP_WHITESPACE ();
15280   if (*input_line_pointer == '$')
15281     {
15282       mips_cpreturn_register = tc_get_register (0);
15283       mips_cpreturn_offset = -1;
15284     }
15285   else
15286     {
15287       mips_cpreturn_offset = get_absolute_expression ();
15288       mips_cpreturn_register = -1;
15289     }
15290   SKIP_WHITESPACE ();
15291   if (*input_line_pointer != ',')
15292     {
15293       as_bad (_("missing argument separator ',' for .cpsetup"));
15294       return;
15295     }
15296   else
15297     ++input_line_pointer;
15298   SKIP_WHITESPACE ();
15299   expression (&ex_sym);
15300
15301   mips_mark_labels ();
15302   mips_assembling_insn = TRUE;
15303
15304   macro_start ();
15305   if (mips_cpreturn_register == -1)
15306     {
15307       ex_off.X_op = O_constant;
15308       ex_off.X_add_symbol = NULL;
15309       ex_off.X_op_symbol = NULL;
15310       ex_off.X_add_number = mips_cpreturn_offset;
15311
15312       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
15313                    BFD_RELOC_LO16, SP);
15314     }
15315   else
15316     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
15317                  mips_gp_register, 0);
15318
15319   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
15320     {
15321       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
15322                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
15323                    BFD_RELOC_HI16_S);
15324
15325       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
15326                    mips_gp_register, -1, BFD_RELOC_GPREL16,
15327                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
15328
15329       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
15330                    mips_gp_register, reg1);
15331     }
15332   else
15333     {
15334       expressionS ex;
15335
15336       ex.X_op = O_symbol;
15337       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
15338       ex.X_op_symbol = NULL;
15339       ex.X_add_number = 0;
15340
15341       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
15342       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
15343
15344       macro_build_lui (&ex, mips_gp_register);
15345       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
15346                    mips_gp_register, BFD_RELOC_LO16);
15347     }
15348
15349   macro_end ();
15350
15351   mips_assembling_insn = FALSE;
15352   demand_empty_rest_of_line ();
15353 }
15354
15355 static void
15356 s_cplocal (int ignore ATTRIBUTE_UNUSED)
15357 {
15358   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
15359      .cplocal is ignored.  */
15360   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15361     {
15362       s_ignore (0);
15363       return;
15364     }
15365
15366   if (mips_opts.mips16)
15367     {
15368       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
15369       ignore_rest_of_line ();
15370       return;
15371     }
15372
15373   mips_gp_register = tc_get_register (0);
15374   demand_empty_rest_of_line ();
15375 }
15376
15377 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
15378    offset from $sp.  The offset is remembered, and after making a PIC
15379    call $gp is restored from that location.  */
15380
15381 static void
15382 s_cprestore (int ignore ATTRIBUTE_UNUSED)
15383 {
15384   expressionS ex;
15385
15386   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
15387      .cprestore is ignored.  */
15388   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
15389     {
15390       s_ignore (0);
15391       return;
15392     }
15393
15394   if (mips_opts.mips16)
15395     {
15396       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
15397       ignore_rest_of_line ();
15398       return;
15399     }
15400
15401   mips_cprestore_offset = get_absolute_expression ();
15402   mips_cprestore_valid = 1;
15403
15404   ex.X_op = O_constant;
15405   ex.X_add_symbol = NULL;
15406   ex.X_op_symbol = NULL;
15407   ex.X_add_number = mips_cprestore_offset;
15408
15409   mips_mark_labels ();
15410   mips_assembling_insn = TRUE;
15411
15412   macro_start ();
15413   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
15414                                 SP, HAVE_64BIT_ADDRESSES);
15415   macro_end ();
15416
15417   mips_assembling_insn = FALSE;
15418   demand_empty_rest_of_line ();
15419 }
15420
15421 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
15422    was given in the preceding .cpsetup, it results in:
15423      ld         $gp, offset($sp)
15424
15425    If a register $reg2 was given there, it results in:
15426      daddu      $gp, $reg2, $0  */
15427
15428 static void
15429 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
15430 {
15431   expressionS ex;
15432
15433   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
15434      We also need NewABI support.  */
15435   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15436     {
15437       s_ignore (0);
15438       return;
15439     }
15440
15441   if (mips_opts.mips16)
15442     {
15443       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
15444       ignore_rest_of_line ();
15445       return;
15446     }
15447
15448   mips_mark_labels ();
15449   mips_assembling_insn = TRUE;
15450
15451   macro_start ();
15452   if (mips_cpreturn_register == -1)
15453     {
15454       ex.X_op = O_constant;
15455       ex.X_add_symbol = NULL;
15456       ex.X_op_symbol = NULL;
15457       ex.X_add_number = mips_cpreturn_offset;
15458
15459       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
15460     }
15461   else
15462     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
15463                  mips_cpreturn_register, 0);
15464   macro_end ();
15465
15466   mips_assembling_insn = FALSE;
15467   demand_empty_rest_of_line ();
15468 }
15469
15470 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
15471    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
15472    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
15473    debug information or MIPS16 TLS.  */
15474
15475 static void
15476 s_tls_rel_directive (const size_t bytes, const char *dirstr,
15477                      bfd_reloc_code_real_type rtype)
15478 {
15479   expressionS ex;
15480   char *p;
15481
15482   expression (&ex);
15483
15484   if (ex.X_op != O_symbol)
15485     {
15486       as_bad (_("Unsupported use of %s"), dirstr);
15487       ignore_rest_of_line ();
15488     }
15489
15490   p = frag_more (bytes);
15491   md_number_to_chars (p, 0, bytes);
15492   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
15493   demand_empty_rest_of_line ();
15494   mips_clear_insn_labels ();
15495 }
15496
15497 /* Handle .dtprelword.  */
15498
15499 static void
15500 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
15501 {
15502   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
15503 }
15504
15505 /* Handle .dtpreldword.  */
15506
15507 static void
15508 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
15509 {
15510   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
15511 }
15512
15513 /* Handle .tprelword.  */
15514
15515 static void
15516 s_tprelword (int ignore ATTRIBUTE_UNUSED)
15517 {
15518   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
15519 }
15520
15521 /* Handle .tpreldword.  */
15522
15523 static void
15524 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
15525 {
15526   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
15527 }
15528
15529 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
15530    code.  It sets the offset to use in gp_rel relocations.  */
15531
15532 static void
15533 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
15534 {
15535   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
15536      We also need NewABI support.  */
15537   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15538     {
15539       s_ignore (0);
15540       return;
15541     }
15542
15543   mips_gprel_offset = get_absolute_expression ();
15544
15545   demand_empty_rest_of_line ();
15546 }
15547
15548 /* Handle the .gpword pseudo-op.  This is used when generating PIC
15549    code.  It generates a 32 bit GP relative reloc.  */
15550
15551 static void
15552 s_gpword (int ignore ATTRIBUTE_UNUSED)
15553 {
15554   segment_info_type *si;
15555   struct insn_label_list *l;
15556   expressionS ex;
15557   char *p;
15558
15559   /* When not generating PIC code, this is treated as .word.  */
15560   if (mips_pic != SVR4_PIC)
15561     {
15562       s_cons (2);
15563       return;
15564     }
15565
15566   si = seg_info (now_seg);
15567   l = si->label_list;
15568   mips_emit_delays ();
15569   if (auto_align)
15570     mips_align (2, 0, l);
15571
15572   expression (&ex);
15573   mips_clear_insn_labels ();
15574
15575   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15576     {
15577       as_bad (_("Unsupported use of .gpword"));
15578       ignore_rest_of_line ();
15579     }
15580
15581   p = frag_more (4);
15582   md_number_to_chars (p, 0, 4);
15583   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15584                BFD_RELOC_GPREL32);
15585
15586   demand_empty_rest_of_line ();
15587 }
15588
15589 static void
15590 s_gpdword (int ignore ATTRIBUTE_UNUSED)
15591 {
15592   segment_info_type *si;
15593   struct insn_label_list *l;
15594   expressionS ex;
15595   char *p;
15596
15597   /* When not generating PIC code, this is treated as .dword.  */
15598   if (mips_pic != SVR4_PIC)
15599     {
15600       s_cons (3);
15601       return;
15602     }
15603
15604   si = seg_info (now_seg);
15605   l = si->label_list;
15606   mips_emit_delays ();
15607   if (auto_align)
15608     mips_align (3, 0, l);
15609
15610   expression (&ex);
15611   mips_clear_insn_labels ();
15612
15613   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15614     {
15615       as_bad (_("Unsupported use of .gpdword"));
15616       ignore_rest_of_line ();
15617     }
15618
15619   p = frag_more (8);
15620   md_number_to_chars (p, 0, 8);
15621   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15622                BFD_RELOC_GPREL32)->fx_tcbit = 1;
15623
15624   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
15625   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
15626            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
15627
15628   demand_empty_rest_of_line ();
15629 }
15630
15631 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
15632    tables.  It generates a R_MIPS_EH reloc.  */
15633
15634 static void
15635 s_ehword (int ignore ATTRIBUTE_UNUSED)
15636 {
15637   expressionS ex;
15638   char *p;
15639
15640   mips_emit_delays ();
15641
15642   expression (&ex);
15643   mips_clear_insn_labels ();
15644
15645   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15646     {
15647       as_bad (_("Unsupported use of .ehword"));
15648       ignore_rest_of_line ();
15649     }
15650
15651   p = frag_more (4);
15652   md_number_to_chars (p, 0, 4);
15653   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15654                BFD_RELOC_MIPS_EH);
15655
15656   demand_empty_rest_of_line ();
15657 }
15658
15659 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
15660    tables in SVR4 PIC code.  */
15661
15662 static void
15663 s_cpadd (int ignore ATTRIBUTE_UNUSED)
15664 {
15665   int reg;
15666
15667   /* This is ignored when not generating SVR4 PIC code.  */
15668   if (mips_pic != SVR4_PIC)
15669     {
15670       s_ignore (0);
15671       return;
15672     }
15673
15674   mips_mark_labels ();
15675   mips_assembling_insn = TRUE;
15676
15677   /* Add $gp to the register named as an argument.  */
15678   macro_start ();
15679   reg = tc_get_register (0);
15680   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
15681   macro_end ();
15682
15683   mips_assembling_insn = FALSE;
15684   demand_empty_rest_of_line ();
15685 }
15686
15687 /* Handle the .insn pseudo-op.  This marks instruction labels in
15688    mips16/micromips mode.  This permits the linker to handle them specially,
15689    such as generating jalx instructions when needed.  We also make
15690    them odd for the duration of the assembly, in order to generate the
15691    right sort of code.  We will make them even in the adjust_symtab
15692    routine, while leaving them marked.  This is convenient for the
15693    debugger and the disassembler.  The linker knows to make them odd
15694    again.  */
15695
15696 static void
15697 s_insn (int ignore ATTRIBUTE_UNUSED)
15698 {
15699   mips_mark_labels ();
15700
15701   demand_empty_rest_of_line ();
15702 }
15703
15704 /* Handle the .nan pseudo-op.  */
15705
15706 static void
15707 s_nan (int ignore ATTRIBUTE_UNUSED)
15708 {
15709   static const char str_legacy[] = "legacy";
15710   static const char str_2008[] = "2008";
15711   size_t i;
15712
15713   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
15714
15715   if (i == sizeof (str_2008) - 1
15716       && memcmp (input_line_pointer, str_2008, i) == 0)
15717     mips_flag_nan2008 = TRUE;
15718   else if (i == sizeof (str_legacy) - 1
15719            && memcmp (input_line_pointer, str_legacy, i) == 0)
15720     mips_flag_nan2008 = FALSE;
15721   else
15722     as_bad (_("Bad .nan directive"));
15723
15724   input_line_pointer += i;
15725   demand_empty_rest_of_line ();
15726 }
15727
15728 /* Handle a .stab[snd] directive.  Ideally these directives would be
15729    implemented in a transparent way, so that removing them would not
15730    have any effect on the generated instructions.  However, s_stab
15731    internally changes the section, so in practice we need to decide
15732    now whether the preceding label marks compressed code.  We do not
15733    support changing the compression mode of a label after a .stab*
15734    directive, such as in:
15735
15736    foo:
15737         .stabs ...
15738         .set mips16
15739
15740    so the current mode wins.  */
15741
15742 static void
15743 s_mips_stab (int type)
15744 {
15745   mips_mark_labels ();
15746   s_stab (type);
15747 }
15748
15749 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
15750
15751 static void
15752 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
15753 {
15754   char *name;
15755   int c;
15756   symbolS *symbolP;
15757   expressionS exp;
15758
15759   name = input_line_pointer;
15760   c = get_symbol_end ();
15761   symbolP = symbol_find_or_make (name);
15762   S_SET_WEAK (symbolP);
15763   *input_line_pointer = c;
15764
15765   SKIP_WHITESPACE ();
15766
15767   if (! is_end_of_line[(unsigned char) *input_line_pointer])
15768     {
15769       if (S_IS_DEFINED (symbolP))
15770         {
15771           as_bad (_("ignoring attempt to redefine symbol %s"),
15772                   S_GET_NAME (symbolP));
15773           ignore_rest_of_line ();
15774           return;
15775         }
15776
15777       if (*input_line_pointer == ',')
15778         {
15779           ++input_line_pointer;
15780           SKIP_WHITESPACE ();
15781         }
15782
15783       expression (&exp);
15784       if (exp.X_op != O_symbol)
15785         {
15786           as_bad (_("bad .weakext directive"));
15787           ignore_rest_of_line ();
15788           return;
15789         }
15790       symbol_set_value_expression (symbolP, &exp);
15791     }
15792
15793   demand_empty_rest_of_line ();
15794 }
15795
15796 /* Parse a register string into a number.  Called from the ECOFF code
15797    to parse .frame.  The argument is non-zero if this is the frame
15798    register, so that we can record it in mips_frame_reg.  */
15799
15800 int
15801 tc_get_register (int frame)
15802 {
15803   unsigned int reg;
15804
15805   SKIP_WHITESPACE ();
15806   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
15807     reg = 0;
15808   if (frame)
15809     {
15810       mips_frame_reg = reg != 0 ? reg : SP;
15811       mips_frame_reg_valid = 1;
15812       mips_cprestore_valid = 0;
15813     }
15814   return reg;
15815 }
15816
15817 valueT
15818 md_section_align (asection *seg, valueT addr)
15819 {
15820   int align = bfd_get_section_alignment (stdoutput, seg);
15821
15822   /* We don't need to align ELF sections to the full alignment.
15823      However, Irix 5 may prefer that we align them at least to a 16
15824      byte boundary.  We don't bother to align the sections if we
15825      are targeted for an embedded system.  */
15826   if (strncmp (TARGET_OS, "elf", 3) == 0)
15827     return addr;
15828   if (align > 4)
15829     align = 4;
15830
15831   return ((addr + (1 << align) - 1) & (-1 << align));
15832 }
15833
15834 /* Utility routine, called from above as well.  If called while the
15835    input file is still being read, it's only an approximation.  (For
15836    example, a symbol may later become defined which appeared to be
15837    undefined earlier.)  */
15838
15839 static int
15840 nopic_need_relax (symbolS *sym, int before_relaxing)
15841 {
15842   if (sym == 0)
15843     return 0;
15844
15845   if (g_switch_value > 0)
15846     {
15847       const char *symname;
15848       int change;
15849
15850       /* Find out whether this symbol can be referenced off the $gp
15851          register.  It can be if it is smaller than the -G size or if
15852          it is in the .sdata or .sbss section.  Certain symbols can
15853          not be referenced off the $gp, although it appears as though
15854          they can.  */
15855       symname = S_GET_NAME (sym);
15856       if (symname != (const char *) NULL
15857           && (strcmp (symname, "eprol") == 0
15858               || strcmp (symname, "etext") == 0
15859               || strcmp (symname, "_gp") == 0
15860               || strcmp (symname, "edata") == 0
15861               || strcmp (symname, "_fbss") == 0
15862               || strcmp (symname, "_fdata") == 0
15863               || strcmp (symname, "_ftext") == 0
15864               || strcmp (symname, "end") == 0
15865               || strcmp (symname, "_gp_disp") == 0))
15866         change = 1;
15867       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
15868                && (0
15869 #ifndef NO_ECOFF_DEBUGGING
15870                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
15871                        && (symbol_get_obj (sym)->ecoff_extern_size
15872                            <= g_switch_value))
15873 #endif
15874                    /* We must defer this decision until after the whole
15875                       file has been read, since there might be a .extern
15876                       after the first use of this symbol.  */
15877                    || (before_relaxing
15878 #ifndef NO_ECOFF_DEBUGGING
15879                        && symbol_get_obj (sym)->ecoff_extern_size == 0
15880 #endif
15881                        && S_GET_VALUE (sym) == 0)
15882                    || (S_GET_VALUE (sym) != 0
15883                        && S_GET_VALUE (sym) <= g_switch_value)))
15884         change = 0;
15885       else
15886         {
15887           const char *segname;
15888
15889           segname = segment_name (S_GET_SEGMENT (sym));
15890           gas_assert (strcmp (segname, ".lit8") != 0
15891                   && strcmp (segname, ".lit4") != 0);
15892           change = (strcmp (segname, ".sdata") != 0
15893                     && strcmp (segname, ".sbss") != 0
15894                     && strncmp (segname, ".sdata.", 7) != 0
15895                     && strncmp (segname, ".sbss.", 6) != 0
15896                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
15897                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
15898         }
15899       return change;
15900     }
15901   else
15902     /* We are not optimizing for the $gp register.  */
15903     return 1;
15904 }
15905
15906
15907 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
15908
15909 static bfd_boolean
15910 pic_need_relax (symbolS *sym, asection *segtype)
15911 {
15912   asection *symsec;
15913
15914   /* Handle the case of a symbol equated to another symbol.  */
15915   while (symbol_equated_reloc_p (sym))
15916     {
15917       symbolS *n;
15918
15919       /* It's possible to get a loop here in a badly written program.  */
15920       n = symbol_get_value_expression (sym)->X_add_symbol;
15921       if (n == sym)
15922         break;
15923       sym = n;
15924     }
15925
15926   if (symbol_section_p (sym))
15927     return TRUE;
15928
15929   symsec = S_GET_SEGMENT (sym);
15930
15931   /* This must duplicate the test in adjust_reloc_syms.  */
15932   return (!bfd_is_und_section (symsec)
15933           && !bfd_is_abs_section (symsec)
15934           && !bfd_is_com_section (symsec)
15935           && !s_is_linkonce (sym, segtype)
15936           /* A global or weak symbol is treated as external.  */
15937           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
15938 }
15939
15940
15941 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
15942    extended opcode.  SEC is the section the frag is in.  */
15943
15944 static int
15945 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
15946 {
15947   int type;
15948   const struct mips_int_operand *operand;
15949   offsetT val;
15950   segT symsec;
15951   fragS *sym_frag;
15952
15953   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
15954     return 0;
15955   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
15956     return 1;
15957
15958   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
15959   operand = mips16_immed_operand (type, FALSE);
15960
15961   sym_frag = symbol_get_frag (fragp->fr_symbol);
15962   val = S_GET_VALUE (fragp->fr_symbol);
15963   symsec = S_GET_SEGMENT (fragp->fr_symbol);
15964
15965   if (operand->root.type == OP_PCREL)
15966     {
15967       const struct mips_pcrel_operand *pcrel_op;
15968       addressT addr;
15969       offsetT maxtiny;
15970
15971       /* We won't have the section when we are called from
15972          mips_relax_frag.  However, we will always have been called
15973          from md_estimate_size_before_relax first.  If this is a
15974          branch to a different section, we mark it as such.  If SEC is
15975          NULL, and the frag is not marked, then it must be a branch to
15976          the same section.  */
15977       pcrel_op = (const struct mips_pcrel_operand *) operand;
15978       if (sec == NULL)
15979         {
15980           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
15981             return 1;
15982         }
15983       else
15984         {
15985           /* Must have been called from md_estimate_size_before_relax.  */
15986           if (symsec != sec)
15987             {
15988               fragp->fr_subtype =
15989                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
15990
15991               /* FIXME: We should support this, and let the linker
15992                  catch branches and loads that are out of range.  */
15993               as_bad_where (fragp->fr_file, fragp->fr_line,
15994                             _("unsupported PC relative reference to different section"));
15995
15996               return 1;
15997             }
15998           if (fragp != sym_frag && sym_frag->fr_address == 0)
15999             /* Assume non-extended on the first relaxation pass.
16000                The address we have calculated will be bogus if this is
16001                a forward branch to another frag, as the forward frag
16002                will have fr_address == 0.  */
16003             return 0;
16004         }
16005
16006       /* In this case, we know for sure that the symbol fragment is in
16007          the same section.  If the relax_marker of the symbol fragment
16008          differs from the relax_marker of this fragment, we have not
16009          yet adjusted the symbol fragment fr_address.  We want to add
16010          in STRETCH in order to get a better estimate of the address.
16011          This particularly matters because of the shift bits.  */
16012       if (stretch != 0
16013           && sym_frag->relax_marker != fragp->relax_marker)
16014         {
16015           fragS *f;
16016
16017           /* Adjust stretch for any alignment frag.  Note that if have
16018              been expanding the earlier code, the symbol may be
16019              defined in what appears to be an earlier frag.  FIXME:
16020              This doesn't handle the fr_subtype field, which specifies
16021              a maximum number of bytes to skip when doing an
16022              alignment.  */
16023           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
16024             {
16025               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
16026                 {
16027                   if (stretch < 0)
16028                     stretch = - ((- stretch)
16029                                  & ~ ((1 << (int) f->fr_offset) - 1));
16030                   else
16031                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
16032                   if (stretch == 0)
16033                     break;
16034                 }
16035             }
16036           if (f != NULL)
16037             val += stretch;
16038         }
16039
16040       addr = fragp->fr_address + fragp->fr_fix;
16041
16042       /* The base address rules are complicated.  The base address of
16043          a branch is the following instruction.  The base address of a
16044          PC relative load or add is the instruction itself, but if it
16045          is in a delay slot (in which case it can not be extended) use
16046          the address of the instruction whose delay slot it is in.  */
16047       if (pcrel_op->include_isa_bit)
16048         {
16049           addr += 2;
16050
16051           /* If we are currently assuming that this frag should be
16052              extended, then, the current address is two bytes
16053              higher.  */
16054           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16055             addr += 2;
16056
16057           /* Ignore the low bit in the target, since it will be set
16058              for a text label.  */
16059           val &= -2;
16060         }
16061       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
16062         addr -= 4;
16063       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
16064         addr -= 2;
16065
16066       val -= addr & -(1 << pcrel_op->align_log2);
16067
16068       /* If any of the shifted bits are set, we must use an extended
16069          opcode.  If the address depends on the size of this
16070          instruction, this can lead to a loop, so we arrange to always
16071          use an extended opcode.  We only check this when we are in
16072          the main relaxation loop, when SEC is NULL.  */
16073       if ((val & ((1 << operand->shift) - 1)) != 0 && sec == NULL)
16074         {
16075           fragp->fr_subtype =
16076             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16077           return 1;
16078         }
16079
16080       /* If we are about to mark a frag as extended because the value
16081          is precisely the next value above maxtiny, then there is a
16082          chance of an infinite loop as in the following code:
16083              la $4,foo
16084              .skip      1020
16085              .align     2
16086            foo:
16087          In this case when the la is extended, foo is 0x3fc bytes
16088          away, so the la can be shrunk, but then foo is 0x400 away, so
16089          the la must be extended.  To avoid this loop, we mark the
16090          frag as extended if it was small, and is about to become
16091          extended with the next value above maxtiny.  */
16092       maxtiny = mips_int_operand_max (operand);
16093       if (val == maxtiny + (1 << operand->shift)
16094           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
16095           && sec == NULL)
16096         {
16097           fragp->fr_subtype =
16098             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16099           return 1;
16100         }
16101     }
16102   else if (symsec != absolute_section && sec != NULL)
16103     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
16104
16105   return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
16106 }
16107
16108 /* Compute the length of a branch sequence, and adjust the
16109    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
16110    worst-case length is computed, with UPDATE being used to indicate
16111    whether an unconditional (-1), branch-likely (+1) or regular (0)
16112    branch is to be computed.  */
16113 static int
16114 relaxed_branch_length (fragS *fragp, asection *sec, int update)
16115 {
16116   bfd_boolean toofar;
16117   int length;
16118
16119   if (fragp
16120       && S_IS_DEFINED (fragp->fr_symbol)
16121       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16122     {
16123       addressT addr;
16124       offsetT val;
16125
16126       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16127
16128       addr = fragp->fr_address + fragp->fr_fix + 4;
16129
16130       val -= addr;
16131
16132       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
16133     }
16134   else if (fragp)
16135     /* If the symbol is not defined or it's in a different segment,
16136        assume the user knows what's going on and emit a short
16137        branch.  */
16138     toofar = FALSE;
16139   else
16140     toofar = TRUE;
16141
16142   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16143     fragp->fr_subtype
16144       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
16145                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
16146                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
16147                              RELAX_BRANCH_LINK (fragp->fr_subtype),
16148                              toofar);
16149
16150   length = 4;
16151   if (toofar)
16152     {
16153       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
16154         length += 8;
16155
16156       if (mips_pic != NO_PIC)
16157         {
16158           /* Additional space for PIC loading of target address.  */
16159           length += 8;
16160           if (mips_opts.isa == ISA_MIPS1)
16161             /* Additional space for $at-stabilizing nop.  */
16162             length += 4;
16163         }
16164
16165       /* If branch is conditional.  */
16166       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
16167         length += 8;
16168     }
16169
16170   return length;
16171 }
16172
16173 /* Compute the length of a branch sequence, and adjust the
16174    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
16175    worst-case length is computed, with UPDATE being used to indicate
16176    whether an unconditional (-1), or regular (0) branch is to be
16177    computed.  */
16178
16179 static int
16180 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
16181 {
16182   bfd_boolean toofar;
16183   int length;
16184
16185   if (fragp
16186       && S_IS_DEFINED (fragp->fr_symbol)
16187       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16188     {
16189       addressT addr;
16190       offsetT val;
16191
16192       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16193       /* Ignore the low bit in the target, since it will be set
16194          for a text label.  */
16195       if ((val & 1) != 0)
16196         --val;
16197
16198       addr = fragp->fr_address + fragp->fr_fix + 4;
16199
16200       val -= addr;
16201
16202       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
16203     }
16204   else if (fragp)
16205     /* If the symbol is not defined or it's in a different segment,
16206        assume the user knows what's going on and emit a short
16207        branch.  */
16208     toofar = FALSE;
16209   else
16210     toofar = TRUE;
16211
16212   if (fragp && update
16213       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16214     fragp->fr_subtype = (toofar
16215                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
16216                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
16217
16218   length = 4;
16219   if (toofar)
16220     {
16221       bfd_boolean compact_known = fragp != NULL;
16222       bfd_boolean compact = FALSE;
16223       bfd_boolean uncond;
16224
16225       if (compact_known)
16226         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16227       if (fragp)
16228         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
16229       else
16230         uncond = update < 0;
16231
16232       /* If label is out of range, we turn branch <br>:
16233
16234                 <br>    label                   # 4 bytes
16235             0:
16236
16237          into:
16238
16239                 j       label                   # 4 bytes
16240                 nop                             # 2 bytes if compact && !PIC
16241             0:
16242        */
16243       if (mips_pic == NO_PIC && (!compact_known || compact))
16244         length += 2;
16245
16246       /* If assembling PIC code, we further turn:
16247
16248                         j       label                   # 4 bytes
16249
16250          into:
16251
16252                         lw/ld   at, %got(label)(gp)     # 4 bytes
16253                         d/addiu at, %lo(label)          # 4 bytes
16254                         jr/c    at                      # 2 bytes
16255        */
16256       if (mips_pic != NO_PIC)
16257         length += 6;
16258
16259       /* If branch <br> is conditional, we prepend negated branch <brneg>:
16260
16261                         <brneg> 0f                      # 4 bytes
16262                         nop                             # 2 bytes if !compact
16263        */
16264       if (!uncond)
16265         length += (compact_known && compact) ? 4 : 6;
16266     }
16267
16268   return length;
16269 }
16270
16271 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
16272    bit accordingly.  */
16273
16274 static int
16275 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
16276 {
16277   bfd_boolean toofar;
16278
16279   if (fragp
16280       && S_IS_DEFINED (fragp->fr_symbol)
16281       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16282     {
16283       addressT addr;
16284       offsetT val;
16285       int type;
16286
16287       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16288       /* Ignore the low bit in the target, since it will be set
16289          for a text label.  */
16290       if ((val & 1) != 0)
16291         --val;
16292
16293       /* Assume this is a 2-byte branch.  */
16294       addr = fragp->fr_address + fragp->fr_fix + 2;
16295
16296       /* We try to avoid the infinite loop by not adding 2 more bytes for
16297          long branches.  */
16298
16299       val -= addr;
16300
16301       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16302       if (type == 'D')
16303         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
16304       else if (type == 'E')
16305         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
16306       else
16307         abort ();
16308     }
16309   else
16310     /* If the symbol is not defined or it's in a different segment,
16311        we emit a normal 32-bit branch.  */
16312     toofar = TRUE;
16313
16314   if (fragp && update
16315       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16316     fragp->fr_subtype
16317       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
16318                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
16319
16320   if (toofar)
16321     return 4;
16322
16323   return 2;
16324 }
16325
16326 /* Estimate the size of a frag before relaxing.  Unless this is the
16327    mips16, we are not really relaxing here, and the final size is
16328    encoded in the subtype information.  For the mips16, we have to
16329    decide whether we are using an extended opcode or not.  */
16330
16331 int
16332 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
16333 {
16334   int change;
16335
16336   if (RELAX_BRANCH_P (fragp->fr_subtype))
16337     {
16338
16339       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
16340
16341       return fragp->fr_var;
16342     }
16343
16344   if (RELAX_MIPS16_P (fragp->fr_subtype))
16345     /* We don't want to modify the EXTENDED bit here; it might get us
16346        into infinite loops.  We change it only in mips_relax_frag().  */
16347     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
16348
16349   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16350     {
16351       int length = 4;
16352
16353       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16354         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
16355       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16356         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
16357       fragp->fr_var = length;
16358
16359       return length;
16360     }
16361
16362   if (mips_pic == NO_PIC)
16363     change = nopic_need_relax (fragp->fr_symbol, 0);
16364   else if (mips_pic == SVR4_PIC)
16365     change = pic_need_relax (fragp->fr_symbol, segtype);
16366   else if (mips_pic == VXWORKS_PIC)
16367     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
16368     change = 0;
16369   else
16370     abort ();
16371
16372   if (change)
16373     {
16374       fragp->fr_subtype |= RELAX_USE_SECOND;
16375       return -RELAX_FIRST (fragp->fr_subtype);
16376     }
16377   else
16378     return -RELAX_SECOND (fragp->fr_subtype);
16379 }
16380
16381 /* This is called to see whether a reloc against a defined symbol
16382    should be converted into a reloc against a section.  */
16383
16384 int
16385 mips_fix_adjustable (fixS *fixp)
16386 {
16387   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
16388       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16389     return 0;
16390
16391   if (fixp->fx_addsy == NULL)
16392     return 1;
16393
16394   /* If symbol SYM is in a mergeable section, relocations of the form
16395      SYM + 0 can usually be made section-relative.  The mergeable data
16396      is then identified by the section offset rather than by the symbol.
16397
16398      However, if we're generating REL LO16 relocations, the offset is split
16399      between the LO16 and parterning high part relocation.  The linker will
16400      need to recalculate the complete offset in order to correctly identify
16401      the merge data.
16402
16403      The linker has traditionally not looked for the parterning high part
16404      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
16405      placed anywhere.  Rather than break backwards compatibility by changing
16406      this, it seems better not to force the issue, and instead keep the
16407      original symbol.  This will work with either linker behavior.  */
16408   if ((lo16_reloc_p (fixp->fx_r_type)
16409        || reloc_needs_lo_p (fixp->fx_r_type))
16410       && HAVE_IN_PLACE_ADDENDS
16411       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
16412     return 0;
16413
16414   /* There is no place to store an in-place offset for JALR relocations.
16415      Likewise an in-range offset of limited PC-relative relocations may
16416      overflow the in-place relocatable field if recalculated against the
16417      start address of the symbol's containing section.  */
16418   if (HAVE_IN_PLACE_ADDENDS
16419       && (limited_pcrel_reloc_p (fixp->fx_r_type)
16420           || jalr_reloc_p (fixp->fx_r_type)))
16421     return 0;
16422
16423   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
16424      to a floating-point stub.  The same is true for non-R_MIPS16_26
16425      relocations against MIPS16 functions; in this case, the stub becomes
16426      the function's canonical address.
16427
16428      Floating-point stubs are stored in unique .mips16.call.* or
16429      .mips16.fn.* sections.  If a stub T for function F is in section S,
16430      the first relocation in section S must be against F; this is how the
16431      linker determines the target function.  All relocations that might
16432      resolve to T must also be against F.  We therefore have the following
16433      restrictions, which are given in an intentionally-redundant way:
16434
16435        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
16436           symbols.
16437
16438        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
16439           if that stub might be used.
16440
16441        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
16442           symbols.
16443
16444        4. We cannot reduce a stub's relocations against MIPS16 symbols if
16445           that stub might be used.
16446
16447      There is a further restriction:
16448
16449        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
16450           R_MICROMIPS_26_S1) against MIPS16 or microMIPS symbols on
16451           targets with in-place addends; the relocation field cannot
16452           encode the low bit.
16453
16454      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
16455      against a MIPS16 symbol.  We deal with (5) by by not reducing any
16456      such relocations on REL targets.
16457
16458      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
16459      relocation against some symbol R, no relocation against R may be
16460      reduced.  (Note that this deals with (2) as well as (1) because
16461      relocations against global symbols will never be reduced on ELF
16462      targets.)  This approach is a little simpler than trying to detect
16463      stub sections, and gives the "all or nothing" per-symbol consistency
16464      that we have for MIPS16 symbols.  */
16465   if (fixp->fx_subsy == NULL
16466       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
16467           || *symbol_get_tc (fixp->fx_addsy)
16468           || (HAVE_IN_PLACE_ADDENDS
16469               && ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
16470               && jmp_reloc_p (fixp->fx_r_type))))
16471     return 0;
16472
16473   return 1;
16474 }
16475
16476 /* Translate internal representation of relocation info to BFD target
16477    format.  */
16478
16479 arelent **
16480 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
16481 {
16482   static arelent *retval[4];
16483   arelent *reloc;
16484   bfd_reloc_code_real_type code;
16485
16486   memset (retval, 0, sizeof(retval));
16487   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
16488   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
16489   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
16490   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
16491
16492   if (fixp->fx_pcrel)
16493     {
16494       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
16495                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
16496                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
16497                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
16498                   || fixp->fx_r_type == BFD_RELOC_32_PCREL);
16499
16500       /* At this point, fx_addnumber is "symbol offset - pcrel address".
16501          Relocations want only the symbol offset.  */
16502       reloc->addend = fixp->fx_addnumber + reloc->address;
16503     }
16504   else
16505     reloc->addend = fixp->fx_addnumber;
16506
16507   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
16508      entry to be used in the relocation's section offset.  */
16509   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16510     {
16511       reloc->address = reloc->addend;
16512       reloc->addend = 0;
16513     }
16514
16515   code = fixp->fx_r_type;
16516
16517   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
16518   if (reloc->howto == NULL)
16519     {
16520       as_bad_where (fixp->fx_file, fixp->fx_line,
16521                     _("Can not represent %s relocation in this object file format"),
16522                     bfd_get_reloc_code_name (code));
16523       retval[0] = NULL;
16524     }
16525
16526   return retval;
16527 }
16528
16529 /* Relax a machine dependent frag.  This returns the amount by which
16530    the current size of the frag should change.  */
16531
16532 int
16533 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
16534 {
16535   if (RELAX_BRANCH_P (fragp->fr_subtype))
16536     {
16537       offsetT old_var = fragp->fr_var;
16538
16539       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
16540
16541       return fragp->fr_var - old_var;
16542     }
16543
16544   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16545     {
16546       offsetT old_var = fragp->fr_var;
16547       offsetT new_var = 4;
16548
16549       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16550         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
16551       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16552         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
16553       fragp->fr_var = new_var;
16554
16555       return new_var - old_var;
16556     }
16557
16558   if (! RELAX_MIPS16_P (fragp->fr_subtype))
16559     return 0;
16560
16561   if (mips16_extended_frag (fragp, NULL, stretch))
16562     {
16563       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16564         return 0;
16565       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
16566       return 2;
16567     }
16568   else
16569     {
16570       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16571         return 0;
16572       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
16573       return -2;
16574     }
16575
16576   return 0;
16577 }
16578
16579 /* Convert a machine dependent frag.  */
16580
16581 void
16582 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
16583 {
16584   if (RELAX_BRANCH_P (fragp->fr_subtype))
16585     {
16586       char *buf;
16587       unsigned long insn;
16588       expressionS exp;
16589       fixS *fixp;
16590
16591       buf = fragp->fr_literal + fragp->fr_fix;
16592       insn = read_insn (buf);
16593
16594       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16595         {
16596           /* We generate a fixup instead of applying it right now
16597              because, if there are linker relaxations, we're going to
16598              need the relocations.  */
16599           exp.X_op = O_symbol;
16600           exp.X_add_symbol = fragp->fr_symbol;
16601           exp.X_add_number = fragp->fr_offset;
16602
16603           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16604                               BFD_RELOC_16_PCREL_S2);
16605           fixp->fx_file = fragp->fr_file;
16606           fixp->fx_line = fragp->fr_line;
16607
16608           buf = write_insn (buf, insn);
16609         }
16610       else
16611         {
16612           int i;
16613
16614           as_warn_where (fragp->fr_file, fragp->fr_line,
16615                          _("Relaxed out-of-range branch into a jump"));
16616
16617           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
16618             goto uncond;
16619
16620           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16621             {
16622               /* Reverse the branch.  */
16623               switch ((insn >> 28) & 0xf)
16624                 {
16625                 case 4:
16626                   /* bc[0-3][tf]l? instructions can have the condition
16627                      reversed by tweaking a single TF bit, and their
16628                      opcodes all have 0x4???????.  */
16629                   gas_assert ((insn & 0xf3e00000) == 0x41000000);
16630                   insn ^= 0x00010000;
16631                   break;
16632
16633                 case 0:
16634                   /* bltz       0x04000000      bgez    0x04010000
16635                      bltzal     0x04100000      bgezal  0x04110000  */
16636                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
16637                   insn ^= 0x00010000;
16638                   break;
16639
16640                 case 1:
16641                   /* beq        0x10000000      bne     0x14000000
16642                      blez       0x18000000      bgtz    0x1c000000  */
16643                   insn ^= 0x04000000;
16644                   break;
16645
16646                 default:
16647                   abort ();
16648                 }
16649             }
16650
16651           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16652             {
16653               /* Clear the and-link bit.  */
16654               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
16655
16656               /* bltzal         0x04100000      bgezal  0x04110000
16657                  bltzall        0x04120000      bgezall 0x04130000  */
16658               insn &= ~0x00100000;
16659             }
16660
16661           /* Branch over the branch (if the branch was likely) or the
16662              full jump (not likely case).  Compute the offset from the
16663              current instruction to branch to.  */
16664           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16665             i = 16;
16666           else
16667             {
16668               /* How many bytes in instructions we've already emitted?  */
16669               i = buf - fragp->fr_literal - fragp->fr_fix;
16670               /* How many bytes in instructions from here to the end?  */
16671               i = fragp->fr_var - i;
16672             }
16673           /* Convert to instruction count.  */
16674           i >>= 2;
16675           /* Branch counts from the next instruction.  */
16676           i--;
16677           insn |= i;
16678           /* Branch over the jump.  */
16679           buf = write_insn (buf, insn);
16680
16681           /* nop */
16682           buf = write_insn (buf, 0);
16683
16684           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16685             {
16686               /* beql $0, $0, 2f */
16687               insn = 0x50000000;
16688               /* Compute the PC offset from the current instruction to
16689                  the end of the variable frag.  */
16690               /* How many bytes in instructions we've already emitted?  */
16691               i = buf - fragp->fr_literal - fragp->fr_fix;
16692               /* How many bytes in instructions from here to the end?  */
16693               i = fragp->fr_var - i;
16694               /* Convert to instruction count.  */
16695               i >>= 2;
16696               /* Don't decrement i, because we want to branch over the
16697                  delay slot.  */
16698               insn |= i;
16699
16700               buf = write_insn (buf, insn);
16701               buf = write_insn (buf, 0);
16702             }
16703
16704         uncond:
16705           if (mips_pic == NO_PIC)
16706             {
16707               /* j or jal.  */
16708               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
16709                       ? 0x0c000000 : 0x08000000);
16710               exp.X_op = O_symbol;
16711               exp.X_add_symbol = fragp->fr_symbol;
16712               exp.X_add_number = fragp->fr_offset;
16713
16714               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16715                                   FALSE, BFD_RELOC_MIPS_JMP);
16716               fixp->fx_file = fragp->fr_file;
16717               fixp->fx_line = fragp->fr_line;
16718
16719               buf = write_insn (buf, insn);
16720             }
16721           else
16722             {
16723               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
16724
16725               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
16726               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
16727               insn |= at << OP_SH_RT;
16728               exp.X_op = O_symbol;
16729               exp.X_add_symbol = fragp->fr_symbol;
16730               exp.X_add_number = fragp->fr_offset;
16731
16732               if (fragp->fr_offset)
16733                 {
16734                   exp.X_add_symbol = make_expr_symbol (&exp);
16735                   exp.X_add_number = 0;
16736                 }
16737
16738               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16739                                   FALSE, BFD_RELOC_MIPS_GOT16);
16740               fixp->fx_file = fragp->fr_file;
16741               fixp->fx_line = fragp->fr_line;
16742
16743               buf = write_insn (buf, insn);
16744
16745               if (mips_opts.isa == ISA_MIPS1)
16746                 /* nop */
16747                 buf = write_insn (buf, 0);
16748
16749               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
16750               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
16751               insn |= at << OP_SH_RS | at << OP_SH_RT;
16752
16753               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16754                                   FALSE, BFD_RELOC_LO16);
16755               fixp->fx_file = fragp->fr_file;
16756               fixp->fx_line = fragp->fr_line;
16757
16758               buf = write_insn (buf, insn);
16759
16760               /* j(al)r $at.  */
16761               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16762                 insn = 0x0000f809;
16763               else
16764                 insn = 0x00000008;
16765               insn |= at << OP_SH_RS;
16766
16767               buf = write_insn (buf, insn);
16768             }
16769         }
16770
16771       fragp->fr_fix += fragp->fr_var;
16772       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16773       return;
16774     }
16775
16776   /* Relax microMIPS branches.  */
16777   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16778     {
16779       char *buf = fragp->fr_literal + fragp->fr_fix;
16780       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16781       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
16782       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16783       bfd_boolean short_ds;
16784       unsigned long insn;
16785       expressionS exp;
16786       fixS *fixp;
16787
16788       exp.X_op = O_symbol;
16789       exp.X_add_symbol = fragp->fr_symbol;
16790       exp.X_add_number = fragp->fr_offset;
16791
16792       fragp->fr_fix += fragp->fr_var;
16793
16794       /* Handle 16-bit branches that fit or are forced to fit.  */
16795       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16796         {
16797           /* We generate a fixup instead of applying it right now,
16798              because if there is linker relaxation, we're going to
16799              need the relocations.  */
16800           if (type == 'D')
16801             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16802                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
16803           else if (type == 'E')
16804             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16805                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
16806           else
16807             abort ();
16808
16809           fixp->fx_file = fragp->fr_file;
16810           fixp->fx_line = fragp->fr_line;
16811
16812           /* These relocations can have an addend that won't fit in
16813              2 octets.  */
16814           fixp->fx_no_overflow = 1;
16815
16816           return;
16817         }
16818
16819       /* Handle 32-bit branches that fit or are forced to fit.  */
16820       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16821           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16822         {
16823           /* We generate a fixup instead of applying it right now,
16824              because if there is linker relaxation, we're going to
16825              need the relocations.  */
16826           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16827                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
16828           fixp->fx_file = fragp->fr_file;
16829           fixp->fx_line = fragp->fr_line;
16830
16831           if (type == 0)
16832             return;
16833         }
16834
16835       /* Relax 16-bit branches to 32-bit branches.  */
16836       if (type != 0)
16837         {
16838           insn = read_compressed_insn (buf, 2);
16839
16840           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
16841             insn = 0x94000000;                          /* beq  */
16842           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
16843             {
16844               unsigned long regno;
16845
16846               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
16847               regno = micromips_to_32_reg_d_map [regno];
16848               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
16849               insn |= regno << MICROMIPSOP_SH_RS;
16850             }
16851           else
16852             abort ();
16853
16854           /* Nothing else to do, just write it out.  */
16855           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16856               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16857             {
16858               buf = write_compressed_insn (buf, insn, 4);
16859               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16860               return;
16861             }
16862         }
16863       else
16864         insn = read_compressed_insn (buf, 4);
16865
16866       /* Relax 32-bit branches to a sequence of instructions.  */
16867       as_warn_where (fragp->fr_file, fragp->fr_line,
16868                      _("Relaxed out-of-range branch into a jump"));
16869
16870       /* Set the short-delay-slot bit.  */
16871       short_ds = al && (insn & 0x02000000) != 0;
16872
16873       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
16874         {
16875           symbolS *l;
16876
16877           /* Reverse the branch.  */
16878           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
16879               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
16880             insn ^= 0x20000000;
16881           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
16882                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
16883                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
16884                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
16885                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
16886                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
16887                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
16888                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
16889                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
16890                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
16891             insn ^= 0x00400000;
16892           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
16893                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
16894                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
16895                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
16896             insn ^= 0x00200000;
16897           else
16898             abort ();
16899
16900           if (al)
16901             {
16902               /* Clear the and-link and short-delay-slot bits.  */
16903               gas_assert ((insn & 0xfda00000) == 0x40200000);
16904
16905               /* bltzal  0x40200000     bgezal  0x40600000  */
16906               /* bltzals 0x42200000     bgezals 0x42600000  */
16907               insn &= ~0x02200000;
16908             }
16909
16910           /* Make a label at the end for use with the branch.  */
16911           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
16912           micromips_label_inc ();
16913           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
16914
16915           /* Refer to it.  */
16916           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
16917                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
16918           fixp->fx_file = fragp->fr_file;
16919           fixp->fx_line = fragp->fr_line;
16920
16921           /* Branch over the jump.  */
16922           buf = write_compressed_insn (buf, insn, 4);
16923           if (!compact)
16924             /* nop */
16925             buf = write_compressed_insn (buf, 0x0c00, 2);
16926         }
16927
16928       if (mips_pic == NO_PIC)
16929         {
16930           unsigned long jal = short_ds ? 0x74000000 : 0xf4000000; /* jal/s  */
16931
16932           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
16933           insn = al ? jal : 0xd4000000;
16934
16935           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16936                               BFD_RELOC_MICROMIPS_JMP);
16937           fixp->fx_file = fragp->fr_file;
16938           fixp->fx_line = fragp->fr_line;
16939
16940           buf = write_compressed_insn (buf, insn, 4);
16941           if (compact)
16942             /* nop */
16943             buf = write_compressed_insn (buf, 0x0c00, 2);
16944         }
16945       else
16946         {
16947           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
16948           unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;      /* jalr/s  */
16949           unsigned long jr = compact ? 0x45a0 : 0x4580;         /* jr/c  */
16950
16951           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
16952           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
16953           insn |= at << MICROMIPSOP_SH_RT;
16954
16955           if (exp.X_add_number)
16956             {
16957               exp.X_add_symbol = make_expr_symbol (&exp);
16958               exp.X_add_number = 0;
16959             }
16960
16961           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16962                               BFD_RELOC_MICROMIPS_GOT16);
16963           fixp->fx_file = fragp->fr_file;
16964           fixp->fx_line = fragp->fr_line;
16965
16966           buf = write_compressed_insn (buf, insn, 4);
16967
16968           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
16969           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
16970           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
16971
16972           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16973                               BFD_RELOC_MICROMIPS_LO16);
16974           fixp->fx_file = fragp->fr_file;
16975           fixp->fx_line = fragp->fr_line;
16976
16977           buf = write_compressed_insn (buf, insn, 4);
16978
16979           /* jr/jrc/jalr/jalrs $at  */
16980           insn = al ? jalr : jr;
16981           insn |= at << MICROMIPSOP_SH_MJ;
16982
16983           buf = write_compressed_insn (buf, insn, 2);
16984         }
16985
16986       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16987       return;
16988     }
16989
16990   if (RELAX_MIPS16_P (fragp->fr_subtype))
16991     {
16992       int type;
16993       const struct mips_int_operand *operand;
16994       offsetT val;
16995       char *buf;
16996       unsigned int user_length, length;
16997       unsigned long insn;
16998       bfd_boolean ext;
16999
17000       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17001       operand = mips16_immed_operand (type, FALSE);
17002
17003       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
17004       val = resolve_symbol_value (fragp->fr_symbol);
17005       if (operand->root.type == OP_PCREL)
17006         {
17007           const struct mips_pcrel_operand *pcrel_op;
17008           addressT addr;
17009
17010           pcrel_op = (const struct mips_pcrel_operand *) operand;
17011           addr = fragp->fr_address + fragp->fr_fix;
17012
17013           /* The rules for the base address of a PC relative reloc are
17014              complicated; see mips16_extended_frag.  */
17015           if (pcrel_op->include_isa_bit)
17016             {
17017               addr += 2;
17018               if (ext)
17019                 addr += 2;
17020               /* Ignore the low bit in the target, since it will be
17021                  set for a text label.  */
17022               val &= -2;
17023             }
17024           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17025             addr -= 4;
17026           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17027             addr -= 2;
17028
17029           addr &= -(1 << pcrel_op->align_log2);
17030           val -= addr;
17031
17032           /* Make sure the section winds up with the alignment we have
17033              assumed.  */
17034           if (operand->shift > 0)
17035             record_alignment (asec, operand->shift);
17036         }
17037
17038       if (ext
17039           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
17040               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
17041         as_warn_where (fragp->fr_file, fragp->fr_line,
17042                        _("extended instruction in delay slot"));
17043
17044       buf = fragp->fr_literal + fragp->fr_fix;
17045
17046       insn = read_compressed_insn (buf, 2);
17047       if (ext)
17048         insn |= MIPS16_EXTEND;
17049
17050       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17051         user_length = 4;
17052       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
17053         user_length = 2;
17054       else
17055         user_length = 0;
17056
17057       mips16_immed (fragp->fr_file, fragp->fr_line, type,
17058                     BFD_RELOC_UNUSED, val, user_length, &insn);
17059
17060       length = (ext ? 4 : 2);
17061       gas_assert (mips16_opcode_length (insn) == length);
17062       write_compressed_insn (buf, insn, length);
17063       fragp->fr_fix += length;
17064     }
17065   else
17066     {
17067       relax_substateT subtype = fragp->fr_subtype;
17068       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
17069       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
17070       int first, second;
17071       fixS *fixp;
17072
17073       first = RELAX_FIRST (subtype);
17074       second = RELAX_SECOND (subtype);
17075       fixp = (fixS *) fragp->fr_opcode;
17076
17077       /* If the delay slot chosen does not match the size of the instruction,
17078          then emit a warning.  */
17079       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
17080            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
17081         {
17082           relax_substateT s;
17083           const char *msg;
17084
17085           s = subtype & (RELAX_DELAY_SLOT_16BIT
17086                          | RELAX_DELAY_SLOT_SIZE_FIRST
17087                          | RELAX_DELAY_SLOT_SIZE_SECOND);
17088           msg = macro_warning (s);
17089           if (msg != NULL)
17090             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
17091           subtype &= ~s;
17092         }
17093
17094       /* Possibly emit a warning if we've chosen the longer option.  */
17095       if (use_second == second_longer)
17096         {
17097           relax_substateT s;
17098           const char *msg;
17099
17100           s = (subtype
17101                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
17102           msg = macro_warning (s);
17103           if (msg != NULL)
17104             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
17105           subtype &= ~s;
17106         }
17107
17108       /* Go through all the fixups for the first sequence.  Disable them
17109          (by marking them as done) if we're going to use the second
17110          sequence instead.  */
17111       while (fixp
17112              && fixp->fx_frag == fragp
17113              && fixp->fx_where < fragp->fr_fix - second)
17114         {
17115           if (subtype & RELAX_USE_SECOND)
17116             fixp->fx_done = 1;
17117           fixp = fixp->fx_next;
17118         }
17119
17120       /* Go through the fixups for the second sequence.  Disable them if
17121          we're going to use the first sequence, otherwise adjust their
17122          addresses to account for the relaxation.  */
17123       while (fixp && fixp->fx_frag == fragp)
17124         {
17125           if (subtype & RELAX_USE_SECOND)
17126             fixp->fx_where -= first;
17127           else
17128             fixp->fx_done = 1;
17129           fixp = fixp->fx_next;
17130         }
17131
17132       /* Now modify the frag contents.  */
17133       if (subtype & RELAX_USE_SECOND)
17134         {
17135           char *start;
17136
17137           start = fragp->fr_literal + fragp->fr_fix - first - second;
17138           memmove (start, start + first, second);
17139           fragp->fr_fix -= first;
17140         }
17141       else
17142         fragp->fr_fix -= second;
17143     }
17144 }
17145
17146 /* This function is called after the relocs have been generated.
17147    We've been storing mips16 text labels as odd.  Here we convert them
17148    back to even for the convenience of the debugger.  */
17149
17150 void
17151 mips_frob_file_after_relocs (void)
17152 {
17153   asymbol **syms;
17154   unsigned int count, i;
17155
17156   syms = bfd_get_outsymbols (stdoutput);
17157   count = bfd_get_symcount (stdoutput);
17158   for (i = 0; i < count; i++, syms++)
17159     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
17160         && ((*syms)->value & 1) != 0)
17161       {
17162         (*syms)->value &= ~1;
17163         /* If the symbol has an odd size, it was probably computed
17164            incorrectly, so adjust that as well.  */
17165         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
17166           ++elf_symbol (*syms)->internal_elf_sym.st_size;
17167       }
17168 }
17169
17170 /* This function is called whenever a label is defined, including fake
17171    labels instantiated off the dot special symbol.  It is used when
17172    handling branch delays; if a branch has a label, we assume we cannot
17173    move it.  This also bumps the value of the symbol by 1 in compressed
17174    code.  */
17175
17176 static void
17177 mips_record_label (symbolS *sym)
17178 {
17179   segment_info_type *si = seg_info (now_seg);
17180   struct insn_label_list *l;
17181
17182   if (free_insn_labels == NULL)
17183     l = (struct insn_label_list *) xmalloc (sizeof *l);
17184   else
17185     {
17186       l = free_insn_labels;
17187       free_insn_labels = l->next;
17188     }
17189
17190   l->label = sym;
17191   l->next = si->label_list;
17192   si->label_list = l;
17193 }
17194
17195 /* This function is called as tc_frob_label() whenever a label is defined
17196    and adds a DWARF-2 record we only want for true labels.  */
17197
17198 void
17199 mips_define_label (symbolS *sym)
17200 {
17201   mips_record_label (sym);
17202   dwarf2_emit_label (sym);
17203 }
17204
17205 /* This function is called by tc_new_dot_label whenever a new dot symbol
17206    is defined.  */
17207
17208 void
17209 mips_add_dot_label (symbolS *sym)
17210 {
17211   mips_record_label (sym);
17212   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
17213     mips_compressed_mark_label (sym);
17214 }
17215 \f
17216 /* Some special processing for a MIPS ELF file.  */
17217
17218 void
17219 mips_elf_final_processing (void)
17220 {
17221   /* Write out the register information.  */
17222   if (mips_abi != N64_ABI)
17223     {
17224       Elf32_RegInfo s;
17225
17226       s.ri_gprmask = mips_gprmask;
17227       s.ri_cprmask[0] = mips_cprmask[0];
17228       s.ri_cprmask[1] = mips_cprmask[1];
17229       s.ri_cprmask[2] = mips_cprmask[2];
17230       s.ri_cprmask[3] = mips_cprmask[3];
17231       /* The gp_value field is set by the MIPS ELF backend.  */
17232
17233       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
17234                                        ((Elf32_External_RegInfo *)
17235                                         mips_regmask_frag));
17236     }
17237   else
17238     {
17239       Elf64_Internal_RegInfo s;
17240
17241       s.ri_gprmask = mips_gprmask;
17242       s.ri_pad = 0;
17243       s.ri_cprmask[0] = mips_cprmask[0];
17244       s.ri_cprmask[1] = mips_cprmask[1];
17245       s.ri_cprmask[2] = mips_cprmask[2];
17246       s.ri_cprmask[3] = mips_cprmask[3];
17247       /* The gp_value field is set by the MIPS ELF backend.  */
17248
17249       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
17250                                        ((Elf64_External_RegInfo *)
17251                                         mips_regmask_frag));
17252     }
17253
17254   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
17255      sort of BFD interface for this.  */
17256   if (mips_any_noreorder)
17257     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
17258   if (mips_pic != NO_PIC)
17259     {
17260       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
17261       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
17262     }
17263   if (mips_abicalls)
17264     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
17265
17266   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
17267      defined at present; this might need to change in future.  */
17268   if (file_ase_mips16)
17269     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
17270   if (file_ase_micromips)
17271     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
17272   if (file_ase & ASE_MDMX)
17273     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
17274
17275   /* Set the MIPS ELF ABI flags.  */
17276   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
17277     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
17278   else if (mips_abi == O64_ABI)
17279     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
17280   else if (mips_abi == EABI_ABI)
17281     {
17282       if (!file_mips_gp32)
17283         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
17284       else
17285         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
17286     }
17287   else if (mips_abi == N32_ABI)
17288     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
17289
17290   /* Nothing to do for N64_ABI.  */
17291
17292   if (mips_32bitmode)
17293     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
17294
17295   if (mips_flag_nan2008)
17296     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
17297
17298 #if 0 /* XXX FIXME */
17299   /* 32 bit code with 64 bit FP registers.  */
17300   if (!file_mips_fp32 && ABI_NEEDS_32BIT_REGS (mips_abi))
17301     elf_elfheader (stdoutput)->e_flags |= ???;
17302 #endif
17303 }
17304 \f
17305 typedef struct proc {
17306   symbolS *func_sym;
17307   symbolS *func_end_sym;
17308   unsigned long reg_mask;
17309   unsigned long reg_offset;
17310   unsigned long fpreg_mask;
17311   unsigned long fpreg_offset;
17312   unsigned long frame_offset;
17313   unsigned long frame_reg;
17314   unsigned long pc_reg;
17315 } procS;
17316
17317 static procS cur_proc;
17318 static procS *cur_proc_ptr;
17319 static int numprocs;
17320
17321 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
17322    as "2", and a normal nop as "0".  */
17323
17324 #define NOP_OPCODE_MIPS         0
17325 #define NOP_OPCODE_MIPS16       1
17326 #define NOP_OPCODE_MICROMIPS    2
17327
17328 char
17329 mips_nop_opcode (void)
17330 {
17331   if (seg_info (now_seg)->tc_segment_info_data.micromips)
17332     return NOP_OPCODE_MICROMIPS;
17333   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
17334     return NOP_OPCODE_MIPS16;
17335   else
17336     return NOP_OPCODE_MIPS;
17337 }
17338
17339 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
17340    32-bit microMIPS NOPs here (if applicable).  */
17341
17342 void
17343 mips_handle_align (fragS *fragp)
17344 {
17345   char nop_opcode;
17346   char *p;
17347   int bytes, size, excess;
17348   valueT opcode;
17349
17350   if (fragp->fr_type != rs_align_code)
17351     return;
17352
17353   p = fragp->fr_literal + fragp->fr_fix;
17354   nop_opcode = *p;
17355   switch (nop_opcode)
17356     {
17357     case NOP_OPCODE_MICROMIPS:
17358       opcode = micromips_nop32_insn.insn_opcode;
17359       size = 4;
17360       break;
17361     case NOP_OPCODE_MIPS16:
17362       opcode = mips16_nop_insn.insn_opcode;
17363       size = 2;
17364       break;
17365     case NOP_OPCODE_MIPS:
17366     default:
17367       opcode = nop_insn.insn_opcode;
17368       size = 4;
17369       break;
17370     }
17371
17372   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
17373   excess = bytes % size;
17374
17375   /* Handle the leading part if we're not inserting a whole number of
17376      instructions, and make it the end of the fixed part of the frag.
17377      Try to fit in a short microMIPS NOP if applicable and possible,
17378      and use zeroes otherwise.  */
17379   gas_assert (excess < 4);
17380   fragp->fr_fix += excess;
17381   switch (excess)
17382     {
17383     case 3:
17384       *p++ = '\0';
17385       /* Fall through.  */
17386     case 2:
17387       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
17388         {
17389           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
17390           break;
17391         }
17392       *p++ = '\0';
17393       /* Fall through.  */
17394     case 1:
17395       *p++ = '\0';
17396       /* Fall through.  */
17397     case 0:
17398       break;
17399     }
17400
17401   md_number_to_chars (p, opcode, size);
17402   fragp->fr_var = size;
17403 }
17404
17405 static void
17406 md_obj_begin (void)
17407 {
17408 }
17409
17410 static void
17411 md_obj_end (void)
17412 {
17413   /* Check for premature end, nesting errors, etc.  */
17414   if (cur_proc_ptr)
17415     as_warn (_("missing .end at end of assembly"));
17416 }
17417
17418 static long
17419 get_number (void)
17420 {
17421   int negative = 0;
17422   long val = 0;
17423
17424   if (*input_line_pointer == '-')
17425     {
17426       ++input_line_pointer;
17427       negative = 1;
17428     }
17429   if (!ISDIGIT (*input_line_pointer))
17430     as_bad (_("expected simple number"));
17431   if (input_line_pointer[0] == '0')
17432     {
17433       if (input_line_pointer[1] == 'x')
17434         {
17435           input_line_pointer += 2;
17436           while (ISXDIGIT (*input_line_pointer))
17437             {
17438               val <<= 4;
17439               val |= hex_value (*input_line_pointer++);
17440             }
17441           return negative ? -val : val;
17442         }
17443       else
17444         {
17445           ++input_line_pointer;
17446           while (ISDIGIT (*input_line_pointer))
17447             {
17448               val <<= 3;
17449               val |= *input_line_pointer++ - '0';
17450             }
17451           return negative ? -val : val;
17452         }
17453     }
17454   if (!ISDIGIT (*input_line_pointer))
17455     {
17456       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
17457               *input_line_pointer, *input_line_pointer);
17458       as_warn (_("invalid number"));
17459       return -1;
17460     }
17461   while (ISDIGIT (*input_line_pointer))
17462     {
17463       val *= 10;
17464       val += *input_line_pointer++ - '0';
17465     }
17466   return negative ? -val : val;
17467 }
17468
17469 /* The .file directive; just like the usual .file directive, but there
17470    is an initial number which is the ECOFF file index.  In the non-ECOFF
17471    case .file implies DWARF-2.  */
17472
17473 static void
17474 s_mips_file (int x ATTRIBUTE_UNUSED)
17475 {
17476   static int first_file_directive = 0;
17477
17478   if (ECOFF_DEBUGGING)
17479     {
17480       get_number ();
17481       s_app_file (0);
17482     }
17483   else
17484     {
17485       char *filename;
17486
17487       filename = dwarf2_directive_file (0);
17488
17489       /* Versions of GCC up to 3.1 start files with a ".file"
17490          directive even for stabs output.  Make sure that this
17491          ".file" is handled.  Note that you need a version of GCC
17492          after 3.1 in order to support DWARF-2 on MIPS.  */
17493       if (filename != NULL && ! first_file_directive)
17494         {
17495           (void) new_logical_line (filename, -1);
17496           s_app_file_string (filename, 0);
17497         }
17498       first_file_directive = 1;
17499     }
17500 }
17501
17502 /* The .loc directive, implying DWARF-2.  */
17503
17504 static void
17505 s_mips_loc (int x ATTRIBUTE_UNUSED)
17506 {
17507   if (!ECOFF_DEBUGGING)
17508     dwarf2_directive_loc (0);
17509 }
17510
17511 /* The .end directive.  */
17512
17513 static void
17514 s_mips_end (int x ATTRIBUTE_UNUSED)
17515 {
17516   symbolS *p;
17517
17518   /* Following functions need their own .frame and .cprestore directives.  */
17519   mips_frame_reg_valid = 0;
17520   mips_cprestore_valid = 0;
17521
17522   if (!is_end_of_line[(unsigned char) *input_line_pointer])
17523     {
17524       p = get_symbol ();
17525       demand_empty_rest_of_line ();
17526     }
17527   else
17528     p = NULL;
17529
17530   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17531     as_warn (_(".end not in text section"));
17532
17533   if (!cur_proc_ptr)
17534     {
17535       as_warn (_(".end directive without a preceding .ent directive."));
17536       demand_empty_rest_of_line ();
17537       return;
17538     }
17539
17540   if (p != NULL)
17541     {
17542       gas_assert (S_GET_NAME (p));
17543       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
17544         as_warn (_(".end symbol does not match .ent symbol."));
17545
17546       if (debug_type == DEBUG_STABS)
17547         stabs_generate_asm_endfunc (S_GET_NAME (p),
17548                                     S_GET_NAME (p));
17549     }
17550   else
17551     as_warn (_(".end directive missing or unknown symbol"));
17552
17553   /* Create an expression to calculate the size of the function.  */
17554   if (p && cur_proc_ptr)
17555     {
17556       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
17557       expressionS *exp = xmalloc (sizeof (expressionS));
17558
17559       obj->size = exp;
17560       exp->X_op = O_subtract;
17561       exp->X_add_symbol = symbol_temp_new_now ();
17562       exp->X_op_symbol = p;
17563       exp->X_add_number = 0;
17564
17565       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
17566     }
17567
17568   /* Generate a .pdr section.  */
17569   if (!ECOFF_DEBUGGING && mips_flag_pdr)
17570     {
17571       segT saved_seg = now_seg;
17572       subsegT saved_subseg = now_subseg;
17573       expressionS exp;
17574       char *fragp;
17575
17576 #ifdef md_flush_pending_output
17577       md_flush_pending_output ();
17578 #endif
17579
17580       gas_assert (pdr_seg);
17581       subseg_set (pdr_seg, 0);
17582
17583       /* Write the symbol.  */
17584       exp.X_op = O_symbol;
17585       exp.X_add_symbol = p;
17586       exp.X_add_number = 0;
17587       emit_expr (&exp, 4);
17588
17589       fragp = frag_more (7 * 4);
17590
17591       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
17592       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
17593       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
17594       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
17595       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
17596       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
17597       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
17598
17599       subseg_set (saved_seg, saved_subseg);
17600     }
17601
17602   cur_proc_ptr = NULL;
17603 }
17604
17605 /* The .aent and .ent directives.  */
17606
17607 static void
17608 s_mips_ent (int aent)
17609 {
17610   symbolS *symbolP;
17611
17612   symbolP = get_symbol ();
17613   if (*input_line_pointer == ',')
17614     ++input_line_pointer;
17615   SKIP_WHITESPACE ();
17616   if (ISDIGIT (*input_line_pointer)
17617       || *input_line_pointer == '-')
17618     get_number ();
17619
17620   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17621     as_warn (_(".ent or .aent not in text section."));
17622
17623   if (!aent && cur_proc_ptr)
17624     as_warn (_("missing .end"));
17625
17626   if (!aent)
17627     {
17628       /* This function needs its own .frame and .cprestore directives.  */
17629       mips_frame_reg_valid = 0;
17630       mips_cprestore_valid = 0;
17631
17632       cur_proc_ptr = &cur_proc;
17633       memset (cur_proc_ptr, '\0', sizeof (procS));
17634
17635       cur_proc_ptr->func_sym = symbolP;
17636
17637       ++numprocs;
17638
17639       if (debug_type == DEBUG_STABS)
17640         stabs_generate_asm_func (S_GET_NAME (symbolP),
17641                                  S_GET_NAME (symbolP));
17642     }
17643
17644   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
17645
17646   demand_empty_rest_of_line ();
17647 }
17648
17649 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
17650    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
17651    s_mips_frame is used so that we can set the PDR information correctly.
17652    We can't use the ecoff routines because they make reference to the ecoff
17653    symbol table (in the mdebug section).  */
17654
17655 static void
17656 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
17657 {
17658   if (ECOFF_DEBUGGING)
17659     s_ignore (ignore);
17660   else
17661     {
17662       long val;
17663
17664       if (cur_proc_ptr == (procS *) NULL)
17665         {
17666           as_warn (_(".frame outside of .ent"));
17667           demand_empty_rest_of_line ();
17668           return;
17669         }
17670
17671       cur_proc_ptr->frame_reg = tc_get_register (1);
17672
17673       SKIP_WHITESPACE ();
17674       if (*input_line_pointer++ != ','
17675           || get_absolute_expression_and_terminator (&val) != ',')
17676         {
17677           as_warn (_("Bad .frame directive"));
17678           --input_line_pointer;
17679           demand_empty_rest_of_line ();
17680           return;
17681         }
17682
17683       cur_proc_ptr->frame_offset = val;
17684       cur_proc_ptr->pc_reg = tc_get_register (0);
17685
17686       demand_empty_rest_of_line ();
17687     }
17688 }
17689
17690 /* The .fmask and .mask directives. If the mdebug section is present
17691    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
17692    embedded targets, s_mips_mask is used so that we can set the PDR
17693    information correctly. We can't use the ecoff routines because they
17694    make reference to the ecoff symbol table (in the mdebug section).  */
17695
17696 static void
17697 s_mips_mask (int reg_type)
17698 {
17699   if (ECOFF_DEBUGGING)
17700     s_ignore (reg_type);
17701   else
17702     {
17703       long mask, off;
17704
17705       if (cur_proc_ptr == (procS *) NULL)
17706         {
17707           as_warn (_(".mask/.fmask outside of .ent"));
17708           demand_empty_rest_of_line ();
17709           return;
17710         }
17711
17712       if (get_absolute_expression_and_terminator (&mask) != ',')
17713         {
17714           as_warn (_("Bad .mask/.fmask directive"));
17715           --input_line_pointer;
17716           demand_empty_rest_of_line ();
17717           return;
17718         }
17719
17720       off = get_absolute_expression ();
17721
17722       if (reg_type == 'F')
17723         {
17724           cur_proc_ptr->fpreg_mask = mask;
17725           cur_proc_ptr->fpreg_offset = off;
17726         }
17727       else
17728         {
17729           cur_proc_ptr->reg_mask = mask;
17730           cur_proc_ptr->reg_offset = off;
17731         }
17732
17733       demand_empty_rest_of_line ();
17734     }
17735 }
17736
17737 /* A table describing all the processors gas knows about.  Names are
17738    matched in the order listed.
17739
17740    To ease comparison, please keep this table in the same order as
17741    gcc's mips_cpu_info_table[].  */
17742 static const struct mips_cpu_info mips_cpu_info_table[] =
17743 {
17744   /* Entries for generic ISAs */
17745   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
17746   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
17747   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
17748   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
17749   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
17750   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
17751   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
17752   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
17753   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
17754
17755   /* MIPS I */
17756   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17757   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17758   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
17759
17760   /* MIPS II */
17761   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
17762
17763   /* MIPS III */
17764   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
17765   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
17766   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
17767   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17768   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17769   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17770   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17771   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
17772   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
17773   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17774   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17775   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
17776   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
17777   /* ST Microelectronics Loongson 2E and 2F cores */
17778   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
17779   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
17780
17781   /* MIPS IV */
17782   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
17783   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
17784   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
17785   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
17786   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
17787   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17788   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
17789   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
17790   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17791   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17792   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17793   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17794   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17795   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
17796   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
17797
17798   /* MIPS 32 */
17799   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17800   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17801   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17802   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
17803
17804   /* MIPS 32 Release 2 */
17805   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17806   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17807   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17808   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
17809   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17810   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17811   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17812   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17813   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17814                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17815   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17816                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17817   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17818   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17819   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17820   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17821   /* Deprecated forms of the above.  */
17822   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17823   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17824   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
17825   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17826   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17827   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17828   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17829   /* Deprecated forms of the above.  */
17830   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17831   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17832   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
17833   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17834   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17835   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17836   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17837   /* Deprecated forms of the above.  */
17838   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17839   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17840   /* 34Kn is a 34kc without DSP.  */
17841   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
17842   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
17843   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17844   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17845   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17846   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17847   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17848   /* Deprecated forms of the above.  */
17849   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17850   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17851   /* 1004K cores are multiprocessor versions of the 34K.  */
17852   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17853   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17854   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17855   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17856
17857   /* MIPS 64 */
17858   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17859   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17860   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17861   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17862
17863   /* Broadcom SB-1 CPU core */
17864   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17865   /* Broadcom SB-1A CPU core */
17866   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17867   
17868   { "loongson3a",     0, 0,                     ISA_MIPS64,   CPU_LOONGSON_3A },
17869
17870   /* MIPS 64 Release 2 */
17871
17872   /* Cavium Networks Octeon CPU core */
17873   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
17874   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
17875   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
17876
17877   /* RMI Xlr */
17878   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
17879
17880   /* Broadcom XLP.
17881      XLP is mostly like XLR, with the prominent exception that it is
17882      MIPS64R2 rather than MIPS64.  */
17883   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
17884
17885   /* End marker */
17886   { NULL, 0, 0, 0, 0 }
17887 };
17888
17889
17890 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
17891    with a final "000" replaced by "k".  Ignore case.
17892
17893    Note: this function is shared between GCC and GAS.  */
17894
17895 static bfd_boolean
17896 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
17897 {
17898   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
17899     given++, canonical++;
17900
17901   return ((*given == 0 && *canonical == 0)
17902           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
17903 }
17904
17905
17906 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
17907    CPU name.  We've traditionally allowed a lot of variation here.
17908
17909    Note: this function is shared between GCC and GAS.  */
17910
17911 static bfd_boolean
17912 mips_matching_cpu_name_p (const char *canonical, const char *given)
17913 {
17914   /* First see if the name matches exactly, or with a final "000"
17915      turned into "k".  */
17916   if (mips_strict_matching_cpu_name_p (canonical, given))
17917     return TRUE;
17918
17919   /* If not, try comparing based on numerical designation alone.
17920      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
17921   if (TOLOWER (*given) == 'r')
17922     given++;
17923   if (!ISDIGIT (*given))
17924     return FALSE;
17925
17926   /* Skip over some well-known prefixes in the canonical name,
17927      hoping to find a number there too.  */
17928   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
17929     canonical += 2;
17930   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
17931     canonical += 2;
17932   else if (TOLOWER (canonical[0]) == 'r')
17933     canonical += 1;
17934
17935   return mips_strict_matching_cpu_name_p (canonical, given);
17936 }
17937
17938
17939 /* Parse an option that takes the name of a processor as its argument.
17940    OPTION is the name of the option and CPU_STRING is the argument.
17941    Return the corresponding processor enumeration if the CPU_STRING is
17942    recognized, otherwise report an error and return null.
17943
17944    A similar function exists in GCC.  */
17945
17946 static const struct mips_cpu_info *
17947 mips_parse_cpu (const char *option, const char *cpu_string)
17948 {
17949   const struct mips_cpu_info *p;
17950
17951   /* 'from-abi' selects the most compatible architecture for the given
17952      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
17953      EABIs, we have to decide whether we're using the 32-bit or 64-bit
17954      version.  Look first at the -mgp options, if given, otherwise base
17955      the choice on MIPS_DEFAULT_64BIT.
17956
17957      Treat NO_ABI like the EABIs.  One reason to do this is that the
17958      plain 'mips' and 'mips64' configs have 'from-abi' as their default
17959      architecture.  This code picks MIPS I for 'mips' and MIPS III for
17960      'mips64', just as we did in the days before 'from-abi'.  */
17961   if (strcasecmp (cpu_string, "from-abi") == 0)
17962     {
17963       if (ABI_NEEDS_32BIT_REGS (mips_abi))
17964         return mips_cpu_info_from_isa (ISA_MIPS1);
17965
17966       if (ABI_NEEDS_64BIT_REGS (mips_abi))
17967         return mips_cpu_info_from_isa (ISA_MIPS3);
17968
17969       if (file_mips_gp32 >= 0)
17970         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
17971
17972       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
17973                                      ? ISA_MIPS3
17974                                      : ISA_MIPS1);
17975     }
17976
17977   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
17978   if (strcasecmp (cpu_string, "default") == 0)
17979     return 0;
17980
17981   for (p = mips_cpu_info_table; p->name != 0; p++)
17982     if (mips_matching_cpu_name_p (p->name, cpu_string))
17983       return p;
17984
17985   as_bad (_("Bad value (%s) for %s"), cpu_string, option);
17986   return 0;
17987 }
17988
17989 /* Return the canonical processor information for ISA (a member of the
17990    ISA_MIPS* enumeration).  */
17991
17992 static const struct mips_cpu_info *
17993 mips_cpu_info_from_isa (int isa)
17994 {
17995   int i;
17996
17997   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
17998     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
17999         && isa == mips_cpu_info_table[i].isa)
18000       return (&mips_cpu_info_table[i]);
18001
18002   return NULL;
18003 }
18004
18005 static const struct mips_cpu_info *
18006 mips_cpu_info_from_arch (int arch)
18007 {
18008   int i;
18009
18010   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18011     if (arch == mips_cpu_info_table[i].cpu)
18012       return (&mips_cpu_info_table[i]);
18013
18014   return NULL;
18015 }
18016 \f
18017 static void
18018 show (FILE *stream, const char *string, int *col_p, int *first_p)
18019 {
18020   if (*first_p)
18021     {
18022       fprintf (stream, "%24s", "");
18023       *col_p = 24;
18024     }
18025   else
18026     {
18027       fprintf (stream, ", ");
18028       *col_p += 2;
18029     }
18030
18031   if (*col_p + strlen (string) > 72)
18032     {
18033       fprintf (stream, "\n%24s", "");
18034       *col_p = 24;
18035     }
18036
18037   fprintf (stream, "%s", string);
18038   *col_p += strlen (string);
18039
18040   *first_p = 0;
18041 }
18042
18043 void
18044 md_show_usage (FILE *stream)
18045 {
18046   int column, first;
18047   size_t i;
18048
18049   fprintf (stream, _("\
18050 MIPS options:\n\
18051 -EB                     generate big endian output\n\
18052 -EL                     generate little endian output\n\
18053 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
18054 -G NUM                  allow referencing objects up to NUM bytes\n\
18055                         implicitly with the gp register [default 8]\n"));
18056   fprintf (stream, _("\
18057 -mips1                  generate MIPS ISA I instructions\n\
18058 -mips2                  generate MIPS ISA II instructions\n\
18059 -mips3                  generate MIPS ISA III instructions\n\
18060 -mips4                  generate MIPS ISA IV instructions\n\
18061 -mips5                  generate MIPS ISA V instructions\n\
18062 -mips32                 generate MIPS32 ISA instructions\n\
18063 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
18064 -mips64                 generate MIPS64 ISA instructions\n\
18065 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
18066 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
18067
18068   first = 1;
18069
18070   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18071     show (stream, mips_cpu_info_table[i].name, &column, &first);
18072   show (stream, "from-abi", &column, &first);
18073   fputc ('\n', stream);
18074
18075   fprintf (stream, _("\
18076 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
18077 -no-mCPU                don't generate code specific to CPU.\n\
18078                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
18079
18080   first = 1;
18081
18082   show (stream, "3900", &column, &first);
18083   show (stream, "4010", &column, &first);
18084   show (stream, "4100", &column, &first);
18085   show (stream, "4650", &column, &first);
18086   fputc ('\n', stream);
18087
18088   fprintf (stream, _("\
18089 -mips16                 generate mips16 instructions\n\
18090 -no-mips16              do not generate mips16 instructions\n"));
18091   fprintf (stream, _("\
18092 -mmicromips             generate microMIPS instructions\n\
18093 -mno-micromips          do not generate microMIPS instructions\n"));
18094   fprintf (stream, _("\
18095 -msmartmips             generate smartmips instructions\n\
18096 -mno-smartmips          do not generate smartmips instructions\n"));  
18097   fprintf (stream, _("\
18098 -mdsp                   generate DSP instructions\n\
18099 -mno-dsp                do not generate DSP instructions\n"));
18100   fprintf (stream, _("\
18101 -mdspr2                 generate DSP R2 instructions\n\
18102 -mno-dspr2              do not generate DSP R2 instructions\n"));
18103   fprintf (stream, _("\
18104 -mmt                    generate MT instructions\n\
18105 -mno-mt                 do not generate MT instructions\n"));
18106   fprintf (stream, _("\
18107 -mmcu                   generate MCU instructions\n\
18108 -mno-mcu                do not generate MCU instructions\n"));
18109   fprintf (stream, _("\
18110 -mvirt                  generate Virtualization instructions\n\
18111 -mno-virt               do not generate Virtualization instructions\n"));
18112   fprintf (stream, _("\
18113 -minsn32                only generate 32-bit microMIPS instructions\n\
18114 -mno-insn32             generate all microMIPS instructions\n"));
18115   fprintf (stream, _("\
18116 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
18117 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
18118 -mfix-vr4120            work around certain VR4120 errata\n\
18119 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
18120 -mfix-24k               insert a nop after ERET and DERET instructions\n\
18121 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
18122 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
18123 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
18124 -msym32                 assume all symbols have 32-bit values\n\
18125 -O0                     remove unneeded NOPs, do not swap branches\n\
18126 -O                      remove unneeded NOPs and swap branches\n\
18127 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
18128 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
18129   fprintf (stream, _("\
18130 -mhard-float            allow floating-point instructions\n\
18131 -msoft-float            do not allow floating-point instructions\n\
18132 -msingle-float          only allow 32-bit floating-point operations\n\
18133 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
18134 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
18135 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
18136 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
18137
18138   first = 1;
18139
18140   show (stream, "legacy", &column, &first);
18141   show (stream, "2008", &column, &first);
18142
18143   fputc ('\n', stream);
18144
18145   fprintf (stream, _("\
18146 -KPIC, -call_shared     generate SVR4 position independent code\n\
18147 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
18148 -mvxworks-pic           generate VxWorks position independent code\n\
18149 -non_shared             do not generate code that can operate with DSOs\n\
18150 -xgot                   assume a 32 bit GOT\n\
18151 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
18152 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
18153                         position dependent (non shared) code\n\
18154 -mabi=ABI               create ABI conformant object file for:\n"));
18155
18156   first = 1;
18157
18158   show (stream, "32", &column, &first);
18159   show (stream, "o64", &column, &first);
18160   show (stream, "n32", &column, &first);
18161   show (stream, "64", &column, &first);
18162   show (stream, "eabi", &column, &first);
18163
18164   fputc ('\n', stream);
18165
18166   fprintf (stream, _("\
18167 -32                     create o32 ABI object file (default)\n\
18168 -n32                    create n32 ABI object file\n\
18169 -64                     create 64 ABI object file\n"));
18170 }
18171
18172 #ifdef TE_IRIX
18173 enum dwarf2_format
18174 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
18175 {
18176   if (HAVE_64BIT_SYMBOLS)
18177     return dwarf2_format_64bit_irix;
18178   else
18179     return dwarf2_format_32bit;
18180 }
18181 #endif
18182
18183 int
18184 mips_dwarf2_addr_size (void)
18185 {
18186   if (HAVE_64BIT_OBJECTS)
18187     return 8;
18188   else
18189     return 4;
18190 }
18191
18192 /* Standard calling conventions leave the CFA at SP on entry.  */
18193 void
18194 mips_cfi_frame_initial_instructions (void)
18195 {
18196   cfi_add_CFA_def_cfa_register (SP);
18197 }
18198
18199 int
18200 tc_mips_regname_to_dw2regnum (char *regname)
18201 {
18202   unsigned int regnum = -1;
18203   unsigned int reg;
18204
18205   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
18206     regnum = reg;
18207
18208   return regnum;
18209 }