* configure.ac (mips*-*-bsd*, mips*-*-ultrix*, mips*-*-osf*)
[platform/upstream/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 #ifdef DEBUG
38 #define DBG(x) printf x
39 #else
40 #define DBG(x)
41 #endif
42
43 #ifdef OBJ_MAYBE_ELF
44 /* Clean up namespace so we can include obj-elf.h too.  */
45 static int mips_output_flavor (void);
46 static int mips_output_flavor (void) { return OUTPUT_FLAVOR; }
47 #undef OBJ_PROCESS_STAB
48 #undef OUTPUT_FLAVOR
49 #undef S_GET_ALIGN
50 #undef S_GET_SIZE
51 #undef S_SET_ALIGN
52 #undef S_SET_SIZE
53 #undef obj_frob_file
54 #undef obj_frob_file_after_relocs
55 #undef obj_frob_symbol
56 #undef obj_pop_insert
57 #undef obj_sec_sym_ok_for_reloc
58 #undef OBJ_COPY_SYMBOL_ATTRIBUTES
59
60 #include "obj-elf.h"
61 /* Fix any of them that we actually care about.  */
62 #undef OUTPUT_FLAVOR
63 #define OUTPUT_FLAVOR mips_output_flavor()
64 #endif
65
66 #if defined (OBJ_ELF)
67 #include "elf/mips.h"
68 #endif
69
70 #ifndef ECOFF_DEBUGGING
71 #define NO_ECOFF_DEBUGGING
72 #define ECOFF_DEBUGGING 0
73 #endif
74
75 int mips_flag_mdebug = -1;
76
77 /* Control generation of .pdr sections.  Off by default on IRIX: the native
78    linker doesn't know about and discards them, but relocations against them
79    remain, leading to rld crashes.  */
80 #ifdef TE_IRIX
81 int mips_flag_pdr = FALSE;
82 #else
83 int mips_flag_pdr = TRUE;
84 #endif
85
86 #include "ecoff.h"
87
88 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
89 static char *mips_regmask_frag;
90 #endif
91
92 #define ZERO 0
93 #define ATREG 1
94 #define S0  16
95 #define S7  23
96 #define TREG 24
97 #define PIC_CALL_REG 25
98 #define KT0 26
99 #define KT1 27
100 #define GP  28
101 #define SP  29
102 #define FP  30
103 #define RA  31
104
105 #define ILLEGAL_REG (32)
106
107 #define AT  mips_opts.at
108
109 extern int target_big_endian;
110
111 /* The name of the readonly data section.  */
112 #define RDATA_SECTION_NAME ".rodata"
113
114 /* Ways in which an instruction can be "appended" to the output.  */
115 enum append_method {
116   /* Just add it normally.  */
117   APPEND_ADD,
118
119   /* Add it normally and then add a nop.  */
120   APPEND_ADD_WITH_NOP,
121
122   /* Turn an instruction with a delay slot into a "compact" version.  */
123   APPEND_ADD_COMPACT,
124
125   /* Insert the instruction before the last one.  */
126   APPEND_SWAP
127 };
128
129 /* Information about an instruction, including its format, operands
130    and fixups.  */
131 struct mips_cl_insn
132 {
133   /* The opcode's entry in mips_opcodes or mips16_opcodes.  */
134   const struct mips_opcode *insn_mo;
135
136   /* The 16-bit or 32-bit bitstring of the instruction itself.  This is
137      a copy of INSN_MO->match with the operands filled in.  If we have
138      decided to use an extended MIPS16 instruction, this includes the
139      extension.  */
140   unsigned long insn_opcode;
141
142   /* The frag that contains the instruction.  */
143   struct frag *frag;
144
145   /* The offset into FRAG of the first instruction byte.  */
146   long where;
147
148   /* The relocs associated with the instruction, if any.  */
149   fixS *fixp[3];
150
151   /* True if this entry cannot be moved from its current position.  */
152   unsigned int fixed_p : 1;
153
154   /* True if this instruction occurred in a .set noreorder block.  */
155   unsigned int noreorder_p : 1;
156
157   /* True for mips16 instructions that jump to an absolute address.  */
158   unsigned int mips16_absolute_jump_p : 1;
159
160   /* True if this instruction is complete.  */
161   unsigned int complete_p : 1;
162
163   /* True if this instruction is cleared from history by unconditional
164      branch.  */
165   unsigned int cleared_p : 1;
166 };
167
168 /* The ABI to use.  */
169 enum mips_abi_level
170 {
171   NO_ABI = 0,
172   O32_ABI,
173   O64_ABI,
174   N32_ABI,
175   N64_ABI,
176   EABI_ABI
177 };
178
179 /* MIPS ABI we are using for this output file.  */
180 static enum mips_abi_level mips_abi = NO_ABI;
181
182 /* Whether or not we have code that can call pic code.  */
183 int mips_abicalls = FALSE;
184
185 /* Whether or not we have code which can be put into a shared
186    library.  */
187 static bfd_boolean mips_in_shared = TRUE;
188
189 /* This is the set of options which may be modified by the .set
190    pseudo-op.  We use a struct so that .set push and .set pop are more
191    reliable.  */
192
193 struct mips_set_options
194 {
195   /* MIPS ISA (Instruction Set Architecture) level.  This is set to -1
196      if it has not been initialized.  Changed by `.set mipsN', and the
197      -mipsN command line option, and the default CPU.  */
198   int isa;
199   /* Enabled Application Specific Extensions (ASEs).  Changed by `.set
200      <asename>', by command line options, and based on the default
201      architecture.  */
202   int ase;
203   /* Whether we are assembling for the mips16 processor.  0 if we are
204      not, 1 if we are, and -1 if the value has not been initialized.
205      Changed by `.set mips16' and `.set nomips16', and the -mips16 and
206      -nomips16 command line options, and the default CPU.  */
207   int mips16;
208   /* Whether we are assembling for the mipsMIPS ASE.  0 if we are not,
209      1 if we are, and -1 if the value has not been initialized.  Changed
210      by `.set micromips' and `.set nomicromips', and the -mmicromips
211      and -mno-micromips command line options, and the default CPU.  */
212   int micromips;
213   /* Non-zero if we should not reorder instructions.  Changed by `.set
214      reorder' and `.set noreorder'.  */
215   int noreorder;
216   /* Non-zero if we should not permit the register designated "assembler
217      temporary" to be used in instructions.  The value is the register
218      number, normally $at ($1).  Changed by `.set at=REG', `.set noat'
219      (same as `.set at=$0') and `.set at' (same as `.set at=$1').  */
220   unsigned int at;
221   /* Non-zero if we should warn when a macro instruction expands into
222      more than one machine instruction.  Changed by `.set nomacro' and
223      `.set macro'.  */
224   int warn_about_macros;
225   /* Non-zero if we should not move instructions.  Changed by `.set
226      move', `.set volatile', `.set nomove', and `.set novolatile'.  */
227   int nomove;
228   /* Non-zero if we should not optimize branches by moving the target
229      of the branch into the delay slot.  Actually, we don't perform
230      this optimization anyhow.  Changed by `.set bopt' and `.set
231      nobopt'.  */
232   int nobopt;
233   /* Non-zero if we should not autoextend mips16 instructions.
234      Changed by `.set autoextend' and `.set noautoextend'.  */
235   int noautoextend;
236   /* Restrict general purpose registers and floating point registers
237      to 32 bit.  This is initially determined when -mgp32 or -mfp32
238      is passed but can changed if the assembler code uses .set mipsN.  */
239   int gp32;
240   int fp32;
241   /* MIPS architecture (CPU) type.  Changed by .set arch=FOO, the -march
242      command line option, and the default CPU.  */
243   int arch;
244   /* True if ".set sym32" is in effect.  */
245   bfd_boolean sym32;
246   /* True if floating-point operations are not allowed.  Changed by .set
247      softfloat or .set hardfloat, by command line options -msoft-float or
248      -mhard-float.  The default is false.  */
249   bfd_boolean soft_float;
250
251   /* True if only single-precision floating-point operations are allowed.
252      Changed by .set singlefloat or .set doublefloat, command-line options
253      -msingle-float or -mdouble-float.  The default is false.  */
254   bfd_boolean single_float;
255 };
256
257 /* This is the struct we use to hold the current set of options.  Note
258    that we must set the isa field to ISA_UNKNOWN and the ASE fields to
259    -1 to indicate that they have not been initialized.  */
260
261 /* True if -mgp32 was passed.  */
262 static int file_mips_gp32 = -1;
263
264 /* True if -mfp32 was passed.  */
265 static int file_mips_fp32 = -1;
266
267 /* 1 if -msoft-float, 0 if -mhard-float.  The default is 0.  */
268 static int file_mips_soft_float = 0;
269
270 /* 1 if -msingle-float, 0 if -mdouble-float.  The default is 0.   */
271 static int file_mips_single_float = 0;
272
273 static struct mips_set_options mips_opts =
274 {
275   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
276   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
277   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* gp32 */ 0,
278   /* fp32 */ 0, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
279   /* soft_float */ FALSE, /* single_float */ FALSE
280 };
281
282 /* The set of ASEs that were selected on the command line, either
283    explicitly via ASE options or implicitly through things like -march.  */
284 static unsigned int file_ase;
285
286 /* Which bits of file_ase were explicitly set or cleared by ASE options.  */
287 static unsigned int file_ase_explicit;
288
289 /* These variables are filled in with the masks of registers used.
290    The object format code reads them and puts them in the appropriate
291    place.  */
292 unsigned long mips_gprmask;
293 unsigned long mips_cprmask[4];
294
295 /* MIPS ISA we are using for this output file.  */
296 static int file_mips_isa = ISA_UNKNOWN;
297
298 /* True if any MIPS16 code was produced.  */
299 static int file_ase_mips16;
300
301 #define ISA_SUPPORTS_MIPS16E (mips_opts.isa == ISA_MIPS32               \
302                               || mips_opts.isa == ISA_MIPS32R2          \
303                               || mips_opts.isa == ISA_MIPS64            \
304                               || mips_opts.isa == ISA_MIPS64R2)
305
306 /* True if any microMIPS code was produced.  */
307 static int file_ase_micromips;
308
309 /* True if we want to create R_MIPS_JALR for jalr $25.  */
310 #ifdef TE_IRIX
311 #define MIPS_JALR_HINT_P(EXPR) HAVE_NEWABI
312 #else
313 /* As a GNU extension, we use R_MIPS_JALR for o32 too.  However,
314    because there's no place for any addend, the only acceptable
315    expression is a bare symbol.  */
316 #define MIPS_JALR_HINT_P(EXPR) \
317   (!HAVE_IN_PLACE_ADDENDS \
318    || ((EXPR)->X_op == O_symbol && (EXPR)->X_add_number == 0))
319 #endif
320
321 /* The argument of the -march= flag.  The architecture we are assembling.  */
322 static int file_mips_arch = CPU_UNKNOWN;
323 static const char *mips_arch_string;
324
325 /* The argument of the -mtune= flag.  The architecture for which we
326    are optimizing.  */
327 static int mips_tune = CPU_UNKNOWN;
328 static const char *mips_tune_string;
329
330 /* True when generating 32-bit code for a 64-bit processor.  */
331 static int mips_32bitmode = 0;
332
333 /* True if the given ABI requires 32-bit registers.  */
334 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
335
336 /* Likewise 64-bit registers.  */
337 #define ABI_NEEDS_64BIT_REGS(ABI)       \
338   ((ABI) == N32_ABI                     \
339    || (ABI) == N64_ABI                  \
340    || (ABI) == O64_ABI)
341
342 /*  Return true if ISA supports 64 bit wide gp registers.  */
343 #define ISA_HAS_64BIT_REGS(ISA)         \
344   ((ISA) == ISA_MIPS3                   \
345    || (ISA) == ISA_MIPS4                \
346    || (ISA) == ISA_MIPS5                \
347    || (ISA) == ISA_MIPS64               \
348    || (ISA) == ISA_MIPS64R2)
349
350 /*  Return true if ISA supports 64 bit wide float registers.  */
351 #define ISA_HAS_64BIT_FPRS(ISA)         \
352   ((ISA) == ISA_MIPS3                   \
353    || (ISA) == ISA_MIPS4                \
354    || (ISA) == ISA_MIPS5                \
355    || (ISA) == ISA_MIPS32R2             \
356    || (ISA) == ISA_MIPS64               \
357    || (ISA) == ISA_MIPS64R2)
358
359 /* Return true if ISA supports 64-bit right rotate (dror et al.)
360    instructions.  */
361 #define ISA_HAS_DROR(ISA)               \
362   ((ISA) == ISA_MIPS64R2                \
363    || (mips_opts.micromips              \
364        && ISA_HAS_64BIT_REGS (ISA))     \
365    )
366
367 /* Return true if ISA supports 32-bit right rotate (ror et al.)
368    instructions.  */
369 #define ISA_HAS_ROR(ISA)                \
370   ((ISA) == ISA_MIPS32R2                \
371    || (ISA) == ISA_MIPS64R2             \
372    || (mips_opts.ase & ASE_SMARTMIPS)   \
373    || mips_opts.micromips               \
374    )
375
376 /* Return true if ISA supports single-precision floats in odd registers.  */
377 #define ISA_HAS_ODD_SINGLE_FPR(ISA)     \
378   ((ISA) == ISA_MIPS32                  \
379    || (ISA) == ISA_MIPS32R2             \
380    || (ISA) == ISA_MIPS64               \
381    || (ISA) == ISA_MIPS64R2)
382
383 /* Return true if ISA supports move to/from high part of a 64-bit
384    floating-point register. */
385 #define ISA_HAS_MXHC1(ISA)              \
386   ((ISA) == ISA_MIPS32R2                \
387    || (ISA) == ISA_MIPS64R2)
388
389 #define HAVE_32BIT_GPRS                            \
390     (mips_opts.gp32 || !ISA_HAS_64BIT_REGS (mips_opts.isa))
391
392 #define HAVE_32BIT_FPRS                            \
393     (mips_opts.fp32 || !ISA_HAS_64BIT_FPRS (mips_opts.isa))
394
395 #define HAVE_64BIT_GPRS (!HAVE_32BIT_GPRS)
396 #define HAVE_64BIT_FPRS (!HAVE_32BIT_FPRS)
397
398 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
399
400 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
401
402 /* True if relocations are stored in-place.  */
403 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
404
405 /* The ABI-derived address size.  */
406 #define HAVE_64BIT_ADDRESSES \
407   (HAVE_64BIT_GPRS && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
408 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
409
410 /* The size of symbolic constants (i.e., expressions of the form
411    "SYMBOL" or "SYMBOL + OFFSET").  */
412 #define HAVE_32BIT_SYMBOLS \
413   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
414 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
415
416 /* Addresses are loaded in different ways, depending on the address size
417    in use.  The n32 ABI Documentation also mandates the use of additions
418    with overflow checking, but existing implementations don't follow it.  */
419 #define ADDRESS_ADD_INSN                                                \
420    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
421
422 #define ADDRESS_ADDI_INSN                                               \
423    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
424
425 #define ADDRESS_LOAD_INSN                                               \
426    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
427
428 #define ADDRESS_STORE_INSN                                              \
429    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
430
431 /* Return true if the given CPU supports the MIPS16 ASE.  */
432 #define CPU_HAS_MIPS16(cpu)                                             \
433    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
434     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
435
436 /* Return true if the given CPU supports the microMIPS ASE.  */
437 #define CPU_HAS_MICROMIPS(cpu)  0
438
439 /* True if CPU has a dror instruction.  */
440 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
441
442 /* True if CPU has a ror instruction.  */
443 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
444
445 /* True if CPU is in the Octeon family */
446 #define CPU_IS_OCTEON(CPU) ((CPU) == CPU_OCTEON || (CPU) == CPU_OCTEONP || (CPU) == CPU_OCTEON2)
447
448 /* True if CPU has seq/sne and seqi/snei instructions.  */
449 #define CPU_HAS_SEQ(CPU)        (CPU_IS_OCTEON (CPU))
450
451 /* True, if CPU has support for ldc1 and sdc1. */
452 #define CPU_HAS_LDC1_SDC1(CPU)  \
453    ((mips_opts.isa != ISA_MIPS1) && ((CPU) != CPU_R5900))
454
455 /* True if mflo and mfhi can be immediately followed by instructions
456    which write to the HI and LO registers.
457
458    According to MIPS specifications, MIPS ISAs I, II, and III need
459    (at least) two instructions between the reads of HI/LO and
460    instructions which write them, and later ISAs do not.  Contradicting
461    the MIPS specifications, some MIPS IV processor user manuals (e.g.
462    the UM for the NEC Vr5000) document needing the instructions between
463    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
464    MIPS64 and later ISAs to have the interlocks, plus any specific
465    earlier-ISA CPUs for which CPU documentation declares that the
466    instructions are really interlocked.  */
467 #define hilo_interlocks \
468   (mips_opts.isa == ISA_MIPS32                        \
469    || mips_opts.isa == ISA_MIPS32R2                   \
470    || mips_opts.isa == ISA_MIPS64                     \
471    || mips_opts.isa == ISA_MIPS64R2                   \
472    || mips_opts.arch == CPU_R4010                     \
473    || mips_opts.arch == CPU_R5900                     \
474    || mips_opts.arch == CPU_R10000                    \
475    || mips_opts.arch == CPU_R12000                    \
476    || mips_opts.arch == CPU_R14000                    \
477    || mips_opts.arch == CPU_R16000                    \
478    || mips_opts.arch == CPU_RM7000                    \
479    || mips_opts.arch == CPU_VR5500                    \
480    || mips_opts.micromips                             \
481    )
482
483 /* Whether the processor uses hardware interlocks to protect reads
484    from the GPRs after they are loaded from memory, and thus does not
485    require nops to be inserted.  This applies to instructions marked
486    INSN_LOAD_MEMORY_DELAY.  These nops are only required at MIPS ISA
487    level I and microMIPS mode instructions are always interlocked.  */
488 #define gpr_interlocks                                \
489   (mips_opts.isa != ISA_MIPS1                         \
490    || mips_opts.arch == CPU_R3900                     \
491    || mips_opts.arch == CPU_R5900                     \
492    || mips_opts.micromips                             \
493    )
494
495 /* Whether the processor uses hardware interlocks to avoid delays
496    required by coprocessor instructions, and thus does not require
497    nops to be inserted.  This applies to instructions marked
498    INSN_LOAD_COPROC_DELAY, INSN_COPROC_MOVE_DELAY, and to delays
499    between instructions marked INSN_WRITE_COND_CODE and ones marked
500    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
501    levels I, II, and III and microMIPS mode instructions are always
502    interlocked.  */
503 /* Itbl support may require additional care here.  */
504 #define cop_interlocks                                \
505   ((mips_opts.isa != ISA_MIPS1                        \
506     && mips_opts.isa != ISA_MIPS2                     \
507     && mips_opts.isa != ISA_MIPS3)                    \
508    || mips_opts.arch == CPU_R4300                     \
509    || mips_opts.micromips                             \
510    )
511
512 /* Whether the processor uses hardware interlocks to protect reads
513    from coprocessor registers after they are loaded from memory, and
514    thus does not require nops to be inserted.  This applies to
515    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
516    requires at MIPS ISA level I and microMIPS mode instructions are
517    always interlocked.  */
518 #define cop_mem_interlocks                            \
519   (mips_opts.isa != ISA_MIPS1                         \
520    || mips_opts.micromips                             \
521    )
522
523 /* Is this a mfhi or mflo instruction?  */
524 #define MF_HILO_INSN(PINFO) \
525   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
526
527 /* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
528    has been selected.  This implies, in particular, that addresses of text
529    labels have their LSB set.  */
530 #define HAVE_CODE_COMPRESSION                                           \
531   ((mips_opts.mips16 | mips_opts.micromips) != 0)
532
533 /* MIPS PIC level.  */
534
535 enum mips_pic_level mips_pic;
536
537 /* 1 if we should generate 32 bit offsets from the $gp register in
538    SVR4_PIC mode.  Currently has no meaning in other modes.  */
539 static int mips_big_got = 0;
540
541 /* 1 if trap instructions should used for overflow rather than break
542    instructions.  */
543 static int mips_trap = 0;
544
545 /* 1 if double width floating point constants should not be constructed
546    by assembling two single width halves into two single width floating
547    point registers which just happen to alias the double width destination
548    register.  On some architectures this aliasing can be disabled by a bit
549    in the status register, and the setting of this bit cannot be determined
550    automatically at assemble time.  */
551 static int mips_disable_float_construction;
552
553 /* Non-zero if any .set noreorder directives were used.  */
554
555 static int mips_any_noreorder;
556
557 /* Non-zero if nops should be inserted when the register referenced in
558    an mfhi/mflo instruction is read in the next two instructions.  */
559 static int mips_7000_hilo_fix;
560
561 /* The size of objects in the small data section.  */
562 static unsigned int g_switch_value = 8;
563 /* Whether the -G option was used.  */
564 static int g_switch_seen = 0;
565
566 #define N_RMASK 0xc4
567 #define N_VFP   0xd4
568
569 /* If we can determine in advance that GP optimization won't be
570    possible, we can skip the relaxation stuff that tries to produce
571    GP-relative references.  This makes delay slot optimization work
572    better.
573
574    This function can only provide a guess, but it seems to work for
575    gcc output.  It needs to guess right for gcc, otherwise gcc
576    will put what it thinks is a GP-relative instruction in a branch
577    delay slot.
578
579    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
580    fixed it for the non-PIC mode.  KR 95/04/07  */
581 static int nopic_need_relax (symbolS *, int);
582
583 /* handle of the OPCODE hash table */
584 static struct hash_control *op_hash = NULL;
585
586 /* The opcode hash table we use for the mips16.  */
587 static struct hash_control *mips16_op_hash = NULL;
588
589 /* The opcode hash table we use for the microMIPS ASE.  */
590 static struct hash_control *micromips_op_hash = NULL;
591
592 /* This array holds the chars that always start a comment.  If the
593     pre-processor is disabled, these aren't very useful */
594 const char comment_chars[] = "#";
595
596 /* This array holds the chars that only start a comment at the beginning of
597    a line.  If the line seems to have the form '# 123 filename'
598    .line and .file directives will appear in the pre-processed output */
599 /* Note that input_file.c hand checks for '#' at the beginning of the
600    first line of the input file.  This is because the compiler outputs
601    #NO_APP at the beginning of its output.  */
602 /* Also note that C style comments are always supported.  */
603 const char line_comment_chars[] = "#";
604
605 /* This array holds machine specific line separator characters.  */
606 const char line_separator_chars[] = ";";
607
608 /* Chars that can be used to separate mant from exp in floating point nums */
609 const char EXP_CHARS[] = "eE";
610
611 /* Chars that mean this number is a floating point constant */
612 /* As in 0f12.456 */
613 /* or    0d1.2345e12 */
614 const char FLT_CHARS[] = "rRsSfFdDxXpP";
615
616 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
617    changed in read.c .  Ideally it shouldn't have to know about it at all,
618    but nothing is ideal around here.
619  */
620
621 static char *insn_error;
622
623 static int auto_align = 1;
624
625 /* When outputting SVR4 PIC code, the assembler needs to know the
626    offset in the stack frame from which to restore the $gp register.
627    This is set by the .cprestore pseudo-op, and saved in this
628    variable.  */
629 static offsetT mips_cprestore_offset = -1;
630
631 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
632    more optimizations, it can use a register value instead of a memory-saved
633    offset and even an other register than $gp as global pointer.  */
634 static offsetT mips_cpreturn_offset = -1;
635 static int mips_cpreturn_register = -1;
636 static int mips_gp_register = GP;
637 static int mips_gprel_offset = 0;
638
639 /* Whether mips_cprestore_offset has been set in the current function
640    (or whether it has already been warned about, if not).  */
641 static int mips_cprestore_valid = 0;
642
643 /* This is the register which holds the stack frame, as set by the
644    .frame pseudo-op.  This is needed to implement .cprestore.  */
645 static int mips_frame_reg = SP;
646
647 /* Whether mips_frame_reg has been set in the current function
648    (or whether it has already been warned about, if not).  */
649 static int mips_frame_reg_valid = 0;
650
651 /* To output NOP instructions correctly, we need to keep information
652    about the previous two instructions.  */
653
654 /* Whether we are optimizing.  The default value of 2 means to remove
655    unneeded NOPs and swap branch instructions when possible.  A value
656    of 1 means to not swap branches.  A value of 0 means to always
657    insert NOPs.  */
658 static int mips_optimize = 2;
659
660 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
661    equivalent to seeing no -g option at all.  */
662 static int mips_debug = 0;
663
664 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
665 #define MAX_VR4130_NOPS 4
666
667 /* The maximum number of NOPs needed to fill delay slots.  */
668 #define MAX_DELAY_NOPS 2
669
670 /* The maximum number of NOPs needed for any purpose.  */
671 #define MAX_NOPS 4
672
673 /* A list of previous instructions, with index 0 being the most recent.
674    We need to look back MAX_NOPS instructions when filling delay slots
675    or working around processor errata.  We need to look back one
676    instruction further if we're thinking about using history[0] to
677    fill a branch delay slot.  */
678 static struct mips_cl_insn history[1 + MAX_NOPS];
679
680 /* Nop instructions used by emit_nop.  */
681 static struct mips_cl_insn nop_insn;
682 static struct mips_cl_insn mips16_nop_insn;
683 static struct mips_cl_insn micromips_nop16_insn;
684 static struct mips_cl_insn micromips_nop32_insn;
685
686 /* The appropriate nop for the current mode.  */
687 #define NOP_INSN (mips_opts.mips16 ? &mips16_nop_insn \
688                   : (mips_opts.micromips ? &micromips_nop16_insn : &nop_insn))
689
690 /* The size of NOP_INSN in bytes.  */
691 #define NOP_INSN_SIZE (HAVE_CODE_COMPRESSION ? 2 : 4)
692
693 /* If this is set, it points to a frag holding nop instructions which
694    were inserted before the start of a noreorder section.  If those
695    nops turn out to be unnecessary, the size of the frag can be
696    decreased.  */
697 static fragS *prev_nop_frag;
698
699 /* The number of nop instructions we created in prev_nop_frag.  */
700 static int prev_nop_frag_holds;
701
702 /* The number of nop instructions that we know we need in
703    prev_nop_frag.  */
704 static int prev_nop_frag_required;
705
706 /* The number of instructions we've seen since prev_nop_frag.  */
707 static int prev_nop_frag_since;
708
709 /* Relocations against symbols are sometimes done in two parts, with a HI
710    relocation and a LO relocation.  Each relocation has only 16 bits of
711    space to store an addend.  This means that in order for the linker to
712    handle carries correctly, it must be able to locate both the HI and
713    the LO relocation.  This means that the relocations must appear in
714    order in the relocation table.
715
716    In order to implement this, we keep track of each unmatched HI
717    relocation.  We then sort them so that they immediately precede the
718    corresponding LO relocation.  */
719
720 struct mips_hi_fixup
721 {
722   /* Next HI fixup.  */
723   struct mips_hi_fixup *next;
724   /* This fixup.  */
725   fixS *fixp;
726   /* The section this fixup is in.  */
727   segT seg;
728 };
729
730 /* The list of unmatched HI relocs.  */
731
732 static struct mips_hi_fixup *mips_hi_fixup_list;
733
734 /* The frag containing the last explicit relocation operator.
735    Null if explicit relocations have not been used.  */
736
737 static fragS *prev_reloc_op_frag;
738
739 /* Map normal MIPS register numbers to mips16 register numbers.  */
740
741 #define X ILLEGAL_REG
742 static const int mips32_to_16_reg_map[] =
743 {
744   X, X, 2, 3, 4, 5, 6, 7,
745   X, X, X, X, X, X, X, X,
746   0, 1, X, X, X, X, X, X,
747   X, X, X, X, X, X, X, X
748 };
749 #undef X
750
751 /* Map mips16 register numbers to normal MIPS register numbers.  */
752
753 static const unsigned int mips16_to_32_reg_map[] =
754 {
755   16, 17, 2, 3, 4, 5, 6, 7
756 };
757
758 /* Map normal MIPS register numbers to microMIPS register numbers.  */
759
760 #define mips32_to_micromips_reg_b_map   mips32_to_16_reg_map
761 #define mips32_to_micromips_reg_c_map   mips32_to_16_reg_map
762 #define mips32_to_micromips_reg_d_map   mips32_to_16_reg_map
763 #define mips32_to_micromips_reg_e_map   mips32_to_16_reg_map
764 #define mips32_to_micromips_reg_f_map   mips32_to_16_reg_map
765 #define mips32_to_micromips_reg_g_map   mips32_to_16_reg_map
766 #define mips32_to_micromips_reg_l_map   mips32_to_16_reg_map
767
768 #define X ILLEGAL_REG
769 /* reg type h: 4, 5, 6.  */
770 static const int mips32_to_micromips_reg_h_map[] =
771 {
772   X, X, X, X, 4, 5, 6, X,
773   X, X, X, X, X, X, X, X,
774   X, X, X, X, X, X, X, X,
775   X, X, X, X, X, X, X, X
776 };
777
778 /* reg type m: 0, 17, 2, 3, 16, 18, 19, 20.  */
779 static const int mips32_to_micromips_reg_m_map[] =
780 {
781   0, X, 2, 3, X, X, X, X,
782   X, X, X, X, X, X, X, X,
783   4, 1, 5, 6, 7, X, X, X,
784   X, X, X, X, X, X, X, X
785 };
786
787 /* reg type q: 0, 2-7. 17.  */
788 static const int mips32_to_micromips_reg_q_map[] =
789 {
790   0, X, 2, 3, 4, 5, 6, 7,
791   X, X, X, X, X, X, X, X,
792   X, 1, X, X, X, X, X, X,
793   X, X, X, X, X, X, X, X
794 };
795
796 #define mips32_to_micromips_reg_n_map  mips32_to_micromips_reg_m_map
797 #undef X
798
799 /* Map microMIPS register numbers to normal MIPS register numbers.  */
800
801 #define micromips_to_32_reg_b_map       mips16_to_32_reg_map
802 #define micromips_to_32_reg_c_map       mips16_to_32_reg_map
803 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
804 #define micromips_to_32_reg_e_map       mips16_to_32_reg_map
805 #define micromips_to_32_reg_f_map       mips16_to_32_reg_map
806 #define micromips_to_32_reg_g_map       mips16_to_32_reg_map
807
808 /* The microMIPS registers with type h.  */
809 static const unsigned int micromips_to_32_reg_h_map[] =
810 {
811   5, 5, 6, 4, 4, 4, 4, 4
812 };
813
814 /* The microMIPS registers with type i.  */
815 static const unsigned int micromips_to_32_reg_i_map[] =
816 {
817   6, 7, 7, 21, 22, 5, 6, 7
818 };
819
820 #define micromips_to_32_reg_l_map       mips16_to_32_reg_map
821
822 /* The microMIPS registers with type m.  */
823 static const unsigned int micromips_to_32_reg_m_map[] =
824 {
825   0, 17, 2, 3, 16, 18, 19, 20
826 };
827
828 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
829
830 /* The microMIPS registers with type q.  */
831 static const unsigned int micromips_to_32_reg_q_map[] =
832 {
833   0, 17, 2, 3, 4, 5, 6, 7
834 };
835
836 /* microMIPS imm type B.  */
837 static const int micromips_imm_b_map[] =
838 {
839   1, 4, 8, 12, 16, 20, 24, -1
840 };
841
842 /* microMIPS imm type C.  */
843 static const int micromips_imm_c_map[] =
844 {
845   128, 1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 63, 64, 255, 32768, 65535
846 };
847
848 /* Classifies the kind of instructions we're interested in when
849    implementing -mfix-vr4120.  */
850 enum fix_vr4120_class
851 {
852   FIX_VR4120_MACC,
853   FIX_VR4120_DMACC,
854   FIX_VR4120_MULT,
855   FIX_VR4120_DMULT,
856   FIX_VR4120_DIV,
857   FIX_VR4120_MTHILO,
858   NUM_FIX_VR4120_CLASSES
859 };
860
861 /* ...likewise -mfix-loongson2f-jump.  */
862 static bfd_boolean mips_fix_loongson2f_jump;
863
864 /* ...likewise -mfix-loongson2f-nop.  */
865 static bfd_boolean mips_fix_loongson2f_nop;
866
867 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
868 static bfd_boolean mips_fix_loongson2f;
869
870 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
871    there must be at least one other instruction between an instruction
872    of type X and an instruction of type Y.  */
873 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
874
875 /* True if -mfix-vr4120 is in force.  */
876 static int mips_fix_vr4120;
877
878 /* ...likewise -mfix-vr4130.  */
879 static int mips_fix_vr4130;
880
881 /* ...likewise -mfix-24k.  */
882 static int mips_fix_24k;
883
884 /* ...likewise -mfix-cn63xxp1 */
885 static bfd_boolean mips_fix_cn63xxp1;
886
887 /* We don't relax branches by default, since this causes us to expand
888    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
889    fail to compute the offset before expanding the macro to the most
890    efficient expansion.  */
891
892 static int mips_relax_branch;
893 \f
894 /* The expansion of many macros depends on the type of symbol that
895    they refer to.  For example, when generating position-dependent code,
896    a macro that refers to a symbol may have two different expansions,
897    one which uses GP-relative addresses and one which uses absolute
898    addresses.  When generating SVR4-style PIC, a macro may have
899    different expansions for local and global symbols.
900
901    We handle these situations by generating both sequences and putting
902    them in variant frags.  In position-dependent code, the first sequence
903    will be the GP-relative one and the second sequence will be the
904    absolute one.  In SVR4 PIC, the first sequence will be for global
905    symbols and the second will be for local symbols.
906
907    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
908    SECOND are the lengths of the two sequences in bytes.  These fields
909    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
910    the subtype has the following flags:
911
912    RELAX_USE_SECOND
913         Set if it has been decided that we should use the second
914         sequence instead of the first.
915
916    RELAX_SECOND_LONGER
917         Set in the first variant frag if the macro's second implementation
918         is longer than its first.  This refers to the macro as a whole,
919         not an individual relaxation.
920
921    RELAX_NOMACRO
922         Set in the first variant frag if the macro appeared in a .set nomacro
923         block and if one alternative requires a warning but the other does not.
924
925    RELAX_DELAY_SLOT
926         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
927         delay slot.
928
929    RELAX_DELAY_SLOT_16BIT
930         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
931         16-bit instruction.
932
933    RELAX_DELAY_SLOT_SIZE_FIRST
934         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
935         the macro is of the wrong size for the branch delay slot.
936
937    RELAX_DELAY_SLOT_SIZE_SECOND
938         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
939         the macro is of the wrong size for the branch delay slot.
940
941    The frag's "opcode" points to the first fixup for relaxable code.
942
943    Relaxable macros are generated using a sequence such as:
944
945       relax_start (SYMBOL);
946       ... generate first expansion ...
947       relax_switch ();
948       ... generate second expansion ...
949       relax_end ();
950
951    The code and fixups for the unwanted alternative are discarded
952    by md_convert_frag.  */
953 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
954
955 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
956 #define RELAX_SECOND(X) ((X) & 0xff)
957 #define RELAX_USE_SECOND 0x10000
958 #define RELAX_SECOND_LONGER 0x20000
959 #define RELAX_NOMACRO 0x40000
960 #define RELAX_DELAY_SLOT 0x80000
961 #define RELAX_DELAY_SLOT_16BIT 0x100000
962 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x200000
963 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x400000
964
965 /* Branch without likely bit.  If label is out of range, we turn:
966
967         beq reg1, reg2, label
968         delay slot
969
970    into
971
972         bne reg1, reg2, 0f
973         nop
974         j label
975      0: delay slot
976
977    with the following opcode replacements:
978
979         beq <-> bne
980         blez <-> bgtz
981         bltz <-> bgez
982         bc1f <-> bc1t
983
984         bltzal <-> bgezal  (with jal label instead of j label)
985
986    Even though keeping the delay slot instruction in the delay slot of
987    the branch would be more efficient, it would be very tricky to do
988    correctly, because we'd have to introduce a variable frag *after*
989    the delay slot instruction, and expand that instead.  Let's do it
990    the easy way for now, even if the branch-not-taken case now costs
991    one additional instruction.  Out-of-range branches are not supposed
992    to be common, anyway.
993
994    Branch likely.  If label is out of range, we turn:
995
996         beql reg1, reg2, label
997         delay slot (annulled if branch not taken)
998
999    into
1000
1001         beql reg1, reg2, 1f
1002         nop
1003         beql $0, $0, 2f
1004         nop
1005      1: j[al] label
1006         delay slot (executed only if branch taken)
1007      2:
1008
1009    It would be possible to generate a shorter sequence by losing the
1010    likely bit, generating something like:
1011
1012         bne reg1, reg2, 0f
1013         nop
1014         j[al] label
1015         delay slot (executed only if branch taken)
1016      0:
1017
1018         beql -> bne
1019         bnel -> beq
1020         blezl -> bgtz
1021         bgtzl -> blez
1022         bltzl -> bgez
1023         bgezl -> bltz
1024         bc1fl -> bc1t
1025         bc1tl -> bc1f
1026
1027         bltzall -> bgezal  (with jal label instead of j label)
1028         bgezall -> bltzal  (ditto)
1029
1030
1031    but it's not clear that it would actually improve performance.  */
1032 #define RELAX_BRANCH_ENCODE(at, uncond, likely, link, toofar)   \
1033   ((relax_substateT)                                            \
1034    (0xc0000000                                                  \
1035     | ((at) & 0x1f)                                             \
1036     | ((toofar) ? 0x20 : 0)                                     \
1037     | ((link) ? 0x40 : 0)                                       \
1038     | ((likely) ? 0x80 : 0)                                     \
1039     | ((uncond) ? 0x100 : 0)))
1040 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1041 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x100) != 0)
1042 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x80) != 0)
1043 #define RELAX_BRANCH_LINK(i) (((i) & 0x40) != 0)
1044 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x20) != 0)
1045 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1046
1047 /* For mips16 code, we use an entirely different form of relaxation.
1048    mips16 supports two versions of most instructions which take
1049    immediate values: a small one which takes some small value, and a
1050    larger one which takes a 16 bit value.  Since branches also follow
1051    this pattern, relaxing these values is required.
1052
1053    We can assemble both mips16 and normal MIPS code in a single
1054    object.  Therefore, we need to support this type of relaxation at
1055    the same time that we support the relaxation described above.  We
1056    use the high bit of the subtype field to distinguish these cases.
1057
1058    The information we store for this type of relaxation is the
1059    argument code found in the opcode file for this relocation, whether
1060    the user explicitly requested a small or extended form, and whether
1061    the relocation is in a jump or jal delay slot.  That tells us the
1062    size of the value, and how it should be stored.  We also store
1063    whether the fragment is considered to be extended or not.  We also
1064    store whether this is known to be a branch to a different section,
1065    whether we have tried to relax this frag yet, and whether we have
1066    ever extended a PC relative fragment because of a shift count.  */
1067 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
1068   (0x80000000                                                   \
1069    | ((type) & 0xff)                                            \
1070    | ((small) ? 0x100 : 0)                                      \
1071    | ((ext) ? 0x200 : 0)                                        \
1072    | ((dslot) ? 0x400 : 0)                                      \
1073    | ((jal_dslot) ? 0x800 : 0))
1074 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1075 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1076 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
1077 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
1078 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
1079 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
1080 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
1081 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
1082 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
1083 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
1084 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
1085 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
1086
1087 /* For microMIPS code, we use relaxation similar to one we use for
1088    MIPS16 code.  Some instructions that take immediate values support
1089    two encodings: a small one which takes some small value, and a
1090    larger one which takes a 16 bit value.  As some branches also follow
1091    this pattern, relaxing these values is required.
1092
1093    We can assemble both microMIPS and normal MIPS code in a single
1094    object.  Therefore, we need to support this type of relaxation at
1095    the same time that we support the relaxation described above.  We
1096    use one of the high bits of the subtype field to distinguish these
1097    cases.
1098
1099    The information we store for this type of relaxation is the argument
1100    code found in the opcode file for this relocation, the register
1101    selected as the assembler temporary, whether the branch is
1102    unconditional, whether it is compact, whether it stores the link
1103    address implicitly in $ra, whether relaxation of out-of-range 32-bit
1104    branches to a sequence of instructions is enabled, and whether the
1105    displacement of a branch is too large to fit as an immediate argument
1106    of a 16-bit and a 32-bit branch, respectively.  */
1107 #define RELAX_MICROMIPS_ENCODE(type, at, uncond, compact, link, \
1108                                relax32, toofar16, toofar32)     \
1109   (0x40000000                                                   \
1110    | ((type) & 0xff)                                            \
1111    | (((at) & 0x1f) << 8)                                       \
1112    | ((uncond) ? 0x2000 : 0)                                    \
1113    | ((compact) ? 0x4000 : 0)                                   \
1114    | ((link) ? 0x8000 : 0)                                      \
1115    | ((relax32) ? 0x10000 : 0)                                  \
1116    | ((toofar16) ? 0x20000 : 0)                                 \
1117    | ((toofar32) ? 0x40000 : 0))
1118 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1119 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1120 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1121 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x2000) != 0)
1122 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x4000) != 0)
1123 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x8000) != 0)
1124 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x10000) != 0)
1125
1126 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x20000) != 0)
1127 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x20000)
1128 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x20000)
1129 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x40000) != 0)
1130 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x40000)
1131 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x40000)
1132
1133 /* Sign-extend 16-bit value X.  */
1134 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1135
1136 /* Is the given value a sign-extended 32-bit value?  */
1137 #define IS_SEXT_32BIT_NUM(x)                                            \
1138   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1139    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1140
1141 /* Is the given value a sign-extended 16-bit value?  */
1142 #define IS_SEXT_16BIT_NUM(x)                                            \
1143   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1144    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1145
1146 /* Is the given value a sign-extended 12-bit value?  */
1147 #define IS_SEXT_12BIT_NUM(x)                                            \
1148   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1149
1150 /* Is the given value a sign-extended 9-bit value?  */
1151 #define IS_SEXT_9BIT_NUM(x)                                             \
1152   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1153
1154 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1155 #define IS_ZEXT_32BIT_NUM(x)                                            \
1156   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1157    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1158
1159 /* Replace bits MASK << SHIFT of STRUCT with the equivalent bits in
1160    VALUE << SHIFT.  VALUE is evaluated exactly once.  */
1161 #define INSERT_BITS(STRUCT, VALUE, MASK, SHIFT) \
1162   (STRUCT) = (((STRUCT) & ~((MASK) << (SHIFT))) \
1163               | (((VALUE) & (MASK)) << (SHIFT)))
1164
1165 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1166    SHIFT places.  */
1167 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1168   (((STRUCT) >> (SHIFT)) & (MASK))
1169
1170 /* Change INSN's opcode so that the operand given by FIELD has value VALUE.
1171    INSN is a mips_cl_insn structure and VALUE is evaluated exactly once.
1172
1173    include/opcode/mips.h specifies operand fields using the macros
1174    OP_MASK_<FIELD> and OP_SH_<FIELD>.  The MIPS16 equivalents start
1175    with "MIPS16OP" instead of "OP".  */
1176 #define INSERT_OPERAND(MICROMIPS, FIELD, INSN, VALUE) \
1177   do \
1178     if (!(MICROMIPS)) \
1179       INSERT_BITS ((INSN).insn_opcode, VALUE, \
1180                    OP_MASK_##FIELD, OP_SH_##FIELD); \
1181     else \
1182       INSERT_BITS ((INSN).insn_opcode, VALUE, \
1183                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD); \
1184   while (0)
1185 #define MIPS16_INSERT_OPERAND(FIELD, INSN, VALUE) \
1186   INSERT_BITS ((INSN).insn_opcode, VALUE, \
1187                 MIPS16OP_MASK_##FIELD, MIPS16OP_SH_##FIELD)
1188
1189 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1190 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1191   (!(MICROMIPS) \
1192    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1193    : EXTRACT_BITS ((INSN).insn_opcode, \
1194                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1195 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1196   EXTRACT_BITS ((INSN).insn_opcode, \
1197                 MIPS16OP_MASK_##FIELD, \
1198                 MIPS16OP_SH_##FIELD)
1199
1200 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1201 #define MIPS16_EXTEND (0xf000U << 16)
1202 \f
1203 /* Whether or not we are emitting a branch-likely macro.  */
1204 static bfd_boolean emit_branch_likely_macro = FALSE;
1205
1206 /* Global variables used when generating relaxable macros.  See the
1207    comment above RELAX_ENCODE for more details about how relaxation
1208    is used.  */
1209 static struct {
1210   /* 0 if we're not emitting a relaxable macro.
1211      1 if we're emitting the first of the two relaxation alternatives.
1212      2 if we're emitting the second alternative.  */
1213   int sequence;
1214
1215   /* The first relaxable fixup in the current frag.  (In other words,
1216      the first fixup that refers to relaxable code.)  */
1217   fixS *first_fixup;
1218
1219   /* sizes[0] says how many bytes of the first alternative are stored in
1220      the current frag.  Likewise sizes[1] for the second alternative.  */
1221   unsigned int sizes[2];
1222
1223   /* The symbol on which the choice of sequence depends.  */
1224   symbolS *symbol;
1225 } mips_relax;
1226 \f
1227 /* Global variables used to decide whether a macro needs a warning.  */
1228 static struct {
1229   /* True if the macro is in a branch delay slot.  */
1230   bfd_boolean delay_slot_p;
1231
1232   /* Set to the length in bytes required if the macro is in a delay slot
1233      that requires a specific length of instruction, otherwise zero.  */
1234   unsigned int delay_slot_length;
1235
1236   /* For relaxable macros, sizes[0] is the length of the first alternative
1237      in bytes and sizes[1] is the length of the second alternative.
1238      For non-relaxable macros, both elements give the length of the
1239      macro in bytes.  */
1240   unsigned int sizes[2];
1241
1242   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1243      instruction of the first alternative in bytes and first_insn_sizes[1]
1244      is the length of the first instruction of the second alternative.
1245      For non-relaxable macros, both elements give the length of the first
1246      instruction in bytes.
1247
1248      Set to zero if we haven't yet seen the first instruction.  */
1249   unsigned int first_insn_sizes[2];
1250
1251   /* For relaxable macros, insns[0] is the number of instructions for the
1252      first alternative and insns[1] is the number of instructions for the
1253      second alternative.
1254
1255      For non-relaxable macros, both elements give the number of
1256      instructions for the macro.  */
1257   unsigned int insns[2];
1258
1259   /* The first variant frag for this macro.  */
1260   fragS *first_frag;
1261 } mips_macro_warning;
1262 \f
1263 /* Prototypes for static functions.  */
1264
1265 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1266
1267 static void append_insn
1268   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1269    bfd_boolean expansionp);
1270 static void mips_no_prev_insn (void);
1271 static void macro_build (expressionS *, const char *, const char *, ...);
1272 static void mips16_macro_build
1273   (expressionS *, const char *, const char *, va_list *);
1274 static void load_register (int, expressionS *, int);
1275 static void macro_start (void);
1276 static void macro_end (void);
1277 static void macro (struct mips_cl_insn * ip);
1278 static void mips16_macro (struct mips_cl_insn * ip);
1279 static void mips_ip (char *str, struct mips_cl_insn * ip);
1280 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1281 static void mips16_immed
1282   (char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1283    unsigned int, unsigned long *);
1284 static size_t my_getSmallExpression
1285   (expressionS *, bfd_reloc_code_real_type *, char *);
1286 static void my_getExpression (expressionS *, char *);
1287 static void s_align (int);
1288 static void s_change_sec (int);
1289 static void s_change_section (int);
1290 static void s_cons (int);
1291 static void s_float_cons (int);
1292 static void s_mips_globl (int);
1293 static void s_option (int);
1294 static void s_mipsset (int);
1295 static void s_abicalls (int);
1296 static void s_cpload (int);
1297 static void s_cpsetup (int);
1298 static void s_cplocal (int);
1299 static void s_cprestore (int);
1300 static void s_cpreturn (int);
1301 static void s_dtprelword (int);
1302 static void s_dtpreldword (int);
1303 static void s_tprelword (int);
1304 static void s_tpreldword (int);
1305 static void s_gpvalue (int);
1306 static void s_gpword (int);
1307 static void s_gpdword (int);
1308 static void s_ehword (int);
1309 static void s_cpadd (int);
1310 static void s_insn (int);
1311 static void md_obj_begin (void);
1312 static void md_obj_end (void);
1313 static void s_mips_ent (int);
1314 static void s_mips_end (int);
1315 static void s_mips_frame (int);
1316 static void s_mips_mask (int reg_type);
1317 static void s_mips_stab (int);
1318 static void s_mips_weakext (int);
1319 static void s_mips_file (int);
1320 static void s_mips_loc (int);
1321 static bfd_boolean pic_need_relax (symbolS *, asection *);
1322 static int relaxed_branch_length (fragS *, asection *, int);
1323 static int validate_mips_insn (const struct mips_opcode *);
1324 static int validate_micromips_insn (const struct mips_opcode *);
1325 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1326 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1327
1328 /* Table and functions used to map between CPU/ISA names, and
1329    ISA levels, and CPU numbers.  */
1330
1331 struct mips_cpu_info
1332 {
1333   const char *name;           /* CPU or ISA name.  */
1334   int flags;                  /* MIPS_CPU_* flags.  */
1335   int ase;                    /* Set of ASEs implemented by the CPU.  */
1336   int isa;                    /* ISA level.  */
1337   int cpu;                    /* CPU number (default CPU if ISA).  */
1338 };
1339
1340 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1341
1342 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1343 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1344 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1345 \f
1346 /* Command-line options.  */
1347 const char *md_shortopts = "O::g::G:";
1348
1349 enum options
1350   {
1351     OPTION_MARCH = OPTION_MD_BASE,
1352     OPTION_MTUNE,
1353     OPTION_MIPS1,
1354     OPTION_MIPS2,
1355     OPTION_MIPS3,
1356     OPTION_MIPS4,
1357     OPTION_MIPS5,
1358     OPTION_MIPS32,
1359     OPTION_MIPS64,
1360     OPTION_MIPS32R2,
1361     OPTION_MIPS64R2,
1362     OPTION_MIPS16,
1363     OPTION_NO_MIPS16,
1364     OPTION_MIPS3D,
1365     OPTION_NO_MIPS3D,
1366     OPTION_MDMX,
1367     OPTION_NO_MDMX,
1368     OPTION_DSP,
1369     OPTION_NO_DSP,
1370     OPTION_MT,
1371     OPTION_NO_MT,
1372     OPTION_VIRT,
1373     OPTION_NO_VIRT,
1374     OPTION_SMARTMIPS,
1375     OPTION_NO_SMARTMIPS,
1376     OPTION_DSPR2,
1377     OPTION_NO_DSPR2,
1378     OPTION_EVA,
1379     OPTION_NO_EVA,
1380     OPTION_MICROMIPS,
1381     OPTION_NO_MICROMIPS,
1382     OPTION_MCU,
1383     OPTION_NO_MCU,
1384     OPTION_COMPAT_ARCH_BASE,
1385     OPTION_M4650,
1386     OPTION_NO_M4650,
1387     OPTION_M4010,
1388     OPTION_NO_M4010,
1389     OPTION_M4100,
1390     OPTION_NO_M4100,
1391     OPTION_M3900,
1392     OPTION_NO_M3900,
1393     OPTION_M7000_HILO_FIX,
1394     OPTION_MNO_7000_HILO_FIX,
1395     OPTION_FIX_24K,
1396     OPTION_NO_FIX_24K,
1397     OPTION_FIX_LOONGSON2F_JUMP,
1398     OPTION_NO_FIX_LOONGSON2F_JUMP,
1399     OPTION_FIX_LOONGSON2F_NOP,
1400     OPTION_NO_FIX_LOONGSON2F_NOP,
1401     OPTION_FIX_VR4120,
1402     OPTION_NO_FIX_VR4120,
1403     OPTION_FIX_VR4130,
1404     OPTION_NO_FIX_VR4130,
1405     OPTION_FIX_CN63XXP1,
1406     OPTION_NO_FIX_CN63XXP1,
1407     OPTION_TRAP,
1408     OPTION_BREAK,
1409     OPTION_EB,
1410     OPTION_EL,
1411     OPTION_FP32,
1412     OPTION_GP32,
1413     OPTION_CONSTRUCT_FLOATS,
1414     OPTION_NO_CONSTRUCT_FLOATS,
1415     OPTION_FP64,
1416     OPTION_GP64,
1417     OPTION_RELAX_BRANCH,
1418     OPTION_NO_RELAX_BRANCH,
1419     OPTION_MSHARED,
1420     OPTION_MNO_SHARED,
1421     OPTION_MSYM32,
1422     OPTION_MNO_SYM32,
1423     OPTION_SOFT_FLOAT,
1424     OPTION_HARD_FLOAT,
1425     OPTION_SINGLE_FLOAT,
1426     OPTION_DOUBLE_FLOAT,
1427     OPTION_32,
1428 #ifdef OBJ_ELF
1429     OPTION_CALL_SHARED,
1430     OPTION_CALL_NONPIC,
1431     OPTION_NON_SHARED,
1432     OPTION_XGOT,
1433     OPTION_MABI,
1434     OPTION_N32,
1435     OPTION_64,
1436     OPTION_MDEBUG,
1437     OPTION_NO_MDEBUG,
1438     OPTION_PDR,
1439     OPTION_NO_PDR,
1440     OPTION_MVXWORKS_PIC,
1441 #endif /* OBJ_ELF */
1442     OPTION_END_OF_ENUM
1443   };
1444
1445 struct option md_longopts[] =
1446 {
1447   /* Options which specify architecture.  */
1448   {"march", required_argument, NULL, OPTION_MARCH},
1449   {"mtune", required_argument, NULL, OPTION_MTUNE},
1450   {"mips0", no_argument, NULL, OPTION_MIPS1},
1451   {"mips1", no_argument, NULL, OPTION_MIPS1},
1452   {"mips2", no_argument, NULL, OPTION_MIPS2},
1453   {"mips3", no_argument, NULL, OPTION_MIPS3},
1454   {"mips4", no_argument, NULL, OPTION_MIPS4},
1455   {"mips5", no_argument, NULL, OPTION_MIPS5},
1456   {"mips32", no_argument, NULL, OPTION_MIPS32},
1457   {"mips64", no_argument, NULL, OPTION_MIPS64},
1458   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1459   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1460
1461   /* Options which specify Application Specific Extensions (ASEs).  */
1462   {"mips16", no_argument, NULL, OPTION_MIPS16},
1463   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1464   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1465   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1466   {"mdmx", no_argument, NULL, OPTION_MDMX},
1467   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1468   {"mdsp", no_argument, NULL, OPTION_DSP},
1469   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1470   {"mmt", no_argument, NULL, OPTION_MT},
1471   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1472   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1473   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1474   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1475   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1476   {"meva", no_argument, NULL, OPTION_EVA},
1477   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1478   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1479   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1480   {"mmcu", no_argument, NULL, OPTION_MCU},
1481   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1482   {"mvirt", no_argument, NULL, OPTION_VIRT},
1483   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1484
1485   /* Old-style architecture options.  Don't add more of these.  */
1486   {"m4650", no_argument, NULL, OPTION_M4650},
1487   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1488   {"m4010", no_argument, NULL, OPTION_M4010},
1489   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1490   {"m4100", no_argument, NULL, OPTION_M4100},
1491   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1492   {"m3900", no_argument, NULL, OPTION_M3900},
1493   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1494
1495   /* Options which enable bug fixes.  */
1496   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1497   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1498   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1499   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1500   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1501   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1502   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1503   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1504   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1505   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1506   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1507   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1508   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1509   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1510   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1511
1512   /* Miscellaneous options.  */
1513   {"trap", no_argument, NULL, OPTION_TRAP},
1514   {"no-break", no_argument, NULL, OPTION_TRAP},
1515   {"break", no_argument, NULL, OPTION_BREAK},
1516   {"no-trap", no_argument, NULL, OPTION_BREAK},
1517   {"EB", no_argument, NULL, OPTION_EB},
1518   {"EL", no_argument, NULL, OPTION_EL},
1519   {"mfp32", no_argument, NULL, OPTION_FP32},
1520   {"mgp32", no_argument, NULL, OPTION_GP32},
1521   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1522   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1523   {"mfp64", no_argument, NULL, OPTION_FP64},
1524   {"mgp64", no_argument, NULL, OPTION_GP64},
1525   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1526   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1527   {"mshared", no_argument, NULL, OPTION_MSHARED},
1528   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1529   {"msym32", no_argument, NULL, OPTION_MSYM32},
1530   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1531   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1532   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1533   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1534   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1535
1536   /* Strictly speaking this next option is ELF specific,
1537      but we allow it for other ports as well in order to
1538      make testing easier.  */
1539   {"32", no_argument, NULL, OPTION_32},
1540
1541   /* ELF-specific options.  */
1542 #ifdef OBJ_ELF
1543   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1544   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1545   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1546   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1547   {"xgot", no_argument, NULL, OPTION_XGOT},
1548   {"mabi", required_argument, NULL, OPTION_MABI},
1549   {"n32", no_argument, NULL, OPTION_N32},
1550   {"64", no_argument, NULL, OPTION_64},
1551   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1552   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1553   {"mpdr", no_argument, NULL, OPTION_PDR},
1554   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1555   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1556 #endif /* OBJ_ELF */
1557
1558   {NULL, no_argument, NULL, 0}
1559 };
1560 size_t md_longopts_size = sizeof (md_longopts);
1561 \f
1562 /* Information about either an Application Specific Extension or an
1563    optional architecture feature that, for simplicity, we treat in the
1564    same way as an ASE.  */
1565 struct mips_ase
1566 {
1567   /* The name of the ASE, used in both the command-line and .set options.  */
1568   const char *name;
1569
1570   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1571      and 64-bit architectures, the flags here refer to the subset that
1572      is available on both.  */
1573   unsigned int flags;
1574
1575   /* The ASE_* flag used for instructions that are available on 64-bit
1576      architectures but that are not included in FLAGS.  */
1577   unsigned int flags64;
1578
1579   /* The command-line options that turn the ASE on and off.  */
1580   int option_on;
1581   int option_off;
1582
1583   /* The minimum required architecture revisions for MIPS32, MIPS64,
1584      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1585   int mips32_rev;
1586   int mips64_rev;
1587   int micromips32_rev;
1588   int micromips64_rev;
1589 };
1590
1591 /* A table of all supported ASEs.  */
1592 static const struct mips_ase mips_ases[] = {
1593   { "dsp", ASE_DSP, ASE_DSP64,
1594     OPTION_DSP, OPTION_NO_DSP,
1595     2, 2, 2, 2 },
1596
1597   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1598     OPTION_DSPR2, OPTION_NO_DSPR2,
1599     2, 2, 2, 2 },
1600
1601   { "eva", ASE_EVA, 0,
1602     OPTION_EVA, OPTION_NO_EVA,
1603     2, 2, 2, 2 },
1604
1605   { "mcu", ASE_MCU, 0,
1606     OPTION_MCU, OPTION_NO_MCU,
1607     2, 2, 2, 2 },
1608
1609   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1610   { "mdmx", ASE_MDMX, 0,
1611     OPTION_MDMX, OPTION_NO_MDMX,
1612     -1, 1, -1, -1 },
1613
1614   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1615   { "mips3d", ASE_MIPS3D, 0,
1616     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1617     2, 1, -1, -1 },
1618
1619   { "mt", ASE_MT, 0,
1620     OPTION_MT, OPTION_NO_MT,
1621     2, 2, -1, -1 },
1622
1623   { "smartmips", ASE_SMARTMIPS, 0,
1624     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1625     1, -1, -1, -1 },
1626
1627   { "virt", ASE_VIRT, ASE_VIRT64,
1628     OPTION_VIRT, OPTION_NO_VIRT,
1629     2, 2, 2, 2 }
1630 };
1631
1632 /* The set of ASEs that require -mfp64.  */
1633 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX)
1634
1635 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1636 static const unsigned int mips_ase_groups[] = {
1637   ASE_DSP | ASE_DSPR2
1638 };
1639 \f
1640 /* Pseudo-op table.
1641
1642    The following pseudo-ops from the Kane and Heinrich MIPS book
1643    should be defined here, but are currently unsupported: .alias,
1644    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1645
1646    The following pseudo-ops from the Kane and Heinrich MIPS book are
1647    specific to the type of debugging information being generated, and
1648    should be defined by the object format: .aent, .begin, .bend,
1649    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1650    .vreg.
1651
1652    The following pseudo-ops from the Kane and Heinrich MIPS book are
1653    not MIPS CPU specific, but are also not specific to the object file
1654    format.  This file is probably the best place to define them, but
1655    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1656
1657 static const pseudo_typeS mips_pseudo_table[] =
1658 {
1659   /* MIPS specific pseudo-ops.  */
1660   {"option", s_option, 0},
1661   {"set", s_mipsset, 0},
1662   {"rdata", s_change_sec, 'r'},
1663   {"sdata", s_change_sec, 's'},
1664   {"livereg", s_ignore, 0},
1665   {"abicalls", s_abicalls, 0},
1666   {"cpload", s_cpload, 0},
1667   {"cpsetup", s_cpsetup, 0},
1668   {"cplocal", s_cplocal, 0},
1669   {"cprestore", s_cprestore, 0},
1670   {"cpreturn", s_cpreturn, 0},
1671   {"dtprelword", s_dtprelword, 0},
1672   {"dtpreldword", s_dtpreldword, 0},
1673   {"tprelword", s_tprelword, 0},
1674   {"tpreldword", s_tpreldword, 0},
1675   {"gpvalue", s_gpvalue, 0},
1676   {"gpword", s_gpword, 0},
1677   {"gpdword", s_gpdword, 0},
1678   {"ehword", s_ehword, 0},
1679   {"cpadd", s_cpadd, 0},
1680   {"insn", s_insn, 0},
1681
1682   /* Relatively generic pseudo-ops that happen to be used on MIPS
1683      chips.  */
1684   {"asciiz", stringer, 8 + 1},
1685   {"bss", s_change_sec, 'b'},
1686   {"err", s_err, 0},
1687   {"half", s_cons, 1},
1688   {"dword", s_cons, 3},
1689   {"weakext", s_mips_weakext, 0},
1690   {"origin", s_org, 0},
1691   {"repeat", s_rept, 0},
1692
1693   /* For MIPS this is non-standard, but we define it for consistency.  */
1694   {"sbss", s_change_sec, 'B'},
1695
1696   /* These pseudo-ops are defined in read.c, but must be overridden
1697      here for one reason or another.  */
1698   {"align", s_align, 0},
1699   {"byte", s_cons, 0},
1700   {"data", s_change_sec, 'd'},
1701   {"double", s_float_cons, 'd'},
1702   {"float", s_float_cons, 'f'},
1703   {"globl", s_mips_globl, 0},
1704   {"global", s_mips_globl, 0},
1705   {"hword", s_cons, 1},
1706   {"int", s_cons, 2},
1707   {"long", s_cons, 2},
1708   {"octa", s_cons, 4},
1709   {"quad", s_cons, 3},
1710   {"section", s_change_section, 0},
1711   {"short", s_cons, 1},
1712   {"single", s_float_cons, 'f'},
1713   {"stabd", s_mips_stab, 'd'},
1714   {"stabn", s_mips_stab, 'n'},
1715   {"stabs", s_mips_stab, 's'},
1716   {"text", s_change_sec, 't'},
1717   {"word", s_cons, 2},
1718
1719   { "extern", ecoff_directive_extern, 0},
1720
1721   { NULL, NULL, 0 },
1722 };
1723
1724 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1725 {
1726   /* These pseudo-ops should be defined by the object file format.
1727      However, a.out doesn't support them, so we have versions here.  */
1728   {"aent", s_mips_ent, 1},
1729   {"bgnb", s_ignore, 0},
1730   {"end", s_mips_end, 0},
1731   {"endb", s_ignore, 0},
1732   {"ent", s_mips_ent, 0},
1733   {"file", s_mips_file, 0},
1734   {"fmask", s_mips_mask, 'F'},
1735   {"frame", s_mips_frame, 0},
1736   {"loc", s_mips_loc, 0},
1737   {"mask", s_mips_mask, 'R'},
1738   {"verstamp", s_ignore, 0},
1739   { NULL, NULL, 0 },
1740 };
1741
1742 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1743    purpose of the `.dc.a' internal pseudo-op.  */
1744
1745 int
1746 mips_address_bytes (void)
1747 {
1748   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1749 }
1750
1751 extern void pop_insert (const pseudo_typeS *);
1752
1753 void
1754 mips_pop_insert (void)
1755 {
1756   pop_insert (mips_pseudo_table);
1757   if (! ECOFF_DEBUGGING)
1758     pop_insert (mips_nonecoff_pseudo_table);
1759 }
1760 \f
1761 /* Symbols labelling the current insn.  */
1762
1763 struct insn_label_list
1764 {
1765   struct insn_label_list *next;
1766   symbolS *label;
1767 };
1768
1769 static struct insn_label_list *free_insn_labels;
1770 #define label_list tc_segment_info_data.labels
1771
1772 static void mips_clear_insn_labels (void);
1773 static void mips_mark_labels (void);
1774 static void mips_compressed_mark_labels (void);
1775
1776 static inline void
1777 mips_clear_insn_labels (void)
1778 {
1779   register struct insn_label_list **pl;
1780   segment_info_type *si;
1781
1782   if (now_seg)
1783     {
1784       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1785         ;
1786       
1787       si = seg_info (now_seg);
1788       *pl = si->label_list;
1789       si->label_list = NULL;
1790     }
1791 }
1792
1793 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1794
1795 static inline void
1796 mips_mark_labels (void)
1797 {
1798   if (HAVE_CODE_COMPRESSION)
1799     mips_compressed_mark_labels ();
1800 }
1801 \f
1802 static char *expr_end;
1803
1804 /* Expressions which appear in instructions.  These are set by
1805    mips_ip.  */
1806
1807 static expressionS imm_expr;
1808 static expressionS imm2_expr;
1809 static expressionS offset_expr;
1810
1811 /* Relocs associated with imm_expr and offset_expr.  */
1812
1813 static bfd_reloc_code_real_type imm_reloc[3]
1814   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1815 static bfd_reloc_code_real_type offset_reloc[3]
1816   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1817
1818 /* This is set to the resulting size of the instruction to be produced
1819    by mips16_ip if an explicit extension is used or by mips_ip if an
1820    explicit size is supplied.  */
1821
1822 static unsigned int forced_insn_length;
1823
1824 /* True if we are assembling an instruction.  All dot symbols defined during
1825    this time should be treated as code labels.  */
1826
1827 static bfd_boolean mips_assembling_insn;
1828
1829 #ifdef OBJ_ELF
1830 /* The pdr segment for per procedure frame/regmask info.  Not used for
1831    ECOFF debugging.  */
1832
1833 static segT pdr_seg;
1834 #endif
1835
1836 /* The default target format to use.  */
1837
1838 #if defined (TE_FreeBSD)
1839 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1840 #elif defined (TE_TMIPS)
1841 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1842 #else
1843 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1844 #endif
1845
1846 const char *
1847 mips_target_format (void)
1848 {
1849   switch (OUTPUT_FLAVOR)
1850     {
1851     case bfd_target_elf_flavour:
1852 #ifdef TE_VXWORKS
1853       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1854         return (target_big_endian
1855                 ? "elf32-bigmips-vxworks"
1856                 : "elf32-littlemips-vxworks");
1857 #endif
1858       return (target_big_endian
1859               ? (HAVE_64BIT_OBJECTS
1860                  ? ELF_TARGET ("elf64-", "big")
1861                  : (HAVE_NEWABI
1862                     ? ELF_TARGET ("elf32-n", "big")
1863                     : ELF_TARGET ("elf32-", "big")))
1864               : (HAVE_64BIT_OBJECTS
1865                  ? ELF_TARGET ("elf64-", "little")
1866                  : (HAVE_NEWABI
1867                     ? ELF_TARGET ("elf32-n", "little")
1868                     : ELF_TARGET ("elf32-", "little"))));
1869     default:
1870       abort ();
1871       return NULL;
1872     }
1873 }
1874
1875 /* Return the ISA revision that is currently in use, or 0 if we are
1876    generating code for MIPS V or below.  */
1877
1878 static int
1879 mips_isa_rev (void)
1880 {
1881   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
1882     return 2;
1883
1884   /* microMIPS implies revision 2 or above.  */
1885   if (mips_opts.micromips)
1886     return 2;
1887
1888   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
1889     return 1;
1890
1891   return 0;
1892 }
1893
1894 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
1895
1896 static unsigned int
1897 mips_ase_mask (unsigned int flags)
1898 {
1899   unsigned int i;
1900
1901   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
1902     if (flags & mips_ase_groups[i])
1903       flags |= mips_ase_groups[i];
1904   return flags;
1905 }
1906
1907 /* Check whether the current ISA supports ASE.  Issue a warning if
1908    appropriate.  */
1909
1910 static void
1911 mips_check_isa_supports_ase (const struct mips_ase *ase)
1912 {
1913   const char *base;
1914   int min_rev, size;
1915   static unsigned int warned_isa;
1916   static unsigned int warned_fp32;
1917
1918   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
1919     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
1920   else
1921     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
1922   if ((min_rev < 0 || mips_isa_rev () < min_rev)
1923       && (warned_isa & ase->flags) != ase->flags)
1924     {
1925       warned_isa |= ase->flags;
1926       base = mips_opts.micromips ? "microMIPS" : "MIPS";
1927       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
1928       if (min_rev < 0)
1929         as_warn (_("The %d-bit %s architecture does not support the"
1930                    " `%s' extension"), size, base, ase->name);
1931       else
1932         as_warn (_("The `%s' extension requires %s%d revision %d or greater"),
1933                  ase->name, base, size, min_rev);
1934     }
1935   if ((ase->flags & FP64_ASES)
1936       && mips_opts.fp32
1937       && (warned_fp32 & ase->flags) != ase->flags)
1938     {
1939       warned_fp32 |= ase->flags;
1940       as_warn (_("The `%s' extension requires 64-bit FPRs"), ase->name);
1941     }
1942 }
1943
1944 /* Check all enabled ASEs to see whether they are supported by the
1945    chosen architecture.  */
1946
1947 static void
1948 mips_check_isa_supports_ases (void)
1949 {
1950   unsigned int i, mask;
1951
1952   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1953     {
1954       mask = mips_ase_mask (mips_ases[i].flags);
1955       if ((mips_opts.ase & mask) == mips_ases[i].flags)
1956         mips_check_isa_supports_ase (&mips_ases[i]);
1957     }
1958 }
1959
1960 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
1961    that were affected.  */
1962
1963 static unsigned int
1964 mips_set_ase (const struct mips_ase *ase, bfd_boolean enabled_p)
1965 {
1966   unsigned int mask;
1967
1968   mask = mips_ase_mask (ase->flags);
1969   mips_opts.ase &= ~mask;
1970   if (enabled_p)
1971     mips_opts.ase |= ase->flags;
1972   return mask;
1973 }
1974
1975 /* Return the ASE called NAME, or null if none.  */
1976
1977 static const struct mips_ase *
1978 mips_lookup_ase (const char *name)
1979 {
1980   unsigned int i;
1981
1982   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1983     if (strcmp (name, mips_ases[i].name) == 0)
1984       return &mips_ases[i];
1985   return NULL;
1986 }
1987
1988 /* Return the length of a microMIPS instruction in bytes.  If bits of
1989    the mask beyond the low 16 are 0, then it is a 16-bit instruction.
1990    Otherwise assume a 32-bit instruction; 48-bit instructions (0x1f
1991    major opcode) will require further modifications to the opcode
1992    table.  */
1993
1994 static inline unsigned int
1995 micromips_insn_length (const struct mips_opcode *mo)
1996 {
1997   return (mo->mask >> 16) == 0 ? 2 : 4;
1998 }
1999
2000 /* Return the length of MIPS16 instruction OPCODE.  */
2001
2002 static inline unsigned int
2003 mips16_opcode_length (unsigned long opcode)
2004 {
2005   return (opcode >> 16) == 0 ? 2 : 4;
2006 }
2007
2008 /* Return the length of instruction INSN.  */
2009
2010 static inline unsigned int
2011 insn_length (const struct mips_cl_insn *insn)
2012 {
2013   if (mips_opts.micromips)
2014     return micromips_insn_length (insn->insn_mo);
2015   else if (mips_opts.mips16)
2016     return mips16_opcode_length (insn->insn_opcode);
2017   else
2018     return 4;
2019 }
2020
2021 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
2022
2023 static void
2024 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
2025 {
2026   size_t i;
2027
2028   insn->insn_mo = mo;
2029   insn->insn_opcode = mo->match;
2030   insn->frag = NULL;
2031   insn->where = 0;
2032   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2033     insn->fixp[i] = NULL;
2034   insn->fixed_p = (mips_opts.noreorder > 0);
2035   insn->noreorder_p = (mips_opts.noreorder > 0);
2036   insn->mips16_absolute_jump_p = 0;
2037   insn->complete_p = 0;
2038   insn->cleared_p = 0;
2039 }
2040
2041 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2042
2043 static void
2044 mips_record_compressed_mode (void)
2045 {
2046   segment_info_type *si;
2047
2048   si = seg_info (now_seg);
2049   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2050     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2051   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2052     si->tc_segment_info_data.micromips = mips_opts.micromips;
2053 }
2054
2055 /* Read a standard MIPS instruction from BUF.  */
2056
2057 static unsigned long
2058 read_insn (char *buf)
2059 {
2060   if (target_big_endian)
2061     return bfd_getb32 ((bfd_byte *) buf);
2062   else
2063     return bfd_getl32 ((bfd_byte *) buf);
2064 }
2065
2066 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2067    the next byte.  */
2068
2069 static char *
2070 write_insn (char *buf, unsigned int insn)
2071 {
2072   md_number_to_chars (buf, insn, 4);
2073   return buf + 4;
2074 }
2075
2076 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2077    has length LENGTH.  */
2078
2079 static unsigned long
2080 read_compressed_insn (char *buf, unsigned int length)
2081 {
2082   unsigned long insn;
2083   unsigned int i;
2084
2085   insn = 0;
2086   for (i = 0; i < length; i += 2)
2087     {
2088       insn <<= 16;
2089       if (target_big_endian)
2090         insn |= bfd_getb16 ((char *) buf);
2091       else
2092         insn |= bfd_getl16 ((char *) buf);
2093       buf += 2;
2094     }
2095   return insn;
2096 }
2097
2098 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2099    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2100
2101 static char *
2102 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2103 {
2104   unsigned int i;
2105
2106   for (i = 0; i < length; i += 2)
2107     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2108   return buf + length;
2109 }
2110
2111 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2112
2113 static void
2114 install_insn (const struct mips_cl_insn *insn)
2115 {
2116   char *f = insn->frag->fr_literal + insn->where;
2117   if (HAVE_CODE_COMPRESSION)
2118     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2119   else
2120     write_insn (f, insn->insn_opcode);
2121   mips_record_compressed_mode ();
2122 }
2123
2124 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2125    and install the opcode in the new location.  */
2126
2127 static void
2128 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2129 {
2130   size_t i;
2131
2132   insn->frag = frag;
2133   insn->where = where;
2134   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2135     if (insn->fixp[i] != NULL)
2136       {
2137         insn->fixp[i]->fx_frag = frag;
2138         insn->fixp[i]->fx_where = where;
2139       }
2140   install_insn (insn);
2141 }
2142
2143 /* Add INSN to the end of the output.  */
2144
2145 static void
2146 add_fixed_insn (struct mips_cl_insn *insn)
2147 {
2148   char *f = frag_more (insn_length (insn));
2149   move_insn (insn, frag_now, f - frag_now->fr_literal);
2150 }
2151
2152 /* Start a variant frag and move INSN to the start of the variant part,
2153    marking it as fixed.  The other arguments are as for frag_var.  */
2154
2155 static void
2156 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2157                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2158 {
2159   frag_grow (max_chars);
2160   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2161   insn->fixed_p = 1;
2162   frag_var (rs_machine_dependent, max_chars, var,
2163             subtype, symbol, offset, NULL);
2164 }
2165
2166 /* Insert N copies of INSN into the history buffer, starting at
2167    position FIRST.  Neither FIRST nor N need to be clipped.  */
2168
2169 static void
2170 insert_into_history (unsigned int first, unsigned int n,
2171                      const struct mips_cl_insn *insn)
2172 {
2173   if (mips_relax.sequence != 2)
2174     {
2175       unsigned int i;
2176
2177       for (i = ARRAY_SIZE (history); i-- > first;)
2178         if (i >= first + n)
2179           history[i] = history[i - n];
2180         else
2181           history[i] = *insn;
2182     }
2183 }
2184
2185 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2186    the idea is to make it obvious at a glance that each errata is
2187    included.  */
2188
2189 static void
2190 init_vr4120_conflicts (void)
2191 {
2192 #define CONFLICT(FIRST, SECOND) \
2193     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2194
2195   /* Errata 21 - [D]DIV[U] after [D]MACC */
2196   CONFLICT (MACC, DIV);
2197   CONFLICT (DMACC, DIV);
2198
2199   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2200   CONFLICT (DMULT, DMULT);
2201   CONFLICT (DMULT, DMACC);
2202   CONFLICT (DMACC, DMULT);
2203   CONFLICT (DMACC, DMACC);
2204
2205   /* Errata 24 - MT{LO,HI} after [D]MACC */
2206   CONFLICT (MACC, MTHILO);
2207   CONFLICT (DMACC, MTHILO);
2208
2209   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2210      instruction is executed immediately after a MACC or DMACC
2211      instruction, the result of [either instruction] is incorrect."  */
2212   CONFLICT (MACC, MULT);
2213   CONFLICT (MACC, DMULT);
2214   CONFLICT (DMACC, MULT);
2215   CONFLICT (DMACC, DMULT);
2216
2217   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2218      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2219      DDIV or DDIVU instruction, the result of the MACC or
2220      DMACC instruction is incorrect.".  */
2221   CONFLICT (DMULT, MACC);
2222   CONFLICT (DMULT, DMACC);
2223   CONFLICT (DIV, MACC);
2224   CONFLICT (DIV, DMACC);
2225
2226 #undef CONFLICT
2227 }
2228
2229 struct regname {
2230   const char *name;
2231   unsigned int num;
2232 };
2233
2234 #define RTYPE_MASK      0x1ff00
2235 #define RTYPE_NUM       0x00100
2236 #define RTYPE_FPU       0x00200
2237 #define RTYPE_FCC       0x00400
2238 #define RTYPE_VEC       0x00800
2239 #define RTYPE_GP        0x01000
2240 #define RTYPE_CP0       0x02000
2241 #define RTYPE_PC        0x04000
2242 #define RTYPE_ACC       0x08000
2243 #define RTYPE_CCC       0x10000
2244 #define RNUM_MASK       0x000ff
2245 #define RWARN           0x80000
2246
2247 #define GENERIC_REGISTER_NUMBERS \
2248     {"$0",      RTYPE_NUM | 0},  \
2249     {"$1",      RTYPE_NUM | 1},  \
2250     {"$2",      RTYPE_NUM | 2},  \
2251     {"$3",      RTYPE_NUM | 3},  \
2252     {"$4",      RTYPE_NUM | 4},  \
2253     {"$5",      RTYPE_NUM | 5},  \
2254     {"$6",      RTYPE_NUM | 6},  \
2255     {"$7",      RTYPE_NUM | 7},  \
2256     {"$8",      RTYPE_NUM | 8},  \
2257     {"$9",      RTYPE_NUM | 9},  \
2258     {"$10",     RTYPE_NUM | 10}, \
2259     {"$11",     RTYPE_NUM | 11}, \
2260     {"$12",     RTYPE_NUM | 12}, \
2261     {"$13",     RTYPE_NUM | 13}, \
2262     {"$14",     RTYPE_NUM | 14}, \
2263     {"$15",     RTYPE_NUM | 15}, \
2264     {"$16",     RTYPE_NUM | 16}, \
2265     {"$17",     RTYPE_NUM | 17}, \
2266     {"$18",     RTYPE_NUM | 18}, \
2267     {"$19",     RTYPE_NUM | 19}, \
2268     {"$20",     RTYPE_NUM | 20}, \
2269     {"$21",     RTYPE_NUM | 21}, \
2270     {"$22",     RTYPE_NUM | 22}, \
2271     {"$23",     RTYPE_NUM | 23}, \
2272     {"$24",     RTYPE_NUM | 24}, \
2273     {"$25",     RTYPE_NUM | 25}, \
2274     {"$26",     RTYPE_NUM | 26}, \
2275     {"$27",     RTYPE_NUM | 27}, \
2276     {"$28",     RTYPE_NUM | 28}, \
2277     {"$29",     RTYPE_NUM | 29}, \
2278     {"$30",     RTYPE_NUM | 30}, \
2279     {"$31",     RTYPE_NUM | 31} 
2280
2281 #define FPU_REGISTER_NAMES       \
2282     {"$f0",     RTYPE_FPU | 0},  \
2283     {"$f1",     RTYPE_FPU | 1},  \
2284     {"$f2",     RTYPE_FPU | 2},  \
2285     {"$f3",     RTYPE_FPU | 3},  \
2286     {"$f4",     RTYPE_FPU | 4},  \
2287     {"$f5",     RTYPE_FPU | 5},  \
2288     {"$f6",     RTYPE_FPU | 6},  \
2289     {"$f7",     RTYPE_FPU | 7},  \
2290     {"$f8",     RTYPE_FPU | 8},  \
2291     {"$f9",     RTYPE_FPU | 9},  \
2292     {"$f10",    RTYPE_FPU | 10}, \
2293     {"$f11",    RTYPE_FPU | 11}, \
2294     {"$f12",    RTYPE_FPU | 12}, \
2295     {"$f13",    RTYPE_FPU | 13}, \
2296     {"$f14",    RTYPE_FPU | 14}, \
2297     {"$f15",    RTYPE_FPU | 15}, \
2298     {"$f16",    RTYPE_FPU | 16}, \
2299     {"$f17",    RTYPE_FPU | 17}, \
2300     {"$f18",    RTYPE_FPU | 18}, \
2301     {"$f19",    RTYPE_FPU | 19}, \
2302     {"$f20",    RTYPE_FPU | 20}, \
2303     {"$f21",    RTYPE_FPU | 21}, \
2304     {"$f22",    RTYPE_FPU | 22}, \
2305     {"$f23",    RTYPE_FPU | 23}, \
2306     {"$f24",    RTYPE_FPU | 24}, \
2307     {"$f25",    RTYPE_FPU | 25}, \
2308     {"$f26",    RTYPE_FPU | 26}, \
2309     {"$f27",    RTYPE_FPU | 27}, \
2310     {"$f28",    RTYPE_FPU | 28}, \
2311     {"$f29",    RTYPE_FPU | 29}, \
2312     {"$f30",    RTYPE_FPU | 30}, \
2313     {"$f31",    RTYPE_FPU | 31}
2314
2315 #define FPU_CONDITION_CODE_NAMES \
2316     {"$fcc0",   RTYPE_FCC | 0},  \
2317     {"$fcc1",   RTYPE_FCC | 1},  \
2318     {"$fcc2",   RTYPE_FCC | 2},  \
2319     {"$fcc3",   RTYPE_FCC | 3},  \
2320     {"$fcc4",   RTYPE_FCC | 4},  \
2321     {"$fcc5",   RTYPE_FCC | 5},  \
2322     {"$fcc6",   RTYPE_FCC | 6},  \
2323     {"$fcc7",   RTYPE_FCC | 7}
2324
2325 #define COPROC_CONDITION_CODE_NAMES         \
2326     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2327     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2328     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2329     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2330     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2331     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2332     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2333     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2334
2335 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2336     {"$a4",     RTYPE_GP | 8},  \
2337     {"$a5",     RTYPE_GP | 9},  \
2338     {"$a6",     RTYPE_GP | 10}, \
2339     {"$a7",     RTYPE_GP | 11}, \
2340     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2341     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2342     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2343     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2344     {"$t0",     RTYPE_GP | 12}, \
2345     {"$t1",     RTYPE_GP | 13}, \
2346     {"$t2",     RTYPE_GP | 14}, \
2347     {"$t3",     RTYPE_GP | 15}
2348
2349 #define O32_SYMBOLIC_REGISTER_NAMES \
2350     {"$t0",     RTYPE_GP | 8},  \
2351     {"$t1",     RTYPE_GP | 9},  \
2352     {"$t2",     RTYPE_GP | 10}, \
2353     {"$t3",     RTYPE_GP | 11}, \
2354     {"$t4",     RTYPE_GP | 12}, \
2355     {"$t5",     RTYPE_GP | 13}, \
2356     {"$t6",     RTYPE_GP | 14}, \
2357     {"$t7",     RTYPE_GP | 15}, \
2358     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2359     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2360     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2361     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */ 
2362
2363 /* Remaining symbolic register names */
2364 #define SYMBOLIC_REGISTER_NAMES \
2365     {"$zero",   RTYPE_GP | 0},  \
2366     {"$at",     RTYPE_GP | 1},  \
2367     {"$AT",     RTYPE_GP | 1},  \
2368     {"$v0",     RTYPE_GP | 2},  \
2369     {"$v1",     RTYPE_GP | 3},  \
2370     {"$a0",     RTYPE_GP | 4},  \
2371     {"$a1",     RTYPE_GP | 5},  \
2372     {"$a2",     RTYPE_GP | 6},  \
2373     {"$a3",     RTYPE_GP | 7},  \
2374     {"$s0",     RTYPE_GP | 16}, \
2375     {"$s1",     RTYPE_GP | 17}, \
2376     {"$s2",     RTYPE_GP | 18}, \
2377     {"$s3",     RTYPE_GP | 19}, \
2378     {"$s4",     RTYPE_GP | 20}, \
2379     {"$s5",     RTYPE_GP | 21}, \
2380     {"$s6",     RTYPE_GP | 22}, \
2381     {"$s7",     RTYPE_GP | 23}, \
2382     {"$t8",     RTYPE_GP | 24}, \
2383     {"$t9",     RTYPE_GP | 25}, \
2384     {"$k0",     RTYPE_GP | 26}, \
2385     {"$kt0",    RTYPE_GP | 26}, \
2386     {"$k1",     RTYPE_GP | 27}, \
2387     {"$kt1",    RTYPE_GP | 27}, \
2388     {"$gp",     RTYPE_GP | 28}, \
2389     {"$sp",     RTYPE_GP | 29}, \
2390     {"$s8",     RTYPE_GP | 30}, \
2391     {"$fp",     RTYPE_GP | 30}, \
2392     {"$ra",     RTYPE_GP | 31}
2393
2394 #define MIPS16_SPECIAL_REGISTER_NAMES \
2395     {"$pc",     RTYPE_PC | 0}
2396
2397 #define MDMX_VECTOR_REGISTER_NAMES \
2398     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2399     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2400     {"$v2",     RTYPE_VEC | 2},  \
2401     {"$v3",     RTYPE_VEC | 3},  \
2402     {"$v4",     RTYPE_VEC | 4},  \
2403     {"$v5",     RTYPE_VEC | 5},  \
2404     {"$v6",     RTYPE_VEC | 6},  \
2405     {"$v7",     RTYPE_VEC | 7},  \
2406     {"$v8",     RTYPE_VEC | 8},  \
2407     {"$v9",     RTYPE_VEC | 9},  \
2408     {"$v10",    RTYPE_VEC | 10}, \
2409     {"$v11",    RTYPE_VEC | 11}, \
2410     {"$v12",    RTYPE_VEC | 12}, \
2411     {"$v13",    RTYPE_VEC | 13}, \
2412     {"$v14",    RTYPE_VEC | 14}, \
2413     {"$v15",    RTYPE_VEC | 15}, \
2414     {"$v16",    RTYPE_VEC | 16}, \
2415     {"$v17",    RTYPE_VEC | 17}, \
2416     {"$v18",    RTYPE_VEC | 18}, \
2417     {"$v19",    RTYPE_VEC | 19}, \
2418     {"$v20",    RTYPE_VEC | 20}, \
2419     {"$v21",    RTYPE_VEC | 21}, \
2420     {"$v22",    RTYPE_VEC | 22}, \
2421     {"$v23",    RTYPE_VEC | 23}, \
2422     {"$v24",    RTYPE_VEC | 24}, \
2423     {"$v25",    RTYPE_VEC | 25}, \
2424     {"$v26",    RTYPE_VEC | 26}, \
2425     {"$v27",    RTYPE_VEC | 27}, \
2426     {"$v28",    RTYPE_VEC | 28}, \
2427     {"$v29",    RTYPE_VEC | 29}, \
2428     {"$v30",    RTYPE_VEC | 30}, \
2429     {"$v31",    RTYPE_VEC | 31}
2430
2431 #define MIPS_DSP_ACCUMULATOR_NAMES \
2432     {"$ac0",    RTYPE_ACC | 0}, \
2433     {"$ac1",    RTYPE_ACC | 1}, \
2434     {"$ac2",    RTYPE_ACC | 2}, \
2435     {"$ac3",    RTYPE_ACC | 3}
2436
2437 static const struct regname reg_names[] = {
2438   GENERIC_REGISTER_NUMBERS,
2439   FPU_REGISTER_NAMES,
2440   FPU_CONDITION_CODE_NAMES,
2441   COPROC_CONDITION_CODE_NAMES,
2442
2443   /* The $txx registers depends on the abi,
2444      these will be added later into the symbol table from
2445      one of the tables below once mips_abi is set after 
2446      parsing of arguments from the command line. */
2447   SYMBOLIC_REGISTER_NAMES,
2448
2449   MIPS16_SPECIAL_REGISTER_NAMES,
2450   MDMX_VECTOR_REGISTER_NAMES,
2451   MIPS_DSP_ACCUMULATOR_NAMES,
2452   {0, 0}
2453 };
2454
2455 static const struct regname reg_names_o32[] = {
2456   O32_SYMBOLIC_REGISTER_NAMES,
2457   {0, 0}
2458 };
2459
2460 static const struct regname reg_names_n32n64[] = {
2461   N32N64_SYMBOLIC_REGISTER_NAMES,
2462   {0, 0}
2463 };
2464
2465 /* Check if S points at a valid register specifier according to TYPES.
2466    If so, then return 1, advance S to consume the specifier and store
2467    the register's number in REGNOP, otherwise return 0.  */
2468
2469 static int
2470 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2471 {
2472   symbolS *symbolP;
2473   char *e;
2474   char save_c;
2475   int reg = -1;
2476
2477   /* Find end of name.  */
2478   e = *s;
2479   if (is_name_beginner (*e))
2480     ++e;
2481   while (is_part_of_name (*e))
2482     ++e;
2483
2484   /* Terminate name.  */
2485   save_c = *e;
2486   *e = '\0';
2487
2488   /* Look for a register symbol.  */
2489   if ((symbolP = symbol_find (*s)) && S_GET_SEGMENT (symbolP) == reg_section)
2490     {
2491       int r = S_GET_VALUE (symbolP);
2492       if (r & types)
2493         reg = r & RNUM_MASK;
2494       else if ((types & RTYPE_VEC) && (r & ~1) == (RTYPE_GP | 2))
2495         /* Convert GP reg $v0/1 to MDMX reg $v0/1!  */
2496         reg = (r & RNUM_MASK) - 2;
2497     }
2498   /* Else see if this is a register defined in an itbl entry.  */
2499   else if ((types & RTYPE_GP) && itbl_have_entries)
2500     {
2501       char *n = *s;
2502       unsigned long r;
2503
2504       if (*n == '$')
2505         ++n;
2506       if (itbl_get_reg_val (n, &r))
2507         reg = r & RNUM_MASK;
2508     }
2509
2510   /* Advance to next token if a register was recognised.  */
2511   if (reg >= 0)
2512     *s = e;
2513   else if (types & RWARN)
2514     as_warn (_("Unrecognized register name `%s'"), *s);
2515
2516   *e = save_c;
2517   if (regnop)
2518     *regnop = reg;
2519   return reg >= 0;
2520 }
2521
2522 /* Check if S points at a valid register list according to TYPES.
2523    If so, then return 1, advance S to consume the list and store
2524    the registers present on the list as a bitmask of ones in REGLISTP,
2525    otherwise return 0.  A valid list comprises a comma-separated
2526    enumeration of valid single registers and/or dash-separated
2527    contiguous register ranges as determined by their numbers.
2528
2529    As a special exception if one of s0-s7 registers is specified as
2530    the range's lower delimiter and s8 (fp) is its upper one, then no
2531    registers whose numbers place them between s7 and s8 (i.e. $24-$29)
2532    are selected; they have to be listed separately if needed.  */
2533
2534 static int
2535 reglist_lookup (char **s, unsigned int types, unsigned int *reglistp)
2536 {
2537   unsigned int reglist = 0;
2538   unsigned int lastregno;
2539   bfd_boolean ok = TRUE;
2540   unsigned int regmask;
2541   char *s_endlist = *s;
2542   char *s_reset = *s;
2543   unsigned int regno;
2544
2545   while (reg_lookup (s, types, &regno))
2546     {
2547       lastregno = regno;
2548       if (**s == '-')
2549         {
2550           (*s)++;
2551           ok = reg_lookup (s, types, &lastregno);
2552           if (ok && lastregno < regno)
2553             ok = FALSE;
2554           if (!ok)
2555             break;
2556         }
2557
2558       if (lastregno == FP && regno >= S0 && regno <= S7)
2559         {
2560           lastregno = S7;
2561           reglist |= 1 << FP;
2562         }
2563       regmask = 1 << lastregno;
2564       regmask = (regmask << 1) - 1;
2565       regmask ^= (1 << regno) - 1;
2566       reglist |= regmask;
2567
2568       s_endlist = *s;
2569       if (**s != ',')
2570         break;
2571       (*s)++;
2572     }
2573
2574   if (ok)
2575     *s = s_endlist;
2576   else
2577     *s = s_reset;
2578   if (reglistp)
2579     *reglistp = reglist;
2580   return ok && reglist != 0;
2581 }
2582
2583 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
2584    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
2585
2586 static bfd_boolean
2587 is_opcode_valid (const struct mips_opcode *mo)
2588 {
2589   int isa = mips_opts.isa;
2590   int ase = mips_opts.ase;
2591   int fp_s, fp_d;
2592   unsigned int i;
2593
2594   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
2595     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2596       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
2597         ase |= mips_ases[i].flags64;
2598
2599   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
2600     return FALSE;
2601
2602   /* Check whether the instruction or macro requires single-precision or
2603      double-precision floating-point support.  Note that this information is
2604      stored differently in the opcode table for insns and macros.  */
2605   if (mo->pinfo == INSN_MACRO)
2606     {
2607       fp_s = mo->pinfo2 & INSN2_M_FP_S;
2608       fp_d = mo->pinfo2 & INSN2_M_FP_D;
2609     }
2610   else
2611     {
2612       fp_s = mo->pinfo & FP_S;
2613       fp_d = mo->pinfo & FP_D;
2614     }
2615
2616   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
2617     return FALSE;
2618
2619   if (fp_s && mips_opts.soft_float)
2620     return FALSE;
2621
2622   return TRUE;
2623 }
2624
2625 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
2626    selected ISA and architecture.  */
2627
2628 static bfd_boolean
2629 is_opcode_valid_16 (const struct mips_opcode *mo)
2630 {
2631   return opcode_is_member (mo, mips_opts.isa, 0, mips_opts.arch);
2632 }
2633
2634 /* Return TRUE if the size of the microMIPS opcode MO matches one
2635    explicitly requested.  Always TRUE in the standard MIPS mode.  */
2636
2637 static bfd_boolean
2638 is_size_valid (const struct mips_opcode *mo)
2639 {
2640   if (!mips_opts.micromips)
2641     return TRUE;
2642
2643   if (!forced_insn_length)
2644     return TRUE;
2645   if (mo->pinfo == INSN_MACRO)
2646     return FALSE;
2647   return forced_insn_length == micromips_insn_length (mo);
2648 }
2649
2650 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
2651    of the preceding instruction.  Always TRUE in the standard MIPS mode.
2652
2653    We don't accept macros in 16-bit delay slots to avoid a case where
2654    a macro expansion fails because it relies on a preceding 32-bit real
2655    instruction to have matched and does not handle the operands correctly.
2656    The only macros that may expand to 16-bit instructions are JAL that
2657    cannot be placed in a delay slot anyway, and corner cases of BALIGN
2658    and BGT (that likewise cannot be placed in a delay slot) that decay to
2659    a NOP.  In all these cases the macros precede any corresponding real
2660    instruction definitions in the opcode table, so they will match in the
2661    second pass where the size of the delay slot is ignored and therefore
2662    produce correct code.  */
2663
2664 static bfd_boolean
2665 is_delay_slot_valid (const struct mips_opcode *mo)
2666 {
2667   if (!mips_opts.micromips)
2668     return TRUE;
2669
2670   if (mo->pinfo == INSN_MACRO)
2671     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
2672   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
2673       && micromips_insn_length (mo) != 4)
2674     return FALSE;
2675   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
2676       && micromips_insn_length (mo) != 2)
2677     return FALSE;
2678
2679   return TRUE;
2680 }
2681
2682 /* This function is called once, at assembler startup time.  It should set up
2683    all the tables, etc. that the MD part of the assembler will need.  */
2684
2685 void
2686 md_begin (void)
2687 {
2688   const char *retval = NULL;
2689   int i = 0;
2690   int broken = 0;
2691
2692   if (mips_pic != NO_PIC)
2693     {
2694       if (g_switch_seen && g_switch_value != 0)
2695         as_bad (_("-G may not be used in position-independent code"));
2696       g_switch_value = 0;
2697     }
2698
2699   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_arch))
2700     as_warn (_("Could not set architecture and machine"));
2701
2702   op_hash = hash_new ();
2703
2704   for (i = 0; i < NUMOPCODES;)
2705     {
2706       const char *name = mips_opcodes[i].name;
2707
2708       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
2709       if (retval != NULL)
2710         {
2711           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
2712                    mips_opcodes[i].name, retval);
2713           /* Probably a memory allocation problem?  Give up now.  */
2714           as_fatal (_("Broken assembler.  No assembly attempted."));
2715         }
2716       do
2717         {
2718           if (mips_opcodes[i].pinfo != INSN_MACRO)
2719             {
2720               if (!validate_mips_insn (&mips_opcodes[i]))
2721                 broken = 1;
2722               if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
2723                 {
2724                   create_insn (&nop_insn, mips_opcodes + i);
2725                   if (mips_fix_loongson2f_nop)
2726                     nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
2727                   nop_insn.fixed_p = 1;
2728                 }
2729             }
2730           ++i;
2731         }
2732       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
2733     }
2734
2735   mips16_op_hash = hash_new ();
2736
2737   i = 0;
2738   while (i < bfd_mips16_num_opcodes)
2739     {
2740       const char *name = mips16_opcodes[i].name;
2741
2742       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
2743       if (retval != NULL)
2744         as_fatal (_("internal: can't hash `%s': %s"),
2745                   mips16_opcodes[i].name, retval);
2746       do
2747         {
2748           if (mips16_opcodes[i].pinfo != INSN_MACRO
2749               && ((mips16_opcodes[i].match & mips16_opcodes[i].mask)
2750                   != mips16_opcodes[i].match))
2751             {
2752               fprintf (stderr, _("internal error: bad mips16 opcode: %s %s\n"),
2753                        mips16_opcodes[i].name, mips16_opcodes[i].args);
2754               broken = 1;
2755             }
2756           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
2757             {
2758               create_insn (&mips16_nop_insn, mips16_opcodes + i);
2759               mips16_nop_insn.fixed_p = 1;
2760             }
2761           ++i;
2762         }
2763       while (i < bfd_mips16_num_opcodes
2764              && strcmp (mips16_opcodes[i].name, name) == 0);
2765     }
2766
2767   micromips_op_hash = hash_new ();
2768
2769   i = 0;
2770   while (i < bfd_micromips_num_opcodes)
2771     {
2772       const char *name = micromips_opcodes[i].name;
2773
2774       retval = hash_insert (micromips_op_hash, name,
2775                             (void *) &micromips_opcodes[i]);
2776       if (retval != NULL)
2777         as_fatal (_("internal: can't hash `%s': %s"),
2778                   micromips_opcodes[i].name, retval);
2779       do
2780         if (micromips_opcodes[i].pinfo != INSN_MACRO)
2781           {
2782             struct mips_cl_insn *micromips_nop_insn;
2783
2784             if (!validate_micromips_insn (&micromips_opcodes[i]))
2785               broken = 1;
2786
2787             if (micromips_insn_length (micromips_opcodes + i) == 2)
2788               micromips_nop_insn = &micromips_nop16_insn;
2789             else if (micromips_insn_length (micromips_opcodes + i) == 4)
2790               micromips_nop_insn = &micromips_nop32_insn;
2791             else
2792               continue;
2793
2794             if (micromips_nop_insn->insn_mo == NULL
2795                 && strcmp (name, "nop") == 0)
2796               {
2797                 create_insn (micromips_nop_insn, micromips_opcodes + i);
2798                 micromips_nop_insn->fixed_p = 1;
2799               }
2800           }
2801       while (++i < bfd_micromips_num_opcodes
2802              && strcmp (micromips_opcodes[i].name, name) == 0);
2803     }
2804
2805   if (broken)
2806     as_fatal (_("Broken assembler.  No assembly attempted."));
2807
2808   /* We add all the general register names to the symbol table.  This
2809      helps us detect invalid uses of them.  */
2810   for (i = 0; reg_names[i].name; i++) 
2811     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
2812                                      reg_names[i].num, /* & RNUM_MASK, */
2813                                      &zero_address_frag));
2814   if (HAVE_NEWABI)
2815     for (i = 0; reg_names_n32n64[i].name; i++) 
2816       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
2817                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
2818                                        &zero_address_frag));
2819   else
2820     for (i = 0; reg_names_o32[i].name; i++) 
2821       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
2822                                        reg_names_o32[i].num, /* & RNUM_MASK, */
2823                                        &zero_address_frag));
2824
2825   mips_no_prev_insn ();
2826
2827   mips_gprmask = 0;
2828   mips_cprmask[0] = 0;
2829   mips_cprmask[1] = 0;
2830   mips_cprmask[2] = 0;
2831   mips_cprmask[3] = 0;
2832
2833   /* set the default alignment for the text section (2**2) */
2834   record_alignment (text_section, 2);
2835
2836   bfd_set_gp_size (stdoutput, g_switch_value);
2837
2838 #ifdef OBJ_ELF
2839   if (IS_ELF)
2840     {
2841       /* On a native system other than VxWorks, sections must be aligned
2842          to 16 byte boundaries.  When configured for an embedded ELF
2843          target, we don't bother.  */
2844       if (strncmp (TARGET_OS, "elf", 3) != 0
2845           && strncmp (TARGET_OS, "vxworks", 7) != 0)
2846         {
2847           (void) bfd_set_section_alignment (stdoutput, text_section, 4);
2848           (void) bfd_set_section_alignment (stdoutput, data_section, 4);
2849           (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
2850         }
2851
2852       /* Create a .reginfo section for register masks and a .mdebug
2853          section for debugging information.  */
2854       {
2855         segT seg;
2856         subsegT subseg;
2857         flagword flags;
2858         segT sec;
2859
2860         seg = now_seg;
2861         subseg = now_subseg;
2862
2863         /* The ABI says this section should be loaded so that the
2864            running program can access it.  However, we don't load it
2865            if we are configured for an embedded target */
2866         flags = SEC_READONLY | SEC_DATA;
2867         if (strncmp (TARGET_OS, "elf", 3) != 0)
2868           flags |= SEC_ALLOC | SEC_LOAD;
2869
2870         if (mips_abi != N64_ABI)
2871           {
2872             sec = subseg_new (".reginfo", (subsegT) 0);
2873
2874             bfd_set_section_flags (stdoutput, sec, flags);
2875             bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
2876
2877             mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
2878           }
2879         else
2880           {
2881             /* The 64-bit ABI uses a .MIPS.options section rather than
2882                .reginfo section.  */
2883             sec = subseg_new (".MIPS.options", (subsegT) 0);
2884             bfd_set_section_flags (stdoutput, sec, flags);
2885             bfd_set_section_alignment (stdoutput, sec, 3);
2886
2887             /* Set up the option header.  */
2888             {
2889               Elf_Internal_Options opthdr;
2890               char *f;
2891
2892               opthdr.kind = ODK_REGINFO;
2893               opthdr.size = (sizeof (Elf_External_Options)
2894                              + sizeof (Elf64_External_RegInfo));
2895               opthdr.section = 0;
2896               opthdr.info = 0;
2897               f = frag_more (sizeof (Elf_External_Options));
2898               bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
2899                                              (Elf_External_Options *) f);
2900
2901               mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
2902             }
2903           }
2904
2905         if (ECOFF_DEBUGGING)
2906           {
2907             sec = subseg_new (".mdebug", (subsegT) 0);
2908             (void) bfd_set_section_flags (stdoutput, sec,
2909                                           SEC_HAS_CONTENTS | SEC_READONLY);
2910             (void) bfd_set_section_alignment (stdoutput, sec, 2);
2911           }
2912         else if (mips_flag_pdr)
2913           {
2914             pdr_seg = subseg_new (".pdr", (subsegT) 0);
2915             (void) bfd_set_section_flags (stdoutput, pdr_seg,
2916                                           SEC_READONLY | SEC_RELOC
2917                                           | SEC_DEBUGGING);
2918             (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
2919           }
2920
2921         subseg_set (seg, subseg);
2922       }
2923     }
2924 #endif /* OBJ_ELF */
2925
2926   if (! ECOFF_DEBUGGING)
2927     md_obj_begin ();
2928
2929   if (mips_fix_vr4120)
2930     init_vr4120_conflicts ();
2931 }
2932
2933 void
2934 md_mips_end (void)
2935 {
2936   mips_emit_delays ();
2937   if (! ECOFF_DEBUGGING)
2938     md_obj_end ();
2939 }
2940
2941 void
2942 md_assemble (char *str)
2943 {
2944   struct mips_cl_insn insn;
2945   bfd_reloc_code_real_type unused_reloc[3]
2946     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
2947
2948   imm_expr.X_op = O_absent;
2949   imm2_expr.X_op = O_absent;
2950   offset_expr.X_op = O_absent;
2951   imm_reloc[0] = BFD_RELOC_UNUSED;
2952   imm_reloc[1] = BFD_RELOC_UNUSED;
2953   imm_reloc[2] = BFD_RELOC_UNUSED;
2954   offset_reloc[0] = BFD_RELOC_UNUSED;
2955   offset_reloc[1] = BFD_RELOC_UNUSED;
2956   offset_reloc[2] = BFD_RELOC_UNUSED;
2957
2958   mips_mark_labels ();
2959   mips_assembling_insn = TRUE;
2960
2961   if (mips_opts.mips16)
2962     mips16_ip (str, &insn);
2963   else
2964     {
2965       mips_ip (str, &insn);
2966       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
2967             str, insn.insn_opcode));
2968     }
2969
2970   if (insn_error)
2971     as_bad ("%s `%s'", insn_error, str);
2972   else if (insn.insn_mo->pinfo == INSN_MACRO)
2973     {
2974       macro_start ();
2975       if (mips_opts.mips16)
2976         mips16_macro (&insn);
2977       else
2978         macro (&insn);
2979       macro_end ();
2980     }
2981   else
2982     {
2983       if (imm_expr.X_op != O_absent)
2984         append_insn (&insn, &imm_expr, imm_reloc, FALSE);
2985       else if (offset_expr.X_op != O_absent)
2986         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
2987       else
2988         append_insn (&insn, NULL, unused_reloc, FALSE);
2989     }
2990
2991   mips_assembling_insn = FALSE;
2992 }
2993
2994 /* Convenience functions for abstracting away the differences between
2995    MIPS16 and non-MIPS16 relocations.  */
2996
2997 static inline bfd_boolean
2998 mips16_reloc_p (bfd_reloc_code_real_type reloc)
2999 {
3000   switch (reloc)
3001     {
3002     case BFD_RELOC_MIPS16_JMP:
3003     case BFD_RELOC_MIPS16_GPREL:
3004     case BFD_RELOC_MIPS16_GOT16:
3005     case BFD_RELOC_MIPS16_CALL16:
3006     case BFD_RELOC_MIPS16_HI16_S:
3007     case BFD_RELOC_MIPS16_HI16:
3008     case BFD_RELOC_MIPS16_LO16:
3009       return TRUE;
3010
3011     default:
3012       return FALSE;
3013     }
3014 }
3015
3016 static inline bfd_boolean
3017 micromips_reloc_p (bfd_reloc_code_real_type reloc)
3018 {
3019   switch (reloc)
3020     {
3021     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3022     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3023     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3024     case BFD_RELOC_MICROMIPS_GPREL16:
3025     case BFD_RELOC_MICROMIPS_JMP:
3026     case BFD_RELOC_MICROMIPS_HI16:
3027     case BFD_RELOC_MICROMIPS_HI16_S:
3028     case BFD_RELOC_MICROMIPS_LO16:
3029     case BFD_RELOC_MICROMIPS_LITERAL:
3030     case BFD_RELOC_MICROMIPS_GOT16:
3031     case BFD_RELOC_MICROMIPS_CALL16:
3032     case BFD_RELOC_MICROMIPS_GOT_HI16:
3033     case BFD_RELOC_MICROMIPS_GOT_LO16:
3034     case BFD_RELOC_MICROMIPS_CALL_HI16:
3035     case BFD_RELOC_MICROMIPS_CALL_LO16:
3036     case BFD_RELOC_MICROMIPS_SUB:
3037     case BFD_RELOC_MICROMIPS_GOT_PAGE:
3038     case BFD_RELOC_MICROMIPS_GOT_OFST:
3039     case BFD_RELOC_MICROMIPS_GOT_DISP:
3040     case BFD_RELOC_MICROMIPS_HIGHEST:
3041     case BFD_RELOC_MICROMIPS_HIGHER:
3042     case BFD_RELOC_MICROMIPS_SCN_DISP:
3043     case BFD_RELOC_MICROMIPS_JALR:
3044       return TRUE;
3045
3046     default:
3047       return FALSE;
3048     }
3049 }
3050
3051 static inline bfd_boolean
3052 jmp_reloc_p (bfd_reloc_code_real_type reloc)
3053 {
3054   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
3055 }
3056
3057 static inline bfd_boolean
3058 got16_reloc_p (bfd_reloc_code_real_type reloc)
3059 {
3060   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
3061           || reloc == BFD_RELOC_MICROMIPS_GOT16);
3062 }
3063
3064 static inline bfd_boolean
3065 hi16_reloc_p (bfd_reloc_code_real_type reloc)
3066 {
3067   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
3068           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
3069 }
3070
3071 static inline bfd_boolean
3072 lo16_reloc_p (bfd_reloc_code_real_type reloc)
3073 {
3074   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
3075           || reloc == BFD_RELOC_MICROMIPS_LO16);
3076 }
3077
3078 static inline bfd_boolean
3079 jalr_reloc_p (bfd_reloc_code_real_type reloc)
3080 {
3081   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
3082 }
3083
3084 /* Return true if RELOC is a PC-relative relocation that does not have
3085    full address range.  */
3086
3087 static inline bfd_boolean
3088 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
3089 {
3090   switch (reloc)
3091     {
3092     case BFD_RELOC_16_PCREL_S2:
3093     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3094     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3095     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3096       return TRUE;
3097
3098     case BFD_RELOC_32_PCREL:
3099       return HAVE_64BIT_ADDRESSES;
3100
3101     default:
3102       return FALSE;
3103     }
3104 }
3105
3106 /* Return true if the given relocation might need a matching %lo().
3107    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
3108    need a matching %lo() when applied to local symbols.  */
3109
3110 static inline bfd_boolean
3111 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
3112 {
3113   return (HAVE_IN_PLACE_ADDENDS
3114           && (hi16_reloc_p (reloc)
3115               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
3116                  all GOT16 relocations evaluate to "G".  */
3117               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
3118 }
3119
3120 /* Return the type of %lo() reloc needed by RELOC, given that
3121    reloc_needs_lo_p.  */
3122
3123 static inline bfd_reloc_code_real_type
3124 matching_lo_reloc (bfd_reloc_code_real_type reloc)
3125 {
3126   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
3127           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
3128              : BFD_RELOC_LO16));
3129 }
3130
3131 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
3132    relocation.  */
3133
3134 static inline bfd_boolean
3135 fixup_has_matching_lo_p (fixS *fixp)
3136 {
3137   return (fixp->fx_next != NULL
3138           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
3139           && fixp->fx_addsy == fixp->fx_next->fx_addsy
3140           && fixp->fx_offset == fixp->fx_next->fx_offset);
3141 }
3142
3143 /* This function returns true if modifying a register requires a
3144    delay.  */
3145
3146 static int
3147 reg_needs_delay (unsigned int reg)
3148 {
3149   unsigned long prev_pinfo;
3150
3151   prev_pinfo = history[0].insn_mo->pinfo;
3152   if (! mips_opts.noreorder
3153       && (((prev_pinfo & INSN_LOAD_MEMORY_DELAY)
3154            && ! gpr_interlocks)
3155           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY)
3156               && ! cop_interlocks)))
3157     {
3158       /* A load from a coprocessor or from memory.  All load delays
3159          delay the use of general register rt for one instruction.  */
3160       /* Itbl support may require additional care here.  */
3161       know (prev_pinfo & INSN_WRITE_GPR_T);
3162       if (reg == EXTRACT_OPERAND (mips_opts.micromips, RT, history[0]))
3163         return 1;
3164     }
3165
3166   return 0;
3167 }
3168
3169 /* Move all labels in LABELS to the current insertion point.  TEXT_P
3170    says whether the labels refer to text or data.  */
3171
3172 static void
3173 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
3174 {
3175   struct insn_label_list *l;
3176   valueT val;
3177
3178   for (l = labels; l != NULL; l = l->next)
3179     {
3180       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
3181       symbol_set_frag (l->label, frag_now);
3182       val = (valueT) frag_now_fix ();
3183       /* MIPS16/microMIPS text labels are stored as odd.  */
3184       if (text_p && HAVE_CODE_COMPRESSION)
3185         ++val;
3186       S_SET_VALUE (l->label, val);
3187     }
3188 }
3189
3190 /* Move all labels in insn_labels to the current insertion point
3191    and treat them as text labels.  */
3192
3193 static void
3194 mips_move_text_labels (void)
3195 {
3196   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
3197 }
3198
3199 static bfd_boolean
3200 s_is_linkonce (symbolS *sym, segT from_seg)
3201 {
3202   bfd_boolean linkonce = FALSE;
3203   segT symseg = S_GET_SEGMENT (sym);
3204
3205   if (symseg != from_seg && !S_IS_LOCAL (sym))
3206     {
3207       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
3208         linkonce = TRUE;
3209 #ifdef OBJ_ELF
3210       /* The GNU toolchain uses an extension for ELF: a section
3211          beginning with the magic string .gnu.linkonce is a
3212          linkonce section.  */
3213       if (strncmp (segment_name (symseg), ".gnu.linkonce",
3214                    sizeof ".gnu.linkonce" - 1) == 0)
3215         linkonce = TRUE;
3216 #endif
3217     }
3218   return linkonce;
3219 }
3220
3221 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
3222    linker to handle them specially, such as generating jalx instructions
3223    when needed.  We also make them odd for the duration of the assembly,
3224    in order to generate the right sort of code.  We will make them even
3225    in the adjust_symtab routine, while leaving them marked.  This is
3226    convenient for the debugger and the disassembler.  The linker knows
3227    to make them odd again.  */
3228
3229 static void
3230 mips_compressed_mark_label (symbolS *label)
3231 {
3232   gas_assert (HAVE_CODE_COMPRESSION);
3233
3234 #if defined(OBJ_ELF) || defined(OBJ_MAYBE_ELF)
3235   if (IS_ELF)
3236     {
3237       if (mips_opts.mips16)
3238         S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
3239       else
3240         S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
3241     }
3242 #endif
3243   if ((S_GET_VALUE (label) & 1) == 0
3244       /* Don't adjust the address if the label is global or weak, or
3245          in a link-once section, since we'll be emitting symbol reloc
3246          references to it which will be patched up by the linker, and
3247          the final value of the symbol may or may not be MIPS16/microMIPS.  */
3248       && !S_IS_WEAK (label)
3249       && !S_IS_EXTERNAL (label)
3250       && !s_is_linkonce (label, now_seg))
3251     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
3252 }
3253
3254 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
3255
3256 static void
3257 mips_compressed_mark_labels (void)
3258 {
3259   struct insn_label_list *l;
3260
3261   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
3262     mips_compressed_mark_label (l->label);
3263 }
3264
3265 /* End the current frag.  Make it a variant frag and record the
3266    relaxation info.  */
3267
3268 static void
3269 relax_close_frag (void)
3270 {
3271   mips_macro_warning.first_frag = frag_now;
3272   frag_var (rs_machine_dependent, 0, 0,
3273             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
3274             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
3275
3276   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
3277   mips_relax.first_fixup = 0;
3278 }
3279
3280 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
3281    See the comment above RELAX_ENCODE for more details.  */
3282
3283 static void
3284 relax_start (symbolS *symbol)
3285 {
3286   gas_assert (mips_relax.sequence == 0);
3287   mips_relax.sequence = 1;
3288   mips_relax.symbol = symbol;
3289 }
3290
3291 /* Start generating the second version of a relaxable sequence.
3292    See the comment above RELAX_ENCODE for more details.  */
3293
3294 static void
3295 relax_switch (void)
3296 {
3297   gas_assert (mips_relax.sequence == 1);
3298   mips_relax.sequence = 2;
3299 }
3300
3301 /* End the current relaxable sequence.  */
3302
3303 static void
3304 relax_end (void)
3305 {
3306   gas_assert (mips_relax.sequence == 2);
3307   relax_close_frag ();
3308   mips_relax.sequence = 0;
3309 }
3310
3311 /* Return true if IP is a delayed branch or jump.  */
3312
3313 static inline bfd_boolean
3314 delayed_branch_p (const struct mips_cl_insn *ip)
3315 {
3316   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
3317                                 | INSN_COND_BRANCH_DELAY
3318                                 | INSN_COND_BRANCH_LIKELY)) != 0;
3319 }
3320
3321 /* Return true if IP is a compact branch or jump.  */
3322
3323 static inline bfd_boolean
3324 compact_branch_p (const struct mips_cl_insn *ip)
3325 {
3326   if (mips_opts.mips16)
3327     return (ip->insn_mo->pinfo & (MIPS16_INSN_UNCOND_BRANCH
3328                                   | MIPS16_INSN_COND_BRANCH)) != 0;
3329   else
3330     return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
3331                                    | INSN2_COND_BRANCH)) != 0;
3332 }
3333
3334 /* Return true if IP is an unconditional branch or jump.  */
3335
3336 static inline bfd_boolean
3337 uncond_branch_p (const struct mips_cl_insn *ip)
3338 {
3339   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
3340           || (mips_opts.mips16
3341               ? (ip->insn_mo->pinfo & MIPS16_INSN_UNCOND_BRANCH) != 0
3342               : (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0));
3343 }
3344
3345 /* Return true if IP is a branch-likely instruction.  */
3346
3347 static inline bfd_boolean
3348 branch_likely_p (const struct mips_cl_insn *ip)
3349 {
3350   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
3351 }
3352
3353 /* Return the type of nop that should be used to fill the delay slot
3354    of delayed branch IP.  */
3355
3356 static struct mips_cl_insn *
3357 get_delay_slot_nop (const struct mips_cl_insn *ip)
3358 {
3359   if (mips_opts.micromips
3360       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
3361     return &micromips_nop32_insn;
3362   return NOP_INSN;
3363 }
3364
3365 /* Return the mask of core registers that IP reads or writes.  */
3366
3367 static unsigned int
3368 gpr_mod_mask (const struct mips_cl_insn *ip)
3369 {
3370   unsigned long pinfo2;
3371   unsigned int mask;
3372
3373   mask = 0;
3374   pinfo2 = ip->insn_mo->pinfo2;
3375   if (mips_opts.micromips)
3376     {
3377       if (pinfo2 & INSN2_MOD_GPR_MD)
3378         mask |= 1 << micromips_to_32_reg_d_map[EXTRACT_OPERAND (1, MD, *ip)];
3379       if (pinfo2 & INSN2_MOD_GPR_MF)
3380         mask |= 1 << micromips_to_32_reg_f_map[EXTRACT_OPERAND (1, MF, *ip)];
3381       if (pinfo2 & INSN2_MOD_SP)
3382         mask |= 1 << SP;
3383     }
3384   return mask;
3385 }
3386
3387 /* Return the mask of core registers that IP reads.  */
3388
3389 static unsigned int
3390 gpr_read_mask (const struct mips_cl_insn *ip)
3391 {
3392   unsigned long pinfo, pinfo2;
3393   unsigned int mask;
3394
3395   mask = gpr_mod_mask (ip);
3396   pinfo = ip->insn_mo->pinfo;
3397   pinfo2 = ip->insn_mo->pinfo2;
3398   if (mips_opts.mips16)
3399     {
3400       if (pinfo & MIPS16_INSN_READ_X)
3401         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)];
3402       if (pinfo & MIPS16_INSN_READ_Y)
3403         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)];
3404       if (pinfo & MIPS16_INSN_READ_T)
3405         mask |= 1 << TREG;
3406       if (pinfo & MIPS16_INSN_READ_SP)
3407         mask |= 1 << SP;
3408       if (pinfo & MIPS16_INSN_READ_31)
3409         mask |= 1 << RA;
3410       if (pinfo & MIPS16_INSN_READ_Z)
3411         mask |= 1 << (mips16_to_32_reg_map
3412                       [MIPS16_EXTRACT_OPERAND (MOVE32Z, *ip)]);
3413       if (pinfo & MIPS16_INSN_READ_GPR_X)
3414         mask |= 1 << MIPS16_EXTRACT_OPERAND (REGR32, *ip);
3415     }
3416   else
3417     {
3418       if (pinfo2 & INSN2_READ_GPR_D)
3419         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
3420       if (pinfo & INSN_READ_GPR_T)
3421         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
3422       if (pinfo & INSN_READ_GPR_S)
3423         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
3424       if (pinfo2 & INSN2_READ_GP)
3425         mask |= 1 << GP;
3426       if (pinfo2 & INSN2_READ_GPR_31)
3427         mask |= 1 << RA;
3428       if (pinfo2 & INSN2_READ_GPR_Z)
3429         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RZ, *ip);
3430     }
3431   if (mips_opts.micromips)
3432     {
3433       if (pinfo2 & INSN2_READ_GPR_MC)
3434         mask |= 1 << micromips_to_32_reg_c_map[EXTRACT_OPERAND (1, MC, *ip)];
3435       if (pinfo2 & INSN2_READ_GPR_ME)
3436         mask |= 1 << micromips_to_32_reg_e_map[EXTRACT_OPERAND (1, ME, *ip)];
3437       if (pinfo2 & INSN2_READ_GPR_MG)
3438         mask |= 1 << micromips_to_32_reg_g_map[EXTRACT_OPERAND (1, MG, *ip)];
3439       if (pinfo2 & INSN2_READ_GPR_MJ)
3440         mask |= 1 << EXTRACT_OPERAND (1, MJ, *ip);
3441       if (pinfo2 & INSN2_READ_GPR_MMN)
3442         {
3443           mask |= 1 << micromips_to_32_reg_m_map[EXTRACT_OPERAND (1, MM, *ip)];
3444           mask |= 1 << micromips_to_32_reg_n_map[EXTRACT_OPERAND (1, MN, *ip)];
3445         }
3446       if (pinfo2 & INSN2_READ_GPR_MP)
3447         mask |= 1 << EXTRACT_OPERAND (1, MP, *ip);
3448       if (pinfo2 & INSN2_READ_GPR_MQ)
3449         mask |= 1 << micromips_to_32_reg_q_map[EXTRACT_OPERAND (1, MQ, *ip)];
3450     }
3451   /* Don't include register 0.  */
3452   return mask & ~1;
3453 }
3454
3455 /* Return the mask of core registers that IP writes.  */
3456
3457 static unsigned int
3458 gpr_write_mask (const struct mips_cl_insn *ip)
3459 {
3460   unsigned long pinfo, pinfo2;
3461   unsigned int mask;
3462
3463   mask = gpr_mod_mask (ip);
3464   pinfo = ip->insn_mo->pinfo;
3465   pinfo2 = ip->insn_mo->pinfo2;
3466   if (mips_opts.mips16)
3467     {
3468       if (pinfo & MIPS16_INSN_WRITE_X)
3469         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)];
3470       if (pinfo & MIPS16_INSN_WRITE_Y)
3471         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)];
3472       if (pinfo & MIPS16_INSN_WRITE_Z)
3473         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RZ, *ip)];
3474       if (pinfo & MIPS16_INSN_WRITE_T)
3475         mask |= 1 << TREG;
3476       if (pinfo & MIPS16_INSN_WRITE_SP)
3477         mask |= 1 << SP;
3478       if (pinfo & MIPS16_INSN_WRITE_31)
3479         mask |= 1 << RA;
3480       if (pinfo & MIPS16_INSN_WRITE_GPR_Y)
3481         mask |= 1 << MIPS16OP_EXTRACT_REG32R (ip->insn_opcode);
3482     }
3483   else
3484     {
3485       if (pinfo & INSN_WRITE_GPR_D)
3486         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
3487       if (pinfo & INSN_WRITE_GPR_T)
3488         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
3489       if (pinfo & INSN_WRITE_GPR_S)
3490         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
3491       if (pinfo & INSN_WRITE_GPR_31)
3492         mask |= 1 << RA;
3493       if (pinfo2 & INSN2_WRITE_GPR_Z)
3494         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RZ, *ip);
3495     }
3496   if (mips_opts.micromips)
3497     {
3498       if (pinfo2 & INSN2_WRITE_GPR_MB)
3499         mask |= 1 << micromips_to_32_reg_b_map[EXTRACT_OPERAND (1, MB, *ip)];
3500       if (pinfo2 & INSN2_WRITE_GPR_MHI)
3501         {
3502           mask |= 1 << micromips_to_32_reg_h_map[EXTRACT_OPERAND (1, MH, *ip)];
3503           mask |= 1 << micromips_to_32_reg_i_map[EXTRACT_OPERAND (1, MI, *ip)];
3504         }
3505       if (pinfo2 & INSN2_WRITE_GPR_MJ)
3506         mask |= 1 << EXTRACT_OPERAND (1, MJ, *ip);
3507       if (pinfo2 & INSN2_WRITE_GPR_MP)
3508         mask |= 1 << EXTRACT_OPERAND (1, MP, *ip);
3509     }
3510   /* Don't include register 0.  */
3511   return mask & ~1;
3512 }
3513
3514 /* Return the mask of floating-point registers that IP reads.  */
3515
3516 static unsigned int
3517 fpr_read_mask (const struct mips_cl_insn *ip)
3518 {
3519   unsigned long pinfo, pinfo2;
3520   unsigned int mask;
3521
3522   mask = 0;
3523   pinfo = ip->insn_mo->pinfo;
3524   pinfo2 = ip->insn_mo->pinfo2;
3525   if (!mips_opts.mips16)
3526     {
3527       if (pinfo2 & INSN2_READ_FPR_D)
3528         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FD, *ip);
3529       if (pinfo & INSN_READ_FPR_S)
3530         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FS, *ip);
3531       if (pinfo & INSN_READ_FPR_T)
3532         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FT, *ip);
3533       if (pinfo & INSN_READ_FPR_R)
3534         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FR, *ip);
3535       if (pinfo2 & INSN2_READ_FPR_Z)
3536         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FZ, *ip);
3537     }
3538   /* Conservatively treat all operands to an FP_D instruction are doubles.
3539      (This is overly pessimistic for things like cvt.d.s.)  */
3540   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
3541     mask |= mask << 1;
3542   return mask;
3543 }
3544
3545 /* Return the mask of floating-point registers that IP writes.  */
3546
3547 static unsigned int
3548 fpr_write_mask (const struct mips_cl_insn *ip)
3549 {
3550   unsigned long pinfo, pinfo2;
3551   unsigned int mask;
3552
3553   mask = 0;
3554   pinfo = ip->insn_mo->pinfo;
3555   pinfo2 = ip->insn_mo->pinfo2;
3556   if (!mips_opts.mips16)
3557     {
3558       if (pinfo & INSN_WRITE_FPR_D)
3559         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FD, *ip);
3560       if (pinfo & INSN_WRITE_FPR_S)
3561         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FS, *ip);
3562       if (pinfo & INSN_WRITE_FPR_T)
3563         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FT, *ip);
3564       if (pinfo2 & INSN2_WRITE_FPR_Z)
3565         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FZ, *ip);
3566     }
3567   /* Conservatively treat all operands to an FP_D instruction are doubles.
3568      (This is overly pessimistic for things like cvt.s.d.)  */
3569   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
3570     mask |= mask << 1;
3571   return mask;
3572 }
3573
3574 /* Classify an instruction according to the FIX_VR4120_* enumeration.
3575    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
3576    by VR4120 errata.  */
3577
3578 static unsigned int
3579 classify_vr4120_insn (const char *name)
3580 {
3581   if (strncmp (name, "macc", 4) == 0)
3582     return FIX_VR4120_MACC;
3583   if (strncmp (name, "dmacc", 5) == 0)
3584     return FIX_VR4120_DMACC;
3585   if (strncmp (name, "mult", 4) == 0)
3586     return FIX_VR4120_MULT;
3587   if (strncmp (name, "dmult", 5) == 0)
3588     return FIX_VR4120_DMULT;
3589   if (strstr (name, "div"))
3590     return FIX_VR4120_DIV;
3591   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
3592     return FIX_VR4120_MTHILO;
3593   return NUM_FIX_VR4120_CLASSES;
3594 }
3595
3596 #define INSN_ERET  0x42000018
3597 #define INSN_DERET 0x4200001f
3598
3599 /* Return the number of instructions that must separate INSN1 and INSN2,
3600    where INSN1 is the earlier instruction.  Return the worst-case value
3601    for any INSN2 if INSN2 is null.  */
3602
3603 static unsigned int
3604 insns_between (const struct mips_cl_insn *insn1,
3605                const struct mips_cl_insn *insn2)
3606 {
3607   unsigned long pinfo1, pinfo2;
3608   unsigned int mask;
3609
3610   /* This function needs to know which pinfo flags are set for INSN2
3611      and which registers INSN2 uses.  The former is stored in PINFO2 and
3612      the latter is tested via INSN2_USES_GPR.  If INSN2 is null, PINFO2
3613      will have every flag set and INSN2_USES_GPR will always return true.  */
3614   pinfo1 = insn1->insn_mo->pinfo;
3615   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
3616
3617 #define INSN2_USES_GPR(REG) \
3618   (insn2 == NULL || (gpr_read_mask (insn2) & (1U << (REG))) != 0)
3619
3620   /* For most targets, write-after-read dependencies on the HI and LO
3621      registers must be separated by at least two instructions.  */
3622   if (!hilo_interlocks)
3623     {
3624       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
3625         return 2;
3626       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
3627         return 2;
3628     }
3629
3630   /* If we're working around r7000 errata, there must be two instructions
3631      between an mfhi or mflo and any instruction that uses the result.  */
3632   if (mips_7000_hilo_fix
3633       && !mips_opts.micromips
3634       && MF_HILO_INSN (pinfo1)
3635       && INSN2_USES_GPR (EXTRACT_OPERAND (0, RD, *insn1)))
3636     return 2;
3637
3638   /* If we're working around 24K errata, one instruction is required
3639      if an ERET or DERET is followed by a branch instruction.  */
3640   if (mips_fix_24k && !mips_opts.micromips)
3641     {
3642       if (insn1->insn_opcode == INSN_ERET
3643           || insn1->insn_opcode == INSN_DERET)
3644         {
3645           if (insn2 == NULL
3646               || insn2->insn_opcode == INSN_ERET
3647               || insn2->insn_opcode == INSN_DERET
3648               || delayed_branch_p (insn2))
3649             return 1;
3650         }
3651     }
3652
3653   /* If working around VR4120 errata, check for combinations that need
3654      a single intervening instruction.  */
3655   if (mips_fix_vr4120 && !mips_opts.micromips)
3656     {
3657       unsigned int class1, class2;
3658
3659       class1 = classify_vr4120_insn (insn1->insn_mo->name);
3660       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
3661         {
3662           if (insn2 == NULL)
3663             return 1;
3664           class2 = classify_vr4120_insn (insn2->insn_mo->name);
3665           if (vr4120_conflicts[class1] & (1 << class2))
3666             return 1;
3667         }
3668     }
3669
3670   if (!HAVE_CODE_COMPRESSION)
3671     {
3672       /* Check for GPR or coprocessor load delays.  All such delays
3673          are on the RT register.  */
3674       /* Itbl support may require additional care here.  */
3675       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY_DELAY))
3676           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
3677         {
3678           know (pinfo1 & INSN_WRITE_GPR_T);
3679           if (INSN2_USES_GPR (EXTRACT_OPERAND (0, RT, *insn1)))
3680             return 1;
3681         }
3682
3683       /* Check for generic coprocessor hazards.
3684
3685          This case is not handled very well.  There is no special
3686          knowledge of CP0 handling, and the coprocessors other than
3687          the floating point unit are not distinguished at all.  */
3688       /* Itbl support may require additional care here. FIXME!
3689          Need to modify this to include knowledge about
3690          user specified delays!  */
3691       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
3692                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
3693         {
3694           /* Handle cases where INSN1 writes to a known general coprocessor
3695              register.  There must be a one instruction delay before INSN2
3696              if INSN2 reads that register, otherwise no delay is needed.  */
3697           mask = fpr_write_mask (insn1);
3698           if (mask != 0)
3699             {
3700               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
3701                 return 1;
3702             }
3703           else
3704             {
3705               /* Read-after-write dependencies on the control registers
3706                  require a two-instruction gap.  */
3707               if ((pinfo1 & INSN_WRITE_COND_CODE)
3708                   && (pinfo2 & INSN_READ_COND_CODE))
3709                 return 2;
3710
3711               /* We don't know exactly what INSN1 does.  If INSN2 is
3712                  also a coprocessor instruction, assume there must be
3713                  a one instruction gap.  */
3714               if (pinfo2 & INSN_COP)
3715                 return 1;
3716             }
3717         }
3718
3719       /* Check for read-after-write dependencies on the coprocessor
3720          control registers in cases where INSN1 does not need a general
3721          coprocessor delay.  This means that INSN1 is a floating point
3722          comparison instruction.  */
3723       /* Itbl support may require additional care here.  */
3724       else if (!cop_interlocks
3725                && (pinfo1 & INSN_WRITE_COND_CODE)
3726                && (pinfo2 & INSN_READ_COND_CODE))
3727         return 1;
3728     }
3729
3730 #undef INSN2_USES_GPR
3731
3732   return 0;
3733 }
3734
3735 /* Return the number of nops that would be needed to work around the
3736    VR4130 mflo/mfhi errata if instruction INSN immediately followed
3737    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
3738    that are contained within the first IGNORE instructions of HIST.  */
3739
3740 static int
3741 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
3742                  const struct mips_cl_insn *insn)
3743 {
3744   int i, j;
3745   unsigned int mask;
3746
3747   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
3748      are not affected by the errata.  */
3749   if (insn != 0
3750       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
3751           || strcmp (insn->insn_mo->name, "mtlo") == 0
3752           || strcmp (insn->insn_mo->name, "mthi") == 0))
3753     return 0;
3754
3755   /* Search for the first MFLO or MFHI.  */
3756   for (i = 0; i < MAX_VR4130_NOPS; i++)
3757     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
3758       {
3759         /* Extract the destination register.  */
3760         mask = gpr_write_mask (&hist[i]);
3761
3762         /* No nops are needed if INSN reads that register.  */
3763         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
3764           return 0;
3765
3766         /* ...or if any of the intervening instructions do.  */
3767         for (j = 0; j < i; j++)
3768           if (gpr_read_mask (&hist[j]) & mask)
3769             return 0;
3770
3771         if (i >= ignore)
3772           return MAX_VR4130_NOPS - i;
3773       }
3774   return 0;
3775 }
3776
3777 #define BASE_REG_EQ(INSN1, INSN2)       \
3778   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
3779       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
3780
3781 /* Return the minimum alignment for this store instruction.  */
3782
3783 static int
3784 fix_24k_align_to (const struct mips_opcode *mo)
3785 {
3786   if (strcmp (mo->name, "sh") == 0)
3787     return 2;
3788
3789   if (strcmp (mo->name, "swc1") == 0
3790       || strcmp (mo->name, "swc2") == 0
3791       || strcmp (mo->name, "sw") == 0
3792       || strcmp (mo->name, "sc") == 0
3793       || strcmp (mo->name, "s.s") == 0)
3794     return 4;
3795
3796   if (strcmp (mo->name, "sdc1") == 0
3797       || strcmp (mo->name, "sdc2") == 0
3798       || strcmp (mo->name, "s.d") == 0)
3799     return 8;
3800
3801   /* sb, swl, swr */
3802   return 1;
3803 }
3804
3805 struct fix_24k_store_info
3806   {
3807     /* Immediate offset, if any, for this store instruction.  */
3808     short off;
3809     /* Alignment required by this store instruction.  */
3810     int align_to;
3811     /* True for register offsets.  */
3812     int register_offset;
3813   };
3814
3815 /* Comparison function used by qsort.  */
3816
3817 static int
3818 fix_24k_sort (const void *a, const void *b)
3819 {
3820   const struct fix_24k_store_info *pos1 = a;
3821   const struct fix_24k_store_info *pos2 = b;
3822
3823   return (pos1->off - pos2->off);
3824 }
3825
3826 /* INSN is a store instruction.  Try to record the store information
3827    in STINFO.  Return false if the information isn't known.  */
3828
3829 static bfd_boolean
3830 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
3831                            const struct mips_cl_insn *insn)
3832 {
3833   /* The instruction must have a known offset.  */
3834   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
3835     return FALSE;
3836
3837   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
3838   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
3839   return TRUE;
3840 }
3841
3842 /* Return the number of nops that would be needed to work around the 24k
3843    "lost data on stores during refill" errata if instruction INSN
3844    immediately followed the 2 instructions described by HIST.
3845    Ignore hazards that are contained within the first IGNORE
3846    instructions of HIST.
3847
3848    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
3849    for the data cache refills and store data. The following describes
3850    the scenario where the store data could be lost.
3851
3852    * A data cache miss, due to either a load or a store, causing fill
3853      data to be supplied by the memory subsystem
3854    * The first three doublewords of fill data are returned and written
3855      into the cache
3856    * A sequence of four stores occurs in consecutive cycles around the
3857      final doubleword of the fill:
3858    * Store A
3859    * Store B
3860    * Store C
3861    * Zero, One or more instructions
3862    * Store D
3863
3864    The four stores A-D must be to different doublewords of the line that
3865    is being filled. The fourth instruction in the sequence above permits
3866    the fill of the final doubleword to be transferred from the FSB into
3867    the cache. In the sequence above, the stores may be either integer
3868    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
3869    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
3870    different doublewords on the line. If the floating point unit is
3871    running in 1:2 mode, it is not possible to create the sequence above
3872    using only floating point store instructions.
3873
3874    In this case, the cache line being filled is incorrectly marked
3875    invalid, thereby losing the data from any store to the line that
3876    occurs between the original miss and the completion of the five
3877    cycle sequence shown above.
3878
3879    The workarounds are:
3880
3881    * Run the data cache in write-through mode.
3882    * Insert a non-store instruction between
3883      Store A and Store B or Store B and Store C.  */
3884   
3885 static int
3886 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
3887               const struct mips_cl_insn *insn)
3888 {
3889   struct fix_24k_store_info pos[3];
3890   int align, i, base_offset;
3891
3892   if (ignore >= 2)
3893     return 0;
3894
3895   /* If the previous instruction wasn't a store, there's nothing to
3896      worry about.  */
3897   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
3898     return 0;
3899
3900   /* If the instructions after the previous one are unknown, we have
3901      to assume the worst.  */
3902   if (!insn)
3903     return 1;
3904
3905   /* Check whether we are dealing with three consecutive stores.  */
3906   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
3907       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
3908     return 0;
3909
3910   /* If we don't know the relationship between the store addresses,
3911      assume the worst.  */
3912   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
3913       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
3914     return 1;
3915
3916   if (!fix_24k_record_store_info (&pos[0], insn)
3917       || !fix_24k_record_store_info (&pos[1], &hist[0])
3918       || !fix_24k_record_store_info (&pos[2], &hist[1]))
3919     return 1;
3920
3921   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
3922
3923   /* Pick a value of ALIGN and X such that all offsets are adjusted by
3924      X bytes and such that the base register + X is known to be aligned
3925      to align bytes.  */
3926
3927   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
3928     align = 8;
3929   else
3930     {
3931       align = pos[0].align_to;
3932       base_offset = pos[0].off;
3933       for (i = 1; i < 3; i++)
3934         if (align < pos[i].align_to)
3935           {
3936             align = pos[i].align_to;
3937             base_offset = pos[i].off;
3938           }
3939       for (i = 0; i < 3; i++)
3940         pos[i].off -= base_offset;
3941     }
3942
3943   pos[0].off &= ~align + 1;
3944   pos[1].off &= ~align + 1;
3945   pos[2].off &= ~align + 1;
3946
3947   /* If any two stores write to the same chunk, they also write to the
3948      same doubleword.  The offsets are still sorted at this point.  */
3949   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
3950     return 0;
3951
3952   /* A range of at least 9 bytes is needed for the stores to be in
3953      non-overlapping doublewords.  */
3954   if (pos[2].off - pos[0].off <= 8)
3955     return 0;
3956
3957   if (pos[2].off - pos[1].off >= 24
3958       || pos[1].off - pos[0].off >= 24
3959       || pos[2].off - pos[0].off >= 32)
3960     return 0;
3961
3962   return 1;
3963 }
3964
3965 /* Return the number of nops that would be needed if instruction INSN
3966    immediately followed the MAX_NOPS instructions given by HIST,
3967    where HIST[0] is the most recent instruction.  Ignore hazards
3968    between INSN and the first IGNORE instructions in HIST.
3969
3970    If INSN is null, return the worse-case number of nops for any
3971    instruction.  */
3972
3973 static int
3974 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
3975                const struct mips_cl_insn *insn)
3976 {
3977   int i, nops, tmp_nops;
3978
3979   nops = 0;
3980   for (i = ignore; i < MAX_DELAY_NOPS; i++)
3981     {
3982       tmp_nops = insns_between (hist + i, insn) - i;
3983       if (tmp_nops > nops)
3984         nops = tmp_nops;
3985     }
3986
3987   if (mips_fix_vr4130 && !mips_opts.micromips)
3988     {
3989       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
3990       if (tmp_nops > nops)
3991         nops = tmp_nops;
3992     }
3993
3994   if (mips_fix_24k && !mips_opts.micromips)
3995     {
3996       tmp_nops = nops_for_24k (ignore, hist, insn);
3997       if (tmp_nops > nops)
3998         nops = tmp_nops;
3999     }
4000
4001   return nops;
4002 }
4003
4004 /* The variable arguments provide NUM_INSNS extra instructions that
4005    might be added to HIST.  Return the largest number of nops that
4006    would be needed after the extended sequence, ignoring hazards
4007    in the first IGNORE instructions.  */
4008
4009 static int
4010 nops_for_sequence (int num_insns, int ignore,
4011                    const struct mips_cl_insn *hist, ...)
4012 {
4013   va_list args;
4014   struct mips_cl_insn buffer[MAX_NOPS];
4015   struct mips_cl_insn *cursor;
4016   int nops;
4017
4018   va_start (args, hist);
4019   cursor = buffer + num_insns;
4020   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
4021   while (cursor > buffer)
4022     *--cursor = *va_arg (args, const struct mips_cl_insn *);
4023
4024   nops = nops_for_insn (ignore, buffer, NULL);
4025   va_end (args);
4026   return nops;
4027 }
4028
4029 /* Like nops_for_insn, but if INSN is a branch, take into account the
4030    worst-case delay for the branch target.  */
4031
4032 static int
4033 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
4034                          const struct mips_cl_insn *insn)
4035 {
4036   int nops, tmp_nops;
4037
4038   nops = nops_for_insn (ignore, hist, insn);
4039   if (delayed_branch_p (insn))
4040     {
4041       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
4042                                     hist, insn, get_delay_slot_nop (insn));
4043       if (tmp_nops > nops)
4044         nops = tmp_nops;
4045     }
4046   else if (compact_branch_p (insn))
4047     {
4048       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
4049       if (tmp_nops > nops)
4050         nops = tmp_nops;
4051     }
4052   return nops;
4053 }
4054
4055 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
4056
4057 static void
4058 fix_loongson2f_nop (struct mips_cl_insn * ip)
4059 {
4060   gas_assert (!HAVE_CODE_COMPRESSION);
4061   if (strcmp (ip->insn_mo->name, "nop") == 0)
4062     ip->insn_opcode = LOONGSON2F_NOP_INSN;
4063 }
4064
4065 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
4066                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
4067
4068 static void
4069 fix_loongson2f_jump (struct mips_cl_insn * ip)
4070 {
4071   gas_assert (!HAVE_CODE_COMPRESSION);
4072   if (strcmp (ip->insn_mo->name, "j") == 0
4073       || strcmp (ip->insn_mo->name, "jr") == 0
4074       || strcmp (ip->insn_mo->name, "jalr") == 0)
4075     {
4076       int sreg;
4077       expressionS ep;
4078
4079       if (! mips_opts.at)
4080         return;
4081
4082       sreg = EXTRACT_OPERAND (0, RS, *ip);
4083       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
4084         return;
4085
4086       ep.X_op = O_constant;
4087       ep.X_add_number = 0xcfff0000;
4088       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
4089       ep.X_add_number = 0xffff;
4090       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
4091       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
4092     }
4093 }
4094
4095 static void
4096 fix_loongson2f (struct mips_cl_insn * ip)
4097 {
4098   if (mips_fix_loongson2f_nop)
4099     fix_loongson2f_nop (ip);
4100
4101   if (mips_fix_loongson2f_jump)
4102     fix_loongson2f_jump (ip);
4103 }
4104
4105 /* IP is a branch that has a delay slot, and we need to fill it
4106    automatically.   Return true if we can do that by swapping IP
4107    with the previous instruction.
4108    ADDRESS_EXPR is an operand of the instruction to be used with
4109    RELOC_TYPE.  */
4110
4111 static bfd_boolean
4112 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
4113   bfd_reloc_code_real_type *reloc_type)
4114 {
4115   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
4116   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
4117
4118   /* -O2 and above is required for this optimization.  */
4119   if (mips_optimize < 2)
4120     return FALSE;
4121
4122   /* If we have seen .set volatile or .set nomove, don't optimize.  */
4123   if (mips_opts.nomove)
4124     return FALSE;
4125
4126   /* We can't swap if the previous instruction's position is fixed.  */
4127   if (history[0].fixed_p)
4128     return FALSE;
4129
4130   /* If the previous previous insn was in a .set noreorder, we can't
4131      swap.  Actually, the MIPS assembler will swap in this situation.
4132      However, gcc configured -with-gnu-as will generate code like
4133
4134         .set    noreorder
4135         lw      $4,XXX
4136         .set    reorder
4137         INSN
4138         bne     $4,$0,foo
4139
4140      in which we can not swap the bne and INSN.  If gcc is not configured
4141      -with-gnu-as, it does not output the .set pseudo-ops.  */
4142   if (history[1].noreorder_p)
4143     return FALSE;
4144
4145   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
4146      This means that the previous instruction was a 4-byte one anyhow.  */
4147   if (mips_opts.mips16 && history[0].fixp[0])
4148     return FALSE;
4149
4150   /* If the branch is itself the target of a branch, we can not swap.
4151      We cheat on this; all we check for is whether there is a label on
4152      this instruction.  If there are any branches to anything other than
4153      a label, users must use .set noreorder.  */
4154   if (seg_info (now_seg)->label_list)
4155     return FALSE;
4156
4157   /* If the previous instruction is in a variant frag other than this
4158      branch's one, we cannot do the swap.  This does not apply to
4159      MIPS16 code, which uses variant frags for different purposes.  */
4160   if (!mips_opts.mips16
4161       && history[0].frag
4162       && history[0].frag->fr_type == rs_machine_dependent)
4163     return FALSE;
4164
4165   /* We do not swap with instructions that cannot architecturally
4166      be placed in a branch delay slot, such as SYNC or ERET.  We
4167      also refrain from swapping with a trap instruction, since it
4168      complicates trap handlers to have the trap instruction be in
4169      a delay slot.  */
4170   prev_pinfo = history[0].insn_mo->pinfo;
4171   if (prev_pinfo & INSN_NO_DELAY_SLOT)
4172     return FALSE;
4173
4174   /* Check for conflicts between the branch and the instructions
4175      before the candidate delay slot.  */
4176   if (nops_for_insn (0, history + 1, ip) > 0)
4177     return FALSE;
4178
4179   /* Check for conflicts between the swapped sequence and the
4180      target of the branch.  */
4181   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
4182     return FALSE;
4183
4184   /* If the branch reads a register that the previous
4185      instruction sets, we can not swap.  */
4186   gpr_read = gpr_read_mask (ip);
4187   prev_gpr_write = gpr_write_mask (&history[0]);
4188   if (gpr_read & prev_gpr_write)
4189     return FALSE;
4190
4191   /* If the branch writes a register that the previous
4192      instruction sets, we can not swap.  */
4193   gpr_write = gpr_write_mask (ip);
4194   if (gpr_write & prev_gpr_write)
4195     return FALSE;
4196
4197   /* If the branch writes a register that the previous
4198      instruction reads, we can not swap.  */
4199   prev_gpr_read = gpr_read_mask (&history[0]);
4200   if (gpr_write & prev_gpr_read)
4201     return FALSE;
4202
4203   /* If one instruction sets a condition code and the
4204      other one uses a condition code, we can not swap.  */
4205   pinfo = ip->insn_mo->pinfo;
4206   if ((pinfo & INSN_READ_COND_CODE)
4207       && (prev_pinfo & INSN_WRITE_COND_CODE))
4208     return FALSE;
4209   if ((pinfo & INSN_WRITE_COND_CODE)
4210       && (prev_pinfo & INSN_READ_COND_CODE))
4211     return FALSE;
4212
4213   /* If the previous instruction uses the PC, we can not swap.  */
4214   prev_pinfo2 = history[0].insn_mo->pinfo2;
4215   if (mips_opts.mips16 && (prev_pinfo & MIPS16_INSN_READ_PC))
4216     return FALSE;
4217   if (mips_opts.micromips && (prev_pinfo2 & INSN2_READ_PC))
4218     return FALSE;
4219
4220   /* If the previous instruction has an incorrect size for a fixed
4221      branch delay slot in microMIPS mode, we cannot swap.  */
4222   pinfo2 = ip->insn_mo->pinfo2;
4223   if (mips_opts.micromips
4224       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
4225       && insn_length (history) != 2)
4226     return FALSE;
4227   if (mips_opts.micromips
4228       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
4229       && insn_length (history) != 4)
4230     return FALSE;
4231
4232   /* On R5900 short loops need to be fixed by inserting a nop in
4233      the branch delay slots.
4234      A short loop can be terminated too early.  */
4235   if (mips_opts.arch == CPU_R5900
4236       /* Check if instruction has a parameter, ignore "j $31". */
4237       && (address_expr != NULL)
4238       /* Parameter must be 16 bit. */
4239       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
4240       /* Branch to same segment. */
4241       && (S_GET_SEGMENT(address_expr->X_add_symbol) == now_seg)
4242       /* Branch to same code fragment. */
4243       && (symbol_get_frag(address_expr->X_add_symbol) == frag_now)
4244       /* Can only calculate branch offset if value is known. */
4245       && symbol_constant_p(address_expr->X_add_symbol)
4246       /* Check if branch is really conditional. */
4247       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
4248         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
4249         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
4250     {
4251       int distance;
4252       /* Check if loop is shorter than 6 instructions including
4253          branch and delay slot.  */
4254       distance = frag_now_fix() - S_GET_VALUE(address_expr->X_add_symbol);
4255       if (distance <= 20)
4256         {
4257           int i;
4258           int rv;
4259
4260           rv = FALSE;
4261           /* When the loop includes branches or jumps,
4262              it is not a short loop. */
4263           for (i = 0; i < (distance / 4); i++)
4264             {
4265               if ((history[i].cleared_p)
4266                   || delayed_branch_p(&history[i]))
4267                 {
4268                   rv = TRUE;
4269                   break;
4270                 }
4271             }
4272           if (rv == FALSE)
4273             {
4274               /* Insert nop after branch to fix short loop. */
4275               return FALSE;
4276             }
4277         }
4278     }
4279
4280   return TRUE;
4281 }
4282
4283 /* Decide how we should add IP to the instruction stream.
4284    ADDRESS_EXPR is an operand of the instruction to be used with
4285    RELOC_TYPE.  */
4286
4287 static enum append_method
4288 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
4289   bfd_reloc_code_real_type *reloc_type)
4290 {
4291   unsigned long pinfo;
4292
4293   /* The relaxed version of a macro sequence must be inherently
4294      hazard-free.  */
4295   if (mips_relax.sequence == 2)
4296     return APPEND_ADD;
4297
4298   /* We must not dabble with instructions in a ".set norerorder" block.  */
4299   if (mips_opts.noreorder)
4300     return APPEND_ADD;
4301
4302   /* Otherwise, it's our responsibility to fill branch delay slots.  */
4303   if (delayed_branch_p (ip))
4304     {
4305       if (!branch_likely_p (ip)
4306           && can_swap_branch_p (ip, address_expr, reloc_type))
4307         return APPEND_SWAP;
4308
4309       pinfo = ip->insn_mo->pinfo;
4310       if (mips_opts.mips16
4311           && ISA_SUPPORTS_MIPS16E
4312           && (pinfo & (MIPS16_INSN_READ_X | MIPS16_INSN_READ_31)))
4313         return APPEND_ADD_COMPACT;
4314
4315       return APPEND_ADD_WITH_NOP;
4316     }
4317
4318   return APPEND_ADD;
4319 }
4320
4321 /* IP is a MIPS16 instruction whose opcode we have just changed.
4322    Point IP->insn_mo to the new opcode's definition.  */
4323
4324 static void
4325 find_altered_mips16_opcode (struct mips_cl_insn *ip)
4326 {
4327   const struct mips_opcode *mo, *end;
4328
4329   end = &mips16_opcodes[bfd_mips16_num_opcodes];
4330   for (mo = ip->insn_mo; mo < end; mo++)
4331     if ((ip->insn_opcode & mo->mask) == mo->match)
4332       {
4333         ip->insn_mo = mo;
4334         return;
4335       }
4336   abort ();
4337 }
4338
4339 /* For microMIPS macros, we need to generate a local number label
4340    as the target of branches.  */
4341 #define MICROMIPS_LABEL_CHAR            '\037'
4342 static unsigned long micromips_target_label;
4343 static char micromips_target_name[32];
4344
4345 static char *
4346 micromips_label_name (void)
4347 {
4348   char *p = micromips_target_name;
4349   char symbol_name_temporary[24];
4350   unsigned long l;
4351   int i;
4352
4353   if (*p)
4354     return p;
4355
4356   i = 0;
4357   l = micromips_target_label;
4358 #ifdef LOCAL_LABEL_PREFIX
4359   *p++ = LOCAL_LABEL_PREFIX;
4360 #endif
4361   *p++ = 'L';
4362   *p++ = MICROMIPS_LABEL_CHAR;
4363   do
4364     {
4365       symbol_name_temporary[i++] = l % 10 + '0';
4366       l /= 10;
4367     }
4368   while (l != 0);
4369   while (i > 0)
4370     *p++ = symbol_name_temporary[--i];
4371   *p = '\0';
4372
4373   return micromips_target_name;
4374 }
4375
4376 static void
4377 micromips_label_expr (expressionS *label_expr)
4378 {
4379   label_expr->X_op = O_symbol;
4380   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
4381   label_expr->X_add_number = 0;
4382 }
4383
4384 static void
4385 micromips_label_inc (void)
4386 {
4387   micromips_target_label++;
4388   *micromips_target_name = '\0';
4389 }
4390
4391 static void
4392 micromips_add_label (void)
4393 {
4394   symbolS *s;
4395
4396   s = colon (micromips_label_name ());
4397   micromips_label_inc ();
4398 #if defined(OBJ_ELF) || defined(OBJ_MAYBE_ELF)
4399   if (IS_ELF)
4400     S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
4401 #else
4402   (void) s;
4403 #endif
4404 }
4405
4406 /* If assembling microMIPS code, then return the microMIPS reloc
4407    corresponding to the requested one if any.  Otherwise return
4408    the reloc unchanged.  */
4409
4410 static bfd_reloc_code_real_type
4411 micromips_map_reloc (bfd_reloc_code_real_type reloc)
4412 {
4413   static const bfd_reloc_code_real_type relocs[][2] =
4414     {
4415       /* Keep sorted incrementally by the left-hand key.  */
4416       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
4417       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
4418       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
4419       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
4420       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
4421       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
4422       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
4423       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
4424       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
4425       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
4426       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
4427       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
4428       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
4429       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
4430       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
4431       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
4432       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
4433       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
4434       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
4435       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
4436       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
4437       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
4438       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
4439       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
4440       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
4441       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
4442       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
4443     };
4444   bfd_reloc_code_real_type r;
4445   size_t i;
4446
4447   if (!mips_opts.micromips)
4448     return reloc;
4449   for (i = 0; i < ARRAY_SIZE (relocs); i++)
4450     {
4451       r = relocs[i][0];
4452       if (r > reloc)
4453         return reloc;
4454       if (r == reloc)
4455         return relocs[i][1];
4456     }
4457   return reloc;
4458 }
4459
4460 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
4461    Return true on success, storing the resolved value in RESULT.  */
4462
4463 static bfd_boolean
4464 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
4465                  offsetT *result)
4466 {
4467   switch (reloc)
4468     {
4469     case BFD_RELOC_MIPS_HIGHEST:
4470     case BFD_RELOC_MICROMIPS_HIGHEST:
4471       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
4472       return TRUE;
4473
4474     case BFD_RELOC_MIPS_HIGHER:
4475     case BFD_RELOC_MICROMIPS_HIGHER:
4476       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
4477       return TRUE;
4478
4479     case BFD_RELOC_HI16_S:
4480     case BFD_RELOC_MICROMIPS_HI16_S:
4481     case BFD_RELOC_MIPS16_HI16_S:
4482       *result = ((operand + 0x8000) >> 16) & 0xffff;
4483       return TRUE;
4484
4485     case BFD_RELOC_HI16:
4486     case BFD_RELOC_MICROMIPS_HI16:
4487     case BFD_RELOC_MIPS16_HI16:
4488       *result = (operand >> 16) & 0xffff;
4489       return TRUE;
4490
4491     case BFD_RELOC_LO16:
4492     case BFD_RELOC_MICROMIPS_LO16:
4493     case BFD_RELOC_MIPS16_LO16:
4494       *result = operand & 0xffff;
4495       return TRUE;
4496
4497     case BFD_RELOC_UNUSED:
4498       *result = operand;
4499       return TRUE;
4500
4501     default:
4502       return FALSE;
4503     }
4504 }
4505
4506 /* Output an instruction.  IP is the instruction information.
4507    ADDRESS_EXPR is an operand of the instruction to be used with
4508    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
4509    a macro expansion.  */
4510
4511 static void
4512 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
4513              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
4514 {
4515   unsigned long prev_pinfo2, pinfo;
4516   bfd_boolean relaxed_branch = FALSE;
4517   enum append_method method;
4518   bfd_boolean relax32;
4519   int branch_disp;
4520
4521   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
4522     fix_loongson2f (ip);
4523
4524   file_ase_mips16 |= mips_opts.mips16;
4525   file_ase_micromips |= mips_opts.micromips;
4526
4527   prev_pinfo2 = history[0].insn_mo->pinfo2;
4528   pinfo = ip->insn_mo->pinfo;
4529
4530   if (mips_opts.micromips
4531       && !expansionp
4532       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
4533            && micromips_insn_length (ip->insn_mo) != 2)
4534           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
4535               && micromips_insn_length (ip->insn_mo) != 4)))
4536     as_warn (_("Wrong size instruction in a %u-bit branch delay slot"),
4537              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
4538
4539   if (address_expr == NULL)
4540     ip->complete_p = 1;
4541   else if (reloc_type[0] <= BFD_RELOC_UNUSED
4542            && reloc_type[1] == BFD_RELOC_UNUSED
4543            && reloc_type[2] == BFD_RELOC_UNUSED
4544            && address_expr->X_op == O_constant)
4545     {
4546       switch (*reloc_type)
4547         {
4548         case BFD_RELOC_MIPS_JMP:
4549           {
4550             int shift;
4551
4552             shift = mips_opts.micromips ? 1 : 2;
4553             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
4554               as_bad (_("jump to misaligned address (0x%lx)"),
4555                       (unsigned long) address_expr->X_add_number);
4556             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
4557                                 & 0x3ffffff);
4558             ip->complete_p = 1;
4559           }
4560           break;
4561
4562         case BFD_RELOC_MIPS16_JMP:
4563           if ((address_expr->X_add_number & 3) != 0)
4564             as_bad (_("jump to misaligned address (0x%lx)"),
4565                     (unsigned long) address_expr->X_add_number);
4566           ip->insn_opcode |=
4567             (((address_expr->X_add_number & 0x7c0000) << 3)
4568                | ((address_expr->X_add_number & 0xf800000) >> 7)
4569                | ((address_expr->X_add_number & 0x3fffc) >> 2));
4570           ip->complete_p = 1;
4571           break;
4572
4573         case BFD_RELOC_16_PCREL_S2:
4574           {
4575             int shift;
4576
4577             shift = mips_opts.micromips ? 1 : 2;
4578             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
4579               as_bad (_("branch to misaligned address (0x%lx)"),
4580                       (unsigned long) address_expr->X_add_number);
4581             if (!mips_relax_branch)
4582               {
4583                 if ((address_expr->X_add_number + (1 << (shift + 15)))
4584                     & ~((1 << (shift + 16)) - 1))
4585                   as_bad (_("branch address range overflow (0x%lx)"),
4586                           (unsigned long) address_expr->X_add_number);
4587                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
4588                                     & 0xffff);
4589               }
4590           }
4591           break;
4592
4593         default:
4594           {
4595             offsetT value;
4596
4597             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
4598                                  &value))
4599               {
4600                 ip->insn_opcode |= value & 0xffff;
4601                 ip->complete_p = 1;
4602               }
4603           }
4604           break;
4605         }
4606     }
4607
4608   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
4609     {
4610       /* There are a lot of optimizations we could do that we don't.
4611          In particular, we do not, in general, reorder instructions.
4612          If you use gcc with optimization, it will reorder
4613          instructions and generally do much more optimization then we
4614          do here; repeating all that work in the assembler would only
4615          benefit hand written assembly code, and does not seem worth
4616          it.  */
4617       int nops = (mips_optimize == 0
4618                   ? nops_for_insn (0, history, NULL)
4619                   : nops_for_insn_or_target (0, history, ip));
4620       if (nops > 0)
4621         {
4622           fragS *old_frag;
4623           unsigned long old_frag_offset;
4624           int i;
4625
4626           old_frag = frag_now;
4627           old_frag_offset = frag_now_fix ();
4628
4629           for (i = 0; i < nops; i++)
4630             add_fixed_insn (NOP_INSN);
4631           insert_into_history (0, nops, NOP_INSN);
4632
4633           if (listing)
4634             {
4635               listing_prev_line ();
4636               /* We may be at the start of a variant frag.  In case we
4637                  are, make sure there is enough space for the frag
4638                  after the frags created by listing_prev_line.  The
4639                  argument to frag_grow here must be at least as large
4640                  as the argument to all other calls to frag_grow in
4641                  this file.  We don't have to worry about being in the
4642                  middle of a variant frag, because the variants insert
4643                  all needed nop instructions themselves.  */
4644               frag_grow (40);
4645             }
4646
4647           mips_move_text_labels ();
4648
4649 #ifndef NO_ECOFF_DEBUGGING
4650           if (ECOFF_DEBUGGING)
4651             ecoff_fix_loc (old_frag, old_frag_offset);
4652 #endif
4653         }
4654     }
4655   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
4656     {
4657       int nops;
4658
4659       /* Work out how many nops in prev_nop_frag are needed by IP,
4660          ignoring hazards generated by the first prev_nop_frag_since
4661          instructions.  */
4662       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
4663       gas_assert (nops <= prev_nop_frag_holds);
4664
4665       /* Enforce NOPS as a minimum.  */
4666       if (nops > prev_nop_frag_required)
4667         prev_nop_frag_required = nops;
4668
4669       if (prev_nop_frag_holds == prev_nop_frag_required)
4670         {
4671           /* Settle for the current number of nops.  Update the history
4672              accordingly (for the benefit of any future .set reorder code).  */
4673           prev_nop_frag = NULL;
4674           insert_into_history (prev_nop_frag_since,
4675                                prev_nop_frag_holds, NOP_INSN);
4676         }
4677       else
4678         {
4679           /* Allow this instruction to replace one of the nops that was
4680              tentatively added to prev_nop_frag.  */
4681           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
4682           prev_nop_frag_holds--;
4683           prev_nop_frag_since++;
4684         }
4685     }
4686
4687   method = get_append_method (ip, address_expr, reloc_type);
4688   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
4689
4690 #ifdef OBJ_ELF
4691   dwarf2_emit_insn (0);
4692   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
4693      so "move" the instruction address accordingly.
4694
4695      Also, it doesn't seem appropriate for the assembler to reorder .loc
4696      entries.  If this instruction is a branch that we are going to swap
4697      with the previous instruction, the two instructions should be
4698      treated as a unit, and the debug information for both instructions
4699      should refer to the start of the branch sequence.  Using the
4700      current position is certainly wrong when swapping a 32-bit branch
4701      and a 16-bit delay slot, since the current position would then be
4702      in the middle of a branch.  */
4703   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
4704 #endif
4705
4706   relax32 = (mips_relax_branch
4707              /* Don't try branch relaxation within .set nomacro, or within
4708                 .set noat if we use $at for PIC computations.  If it turns
4709                 out that the branch was out-of-range, we'll get an error.  */
4710              && !mips_opts.warn_about_macros
4711              && (mips_opts.at || mips_pic == NO_PIC)
4712              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
4713                 as they have no complementing branches.  */
4714              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
4715
4716   if (!HAVE_CODE_COMPRESSION
4717       && address_expr
4718       && relax32
4719       && *reloc_type == BFD_RELOC_16_PCREL_S2
4720       && delayed_branch_p (ip))
4721     {
4722       relaxed_branch = TRUE;
4723       add_relaxed_insn (ip, (relaxed_branch_length
4724                              (NULL, NULL,
4725                               uncond_branch_p (ip) ? -1
4726                               : branch_likely_p (ip) ? 1
4727                               : 0)), 4,
4728                         RELAX_BRANCH_ENCODE
4729                         (AT,
4730                          uncond_branch_p (ip),
4731                          branch_likely_p (ip),
4732                          pinfo & INSN_WRITE_GPR_31,
4733                          0),
4734                         address_expr->X_add_symbol,
4735                         address_expr->X_add_number);
4736       *reloc_type = BFD_RELOC_UNUSED;
4737     }
4738   else if (mips_opts.micromips
4739            && address_expr
4740            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
4741                || *reloc_type > BFD_RELOC_UNUSED)
4742            && (delayed_branch_p (ip) || compact_branch_p (ip))
4743            /* Don't try branch relaxation when users specify
4744               16-bit/32-bit instructions.  */
4745            && !forced_insn_length)
4746     {
4747       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
4748       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
4749       int uncond = uncond_branch_p (ip) ? -1 : 0;
4750       int compact = compact_branch_p (ip);
4751       int al = pinfo & INSN_WRITE_GPR_31;
4752       int length32;
4753
4754       gas_assert (address_expr != NULL);
4755       gas_assert (!mips_relax.sequence);
4756
4757       relaxed_branch = TRUE;
4758       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
4759       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
4760                         RELAX_MICROMIPS_ENCODE (type, AT, uncond, compact, al,
4761                                                 relax32, 0, 0),
4762                         address_expr->X_add_symbol,
4763                         address_expr->X_add_number);
4764       *reloc_type = BFD_RELOC_UNUSED;
4765     }
4766   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
4767     {
4768       /* We need to set up a variant frag.  */
4769       gas_assert (address_expr != NULL);
4770       add_relaxed_insn (ip, 4, 0,
4771                         RELAX_MIPS16_ENCODE
4772                         (*reloc_type - BFD_RELOC_UNUSED,
4773                          forced_insn_length == 2, forced_insn_length == 4,
4774                          delayed_branch_p (&history[0]),
4775                          history[0].mips16_absolute_jump_p),
4776                         make_expr_symbol (address_expr), 0);
4777     }
4778   else if (mips_opts.mips16 && insn_length (ip) == 2)
4779     {
4780       if (!delayed_branch_p (ip))
4781         /* Make sure there is enough room to swap this instruction with
4782            a following jump instruction.  */
4783         frag_grow (6);
4784       add_fixed_insn (ip);
4785     }
4786   else
4787     {
4788       if (mips_opts.mips16
4789           && mips_opts.noreorder
4790           && delayed_branch_p (&history[0]))
4791         as_warn (_("extended instruction in delay slot"));
4792
4793       if (mips_relax.sequence)
4794         {
4795           /* If we've reached the end of this frag, turn it into a variant
4796              frag and record the information for the instructions we've
4797              written so far.  */
4798           if (frag_room () < 4)
4799             relax_close_frag ();
4800           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
4801         }
4802
4803       if (mips_relax.sequence != 2)
4804         {
4805           if (mips_macro_warning.first_insn_sizes[0] == 0)
4806             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
4807           mips_macro_warning.sizes[0] += insn_length (ip);
4808           mips_macro_warning.insns[0]++;
4809         }
4810       if (mips_relax.sequence != 1)
4811         {
4812           if (mips_macro_warning.first_insn_sizes[1] == 0)
4813             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
4814           mips_macro_warning.sizes[1] += insn_length (ip);
4815           mips_macro_warning.insns[1]++;
4816         }
4817
4818       if (mips_opts.mips16)
4819         {
4820           ip->fixed_p = 1;
4821           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
4822         }
4823       add_fixed_insn (ip);
4824     }
4825
4826   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
4827     {
4828       bfd_reloc_code_real_type final_type[3];
4829       reloc_howto_type *howto0;
4830       reloc_howto_type *howto;
4831       int i;
4832
4833       /* Perform any necessary conversion to microMIPS relocations
4834          and find out how many relocations there actually are.  */
4835       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
4836         final_type[i] = micromips_map_reloc (reloc_type[i]);
4837
4838       /* In a compound relocation, it is the final (outermost)
4839          operator that determines the relocated field.  */
4840       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
4841       if (!howto)
4842         abort ();
4843
4844       if (i > 1)
4845         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
4846       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
4847                                  bfd_get_reloc_size (howto),
4848                                  address_expr,
4849                                  howto0 && howto0->pc_relative,
4850                                  final_type[0]);
4851
4852       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
4853       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
4854         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
4855
4856       /* These relocations can have an addend that won't fit in
4857          4 octets for 64bit assembly.  */
4858       if (HAVE_64BIT_GPRS
4859           && ! howto->partial_inplace
4860           && (reloc_type[0] == BFD_RELOC_16
4861               || reloc_type[0] == BFD_RELOC_32
4862               || reloc_type[0] == BFD_RELOC_MIPS_JMP
4863               || reloc_type[0] == BFD_RELOC_GPREL16
4864               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
4865               || reloc_type[0] == BFD_RELOC_GPREL32
4866               || reloc_type[0] == BFD_RELOC_64
4867               || reloc_type[0] == BFD_RELOC_CTOR
4868               || reloc_type[0] == BFD_RELOC_MIPS_SUB
4869               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
4870               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
4871               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
4872               || reloc_type[0] == BFD_RELOC_MIPS_REL16
4873               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
4874               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
4875               || hi16_reloc_p (reloc_type[0])
4876               || lo16_reloc_p (reloc_type[0])))
4877         ip->fixp[0]->fx_no_overflow = 1;
4878
4879       /* These relocations can have an addend that won't fit in 2 octets.  */
4880       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
4881           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
4882         ip->fixp[0]->fx_no_overflow = 1;
4883
4884       if (mips_relax.sequence)
4885         {
4886           if (mips_relax.first_fixup == 0)
4887             mips_relax.first_fixup = ip->fixp[0];
4888         }
4889       else if (reloc_needs_lo_p (*reloc_type))
4890         {
4891           struct mips_hi_fixup *hi_fixup;
4892
4893           /* Reuse the last entry if it already has a matching %lo.  */
4894           hi_fixup = mips_hi_fixup_list;
4895           if (hi_fixup == 0
4896               || !fixup_has_matching_lo_p (hi_fixup->fixp))
4897             {
4898               hi_fixup = ((struct mips_hi_fixup *)
4899                           xmalloc (sizeof (struct mips_hi_fixup)));
4900               hi_fixup->next = mips_hi_fixup_list;
4901               mips_hi_fixup_list = hi_fixup;
4902             }
4903           hi_fixup->fixp = ip->fixp[0];
4904           hi_fixup->seg = now_seg;
4905         }
4906
4907       /* Add fixups for the second and third relocations, if given.
4908          Note that the ABI allows the second relocation to be
4909          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
4910          moment we only use RSS_UNDEF, but we could add support
4911          for the others if it ever becomes necessary.  */
4912       for (i = 1; i < 3; i++)
4913         if (reloc_type[i] != BFD_RELOC_UNUSED)
4914           {
4915             ip->fixp[i] = fix_new (ip->frag, ip->where,
4916                                    ip->fixp[0]->fx_size, NULL, 0,
4917                                    FALSE, final_type[i]);
4918
4919             /* Use fx_tcbit to mark compound relocs.  */
4920             ip->fixp[0]->fx_tcbit = 1;
4921             ip->fixp[i]->fx_tcbit = 1;
4922           }
4923     }
4924   install_insn (ip);
4925
4926   /* Update the register mask information.  */
4927   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
4928   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
4929
4930   switch (method)
4931     {
4932     case APPEND_ADD:
4933       insert_into_history (0, 1, ip);
4934       break;
4935
4936     case APPEND_ADD_WITH_NOP:
4937       {
4938         struct mips_cl_insn *nop;
4939
4940         insert_into_history (0, 1, ip);
4941         nop = get_delay_slot_nop (ip);
4942         add_fixed_insn (nop);
4943         insert_into_history (0, 1, nop);
4944         if (mips_relax.sequence)
4945           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
4946       }
4947       break;
4948
4949     case APPEND_ADD_COMPACT:
4950       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
4951       gas_assert (mips_opts.mips16);
4952       ip->insn_opcode |= 0x0080;
4953       find_altered_mips16_opcode (ip);
4954       install_insn (ip);
4955       insert_into_history (0, 1, ip);
4956       break;
4957
4958     case APPEND_SWAP:
4959       {
4960         struct mips_cl_insn delay = history[0];
4961         if (mips_opts.mips16)
4962           {
4963             know (delay.frag == ip->frag);
4964             move_insn (ip, delay.frag, delay.where);
4965             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
4966           }
4967         else if (relaxed_branch || delay.frag != ip->frag)
4968           {
4969             /* Add the delay slot instruction to the end of the
4970                current frag and shrink the fixed part of the
4971                original frag.  If the branch occupies the tail of
4972                the latter, move it backwards to cover the gap.  */
4973             delay.frag->fr_fix -= branch_disp;
4974             if (delay.frag == ip->frag)
4975               move_insn (ip, ip->frag, ip->where - branch_disp);
4976             add_fixed_insn (&delay);
4977           }
4978         else
4979           {
4980             move_insn (&delay, ip->frag,
4981                        ip->where - branch_disp + insn_length (ip));
4982             move_insn (ip, history[0].frag, history[0].where);
4983           }
4984         history[0] = *ip;
4985         delay.fixed_p = 1;
4986         insert_into_history (0, 1, &delay);
4987       }
4988       break;
4989     }
4990
4991   /* If we have just completed an unconditional branch, clear the history.  */
4992   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
4993       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
4994     {
4995       unsigned int i;
4996
4997       mips_no_prev_insn ();
4998
4999       for (i = 0; i < ARRAY_SIZE (history); i++)
5000         history[i].cleared_p = 1;
5001     }
5002
5003   /* We need to emit a label at the end of branch-likely macros.  */
5004   if (emit_branch_likely_macro)
5005     {
5006       emit_branch_likely_macro = FALSE;
5007       micromips_add_label ();
5008     }
5009
5010   /* We just output an insn, so the next one doesn't have a label.  */
5011   mips_clear_insn_labels ();
5012 }
5013
5014 /* Forget that there was any previous instruction or label.
5015    When BRANCH is true, the branch history is also flushed.  */
5016
5017 static void
5018 mips_no_prev_insn (void)
5019 {
5020   prev_nop_frag = NULL;
5021   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
5022   mips_clear_insn_labels ();
5023 }
5024
5025 /* This function must be called before we emit something other than
5026    instructions.  It is like mips_no_prev_insn except that it inserts
5027    any NOPS that might be needed by previous instructions.  */
5028
5029 void
5030 mips_emit_delays (void)
5031 {
5032   if (! mips_opts.noreorder)
5033     {
5034       int nops = nops_for_insn (0, history, NULL);
5035       if (nops > 0)
5036         {
5037           while (nops-- > 0)
5038             add_fixed_insn (NOP_INSN);
5039           mips_move_text_labels ();
5040         }
5041     }
5042   mips_no_prev_insn ();
5043 }
5044
5045 /* Start a (possibly nested) noreorder block.  */
5046
5047 static void
5048 start_noreorder (void)
5049 {
5050   if (mips_opts.noreorder == 0)
5051     {
5052       unsigned int i;
5053       int nops;
5054
5055       /* None of the instructions before the .set noreorder can be moved.  */
5056       for (i = 0; i < ARRAY_SIZE (history); i++)
5057         history[i].fixed_p = 1;
5058
5059       /* Insert any nops that might be needed between the .set noreorder
5060          block and the previous instructions.  We will later remove any
5061          nops that turn out not to be needed.  */
5062       nops = nops_for_insn (0, history, NULL);
5063       if (nops > 0)
5064         {
5065           if (mips_optimize != 0)
5066             {
5067               /* Record the frag which holds the nop instructions, so
5068                  that we can remove them if we don't need them.  */
5069               frag_grow (nops * NOP_INSN_SIZE);
5070               prev_nop_frag = frag_now;
5071               prev_nop_frag_holds = nops;
5072               prev_nop_frag_required = 0;
5073               prev_nop_frag_since = 0;
5074             }
5075
5076           for (; nops > 0; --nops)
5077             add_fixed_insn (NOP_INSN);
5078
5079           /* Move on to a new frag, so that it is safe to simply
5080              decrease the size of prev_nop_frag.  */
5081           frag_wane (frag_now);
5082           frag_new (0);
5083           mips_move_text_labels ();
5084         }
5085       mips_mark_labels ();
5086       mips_clear_insn_labels ();
5087     }
5088   mips_opts.noreorder++;
5089   mips_any_noreorder = 1;
5090 }
5091
5092 /* End a nested noreorder block.  */
5093
5094 static void
5095 end_noreorder (void)
5096 {
5097   mips_opts.noreorder--;
5098   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
5099     {
5100       /* Commit to inserting prev_nop_frag_required nops and go back to
5101          handling nop insertion the .set reorder way.  */
5102       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
5103                                 * NOP_INSN_SIZE);
5104       insert_into_history (prev_nop_frag_since,
5105                            prev_nop_frag_required, NOP_INSN);
5106       prev_nop_frag = NULL;
5107     }
5108 }
5109
5110 /* Set up global variables for the start of a new macro.  */
5111
5112 static void
5113 macro_start (void)
5114 {
5115   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
5116   memset (&mips_macro_warning.first_insn_sizes, 0,
5117           sizeof (mips_macro_warning.first_insn_sizes));
5118   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
5119   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
5120                                      && delayed_branch_p (&history[0]));
5121   switch (history[0].insn_mo->pinfo2
5122           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
5123     {
5124     case INSN2_BRANCH_DELAY_32BIT:
5125       mips_macro_warning.delay_slot_length = 4;
5126       break;
5127     case INSN2_BRANCH_DELAY_16BIT:
5128       mips_macro_warning.delay_slot_length = 2;
5129       break;
5130     default:
5131       mips_macro_warning.delay_slot_length = 0;
5132       break;
5133     }
5134   mips_macro_warning.first_frag = NULL;
5135 }
5136
5137 /* Given that a macro is longer than one instruction or of the wrong size,
5138    return the appropriate warning for it.  Return null if no warning is
5139    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
5140    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
5141    and RELAX_NOMACRO.  */
5142
5143 static const char *
5144 macro_warning (relax_substateT subtype)
5145 {
5146   if (subtype & RELAX_DELAY_SLOT)
5147     return _("Macro instruction expanded into multiple instructions"
5148              " in a branch delay slot");
5149   else if (subtype & RELAX_NOMACRO)
5150     return _("Macro instruction expanded into multiple instructions");
5151   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
5152                       | RELAX_DELAY_SLOT_SIZE_SECOND))
5153     return ((subtype & RELAX_DELAY_SLOT_16BIT)
5154             ? _("Macro instruction expanded into a wrong size instruction"
5155                 " in a 16-bit branch delay slot")
5156             : _("Macro instruction expanded into a wrong size instruction"
5157                 " in a 32-bit branch delay slot"));
5158   else
5159     return 0;
5160 }
5161
5162 /* Finish up a macro.  Emit warnings as appropriate.  */
5163
5164 static void
5165 macro_end (void)
5166 {
5167   /* Relaxation warning flags.  */
5168   relax_substateT subtype = 0;
5169
5170   /* Check delay slot size requirements.  */
5171   if (mips_macro_warning.delay_slot_length == 2)
5172     subtype |= RELAX_DELAY_SLOT_16BIT;
5173   if (mips_macro_warning.delay_slot_length != 0)
5174     {
5175       if (mips_macro_warning.delay_slot_length
5176           != mips_macro_warning.first_insn_sizes[0])
5177         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
5178       if (mips_macro_warning.delay_slot_length
5179           != mips_macro_warning.first_insn_sizes[1])
5180         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
5181     }
5182
5183   /* Check instruction count requirements.  */
5184   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
5185     {
5186       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
5187         subtype |= RELAX_SECOND_LONGER;
5188       if (mips_opts.warn_about_macros)
5189         subtype |= RELAX_NOMACRO;
5190       if (mips_macro_warning.delay_slot_p)
5191         subtype |= RELAX_DELAY_SLOT;
5192     }
5193
5194   /* If both alternatives fail to fill a delay slot correctly,
5195      emit the warning now.  */
5196   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
5197       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
5198     {
5199       relax_substateT s;
5200       const char *msg;
5201
5202       s = subtype & (RELAX_DELAY_SLOT_16BIT
5203                      | RELAX_DELAY_SLOT_SIZE_FIRST
5204                      | RELAX_DELAY_SLOT_SIZE_SECOND);
5205       msg = macro_warning (s);
5206       if (msg != NULL)
5207         as_warn ("%s", msg);
5208       subtype &= ~s;
5209     }
5210
5211   /* If both implementations are longer than 1 instruction, then emit the
5212      warning now.  */
5213   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
5214     {
5215       relax_substateT s;
5216       const char *msg;
5217
5218       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
5219       msg = macro_warning (s);
5220       if (msg != NULL)
5221         as_warn ("%s", msg);
5222       subtype &= ~s;
5223     }
5224
5225   /* If any flags still set, then one implementation might need a warning
5226      and the other either will need one of a different kind or none at all.
5227      Pass any remaining flags over to relaxation.  */
5228   if (mips_macro_warning.first_frag != NULL)
5229     mips_macro_warning.first_frag->fr_subtype |= subtype;
5230 }
5231
5232 /* Instruction operand formats used in macros that vary between
5233    standard MIPS and microMIPS code.  */
5234
5235 static const char * const brk_fmt[2] = { "c", "mF" };
5236 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
5237 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
5238 static const char * const lui_fmt[2] = { "t,u", "s,u" };
5239 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
5240 static const char * const mfhl_fmt[2] = { "d", "mj" };
5241 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
5242 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
5243
5244 #define BRK_FMT (brk_fmt[mips_opts.micromips])
5245 #define COP12_FMT (cop12_fmt[mips_opts.micromips])
5246 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
5247 #define LUI_FMT (lui_fmt[mips_opts.micromips])
5248 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
5249 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips])
5250 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
5251 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
5252
5253 /* Read a macro's relocation codes from *ARGS and store them in *R.
5254    The first argument in *ARGS will be either the code for a single
5255    relocation or -1 followed by the three codes that make up a
5256    composite relocation.  */
5257
5258 static void
5259 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
5260 {
5261   int i, next;
5262
5263   next = va_arg (*args, int);
5264   if (next >= 0)
5265     r[0] = (bfd_reloc_code_real_type) next;
5266   else
5267     for (i = 0; i < 3; i++)
5268       r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
5269 }
5270
5271 /* Build an instruction created by a macro expansion.  This is passed
5272    a pointer to the count of instructions created so far, an
5273    expression, the name of the instruction to build, an operand format
5274    string, and corresponding arguments.  */
5275
5276 static void
5277 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
5278 {
5279   const struct mips_opcode *mo = NULL;
5280   bfd_reloc_code_real_type r[3];
5281   const struct mips_opcode *amo;
5282   struct hash_control *hash;
5283   struct mips_cl_insn insn;
5284   va_list args;
5285
5286   va_start (args, fmt);
5287
5288   if (mips_opts.mips16)
5289     {
5290       mips16_macro_build (ep, name, fmt, &args);
5291       va_end (args);
5292       return;
5293     }
5294
5295   r[0] = BFD_RELOC_UNUSED;
5296   r[1] = BFD_RELOC_UNUSED;
5297   r[2] = BFD_RELOC_UNUSED;
5298   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
5299   amo = (struct mips_opcode *) hash_find (hash, name);
5300   gas_assert (amo);
5301   gas_assert (strcmp (name, amo->name) == 0);
5302
5303   do
5304     {
5305       /* Search until we get a match for NAME.  It is assumed here that
5306          macros will never generate MDMX, MIPS-3D, or MT instructions.
5307          We try to match an instruction that fulfils the branch delay
5308          slot instruction length requirement (if any) of the previous
5309          instruction.  While doing this we record the first instruction
5310          seen that matches all the other conditions and use it anyway
5311          if the requirement cannot be met; we will issue an appropriate
5312          warning later on.  */
5313       if (strcmp (fmt, amo->args) == 0
5314           && amo->pinfo != INSN_MACRO
5315           && is_opcode_valid (amo)
5316           && is_size_valid (amo))
5317         {
5318           if (is_delay_slot_valid (amo))
5319             {
5320               mo = amo;
5321               break;
5322             }
5323           else if (!mo)
5324             mo = amo;
5325         }
5326
5327       ++amo;
5328       gas_assert (amo->name);
5329     }
5330   while (strcmp (name, amo->name) == 0);
5331
5332   gas_assert (mo);
5333   create_insn (&insn, mo);
5334   for (;;)
5335     {
5336       switch (*fmt++)
5337         {
5338         case '\0':
5339           break;
5340
5341         case ',':
5342         case '(':
5343         case ')':
5344           continue;
5345
5346         case '+':
5347           switch (*fmt++)
5348             {
5349             case 'A':
5350             case 'E':
5351               INSERT_OPERAND (mips_opts.micromips,
5352                               EXTLSB, insn, va_arg (args, int));
5353               continue;
5354
5355             case 'B':
5356             case 'F':
5357               /* Note that in the macro case, these arguments are already
5358                  in MSB form.  (When handling the instruction in the
5359                  non-macro case, these arguments are sizes from which
5360                  MSB values must be calculated.)  */
5361               INSERT_OPERAND (mips_opts.micromips,
5362                               INSMSB, insn, va_arg (args, int));
5363               continue;
5364
5365             case 'J':
5366               gas_assert (!mips_opts.micromips);
5367               INSERT_OPERAND (0, CODE10, insn, va_arg (args, int));
5368               continue;
5369
5370             case 'C':
5371             case 'G':
5372             case 'H':
5373               /* Note that in the macro case, these arguments are already
5374                  in MSBD form.  (When handling the instruction in the
5375                  non-macro case, these arguments are sizes from which
5376                  MSBD values must be calculated.)  */
5377               INSERT_OPERAND (mips_opts.micromips,
5378                               EXTMSBD, insn, va_arg (args, int));
5379               continue;
5380
5381             case 'Q':
5382               gas_assert (!mips_opts.micromips);
5383               INSERT_OPERAND (0, SEQI, insn, va_arg (args, int));
5384               continue;
5385
5386             case 'j':
5387               INSERT_OPERAND (mips_opts.micromips, EVAOFFSET, insn, va_arg (args, int));
5388               continue;
5389
5390             default:
5391               abort ();
5392             }
5393           continue;
5394
5395         case '2':
5396           INSERT_OPERAND (mips_opts.micromips, BP, insn, va_arg (args, int));
5397           continue;
5398
5399         case 'n':
5400           gas_assert (mips_opts.micromips);
5401         case 't':
5402         case 'w':
5403         case 'E':
5404           INSERT_OPERAND (mips_opts.micromips, RT, insn, va_arg (args, int));
5405           continue;
5406
5407         case 'c':
5408           gas_assert (!mips_opts.micromips);
5409           INSERT_OPERAND (0, CODE, insn, va_arg (args, int));
5410           continue;
5411
5412         case 'W':
5413           gas_assert (!mips_opts.micromips);
5414         case 'T':
5415           INSERT_OPERAND (mips_opts.micromips, FT, insn, va_arg (args, int));
5416           continue;
5417
5418         case 'G':
5419           if (mips_opts.micromips)
5420             INSERT_OPERAND (1, RS, insn, va_arg (args, int));
5421           else
5422             INSERT_OPERAND (0, RD, insn, va_arg (args, int));
5423           continue;
5424
5425         case 'K':
5426           gas_assert (!mips_opts.micromips);
5427         case 'd':
5428           INSERT_OPERAND (mips_opts.micromips, RD, insn, va_arg (args, int));
5429           continue;
5430
5431         case 'U':
5432           gas_assert (!mips_opts.micromips);
5433           {
5434             int tmp = va_arg (args, int);
5435
5436             INSERT_OPERAND (0, RT, insn, tmp);
5437             INSERT_OPERAND (0, RD, insn, tmp);
5438           }
5439           continue;
5440
5441         case 'V':
5442         case 'S':
5443           gas_assert (!mips_opts.micromips);
5444           INSERT_OPERAND (0, FS, insn, va_arg (args, int));
5445           continue;
5446
5447         case 'z':
5448           continue;
5449
5450         case '<':
5451           INSERT_OPERAND (mips_opts.micromips,
5452                           SHAMT, insn, va_arg (args, int));
5453           continue;
5454
5455         case 'D':
5456           gas_assert (!mips_opts.micromips);
5457           INSERT_OPERAND (0, FD, insn, va_arg (args, int));
5458           continue;
5459
5460         case 'B':
5461           gas_assert (!mips_opts.micromips);
5462           INSERT_OPERAND (0, CODE20, insn, va_arg (args, int));
5463           continue;
5464
5465         case 'J':
5466           gas_assert (!mips_opts.micromips);
5467           INSERT_OPERAND (0, CODE19, insn, va_arg (args, int));
5468           continue;
5469
5470         case 'q':
5471           gas_assert (!mips_opts.micromips);
5472           INSERT_OPERAND (0, CODE2, insn, va_arg (args, int));
5473           continue;
5474
5475         case 'b':
5476         case 's':
5477         case 'r':
5478         case 'v':
5479           INSERT_OPERAND (mips_opts.micromips, RS, insn, va_arg (args, int));
5480           continue;
5481
5482         case 'i':
5483         case 'j':
5484           macro_read_relocs (&args, r);
5485           gas_assert (*r == BFD_RELOC_GPREL16
5486                       || *r == BFD_RELOC_MIPS_HIGHER
5487                       || *r == BFD_RELOC_HI16_S
5488                       || *r == BFD_RELOC_LO16
5489                       || *r == BFD_RELOC_MIPS_GOT_OFST);
5490           continue;
5491
5492         case 'o':
5493           macro_read_relocs (&args, r);
5494           continue;
5495
5496         case 'u':
5497           macro_read_relocs (&args, r);
5498           gas_assert (ep != NULL
5499                       && (ep->X_op == O_constant
5500                           || (ep->X_op == O_symbol
5501                               && (*r == BFD_RELOC_MIPS_HIGHEST
5502                                   || *r == BFD_RELOC_HI16_S
5503                                   || *r == BFD_RELOC_HI16
5504                                   || *r == BFD_RELOC_GPREL16
5505                                   || *r == BFD_RELOC_MIPS_GOT_HI16
5506                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
5507           continue;
5508
5509         case 'p':
5510           gas_assert (ep != NULL);
5511
5512           /*
5513            * This allows macro() to pass an immediate expression for
5514            * creating short branches without creating a symbol.
5515            *
5516            * We don't allow branch relaxation for these branches, as
5517            * they should only appear in ".set nomacro" anyway.
5518            */
5519           if (ep->X_op == O_constant)
5520             {
5521               /* For microMIPS we always use relocations for branches.
5522                  So we should not resolve immediate values.  */
5523               gas_assert (!mips_opts.micromips);
5524
5525               if ((ep->X_add_number & 3) != 0)
5526                 as_bad (_("branch to misaligned address (0x%lx)"),
5527                         (unsigned long) ep->X_add_number);
5528               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
5529                 as_bad (_("branch address range overflow (0x%lx)"),
5530                         (unsigned long) ep->X_add_number);
5531               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
5532               ep = NULL;
5533             }
5534           else
5535             *r = BFD_RELOC_16_PCREL_S2;
5536           continue;
5537
5538         case 'a':
5539           gas_assert (ep != NULL);
5540           *r = BFD_RELOC_MIPS_JMP;
5541           continue;
5542
5543         case 'C':
5544           gas_assert (!mips_opts.micromips);
5545           INSERT_OPERAND (0, COPZ, insn, va_arg (args, unsigned long));
5546           continue;
5547
5548         case 'k':
5549           INSERT_OPERAND (mips_opts.micromips,
5550                           CACHE, insn, va_arg (args, unsigned long));
5551           continue;
5552
5553         case '|':
5554           gas_assert (mips_opts.micromips);
5555           INSERT_OPERAND (1, TRAP, insn, va_arg (args, int));
5556           continue;
5557
5558         case '.':
5559           gas_assert (mips_opts.micromips);
5560           INSERT_OPERAND (1, OFFSET10, insn, va_arg (args, int));
5561           continue;
5562
5563         case '\\':
5564           INSERT_OPERAND (mips_opts.micromips,
5565                           3BITPOS, insn, va_arg (args, unsigned int));
5566           continue;
5567
5568         case '~':
5569           INSERT_OPERAND (mips_opts.micromips,
5570                           OFFSET12, insn, va_arg (args, unsigned long));
5571           continue;
5572
5573         case 'N':
5574           gas_assert (mips_opts.micromips);
5575           INSERT_OPERAND (1, BCC, insn, va_arg (args, int));
5576           continue;
5577
5578         case 'm':       /* Opcode extension character.  */
5579           gas_assert (mips_opts.micromips);
5580           switch (*fmt++)
5581             {
5582             case 'j':
5583               INSERT_OPERAND (1, MJ, insn, va_arg (args, int));
5584               break;
5585
5586             case 'p':
5587               INSERT_OPERAND (1, MP, insn, va_arg (args, int));
5588               break;
5589
5590             case 'F':
5591               INSERT_OPERAND (1, IMMF, insn, va_arg (args, int));
5592               break;
5593
5594             default:
5595               abort ();
5596             }
5597           continue;
5598
5599         default:
5600           abort ();
5601         }
5602       break;
5603     }
5604   va_end (args);
5605   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
5606
5607   append_insn (&insn, ep, r, TRUE);
5608 }
5609
5610 static void
5611 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
5612                     va_list *args)
5613 {
5614   struct mips_opcode *mo;
5615   struct mips_cl_insn insn;
5616   bfd_reloc_code_real_type r[3]
5617     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
5618
5619   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
5620   gas_assert (mo);
5621   gas_assert (strcmp (name, mo->name) == 0);
5622
5623   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
5624     {
5625       ++mo;
5626       gas_assert (mo->name);
5627       gas_assert (strcmp (name, mo->name) == 0);
5628     }
5629
5630   create_insn (&insn, mo);
5631   for (;;)
5632     {
5633       int c;
5634
5635       c = *fmt++;
5636       switch (c)
5637         {
5638         case '\0':
5639           break;
5640
5641         case ',':
5642         case '(':
5643         case ')':
5644           continue;
5645
5646         case 'y':
5647         case 'w':
5648           MIPS16_INSERT_OPERAND (RY, insn, va_arg (*args, int));
5649           continue;
5650
5651         case 'x':
5652         case 'v':
5653           MIPS16_INSERT_OPERAND (RX, insn, va_arg (*args, int));
5654           continue;
5655
5656         case 'z':
5657           MIPS16_INSERT_OPERAND (RZ, insn, va_arg (*args, int));
5658           continue;
5659
5660         case 'Z':
5661           MIPS16_INSERT_OPERAND (MOVE32Z, insn, va_arg (*args, int));
5662           continue;
5663
5664         case '0':
5665         case 'S':
5666         case 'P':
5667         case 'R':
5668           continue;
5669
5670         case 'X':
5671           MIPS16_INSERT_OPERAND (REGR32, insn, va_arg (*args, int));
5672           continue;
5673
5674         case 'Y':
5675           {
5676             int regno;
5677
5678             regno = va_arg (*args, int);
5679             regno = ((regno & 7) << 2) | ((regno & 0x18) >> 3);
5680             MIPS16_INSERT_OPERAND (REG32R, insn, regno);
5681           }
5682           continue;
5683
5684         case '<':
5685         case '>':
5686         case '4':
5687         case '5':
5688         case 'H':
5689         case 'W':
5690         case 'D':
5691         case 'j':
5692         case '8':
5693         case 'V':
5694         case 'C':
5695         case 'U':
5696         case 'k':
5697         case 'K':
5698         case 'p':
5699         case 'q':
5700           {
5701             offsetT value;
5702
5703             gas_assert (ep != NULL);
5704
5705             if (ep->X_op != O_constant)
5706               *r = (int) BFD_RELOC_UNUSED + c;
5707             else if (calculate_reloc (*r, ep->X_add_number, &value))
5708               {
5709                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
5710                 ep = NULL;
5711                 *r = BFD_RELOC_UNUSED;
5712               }
5713           }
5714           continue;
5715
5716         case '6':
5717           MIPS16_INSERT_OPERAND (IMM6, insn, va_arg (*args, int));
5718           continue;
5719         }
5720
5721       break;
5722     }
5723
5724   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
5725
5726   append_insn (&insn, ep, r, TRUE);
5727 }
5728
5729 /*
5730  * Sign-extend 32-bit mode constants that have bit 31 set and all
5731  * higher bits unset.
5732  */
5733 static void
5734 normalize_constant_expr (expressionS *ex)
5735 {
5736   if (ex->X_op == O_constant
5737       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
5738     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
5739                         - 0x80000000);
5740 }
5741
5742 /*
5743  * Sign-extend 32-bit mode address offsets that have bit 31 set and
5744  * all higher bits unset.
5745  */
5746 static void
5747 normalize_address_expr (expressionS *ex)
5748 {
5749   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
5750         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
5751       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
5752     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
5753                         - 0x80000000);
5754 }
5755
5756 /*
5757  * Generate a "jalr" instruction with a relocation hint to the called
5758  * function.  This occurs in NewABI PIC code.
5759  */
5760 static void
5761 macro_build_jalr (expressionS *ep, int cprestore)
5762 {
5763   static const bfd_reloc_code_real_type jalr_relocs[2]
5764     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
5765   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
5766   const char *jalr;
5767   char *f = NULL;
5768
5769   if (MIPS_JALR_HINT_P (ep))
5770     {
5771       frag_grow (8);
5772       f = frag_more (0);
5773     }
5774   if (mips_opts.micromips)
5775     {
5776       jalr = mips_opts.noreorder && !cprestore ? "jalr" : "jalrs";
5777       if (MIPS_JALR_HINT_P (ep)
5778           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
5779         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
5780       else
5781         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
5782     }
5783   else
5784     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
5785   if (MIPS_JALR_HINT_P (ep))
5786     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
5787 }
5788
5789 /*
5790  * Generate a "lui" instruction.
5791  */
5792 static void
5793 macro_build_lui (expressionS *ep, int regnum)
5794 {
5795   gas_assert (! mips_opts.mips16);
5796
5797   if (ep->X_op != O_constant)
5798     {
5799       gas_assert (ep->X_op == O_symbol);
5800       /* _gp_disp is a special case, used from s_cpload.
5801          __gnu_local_gp is used if mips_no_shared.  */
5802       gas_assert (mips_pic == NO_PIC
5803               || (! HAVE_NEWABI
5804                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
5805               || (! mips_in_shared
5806                   && strcmp (S_GET_NAME (ep->X_add_symbol),
5807                              "__gnu_local_gp") == 0));
5808     }
5809
5810   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
5811 }
5812
5813 /* Generate a sequence of instructions to do a load or store from a constant
5814    offset off of a base register (breg) into/from a target register (treg),
5815    using AT if necessary.  */
5816 static void
5817 macro_build_ldst_constoffset (expressionS *ep, const char *op,
5818                               int treg, int breg, int dbl)
5819 {
5820   gas_assert (ep->X_op == O_constant);
5821
5822   /* Sign-extending 32-bit constants makes their handling easier.  */
5823   if (!dbl)
5824     normalize_constant_expr (ep);
5825
5826   /* Right now, this routine can only handle signed 32-bit constants.  */
5827   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
5828     as_warn (_("operand overflow"));
5829
5830   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
5831     {
5832       /* Signed 16-bit offset will fit in the op.  Easy!  */
5833       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
5834     }
5835   else
5836     {
5837       /* 32-bit offset, need multiple instructions and AT, like:
5838            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
5839            addu     $tempreg,$tempreg,$breg
5840            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
5841          to handle the complete offset.  */
5842       macro_build_lui (ep, AT);
5843       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
5844       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
5845
5846       if (!mips_opts.at)
5847         as_bad (_("Macro used $at after \".set noat\""));
5848     }
5849 }
5850
5851 /*                      set_at()
5852  * Generates code to set the $at register to true (one)
5853  * if reg is less than the immediate expression.
5854  */
5855 static void
5856 set_at (int reg, int unsignedp)
5857 {
5858   if (imm_expr.X_op == O_constant
5859       && imm_expr.X_add_number >= -0x8000
5860       && imm_expr.X_add_number < 0x8000)
5861     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
5862                  AT, reg, BFD_RELOC_LO16);
5863   else
5864     {
5865       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
5866       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
5867     }
5868 }
5869
5870 /* Warn if an expression is not a constant.  */
5871
5872 static void
5873 check_absolute_expr (struct mips_cl_insn *ip, expressionS *ex)
5874 {
5875   if (ex->X_op == O_big)
5876     as_bad (_("unsupported large constant"));
5877   else if (ex->X_op != O_constant)
5878     as_bad (_("Instruction %s requires absolute expression"),
5879             ip->insn_mo->name);
5880
5881   if (HAVE_32BIT_GPRS)
5882     normalize_constant_expr (ex);
5883 }
5884
5885 /* Count the leading zeroes by performing a binary chop. This is a
5886    bulky bit of source, but performance is a LOT better for the
5887    majority of values than a simple loop to count the bits:
5888        for (lcnt = 0; (lcnt < 32); lcnt++)
5889          if ((v) & (1 << (31 - lcnt)))
5890            break;
5891   However it is not code size friendly, and the gain will drop a bit
5892   on certain cached systems.
5893 */
5894 #define COUNT_TOP_ZEROES(v)             \
5895   (((v) & ~0xffff) == 0                 \
5896    ? ((v) & ~0xff) == 0                 \
5897      ? ((v) & ~0xf) == 0                \
5898        ? ((v) & ~0x3) == 0              \
5899          ? ((v) & ~0x1) == 0            \
5900            ? !(v)                       \
5901              ? 32                       \
5902              : 31                       \
5903            : 30                         \
5904          : ((v) & ~0x7) == 0            \
5905            ? 29                         \
5906            : 28                         \
5907        : ((v) & ~0x3f) == 0             \
5908          ? ((v) & ~0x1f) == 0           \
5909            ? 27                         \
5910            : 26                         \
5911          : ((v) & ~0x7f) == 0           \
5912            ? 25                         \
5913            : 24                         \
5914      : ((v) & ~0xfff) == 0              \
5915        ? ((v) & ~0x3ff) == 0            \
5916          ? ((v) & ~0x1ff) == 0          \
5917            ? 23                         \
5918            : 22                         \
5919          : ((v) & ~0x7ff) == 0          \
5920            ? 21                         \
5921            : 20                         \
5922        : ((v) & ~0x3fff) == 0           \
5923          ? ((v) & ~0x1fff) == 0         \
5924            ? 19                         \
5925            : 18                         \
5926          : ((v) & ~0x7fff) == 0         \
5927            ? 17                         \
5928            : 16                         \
5929    : ((v) & ~0xffffff) == 0             \
5930      ? ((v) & ~0xfffff) == 0            \
5931        ? ((v) & ~0x3ffff) == 0          \
5932          ? ((v) & ~0x1ffff) == 0        \
5933            ? 15                         \
5934            : 14                         \
5935          : ((v) & ~0x7ffff) == 0        \
5936            ? 13                         \
5937            : 12                         \
5938        : ((v) & ~0x3fffff) == 0         \
5939          ? ((v) & ~0x1fffff) == 0       \
5940            ? 11                         \
5941            : 10                         \
5942          : ((v) & ~0x7fffff) == 0       \
5943            ? 9                          \
5944            : 8                          \
5945      : ((v) & ~0xfffffff) == 0          \
5946        ? ((v) & ~0x3ffffff) == 0        \
5947          ? ((v) & ~0x1ffffff) == 0      \
5948            ? 7                          \
5949            : 6                          \
5950          : ((v) & ~0x7ffffff) == 0      \
5951            ? 5                          \
5952            : 4                          \
5953        : ((v) & ~0x3fffffff) == 0       \
5954          ? ((v) & ~0x1fffffff) == 0     \
5955            ? 3                          \
5956            : 2                          \
5957          : ((v) & ~0x7fffffff) == 0     \
5958            ? 1                          \
5959            : 0)
5960
5961 /*                      load_register()
5962  *  This routine generates the least number of instructions necessary to load
5963  *  an absolute expression value into a register.
5964  */
5965 static void
5966 load_register (int reg, expressionS *ep, int dbl)
5967 {
5968   int freg;
5969   expressionS hi32, lo32;
5970
5971   if (ep->X_op != O_big)
5972     {
5973       gas_assert (ep->X_op == O_constant);
5974
5975       /* Sign-extending 32-bit constants makes their handling easier.  */
5976       if (!dbl)
5977         normalize_constant_expr (ep);
5978
5979       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
5980         {
5981           /* We can handle 16 bit signed values with an addiu to
5982              $zero.  No need to ever use daddiu here, since $zero and
5983              the result are always correct in 32 bit mode.  */
5984           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
5985           return;
5986         }
5987       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
5988         {
5989           /* We can handle 16 bit unsigned values with an ori to
5990              $zero.  */
5991           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
5992           return;
5993         }
5994       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
5995         {
5996           /* 32 bit values require an lui.  */
5997           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
5998           if ((ep->X_add_number & 0xffff) != 0)
5999             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
6000           return;
6001         }
6002     }
6003
6004   /* The value is larger than 32 bits.  */
6005
6006   if (!dbl || HAVE_32BIT_GPRS)
6007     {
6008       char value[32];
6009
6010       sprintf_vma (value, ep->X_add_number);
6011       as_bad (_("Number (0x%s) larger than 32 bits"), value);
6012       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
6013       return;
6014     }
6015
6016   if (ep->X_op != O_big)
6017     {
6018       hi32 = *ep;
6019       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
6020       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
6021       hi32.X_add_number &= 0xffffffff;
6022       lo32 = *ep;
6023       lo32.X_add_number &= 0xffffffff;
6024     }
6025   else
6026     {
6027       gas_assert (ep->X_add_number > 2);
6028       if (ep->X_add_number == 3)
6029         generic_bignum[3] = 0;
6030       else if (ep->X_add_number > 4)
6031         as_bad (_("Number larger than 64 bits"));
6032       lo32.X_op = O_constant;
6033       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
6034       hi32.X_op = O_constant;
6035       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
6036     }
6037
6038   if (hi32.X_add_number == 0)
6039     freg = 0;
6040   else
6041     {
6042       int shift, bit;
6043       unsigned long hi, lo;
6044
6045       if (hi32.X_add_number == (offsetT) 0xffffffff)
6046         {
6047           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
6048             {
6049               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
6050               return;
6051             }
6052           if (lo32.X_add_number & 0x80000000)
6053             {
6054               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
6055               if (lo32.X_add_number & 0xffff)
6056                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
6057               return;
6058             }
6059         }
6060
6061       /* Check for 16bit shifted constant.  We know that hi32 is
6062          non-zero, so start the mask on the first bit of the hi32
6063          value.  */
6064       shift = 17;
6065       do
6066         {
6067           unsigned long himask, lomask;
6068
6069           if (shift < 32)
6070             {
6071               himask = 0xffff >> (32 - shift);
6072               lomask = (0xffff << shift) & 0xffffffff;
6073             }
6074           else
6075             {
6076               himask = 0xffff << (shift - 32);
6077               lomask = 0;
6078             }
6079           if ((hi32.X_add_number & ~(offsetT) himask) == 0
6080               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
6081             {
6082               expressionS tmp;
6083
6084               tmp.X_op = O_constant;
6085               if (shift < 32)
6086                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
6087                                     | (lo32.X_add_number >> shift));
6088               else
6089                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
6090               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
6091               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
6092                            reg, reg, (shift >= 32) ? shift - 32 : shift);
6093               return;
6094             }
6095           ++shift;
6096         }
6097       while (shift <= (64 - 16));
6098
6099       /* Find the bit number of the lowest one bit, and store the
6100          shifted value in hi/lo.  */
6101       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
6102       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
6103       if (lo != 0)
6104         {
6105           bit = 0;
6106           while ((lo & 1) == 0)
6107             {
6108               lo >>= 1;
6109               ++bit;
6110             }
6111           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
6112           hi >>= bit;
6113         }
6114       else
6115         {
6116           bit = 32;
6117           while ((hi & 1) == 0)
6118             {
6119               hi >>= 1;
6120               ++bit;
6121             }
6122           lo = hi;
6123           hi = 0;
6124         }
6125
6126       /* Optimize if the shifted value is a (power of 2) - 1.  */
6127       if ((hi == 0 && ((lo + 1) & lo) == 0)
6128           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
6129         {
6130           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
6131           if (shift != 0)
6132             {
6133               expressionS tmp;
6134
6135               /* This instruction will set the register to be all
6136                  ones.  */
6137               tmp.X_op = O_constant;
6138               tmp.X_add_number = (offsetT) -1;
6139               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
6140               if (bit != 0)
6141                 {
6142                   bit += shift;
6143                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
6144                                reg, reg, (bit >= 32) ? bit - 32 : bit);
6145                 }
6146               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
6147                            reg, reg, (shift >= 32) ? shift - 32 : shift);
6148               return;
6149             }
6150         }
6151
6152       /* Sign extend hi32 before calling load_register, because we can
6153          generally get better code when we load a sign extended value.  */
6154       if ((hi32.X_add_number & 0x80000000) != 0)
6155         hi32.X_add_number |= ~(offsetT) 0xffffffff;
6156       load_register (reg, &hi32, 0);
6157       freg = reg;
6158     }
6159   if ((lo32.X_add_number & 0xffff0000) == 0)
6160     {
6161       if (freg != 0)
6162         {
6163           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
6164           freg = reg;
6165         }
6166     }
6167   else
6168     {
6169       expressionS mid16;
6170
6171       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
6172         {
6173           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
6174           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
6175           return;
6176         }
6177
6178       if (freg != 0)
6179         {
6180           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
6181           freg = reg;
6182         }
6183       mid16 = lo32;
6184       mid16.X_add_number >>= 16;
6185       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
6186       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
6187       freg = reg;
6188     }
6189   if ((lo32.X_add_number & 0xffff) != 0)
6190     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
6191 }
6192
6193 static inline void
6194 load_delay_nop (void)
6195 {
6196   if (!gpr_interlocks)
6197     macro_build (NULL, "nop", "");
6198 }
6199
6200 /* Load an address into a register.  */
6201
6202 static void
6203 load_address (int reg, expressionS *ep, int *used_at)
6204 {
6205   if (ep->X_op != O_constant
6206       && ep->X_op != O_symbol)
6207     {
6208       as_bad (_("expression too complex"));
6209       ep->X_op = O_constant;
6210     }
6211
6212   if (ep->X_op == O_constant)
6213     {
6214       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
6215       return;
6216     }
6217
6218   if (mips_pic == NO_PIC)
6219     {
6220       /* If this is a reference to a GP relative symbol, we want
6221            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
6222          Otherwise we want
6223            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
6224            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
6225          If we have an addend, we always use the latter form.
6226
6227          With 64bit address space and a usable $at we want
6228            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
6229            lui          $at,<sym>               (BFD_RELOC_HI16_S)
6230            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
6231            daddiu       $at,<sym>               (BFD_RELOC_LO16)
6232            dsll32       $reg,0
6233            daddu        $reg,$reg,$at
6234
6235          If $at is already in use, we use a path which is suboptimal
6236          on superscalar processors.
6237            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
6238            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
6239            dsll         $reg,16
6240            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
6241            dsll         $reg,16
6242            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
6243
6244          For GP relative symbols in 64bit address space we can use
6245          the same sequence as in 32bit address space.  */
6246       if (HAVE_64BIT_SYMBOLS)
6247         {
6248           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
6249               && !nopic_need_relax (ep->X_add_symbol, 1))
6250             {
6251               relax_start (ep->X_add_symbol);
6252               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
6253                            mips_gp_register, BFD_RELOC_GPREL16);
6254               relax_switch ();
6255             }
6256
6257           if (*used_at == 0 && mips_opts.at)
6258             {
6259               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
6260               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
6261               macro_build (ep, "daddiu", "t,r,j", reg, reg,
6262                            BFD_RELOC_MIPS_HIGHER);
6263               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
6264               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
6265               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
6266               *used_at = 1;
6267             }
6268           else
6269             {
6270               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
6271               macro_build (ep, "daddiu", "t,r,j", reg, reg,
6272                            BFD_RELOC_MIPS_HIGHER);
6273               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
6274               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
6275               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
6276               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
6277             }
6278
6279           if (mips_relax.sequence)
6280             relax_end ();
6281         }
6282       else
6283         {
6284           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
6285               && !nopic_need_relax (ep->X_add_symbol, 1))
6286             {
6287               relax_start (ep->X_add_symbol);
6288               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
6289                            mips_gp_register, BFD_RELOC_GPREL16);
6290               relax_switch ();
6291             }
6292           macro_build_lui (ep, reg);
6293           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
6294                        reg, reg, BFD_RELOC_LO16);
6295           if (mips_relax.sequence)
6296             relax_end ();
6297         }
6298     }
6299   else if (!mips_big_got)
6300     {
6301       expressionS ex;
6302
6303       /* If this is a reference to an external symbol, we want
6304            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
6305          Otherwise we want
6306            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
6307            nop
6308            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
6309          If there is a constant, it must be added in after.
6310
6311          If we have NewABI, we want
6312            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
6313          unless we're referencing a global symbol with a non-zero
6314          offset, in which case cst must be added separately.  */
6315       if (HAVE_NEWABI)
6316         {
6317           if (ep->X_add_number)
6318             {
6319               ex.X_add_number = ep->X_add_number;
6320               ep->X_add_number = 0;
6321               relax_start (ep->X_add_symbol);
6322               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
6323                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
6324               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
6325                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6326               ex.X_op = O_constant;
6327               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
6328                            reg, reg, BFD_RELOC_LO16);
6329               ep->X_add_number = ex.X_add_number;
6330               relax_switch ();
6331             }
6332           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
6333                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
6334           if (mips_relax.sequence)
6335             relax_end ();
6336         }
6337       else
6338         {
6339           ex.X_add_number = ep->X_add_number;
6340           ep->X_add_number = 0;
6341           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
6342                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
6343           load_delay_nop ();
6344           relax_start (ep->X_add_symbol);
6345           relax_switch ();
6346           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
6347                        BFD_RELOC_LO16);
6348           relax_end ();
6349
6350           if (ex.X_add_number != 0)
6351             {
6352               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
6353                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6354               ex.X_op = O_constant;
6355               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
6356                            reg, reg, BFD_RELOC_LO16);
6357             }
6358         }
6359     }
6360   else if (mips_big_got)
6361     {
6362       expressionS ex;
6363
6364       /* This is the large GOT case.  If this is a reference to an
6365          external symbol, we want
6366            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
6367            addu         $reg,$reg,$gp
6368            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
6369
6370          Otherwise, for a reference to a local symbol in old ABI, we want
6371            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
6372            nop
6373            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
6374          If there is a constant, it must be added in after.
6375
6376          In the NewABI, for local symbols, with or without offsets, we want:
6377            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
6378            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
6379       */
6380       if (HAVE_NEWABI)
6381         {
6382           ex.X_add_number = ep->X_add_number;
6383           ep->X_add_number = 0;
6384           relax_start (ep->X_add_symbol);
6385           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
6386           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6387                        reg, reg, mips_gp_register);
6388           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
6389                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
6390           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
6391             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6392           else if (ex.X_add_number)
6393             {
6394               ex.X_op = O_constant;
6395               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
6396                            BFD_RELOC_LO16);
6397             }
6398
6399           ep->X_add_number = ex.X_add_number;
6400           relax_switch ();
6401           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
6402                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
6403           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
6404                        BFD_RELOC_MIPS_GOT_OFST);
6405           relax_end ();
6406         }
6407       else
6408         {
6409           ex.X_add_number = ep->X_add_number;
6410           ep->X_add_number = 0;
6411           relax_start (ep->X_add_symbol);
6412           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
6413           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6414                        reg, reg, mips_gp_register);
6415           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
6416                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
6417           relax_switch ();
6418           if (reg_needs_delay (mips_gp_register))
6419             {
6420               /* We need a nop before loading from $gp.  This special
6421                  check is required because the lui which starts the main
6422                  instruction stream does not refer to $gp, and so will not
6423                  insert the nop which may be required.  */
6424               macro_build (NULL, "nop", "");
6425             }
6426           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
6427                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
6428           load_delay_nop ();
6429           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
6430                        BFD_RELOC_LO16);
6431           relax_end ();
6432
6433           if (ex.X_add_number != 0)
6434             {
6435               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
6436                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6437               ex.X_op = O_constant;
6438               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
6439                            BFD_RELOC_LO16);
6440             }
6441         }
6442     }
6443   else
6444     abort ();
6445
6446   if (!mips_opts.at && *used_at == 1)
6447     as_bad (_("Macro used $at after \".set noat\""));
6448 }
6449
6450 /* Move the contents of register SOURCE into register DEST.  */
6451
6452 static void
6453 move_register (int dest, int source)
6454 {
6455   /* Prefer to use a 16-bit microMIPS instruction unless the previous
6456      instruction specifically requires a 32-bit one.  */
6457   if (mips_opts.micromips
6458       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
6459     macro_build (NULL, "move", "mp,mj", dest, source);
6460   else
6461     macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
6462                  dest, source, 0);
6463 }
6464
6465 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
6466    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
6467    The two alternatives are:
6468
6469    Global symbol                Local sybmol
6470    -------------                ------------
6471    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
6472    ...                          ...
6473    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
6474
6475    load_got_offset emits the first instruction and add_got_offset
6476    emits the second for a 16-bit offset or add_got_offset_hilo emits
6477    a sequence to add a 32-bit offset using a scratch register.  */
6478
6479 static void
6480 load_got_offset (int dest, expressionS *local)
6481 {
6482   expressionS global;
6483
6484   global = *local;
6485   global.X_add_number = 0;
6486
6487   relax_start (local->X_add_symbol);
6488   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
6489                BFD_RELOC_MIPS_GOT16, mips_gp_register);
6490   relax_switch ();
6491   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
6492                BFD_RELOC_MIPS_GOT16, mips_gp_register);
6493   relax_end ();
6494 }
6495
6496 static void
6497 add_got_offset (int dest, expressionS *local)
6498 {
6499   expressionS global;
6500
6501   global.X_op = O_constant;
6502   global.X_op_symbol = NULL;
6503   global.X_add_symbol = NULL;
6504   global.X_add_number = local->X_add_number;
6505
6506   relax_start (local->X_add_symbol);
6507   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
6508                dest, dest, BFD_RELOC_LO16);
6509   relax_switch ();
6510   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
6511   relax_end ();
6512 }
6513
6514 static void
6515 add_got_offset_hilo (int dest, expressionS *local, int tmp)
6516 {
6517   expressionS global;
6518   int hold_mips_optimize;
6519
6520   global.X_op = O_constant;
6521   global.X_op_symbol = NULL;
6522   global.X_add_symbol = NULL;
6523   global.X_add_number = local->X_add_number;
6524
6525   relax_start (local->X_add_symbol);
6526   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
6527   relax_switch ();
6528   /* Set mips_optimize around the lui instruction to avoid
6529      inserting an unnecessary nop after the lw.  */
6530   hold_mips_optimize = mips_optimize;
6531   mips_optimize = 2;
6532   macro_build_lui (&global, tmp);
6533   mips_optimize = hold_mips_optimize;
6534   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
6535   relax_end ();
6536
6537   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
6538 }
6539
6540 /* Emit a sequence of instructions to emulate a branch likely operation.
6541    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
6542    is its complementing branch with the original condition negated.
6543    CALL is set if the original branch specified the link operation.
6544    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
6545
6546    Code like this is produced in the noreorder mode:
6547
6548         BRNEG   <args>, 1f
6549          nop
6550         b       <sym>
6551          delay slot (executed only if branch taken)
6552     1:
6553
6554    or, if CALL is set:
6555
6556         BRNEG   <args>, 1f
6557          nop
6558         bal     <sym>
6559          delay slot (executed only if branch taken)
6560     1:
6561
6562    In the reorder mode the delay slot would be filled with a nop anyway,
6563    so code produced is simply:
6564
6565         BR      <args>, <sym>
6566          nop
6567
6568    This function is used when producing code for the microMIPS ASE that
6569    does not implement branch likely instructions in hardware.  */
6570
6571 static void
6572 macro_build_branch_likely (const char *br, const char *brneg,
6573                            int call, expressionS *ep, const char *fmt,
6574                            unsigned int sreg, unsigned int treg)
6575 {
6576   int noreorder = mips_opts.noreorder;
6577   expressionS expr1;
6578
6579   gas_assert (mips_opts.micromips);
6580   start_noreorder ();
6581   if (noreorder)
6582     {
6583       micromips_label_expr (&expr1);
6584       macro_build (&expr1, brneg, fmt, sreg, treg);
6585       macro_build (NULL, "nop", "");
6586       macro_build (ep, call ? "bal" : "b", "p");
6587
6588       /* Set to true so that append_insn adds a label.  */
6589       emit_branch_likely_macro = TRUE;
6590     }
6591   else
6592     {
6593       macro_build (ep, br, fmt, sreg, treg);
6594       macro_build (NULL, "nop", "");
6595     }
6596   end_noreorder ();
6597 }
6598
6599 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
6600    the condition code tested.  EP specifies the branch target.  */
6601
6602 static void
6603 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
6604 {
6605   const int call = 0;
6606   const char *brneg;
6607   const char *br;
6608
6609   switch (type)
6610     {
6611     case M_BC1FL:
6612       br = "bc1f";
6613       brneg = "bc1t";
6614       break;
6615     case M_BC1TL:
6616       br = "bc1t";
6617       brneg = "bc1f";
6618       break;
6619     case M_BC2FL:
6620       br = "bc2f";
6621       brneg = "bc2t";
6622       break;
6623     case M_BC2TL:
6624       br = "bc2t";
6625       brneg = "bc2f";
6626       break;
6627     default:
6628       abort ();
6629     }
6630   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
6631 }
6632
6633 /* Emit a two-argument branch macro specified by TYPE, using SREG as
6634    the register tested.  EP specifies the branch target.  */
6635
6636 static void
6637 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
6638 {
6639   const char *brneg = NULL;
6640   const char *br;
6641   int call = 0;
6642
6643   switch (type)
6644     {
6645     case M_BGEZ:
6646       br = "bgez";
6647       break;
6648     case M_BGEZL:
6649       br = mips_opts.micromips ? "bgez" : "bgezl";
6650       brneg = "bltz";
6651       break;
6652     case M_BGEZALL:
6653       gas_assert (mips_opts.micromips);
6654       br = "bgezals";
6655       brneg = "bltz";
6656       call = 1;
6657       break;
6658     case M_BGTZ:
6659       br = "bgtz";
6660       break;
6661     case M_BGTZL:
6662       br = mips_opts.micromips ? "bgtz" : "bgtzl";
6663       brneg = "blez";
6664       break;
6665     case M_BLEZ:
6666       br = "blez";
6667       break;
6668     case M_BLEZL:
6669       br = mips_opts.micromips ? "blez" : "blezl";
6670       brneg = "bgtz";
6671       break;
6672     case M_BLTZ:
6673       br = "bltz";
6674       break;
6675     case M_BLTZL:
6676       br = mips_opts.micromips ? "bltz" : "bltzl";
6677       brneg = "bgez";
6678       break;
6679     case M_BLTZALL:
6680       gas_assert (mips_opts.micromips);
6681       br = "bltzals";
6682       brneg = "bgez";
6683       call = 1;
6684       break;
6685     default:
6686       abort ();
6687     }
6688   if (mips_opts.micromips && brneg)
6689     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
6690   else
6691     macro_build (ep, br, "s,p", sreg);
6692 }
6693
6694 /* Emit a three-argument branch macro specified by TYPE, using SREG and
6695    TREG as the registers tested.  EP specifies the branch target.  */
6696
6697 static void
6698 macro_build_branch_rsrt (int type, expressionS *ep,
6699                          unsigned int sreg, unsigned int treg)
6700 {
6701   const char *brneg = NULL;
6702   const int call = 0;
6703   const char *br;
6704
6705   switch (type)
6706     {
6707     case M_BEQ:
6708     case M_BEQ_I:
6709       br = "beq";
6710       break;
6711     case M_BEQL:
6712     case M_BEQL_I:
6713       br = mips_opts.micromips ? "beq" : "beql";
6714       brneg = "bne";
6715       break;
6716     case M_BNE:
6717     case M_BNE_I:
6718       br = "bne";
6719       break;
6720     case M_BNEL:
6721     case M_BNEL_I:
6722       br = mips_opts.micromips ? "bne" : "bnel";
6723       brneg = "beq";
6724       break;
6725     default:
6726       abort ();
6727     }
6728   if (mips_opts.micromips && brneg)
6729     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
6730   else
6731     macro_build (ep, br, "s,t,p", sreg, treg);
6732 }
6733
6734 /*
6735  *                      Build macros
6736  *   This routine implements the seemingly endless macro or synthesized
6737  * instructions and addressing modes in the mips assembly language. Many
6738  * of these macros are simple and are similar to each other. These could
6739  * probably be handled by some kind of table or grammar approach instead of
6740  * this verbose method. Others are not simple macros but are more like
6741  * optimizing code generation.
6742  *   One interesting optimization is when several store macros appear
6743  * consecutively that would load AT with the upper half of the same address.
6744  * The ensuing load upper instructions are ommited. This implies some kind
6745  * of global optimization. We currently only optimize within a single macro.
6746  *   For many of the load and store macros if the address is specified as a
6747  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
6748  * first load register 'at' with zero and use it as the base register. The
6749  * mips assembler simply uses register $zero. Just one tiny optimization
6750  * we're missing.
6751  */
6752 static void
6753 macro (struct mips_cl_insn *ip)
6754 {
6755   unsigned int treg, sreg, dreg, breg;
6756   unsigned int tempreg;
6757   int mask;
6758   int used_at = 0;
6759   expressionS label_expr;
6760   expressionS expr1;
6761   expressionS *ep;
6762   const char *s;
6763   const char *s2;
6764   const char *fmt;
6765   int likely = 0;
6766   int coproc = 0;
6767   int offbits = 16;
6768   int call = 0;
6769   int jals = 0;
6770   int dbl = 0;
6771   int imm = 0;
6772   int ust = 0;
6773   int lp = 0;
6774   int ab = 0;
6775   int off;
6776   offsetT maxnum;
6777   bfd_reloc_code_real_type r;
6778   int hold_mips_optimize;
6779
6780   gas_assert (! mips_opts.mips16);
6781
6782   treg = EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
6783   dreg = EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
6784   sreg = breg = EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
6785   mask = ip->insn_mo->mask;
6786
6787   label_expr.X_op = O_constant;
6788   label_expr.X_op_symbol = NULL;
6789   label_expr.X_add_symbol = NULL;
6790   label_expr.X_add_number = 0;
6791
6792   expr1.X_op = O_constant;
6793   expr1.X_op_symbol = NULL;
6794   expr1.X_add_symbol = NULL;
6795   expr1.X_add_number = 1;
6796
6797   switch (mask)
6798     {
6799     case M_DABS:
6800       dbl = 1;
6801     case M_ABS:
6802       /*    bgez    $a0,1f
6803             move    v0,$a0
6804             sub     v0,$zero,$a0
6805          1:
6806        */
6807
6808       start_noreorder ();
6809
6810       if (mips_opts.micromips)
6811         micromips_label_expr (&label_expr);
6812       else
6813         label_expr.X_add_number = 8;
6814       macro_build (&label_expr, "bgez", "s,p", sreg);
6815       if (dreg == sreg)
6816         macro_build (NULL, "nop", "");
6817       else
6818         move_register (dreg, sreg);
6819       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", dreg, 0, sreg);
6820       if (mips_opts.micromips)
6821         micromips_add_label ();
6822
6823       end_noreorder ();
6824       break;
6825
6826     case M_ADD_I:
6827       s = "addi";
6828       s2 = "add";
6829       goto do_addi;
6830     case M_ADDU_I:
6831       s = "addiu";
6832       s2 = "addu";
6833       goto do_addi;
6834     case M_DADD_I:
6835       dbl = 1;
6836       s = "daddi";
6837       s2 = "dadd";
6838       if (!mips_opts.micromips)
6839         goto do_addi;
6840       if (imm_expr.X_op == O_constant
6841           && imm_expr.X_add_number >= -0x200
6842           && imm_expr.X_add_number < 0x200)
6843         {
6844           macro_build (NULL, s, "t,r,.", treg, sreg, imm_expr.X_add_number);
6845           break;
6846         }
6847       goto do_addi_i;
6848     case M_DADDU_I:
6849       dbl = 1;
6850       s = "daddiu";
6851       s2 = "daddu";
6852     do_addi:
6853       if (imm_expr.X_op == O_constant
6854           && imm_expr.X_add_number >= -0x8000
6855           && imm_expr.X_add_number < 0x8000)
6856         {
6857           macro_build (&imm_expr, s, "t,r,j", treg, sreg, BFD_RELOC_LO16);
6858           break;
6859         }
6860     do_addi_i:
6861       used_at = 1;
6862       load_register (AT, &imm_expr, dbl);
6863       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
6864       break;
6865
6866     case M_AND_I:
6867       s = "andi";
6868       s2 = "and";
6869       goto do_bit;
6870     case M_OR_I:
6871       s = "ori";
6872       s2 = "or";
6873       goto do_bit;
6874     case M_NOR_I:
6875       s = "";
6876       s2 = "nor";
6877       goto do_bit;
6878     case M_XOR_I:
6879       s = "xori";
6880       s2 = "xor";
6881     do_bit:
6882       if (imm_expr.X_op == O_constant
6883           && imm_expr.X_add_number >= 0
6884           && imm_expr.X_add_number < 0x10000)
6885         {
6886           if (mask != M_NOR_I)
6887             macro_build (&imm_expr, s, "t,r,i", treg, sreg, BFD_RELOC_LO16);
6888           else
6889             {
6890               macro_build (&imm_expr, "ori", "t,r,i",
6891                            treg, sreg, BFD_RELOC_LO16);
6892               macro_build (NULL, "nor", "d,v,t", treg, treg, 0);
6893             }
6894           break;
6895         }
6896
6897       used_at = 1;
6898       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
6899       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
6900       break;
6901
6902     case M_BALIGN:
6903       switch (imm_expr.X_add_number)
6904         {
6905         case 0:
6906           macro_build (NULL, "nop", "");
6907           break;
6908         case 2:
6909           macro_build (NULL, "packrl.ph", "d,s,t", treg, treg, sreg);
6910           break;
6911         case 1:
6912         case 3:
6913           macro_build (NULL, "balign", "t,s,2", treg, sreg,
6914                        (int) imm_expr.X_add_number);
6915           break;
6916         default:
6917           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
6918                   (unsigned long) imm_expr.X_add_number);
6919           break;
6920         }
6921       break;
6922
6923     case M_BC1FL:
6924     case M_BC1TL:
6925     case M_BC2FL:
6926     case M_BC2TL:
6927       gas_assert (mips_opts.micromips);
6928       macro_build_branch_ccl (mask, &offset_expr,
6929                               EXTRACT_OPERAND (1, BCC, *ip));
6930       break;
6931
6932     case M_BEQ_I:
6933     case M_BEQL_I:
6934     case M_BNE_I:
6935     case M_BNEL_I:
6936       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6937         treg = 0;
6938       else
6939         {
6940           treg = AT;
6941           used_at = 1;
6942           load_register (treg, &imm_expr, HAVE_64BIT_GPRS);
6943         }
6944       /* Fall through.  */
6945     case M_BEQL:
6946     case M_BNEL:
6947       macro_build_branch_rsrt (mask, &offset_expr, sreg, treg);
6948       break;
6949
6950     case M_BGEL:
6951       likely = 1;
6952     case M_BGE:
6953       if (treg == 0)
6954         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, sreg);
6955       else if (sreg == 0)
6956         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, treg);
6957       else
6958         {
6959           used_at = 1;
6960           macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
6961           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6962                                    &offset_expr, AT, ZERO);
6963         }
6964       break;
6965
6966     case M_BGEZL:
6967     case M_BGEZALL:
6968     case M_BGTZL:
6969     case M_BLEZL:
6970     case M_BLTZL:
6971     case M_BLTZALL:
6972       macro_build_branch_rs (mask, &offset_expr, sreg);
6973       break;
6974
6975     case M_BGTL_I:
6976       likely = 1;
6977     case M_BGT_I:
6978       /* Check for > max integer.  */
6979       maxnum = 0x7fffffff;
6980       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
6981         {
6982           maxnum <<= 16;
6983           maxnum |= 0xffff;
6984           maxnum <<= 16;
6985           maxnum |= 0xffff;
6986         }
6987       if (imm_expr.X_op == O_constant
6988           && imm_expr.X_add_number >= maxnum
6989           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
6990         {
6991         do_false:
6992           /* Result is always false.  */
6993           if (! likely)
6994             macro_build (NULL, "nop", "");
6995           else
6996             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
6997           break;
6998         }
6999       if (imm_expr.X_op != O_constant)
7000         as_bad (_("Unsupported large constant"));
7001       ++imm_expr.X_add_number;
7002       /* FALLTHROUGH */
7003     case M_BGE_I:
7004     case M_BGEL_I:
7005       if (mask == M_BGEL_I)
7006         likely = 1;
7007       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7008         {
7009           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
7010                                  &offset_expr, sreg);
7011           break;
7012         }
7013       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7014         {
7015           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
7016                                  &offset_expr, sreg);
7017           break;
7018         }
7019       maxnum = 0x7fffffff;
7020       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
7021         {
7022           maxnum <<= 16;
7023           maxnum |= 0xffff;
7024           maxnum <<= 16;
7025           maxnum |= 0xffff;
7026         }
7027       maxnum = - maxnum - 1;
7028       if (imm_expr.X_op == O_constant
7029           && imm_expr.X_add_number <= maxnum
7030           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
7031         {
7032         do_true:
7033           /* result is always true */
7034           as_warn (_("Branch %s is always true"), ip->insn_mo->name);
7035           macro_build (&offset_expr, "b", "p");
7036           break;
7037         }
7038       used_at = 1;
7039       set_at (sreg, 0);
7040       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7041                                &offset_expr, AT, ZERO);
7042       break;
7043
7044     case M_BGEUL:
7045       likely = 1;
7046     case M_BGEU:
7047       if (treg == 0)
7048         goto do_true;
7049       else if (sreg == 0)
7050         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7051                                  &offset_expr, ZERO, treg);
7052       else
7053         {
7054           used_at = 1;
7055           macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
7056           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7057                                    &offset_expr, AT, ZERO);
7058         }
7059       break;
7060
7061     case M_BGTUL_I:
7062       likely = 1;
7063     case M_BGTU_I:
7064       if (sreg == 0
7065           || (HAVE_32BIT_GPRS
7066               && imm_expr.X_op == O_constant
7067               && imm_expr.X_add_number == -1))
7068         goto do_false;
7069       if (imm_expr.X_op != O_constant)
7070         as_bad (_("Unsupported large constant"));
7071       ++imm_expr.X_add_number;
7072       /* FALLTHROUGH */
7073     case M_BGEU_I:
7074     case M_BGEUL_I:
7075       if (mask == M_BGEUL_I)
7076         likely = 1;
7077       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7078         goto do_true;
7079       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7080         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7081                                  &offset_expr, sreg, ZERO);
7082       else
7083         {
7084           used_at = 1;
7085           set_at (sreg, 1);
7086           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7087                                    &offset_expr, AT, ZERO);
7088         }
7089       break;
7090
7091     case M_BGTL:
7092       likely = 1;
7093     case M_BGT:
7094       if (treg == 0)
7095         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, sreg);
7096       else if (sreg == 0)
7097         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, treg);
7098       else
7099         {
7100           used_at = 1;
7101           macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
7102           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7103                                    &offset_expr, AT, ZERO);
7104         }
7105       break;
7106
7107     case M_BGTUL:
7108       likely = 1;
7109     case M_BGTU:
7110       if (treg == 0)
7111         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7112                                  &offset_expr, sreg, ZERO);
7113       else if (sreg == 0)
7114         goto do_false;
7115       else
7116         {
7117           used_at = 1;
7118           macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
7119           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7120                                    &offset_expr, AT, ZERO);
7121         }
7122       break;
7123
7124     case M_BLEL:
7125       likely = 1;
7126     case M_BLE:
7127       if (treg == 0)
7128         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, sreg);
7129       else if (sreg == 0)
7130         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, treg);
7131       else
7132         {
7133           used_at = 1;
7134           macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
7135           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7136                                    &offset_expr, AT, ZERO);
7137         }
7138       break;
7139
7140     case M_BLEL_I:
7141       likely = 1;
7142     case M_BLE_I:
7143       maxnum = 0x7fffffff;
7144       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
7145         {
7146           maxnum <<= 16;
7147           maxnum |= 0xffff;
7148           maxnum <<= 16;
7149           maxnum |= 0xffff;
7150         }
7151       if (imm_expr.X_op == O_constant
7152           && imm_expr.X_add_number >= maxnum
7153           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
7154         goto do_true;
7155       if (imm_expr.X_op != O_constant)
7156         as_bad (_("Unsupported large constant"));
7157       ++imm_expr.X_add_number;
7158       /* FALLTHROUGH */
7159     case M_BLT_I:
7160     case M_BLTL_I:
7161       if (mask == M_BLTL_I)
7162         likely = 1;
7163       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7164         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, sreg);
7165       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7166         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, sreg);
7167       else
7168         {
7169           used_at = 1;
7170           set_at (sreg, 0);
7171           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7172                                    &offset_expr, AT, ZERO);
7173         }
7174       break;
7175
7176     case M_BLEUL:
7177       likely = 1;
7178     case M_BLEU:
7179       if (treg == 0)
7180         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7181                                  &offset_expr, sreg, ZERO);
7182       else if (sreg == 0)
7183         goto do_true;
7184       else
7185         {
7186           used_at = 1;
7187           macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
7188           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7189                                    &offset_expr, AT, ZERO);
7190         }
7191       break;
7192
7193     case M_BLEUL_I:
7194       likely = 1;
7195     case M_BLEU_I:
7196       if (sreg == 0
7197           || (HAVE_32BIT_GPRS
7198               && imm_expr.X_op == O_constant
7199               && imm_expr.X_add_number == -1))
7200         goto do_true;
7201       if (imm_expr.X_op != O_constant)
7202         as_bad (_("Unsupported large constant"));
7203       ++imm_expr.X_add_number;
7204       /* FALLTHROUGH */
7205     case M_BLTU_I:
7206     case M_BLTUL_I:
7207       if (mask == M_BLTUL_I)
7208         likely = 1;
7209       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7210         goto do_false;
7211       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7212         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7213                                  &offset_expr, sreg, ZERO);
7214       else
7215         {
7216           used_at = 1;
7217           set_at (sreg, 1);
7218           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7219                                    &offset_expr, AT, ZERO);
7220         }
7221       break;
7222
7223     case M_BLTL:
7224       likely = 1;
7225     case M_BLT:
7226       if (treg == 0)
7227         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, sreg);
7228       else if (sreg == 0)
7229         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, treg);
7230       else
7231         {
7232           used_at = 1;
7233           macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
7234           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7235                                    &offset_expr, AT, ZERO);
7236         }
7237       break;
7238
7239     case M_BLTUL:
7240       likely = 1;
7241     case M_BLTU:
7242       if (treg == 0)
7243         goto do_false;
7244       else if (sreg == 0)
7245         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7246                                  &offset_expr, ZERO, treg);
7247       else
7248         {
7249           used_at = 1;
7250           macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
7251           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7252                                    &offset_expr, AT, ZERO);
7253         }
7254       break;
7255
7256     case M_DEXT:
7257       {
7258         /* Use unsigned arithmetic.  */
7259         addressT pos;
7260         addressT size;
7261
7262         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
7263           {
7264             as_bad (_("Unsupported large constant"));
7265             pos = size = 1;
7266           }
7267         else
7268           {
7269             pos = imm_expr.X_add_number;
7270             size = imm2_expr.X_add_number;
7271           }
7272
7273         if (pos > 63)
7274           {
7275             as_bad (_("Improper position (%lu)"), (unsigned long) pos);
7276             pos = 1;
7277           }
7278         if (size == 0 || size > 64 || (pos + size - 1) > 63)
7279           {
7280             as_bad (_("Improper extract size (%lu, position %lu)"),
7281                     (unsigned long) size, (unsigned long) pos);
7282             size = 1;
7283           }
7284
7285         if (size <= 32 && pos < 32)
7286           {
7287             s = "dext";
7288             fmt = "t,r,+A,+C";
7289           }
7290         else if (size <= 32)
7291           {
7292             s = "dextu";
7293             fmt = "t,r,+E,+H";
7294           }
7295         else
7296           {
7297             s = "dextm";
7298             fmt = "t,r,+A,+G";
7299           }
7300         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
7301                      (int) (size - 1));
7302       }
7303       break;
7304
7305     case M_DINS:
7306       {
7307         /* Use unsigned arithmetic.  */
7308         addressT pos;
7309         addressT size;
7310
7311         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
7312           {
7313             as_bad (_("Unsupported large constant"));
7314             pos = size = 1;
7315           }
7316         else
7317           {
7318             pos = imm_expr.X_add_number;
7319             size = imm2_expr.X_add_number;
7320           }
7321
7322         if (pos > 63)
7323           {
7324             as_bad (_("Improper position (%lu)"), (unsigned long) pos);
7325             pos = 1;
7326           }
7327         if (size == 0 || size > 64 || (pos + size - 1) > 63)
7328           {
7329             as_bad (_("Improper insert size (%lu, position %lu)"),
7330                     (unsigned long) size, (unsigned long) pos);
7331             size = 1;
7332           }
7333
7334         if (pos < 32 && (pos + size - 1) < 32)
7335           {
7336             s = "dins";
7337             fmt = "t,r,+A,+B";
7338           }
7339         else if (pos >= 32)
7340           {
7341             s = "dinsu";
7342             fmt = "t,r,+E,+F";
7343           }
7344         else
7345           {
7346             s = "dinsm";
7347             fmt = "t,r,+A,+F";
7348           }
7349         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
7350                      (int) (pos + size - 1));
7351       }
7352       break;
7353
7354     case M_DDIV_3:
7355       dbl = 1;
7356     case M_DIV_3:
7357       s = "mflo";
7358       goto do_div3;
7359     case M_DREM_3:
7360       dbl = 1;
7361     case M_REM_3:
7362       s = "mfhi";
7363     do_div3:
7364       if (treg == 0)
7365         {
7366           as_warn (_("Divide by zero."));
7367           if (mips_trap)
7368             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
7369           else
7370             macro_build (NULL, "break", BRK_FMT, 7);
7371           break;
7372         }
7373
7374       start_noreorder ();
7375       if (mips_trap)
7376         {
7377           macro_build (NULL, "teq", TRAP_FMT, treg, ZERO, 7);
7378           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
7379         }
7380       else
7381         {
7382           if (mips_opts.micromips)
7383             micromips_label_expr (&label_expr);
7384           else
7385             label_expr.X_add_number = 8;
7386           macro_build (&label_expr, "bne", "s,t,p", treg, ZERO);
7387           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
7388           macro_build (NULL, "break", BRK_FMT, 7);
7389           if (mips_opts.micromips)
7390             micromips_add_label ();
7391         }
7392       expr1.X_add_number = -1;
7393       used_at = 1;
7394       load_register (AT, &expr1, dbl);
7395       if (mips_opts.micromips)
7396         micromips_label_expr (&label_expr);
7397       else
7398         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
7399       macro_build (&label_expr, "bne", "s,t,p", treg, AT);
7400       if (dbl)
7401         {
7402           expr1.X_add_number = 1;
7403           load_register (AT, &expr1, dbl);
7404           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
7405         }
7406       else
7407         {
7408           expr1.X_add_number = 0x80000000;
7409           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
7410         }
7411       if (mips_trap)
7412         {
7413           macro_build (NULL, "teq", TRAP_FMT, sreg, AT, 6);
7414           /* We want to close the noreorder block as soon as possible, so
7415              that later insns are available for delay slot filling.  */
7416           end_noreorder ();
7417         }
7418       else
7419         {
7420           if (mips_opts.micromips)
7421             micromips_label_expr (&label_expr);
7422           else
7423             label_expr.X_add_number = 8;
7424           macro_build (&label_expr, "bne", "s,t,p", sreg, AT);
7425           macro_build (NULL, "nop", "");
7426
7427           /* We want to close the noreorder block as soon as possible, so
7428              that later insns are available for delay slot filling.  */
7429           end_noreorder ();
7430
7431           macro_build (NULL, "break", BRK_FMT, 6);
7432         }
7433       if (mips_opts.micromips)
7434         micromips_add_label ();
7435       macro_build (NULL, s, MFHL_FMT, dreg);
7436       break;
7437
7438     case M_DIV_3I:
7439       s = "div";
7440       s2 = "mflo";
7441       goto do_divi;
7442     case M_DIVU_3I:
7443       s = "divu";
7444       s2 = "mflo";
7445       goto do_divi;
7446     case M_REM_3I:
7447       s = "div";
7448       s2 = "mfhi";
7449       goto do_divi;
7450     case M_REMU_3I:
7451       s = "divu";
7452       s2 = "mfhi";
7453       goto do_divi;
7454     case M_DDIV_3I:
7455       dbl = 1;
7456       s = "ddiv";
7457       s2 = "mflo";
7458       goto do_divi;
7459     case M_DDIVU_3I:
7460       dbl = 1;
7461       s = "ddivu";
7462       s2 = "mflo";
7463       goto do_divi;
7464     case M_DREM_3I:
7465       dbl = 1;
7466       s = "ddiv";
7467       s2 = "mfhi";
7468       goto do_divi;
7469     case M_DREMU_3I:
7470       dbl = 1;
7471       s = "ddivu";
7472       s2 = "mfhi";
7473     do_divi:
7474       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7475         {
7476           as_warn (_("Divide by zero."));
7477           if (mips_trap)
7478             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
7479           else
7480             macro_build (NULL, "break", BRK_FMT, 7);
7481           break;
7482         }
7483       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7484         {
7485           if (strcmp (s2, "mflo") == 0)
7486             move_register (dreg, sreg);
7487           else
7488             move_register (dreg, ZERO);
7489           break;
7490         }
7491       if (imm_expr.X_op == O_constant
7492           && imm_expr.X_add_number == -1
7493           && s[strlen (s) - 1] != 'u')
7494         {
7495           if (strcmp (s2, "mflo") == 0)
7496             {
7497               macro_build (NULL, dbl ? "dneg" : "neg", "d,w", dreg, sreg);
7498             }
7499           else
7500             move_register (dreg, ZERO);
7501           break;
7502         }
7503
7504       used_at = 1;
7505       load_register (AT, &imm_expr, dbl);
7506       macro_build (NULL, s, "z,s,t", sreg, AT);
7507       macro_build (NULL, s2, MFHL_FMT, dreg);
7508       break;
7509
7510     case M_DIVU_3:
7511       s = "divu";
7512       s2 = "mflo";
7513       goto do_divu3;
7514     case M_REMU_3:
7515       s = "divu";
7516       s2 = "mfhi";
7517       goto do_divu3;
7518     case M_DDIVU_3:
7519       s = "ddivu";
7520       s2 = "mflo";
7521       goto do_divu3;
7522     case M_DREMU_3:
7523       s = "ddivu";
7524       s2 = "mfhi";
7525     do_divu3:
7526       start_noreorder ();
7527       if (mips_trap)
7528         {
7529           macro_build (NULL, "teq", TRAP_FMT, treg, ZERO, 7);
7530           macro_build (NULL, s, "z,s,t", sreg, treg);
7531           /* We want to close the noreorder block as soon as possible, so
7532              that later insns are available for delay slot filling.  */
7533           end_noreorder ();
7534         }
7535       else
7536         {
7537           if (mips_opts.micromips)
7538             micromips_label_expr (&label_expr);
7539           else
7540             label_expr.X_add_number = 8;
7541           macro_build (&label_expr, "bne", "s,t,p", treg, ZERO);
7542           macro_build (NULL, s, "z,s,t", sreg, treg);
7543
7544           /* We want to close the noreorder block as soon as possible, so
7545              that later insns are available for delay slot filling.  */
7546           end_noreorder ();
7547           macro_build (NULL, "break", BRK_FMT, 7);
7548           if (mips_opts.micromips)
7549             micromips_add_label ();
7550         }
7551       macro_build (NULL, s2, MFHL_FMT, dreg);
7552       break;
7553
7554     case M_DLCA_AB:
7555       dbl = 1;
7556     case M_LCA_AB:
7557       call = 1;
7558       goto do_la;
7559     case M_DLA_AB:
7560       dbl = 1;
7561     case M_LA_AB:
7562     do_la:
7563       /* Load the address of a symbol into a register.  If breg is not
7564          zero, we then add a base register to it.  */
7565
7566       if (dbl && HAVE_32BIT_GPRS)
7567         as_warn (_("dla used to load 32-bit register"));
7568
7569       if (!dbl && HAVE_64BIT_OBJECTS)
7570         as_warn (_("la used to load 64-bit address"));
7571
7572       if (offset_expr.X_op == O_constant
7573           && offset_expr.X_add_number >= -0x8000
7574           && offset_expr.X_add_number < 0x8000)
7575         {
7576           macro_build (&offset_expr, ADDRESS_ADDI_INSN,
7577                        "t,r,j", treg, sreg, BFD_RELOC_LO16);
7578           break;
7579         }
7580
7581       if (mips_opts.at && (treg == breg))
7582         {
7583           tempreg = AT;
7584           used_at = 1;
7585         }
7586       else
7587         {
7588           tempreg = treg;
7589         }
7590
7591       if (offset_expr.X_op != O_symbol
7592           && offset_expr.X_op != O_constant)
7593         {
7594           as_bad (_("Expression too complex"));
7595           offset_expr.X_op = O_constant;
7596         }
7597
7598       if (offset_expr.X_op == O_constant)
7599         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
7600       else if (mips_pic == NO_PIC)
7601         {
7602           /* If this is a reference to a GP relative symbol, we want
7603                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
7604              Otherwise we want
7605                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
7606                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
7607              If we have a constant, we need two instructions anyhow,
7608              so we may as well always use the latter form.
7609
7610              With 64bit address space and a usable $at we want
7611                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
7612                lui      $at,<sym>               (BFD_RELOC_HI16_S)
7613                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
7614                daddiu   $at,<sym>               (BFD_RELOC_LO16)
7615                dsll32   $tempreg,0
7616                daddu    $tempreg,$tempreg,$at
7617
7618              If $at is already in use, we use a path which is suboptimal
7619              on superscalar processors.
7620                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
7621                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
7622                dsll     $tempreg,16
7623                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
7624                dsll     $tempreg,16
7625                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
7626
7627              For GP relative symbols in 64bit address space we can use
7628              the same sequence as in 32bit address space.  */
7629           if (HAVE_64BIT_SYMBOLS)
7630             {
7631               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
7632                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
7633                 {
7634                   relax_start (offset_expr.X_add_symbol);
7635                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7636                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
7637                   relax_switch ();
7638                 }
7639
7640               if (used_at == 0 && mips_opts.at)
7641                 {
7642                   macro_build (&offset_expr, "lui", LUI_FMT,
7643                                tempreg, BFD_RELOC_MIPS_HIGHEST);
7644                   macro_build (&offset_expr, "lui", LUI_FMT,
7645                                AT, BFD_RELOC_HI16_S);
7646                   macro_build (&offset_expr, "daddiu", "t,r,j",
7647                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
7648                   macro_build (&offset_expr, "daddiu", "t,r,j",
7649                                AT, AT, BFD_RELOC_LO16);
7650                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
7651                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
7652                   used_at = 1;
7653                 }
7654               else
7655                 {
7656                   macro_build (&offset_expr, "lui", LUI_FMT,
7657                                tempreg, BFD_RELOC_MIPS_HIGHEST);
7658                   macro_build (&offset_expr, "daddiu", "t,r,j",
7659                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
7660                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
7661                   macro_build (&offset_expr, "daddiu", "t,r,j",
7662                                tempreg, tempreg, BFD_RELOC_HI16_S);
7663                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
7664                   macro_build (&offset_expr, "daddiu", "t,r,j",
7665                                tempreg, tempreg, BFD_RELOC_LO16);
7666                 }
7667
7668               if (mips_relax.sequence)
7669                 relax_end ();
7670             }
7671           else
7672             {
7673               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
7674                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
7675                 {
7676                   relax_start (offset_expr.X_add_symbol);
7677                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7678                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
7679                   relax_switch ();
7680                 }
7681               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
7682                 as_bad (_("Offset too large"));
7683               macro_build_lui (&offset_expr, tempreg);
7684               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7685                            tempreg, tempreg, BFD_RELOC_LO16);
7686               if (mips_relax.sequence)
7687                 relax_end ();
7688             }
7689         }
7690       else if (!mips_big_got && !HAVE_NEWABI)
7691         {
7692           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
7693
7694           /* If this is a reference to an external symbol, and there
7695              is no constant, we want
7696                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7697              or for lca or if tempreg is PIC_CALL_REG
7698                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
7699              For a local symbol, we want
7700                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7701                nop
7702                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
7703
7704              If we have a small constant, and this is a reference to
7705              an external symbol, we want
7706                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7707                nop
7708                addiu    $tempreg,$tempreg,<constant>
7709              For a local symbol, we want the same instruction
7710              sequence, but we output a BFD_RELOC_LO16 reloc on the
7711              addiu instruction.
7712
7713              If we have a large constant, and this is a reference to
7714              an external symbol, we want
7715                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7716                lui      $at,<hiconstant>
7717                addiu    $at,$at,<loconstant>
7718                addu     $tempreg,$tempreg,$at
7719              For a local symbol, we want the same instruction
7720              sequence, but we output a BFD_RELOC_LO16 reloc on the
7721              addiu instruction.
7722            */
7723
7724           if (offset_expr.X_add_number == 0)
7725             {
7726               if (mips_pic == SVR4_PIC
7727                   && breg == 0
7728                   && (call || tempreg == PIC_CALL_REG))
7729                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
7730
7731               relax_start (offset_expr.X_add_symbol);
7732               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7733                            lw_reloc_type, mips_gp_register);
7734               if (breg != 0)
7735                 {
7736                   /* We're going to put in an addu instruction using
7737                      tempreg, so we may as well insert the nop right
7738                      now.  */
7739                   load_delay_nop ();
7740                 }
7741               relax_switch ();
7742               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7743                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
7744               load_delay_nop ();
7745               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7746                            tempreg, tempreg, BFD_RELOC_LO16);
7747               relax_end ();
7748               /* FIXME: If breg == 0, and the next instruction uses
7749                  $tempreg, then if this variant case is used an extra
7750                  nop will be generated.  */
7751             }
7752           else if (offset_expr.X_add_number >= -0x8000
7753                    && offset_expr.X_add_number < 0x8000)
7754             {
7755               load_got_offset (tempreg, &offset_expr);
7756               load_delay_nop ();
7757               add_got_offset (tempreg, &offset_expr);
7758             }
7759           else
7760             {
7761               expr1.X_add_number = offset_expr.X_add_number;
7762               offset_expr.X_add_number =
7763                 SEXT_16BIT (offset_expr.X_add_number);
7764               load_got_offset (tempreg, &offset_expr);
7765               offset_expr.X_add_number = expr1.X_add_number;
7766               /* If we are going to add in a base register, and the
7767                  target register and the base register are the same,
7768                  then we are using AT as a temporary register.  Since
7769                  we want to load the constant into AT, we add our
7770                  current AT (from the global offset table) and the
7771                  register into the register now, and pretend we were
7772                  not using a base register.  */
7773               if (breg == treg)
7774                 {
7775                   load_delay_nop ();
7776                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7777                                treg, AT, breg);
7778                   breg = 0;
7779                   tempreg = treg;
7780                 }
7781               add_got_offset_hilo (tempreg, &offset_expr, AT);
7782               used_at = 1;
7783             }
7784         }
7785       else if (!mips_big_got && HAVE_NEWABI)
7786         {
7787           int add_breg_early = 0;
7788
7789           /* If this is a reference to an external, and there is no
7790              constant, or local symbol (*), with or without a
7791              constant, we want
7792                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7793              or for lca or if tempreg is PIC_CALL_REG
7794                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
7795
7796              If we have a small constant, and this is a reference to
7797              an external symbol, we want
7798                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7799                addiu    $tempreg,$tempreg,<constant>
7800
7801              If we have a large constant, and this is a reference to
7802              an external symbol, we want
7803                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7804                lui      $at,<hiconstant>
7805                addiu    $at,$at,<loconstant>
7806                addu     $tempreg,$tempreg,$at
7807
7808              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
7809              local symbols, even though it introduces an additional
7810              instruction.  */
7811
7812           if (offset_expr.X_add_number)
7813             {
7814               expr1.X_add_number = offset_expr.X_add_number;
7815               offset_expr.X_add_number = 0;
7816
7817               relax_start (offset_expr.X_add_symbol);
7818               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7819                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7820
7821               if (expr1.X_add_number >= -0x8000
7822                   && expr1.X_add_number < 0x8000)
7823                 {
7824                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
7825                                tempreg, tempreg, BFD_RELOC_LO16);
7826                 }
7827               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
7828                 {
7829                   /* If we are going to add in a base register, and the
7830                      target register and the base register are the same,
7831                      then we are using AT as a temporary register.  Since
7832                      we want to load the constant into AT, we add our
7833                      current AT (from the global offset table) and the
7834                      register into the register now, and pretend we were
7835                      not using a base register.  */
7836                   if (breg != treg)
7837                     dreg = tempreg;
7838                   else
7839                     {
7840                       gas_assert (tempreg == AT);
7841                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7842                                    treg, AT, breg);
7843                       dreg = treg;
7844                       add_breg_early = 1;
7845                     }
7846
7847                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
7848                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7849                                dreg, dreg, AT);
7850
7851                   used_at = 1;
7852                 }
7853               else
7854                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
7855
7856               relax_switch ();
7857               offset_expr.X_add_number = expr1.X_add_number;
7858
7859               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7860                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7861               if (add_breg_early)
7862                 {
7863                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7864                                treg, tempreg, breg);
7865                   breg = 0;
7866                   tempreg = treg;
7867                 }
7868               relax_end ();
7869             }
7870           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
7871             {
7872               relax_start (offset_expr.X_add_symbol);
7873               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7874                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
7875               relax_switch ();
7876               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7877                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7878               relax_end ();
7879             }
7880           else
7881             {
7882               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7883                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7884             }
7885         }
7886       else if (mips_big_got && !HAVE_NEWABI)
7887         {
7888           int gpdelay;
7889           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
7890           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
7891           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
7892
7893           /* This is the large GOT case.  If this is a reference to an
7894              external symbol, and there is no constant, we want
7895                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7896                addu     $tempreg,$tempreg,$gp
7897                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7898              or for lca or if tempreg is PIC_CALL_REG
7899                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
7900                addu     $tempreg,$tempreg,$gp
7901                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
7902              For a local symbol, we want
7903                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7904                nop
7905                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
7906
7907              If we have a small constant, and this is a reference to
7908              an external symbol, we want
7909                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7910                addu     $tempreg,$tempreg,$gp
7911                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7912                nop
7913                addiu    $tempreg,$tempreg,<constant>
7914              For a local symbol, we want
7915                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7916                nop
7917                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
7918
7919              If we have a large constant, and this is a reference to
7920              an external symbol, we want
7921                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7922                addu     $tempreg,$tempreg,$gp
7923                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7924                lui      $at,<hiconstant>
7925                addiu    $at,$at,<loconstant>
7926                addu     $tempreg,$tempreg,$at
7927              For a local symbol, we want
7928                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7929                lui      $at,<hiconstant>
7930                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
7931                addu     $tempreg,$tempreg,$at
7932           */
7933
7934           expr1.X_add_number = offset_expr.X_add_number;
7935           offset_expr.X_add_number = 0;
7936           relax_start (offset_expr.X_add_symbol);
7937           gpdelay = reg_needs_delay (mips_gp_register);
7938           if (expr1.X_add_number == 0 && breg == 0
7939               && (call || tempreg == PIC_CALL_REG))
7940             {
7941               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
7942               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
7943             }
7944           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
7945           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7946                        tempreg, tempreg, mips_gp_register);
7947           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7948                        tempreg, lw_reloc_type, tempreg);
7949           if (expr1.X_add_number == 0)
7950             {
7951               if (breg != 0)
7952                 {
7953                   /* We're going to put in an addu instruction using
7954                      tempreg, so we may as well insert the nop right
7955                      now.  */
7956                   load_delay_nop ();
7957                 }
7958             }
7959           else if (expr1.X_add_number >= -0x8000
7960                    && expr1.X_add_number < 0x8000)
7961             {
7962               load_delay_nop ();
7963               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
7964                            tempreg, tempreg, BFD_RELOC_LO16);
7965             }
7966           else
7967             {
7968               /* If we are going to add in a base register, and the
7969                  target register and the base register are the same,
7970                  then we are using AT as a temporary register.  Since
7971                  we want to load the constant into AT, we add our
7972                  current AT (from the global offset table) and the
7973                  register into the register now, and pretend we were
7974                  not using a base register.  */
7975               if (breg != treg)
7976                 dreg = tempreg;
7977               else
7978                 {
7979                   gas_assert (tempreg == AT);
7980                   load_delay_nop ();
7981                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7982                                treg, AT, breg);
7983                   dreg = treg;
7984                 }
7985
7986               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
7987               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
7988
7989               used_at = 1;
7990             }
7991           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
7992           relax_switch ();
7993
7994           if (gpdelay)
7995             {
7996               /* This is needed because this instruction uses $gp, but
7997                  the first instruction on the main stream does not.  */
7998               macro_build (NULL, "nop", "");
7999             }
8000
8001           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8002                        local_reloc_type, mips_gp_register);
8003           if (expr1.X_add_number >= -0x8000
8004               && expr1.X_add_number < 0x8000)
8005             {
8006               load_delay_nop ();
8007               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8008                            tempreg, tempreg, BFD_RELOC_LO16);
8009               /* FIXME: If add_number is 0, and there was no base
8010                  register, the external symbol case ended with a load,
8011                  so if the symbol turns out to not be external, and
8012                  the next instruction uses tempreg, an unnecessary nop
8013                  will be inserted.  */
8014             }
8015           else
8016             {
8017               if (breg == treg)
8018                 {
8019                   /* We must add in the base register now, as in the
8020                      external symbol case.  */
8021                   gas_assert (tempreg == AT);
8022                   load_delay_nop ();
8023                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8024                                treg, AT, breg);
8025                   tempreg = treg;
8026                   /* We set breg to 0 because we have arranged to add
8027                      it in in both cases.  */
8028                   breg = 0;
8029                 }
8030
8031               macro_build_lui (&expr1, AT);
8032               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8033                            AT, AT, BFD_RELOC_LO16);
8034               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8035                            tempreg, tempreg, AT);
8036               used_at = 1;
8037             }
8038           relax_end ();
8039         }
8040       else if (mips_big_got && HAVE_NEWABI)
8041         {
8042           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
8043           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
8044           int add_breg_early = 0;
8045
8046           /* This is the large GOT case.  If this is a reference to an
8047              external symbol, and there is no constant, we want
8048                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8049                add      $tempreg,$tempreg,$gp
8050                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8051              or for lca or if tempreg is PIC_CALL_REG
8052                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
8053                add      $tempreg,$tempreg,$gp
8054                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
8055
8056              If we have a small constant, and this is a reference to
8057              an external symbol, we want
8058                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8059                add      $tempreg,$tempreg,$gp
8060                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8061                addi     $tempreg,$tempreg,<constant>
8062
8063              If we have a large constant, and this is a reference to
8064              an external symbol, we want
8065                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8066                addu     $tempreg,$tempreg,$gp
8067                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8068                lui      $at,<hiconstant>
8069                addi     $at,$at,<loconstant>
8070                add      $tempreg,$tempreg,$at
8071
8072              If we have NewABI, and we know it's a local symbol, we want
8073                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
8074                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
8075              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
8076
8077           relax_start (offset_expr.X_add_symbol);
8078
8079           expr1.X_add_number = offset_expr.X_add_number;
8080           offset_expr.X_add_number = 0;
8081
8082           if (expr1.X_add_number == 0 && breg == 0
8083               && (call || tempreg == PIC_CALL_REG))
8084             {
8085               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
8086               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
8087             }
8088           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
8089           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8090                        tempreg, tempreg, mips_gp_register);
8091           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8092                        tempreg, lw_reloc_type, tempreg);
8093
8094           if (expr1.X_add_number == 0)
8095             ;
8096           else if (expr1.X_add_number >= -0x8000
8097                    && expr1.X_add_number < 0x8000)
8098             {
8099               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
8100                            tempreg, tempreg, BFD_RELOC_LO16);
8101             }
8102           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
8103             {
8104               /* If we are going to add in a base register, and the
8105                  target register and the base register are the same,
8106                  then we are using AT as a temporary register.  Since
8107                  we want to load the constant into AT, we add our
8108                  current AT (from the global offset table) and the
8109                  register into the register now, and pretend we were
8110                  not using a base register.  */
8111               if (breg != treg)
8112                 dreg = tempreg;
8113               else
8114                 {
8115                   gas_assert (tempreg == AT);
8116                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8117                                treg, AT, breg);
8118                   dreg = treg;
8119                   add_breg_early = 1;
8120                 }
8121
8122               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
8123               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
8124
8125               used_at = 1;
8126             }
8127           else
8128             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
8129
8130           relax_switch ();
8131           offset_expr.X_add_number = expr1.X_add_number;
8132           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8133                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
8134           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
8135                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
8136           if (add_breg_early)
8137             {
8138               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8139                            treg, tempreg, breg);
8140               breg = 0;
8141               tempreg = treg;
8142             }
8143           relax_end ();
8144         }
8145       else
8146         abort ();
8147
8148       if (breg != 0)
8149         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", treg, tempreg, breg);
8150       break;
8151
8152     case M_MSGSND:
8153       gas_assert (!mips_opts.micromips);
8154       {
8155         unsigned long temp = (treg << 16) | (0x01);
8156         macro_build (NULL, "c2", "C", temp);
8157       }
8158       break;
8159
8160     case M_MSGLD:
8161       gas_assert (!mips_opts.micromips);
8162       {
8163         unsigned long temp = (0x02);
8164         macro_build (NULL, "c2", "C", temp);
8165       }
8166       break;
8167
8168     case M_MSGLD_T:
8169       gas_assert (!mips_opts.micromips);
8170       {
8171         unsigned long temp = (treg << 16) | (0x02);
8172         macro_build (NULL, "c2", "C", temp);
8173       }
8174       break;
8175
8176     case M_MSGWAIT:
8177       gas_assert (!mips_opts.micromips);
8178       macro_build (NULL, "c2", "C", 3);
8179       break;
8180
8181     case M_MSGWAIT_T:
8182       gas_assert (!mips_opts.micromips);
8183       {
8184         unsigned long temp = (treg << 16) | 0x03;
8185         macro_build (NULL, "c2", "C", temp);
8186       }
8187       break;
8188
8189     case M_J_A:
8190       /* The j instruction may not be used in PIC code, since it
8191          requires an absolute address.  We convert it to a b
8192          instruction.  */
8193       if (mips_pic == NO_PIC)
8194         macro_build (&offset_expr, "j", "a");
8195       else
8196         macro_build (&offset_expr, "b", "p");
8197       break;
8198
8199       /* The jal instructions must be handled as macros because when
8200          generating PIC code they expand to multi-instruction
8201          sequences.  Normally they are simple instructions.  */
8202     case M_JALS_1:
8203       dreg = RA;
8204       /* Fall through.  */
8205     case M_JALS_2:
8206       gas_assert (mips_opts.micromips);
8207       jals = 1;
8208       goto jal;
8209     case M_JAL_1:
8210       dreg = RA;
8211       /* Fall through.  */
8212     case M_JAL_2:
8213     jal:
8214       if (mips_pic == NO_PIC)
8215         {
8216           s = jals ? "jalrs" : "jalr";
8217           if (mips_opts.micromips
8218               && dreg == RA
8219               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8220             macro_build (NULL, s, "mj", sreg);
8221           else
8222             macro_build (NULL, s, JALR_FMT, dreg, sreg);
8223         }
8224       else
8225         {
8226           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
8227                            && mips_cprestore_offset >= 0);
8228
8229           if (sreg != PIC_CALL_REG)
8230             as_warn (_("MIPS PIC call to register other than $25"));
8231
8232           s = (mips_opts.micromips && (!mips_opts.noreorder || cprestore)
8233                ? "jalrs" : "jalr");
8234           if (mips_opts.micromips
8235               && dreg == RA
8236               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8237             macro_build (NULL, s, "mj", sreg);
8238           else
8239             macro_build (NULL, s, JALR_FMT, dreg, sreg);
8240           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
8241             {
8242               if (mips_cprestore_offset < 0)
8243                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
8244               else
8245                 {
8246                   if (!mips_frame_reg_valid)
8247                     {
8248                       as_warn (_("No .frame pseudo-op used in PIC code"));
8249                       /* Quiet this warning.  */
8250                       mips_frame_reg_valid = 1;
8251                     }
8252                   if (!mips_cprestore_valid)
8253                     {
8254                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
8255                       /* Quiet this warning.  */
8256                       mips_cprestore_valid = 1;
8257                     }
8258                   if (mips_opts.noreorder)
8259                     macro_build (NULL, "nop", "");
8260                   expr1.X_add_number = mips_cprestore_offset;
8261                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
8262                                                 mips_gp_register,
8263                                                 mips_frame_reg,
8264                                                 HAVE_64BIT_ADDRESSES);
8265                 }
8266             }
8267         }
8268
8269       break;
8270
8271     case M_JALS_A:
8272       gas_assert (mips_opts.micromips);
8273       jals = 1;
8274       /* Fall through.  */
8275     case M_JAL_A:
8276       if (mips_pic == NO_PIC)
8277         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
8278       else if (mips_pic == SVR4_PIC)
8279         {
8280           /* If this is a reference to an external symbol, and we are
8281              using a small GOT, we want
8282                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
8283                nop
8284                jalr     $ra,$25
8285                nop
8286                lw       $gp,cprestore($sp)
8287              The cprestore value is set using the .cprestore
8288              pseudo-op.  If we are using a big GOT, we want
8289                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
8290                addu     $25,$25,$gp
8291                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
8292                nop
8293                jalr     $ra,$25
8294                nop
8295                lw       $gp,cprestore($sp)
8296              If the symbol is not external, we want
8297                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
8298                nop
8299                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
8300                jalr     $ra,$25
8301                nop
8302                lw $gp,cprestore($sp)
8303
8304              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
8305              sequences above, minus nops, unless the symbol is local,
8306              which enables us to use GOT_PAGE/GOT_OFST (big got) or
8307              GOT_DISP.  */
8308           if (HAVE_NEWABI)
8309             {
8310               if (!mips_big_got)
8311                 {
8312                   relax_start (offset_expr.X_add_symbol);
8313                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8314                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
8315                                mips_gp_register);
8316                   relax_switch ();
8317                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8318                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
8319                                mips_gp_register);
8320                   relax_end ();
8321                 }
8322               else
8323                 {
8324                   relax_start (offset_expr.X_add_symbol);
8325                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
8326                                BFD_RELOC_MIPS_CALL_HI16);
8327                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
8328                                PIC_CALL_REG, mips_gp_register);
8329                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8330                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
8331                                PIC_CALL_REG);
8332                   relax_switch ();
8333                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8334                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
8335                                mips_gp_register);
8336                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8337                                PIC_CALL_REG, PIC_CALL_REG,
8338                                BFD_RELOC_MIPS_GOT_OFST);
8339                   relax_end ();
8340                 }
8341
8342               macro_build_jalr (&offset_expr, 0);
8343             }
8344           else
8345             {
8346               relax_start (offset_expr.X_add_symbol);
8347               if (!mips_big_got)
8348                 {
8349                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8350                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
8351                                mips_gp_register);
8352                   load_delay_nop ();
8353                   relax_switch ();
8354                 }
8355               else
8356                 {
8357                   int gpdelay;
8358
8359                   gpdelay = reg_needs_delay (mips_gp_register);
8360                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
8361                                BFD_RELOC_MIPS_CALL_HI16);
8362                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
8363                                PIC_CALL_REG, mips_gp_register);
8364                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8365                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
8366                                PIC_CALL_REG);
8367                   load_delay_nop ();
8368                   relax_switch ();
8369                   if (gpdelay)
8370                     macro_build (NULL, "nop", "");
8371                 }
8372               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8373                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
8374                            mips_gp_register);
8375               load_delay_nop ();
8376               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8377                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
8378               relax_end ();
8379               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
8380
8381               if (mips_cprestore_offset < 0)
8382                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
8383               else
8384                 {
8385                   if (!mips_frame_reg_valid)
8386                     {
8387                       as_warn (_("No .frame pseudo-op used in PIC code"));
8388                       /* Quiet this warning.  */
8389                       mips_frame_reg_valid = 1;
8390                     }
8391                   if (!mips_cprestore_valid)
8392                     {
8393                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
8394                       /* Quiet this warning.  */
8395                       mips_cprestore_valid = 1;
8396                     }
8397                   if (mips_opts.noreorder)
8398                     macro_build (NULL, "nop", "");
8399                   expr1.X_add_number = mips_cprestore_offset;
8400                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
8401                                                 mips_gp_register,
8402                                                 mips_frame_reg,
8403                                                 HAVE_64BIT_ADDRESSES);
8404                 }
8405             }
8406         }
8407       else if (mips_pic == VXWORKS_PIC)
8408         as_bad (_("Non-PIC jump used in PIC library"));
8409       else
8410         abort ();
8411
8412       break;
8413
8414     case M_LBUE_AB:
8415       ab = 1;
8416     case M_LBUE_OB:
8417       s = "lbue";
8418       fmt = "t,+j(b)";
8419       offbits = 9;
8420       goto ld_st;
8421     case M_LHUE_AB:
8422       ab = 1;
8423     case M_LHUE_OB:
8424       s = "lhue";
8425       fmt = "t,+j(b)";
8426       offbits = 9;
8427       goto ld_st;
8428     case M_LBE_AB:
8429       ab = 1;
8430     case M_LBE_OB:
8431       s = "lbe";
8432       fmt = "t,+j(b)";
8433       offbits = 9;
8434       goto ld_st;
8435     case M_LHE_AB:
8436       ab = 1;
8437     case M_LHE_OB:
8438       s = "lhe";
8439       fmt = "t,+j(b)";
8440       offbits = 9;
8441       goto ld_st;
8442     case M_LLE_AB:
8443       ab = 1;
8444     case M_LLE_OB:
8445       s = "lle";
8446       fmt = "t,+j(b)";
8447       offbits = 9;
8448       goto ld_st;
8449     case M_LWE_AB:
8450       ab = 1;
8451     case M_LWE_OB:
8452       s = "lwe";
8453       fmt = "t,+j(b)";
8454       offbits = 9;
8455       goto ld_st;
8456     case M_LWLE_AB:
8457       ab = 1;
8458     case M_LWLE_OB:
8459       s = "lwle";
8460       fmt = "t,+j(b)";
8461       offbits = 9;
8462       goto ld_st;
8463     case M_LWRE_AB:
8464       ab = 1;
8465     case M_LWRE_OB:
8466       s = "lwre";
8467       fmt = "t,+j(b)";
8468       offbits = 9;
8469       goto ld_st;
8470     case M_SBE_AB:
8471       ab = 1;
8472     case M_SBE_OB:
8473       s = "sbe";
8474       fmt = "t,+j(b)";
8475       offbits = 9;
8476       goto ld_st;
8477     case M_SCE_AB:
8478       ab = 1;
8479     case M_SCE_OB:
8480       s = "sce";
8481       fmt = "t,+j(b)";
8482       offbits = 9;
8483       goto ld_st;
8484     case M_SHE_AB:
8485       ab = 1;
8486     case M_SHE_OB:
8487       s = "she";
8488       fmt = "t,+j(b)";
8489       offbits = 9;
8490       goto ld_st;
8491     case M_SWE_AB:
8492       ab = 1;
8493     case M_SWE_OB:
8494       s = "swe";
8495       fmt = "t,+j(b)";
8496       offbits = 9;
8497       goto ld_st;
8498     case M_SWLE_AB:
8499       ab = 1;
8500     case M_SWLE_OB:
8501       s = "swle";
8502       fmt = "t,+j(b)";
8503       offbits = 9;
8504       goto ld_st;
8505     case M_SWRE_AB:
8506       ab = 1;
8507     case M_SWRE_OB:
8508       s = "swre";
8509       fmt = "t,+j(b)";
8510       offbits = 9;
8511       goto ld_st;
8512     case M_ACLR_AB:
8513       ab = 1;
8514     case M_ACLR_OB:
8515       s = "aclr";
8516       treg = EXTRACT_OPERAND (mips_opts.micromips, 3BITPOS, *ip);
8517       fmt = "\\,~(b)";
8518       offbits = 12;
8519       goto ld_st;
8520     case M_ASET_AB:
8521       ab = 1;
8522     case M_ASET_OB:
8523       s = "aset";
8524       treg = EXTRACT_OPERAND (mips_opts.micromips, 3BITPOS, *ip);
8525       fmt = "\\,~(b)";
8526       offbits = 12;
8527       goto ld_st;
8528     case M_LB_AB:
8529       ab = 1;
8530       s = "lb";
8531       fmt = "t,o(b)";
8532       goto ld;
8533     case M_LBU_AB:
8534       ab = 1;
8535       s = "lbu";
8536       fmt = "t,o(b)";
8537       goto ld;
8538     case M_LH_AB:
8539       ab = 1;
8540       s = "lh";
8541       fmt = "t,o(b)";
8542       goto ld;
8543     case M_LHU_AB:
8544       ab = 1;
8545       s = "lhu";
8546       fmt = "t,o(b)";
8547       goto ld;
8548     case M_LW_AB:
8549       ab = 1;
8550       s = "lw";
8551       fmt = "t,o(b)";
8552       goto ld;
8553     case M_LWC0_AB:
8554       ab = 1;
8555       gas_assert (!mips_opts.micromips);
8556       s = "lwc0";
8557       fmt = "E,o(b)";
8558       /* Itbl support may require additional care here.  */
8559       coproc = 1;
8560       goto ld_st;
8561     case M_LWC1_AB:
8562       ab = 1;
8563       s = "lwc1";
8564       fmt = "T,o(b)";
8565       /* Itbl support may require additional care here.  */
8566       coproc = 1;
8567       goto ld_st;
8568     case M_LWC2_AB:
8569       ab = 1;
8570     case M_LWC2_OB:
8571       s = "lwc2";
8572       fmt = COP12_FMT;
8573       offbits = (mips_opts.micromips ? 12 : 16);
8574       /* Itbl support may require additional care here.  */
8575       coproc = 1;
8576       goto ld_st;
8577     case M_LWC3_AB:
8578       ab = 1;
8579       gas_assert (!mips_opts.micromips);
8580       s = "lwc3";
8581       fmt = "E,o(b)";
8582       /* Itbl support may require additional care here.  */
8583       coproc = 1;
8584       goto ld_st;
8585     case M_LWL_AB:
8586       ab = 1;
8587     case M_LWL_OB:
8588       s = "lwl";
8589       fmt = MEM12_FMT;
8590       offbits = (mips_opts.micromips ? 12 : 16);
8591       goto ld_st;
8592     case M_LWR_AB:
8593       ab = 1;
8594     case M_LWR_OB:
8595       s = "lwr";
8596       fmt = MEM12_FMT;
8597       offbits = (mips_opts.micromips ? 12 : 16);
8598       goto ld_st;
8599     case M_LDC1_AB:
8600       ab = 1;
8601       s = "ldc1";
8602       fmt = "T,o(b)";
8603       /* Itbl support may require additional care here.  */
8604       coproc = 1;
8605       goto ld_st;
8606     case M_LDC2_AB:
8607       ab = 1;
8608     case M_LDC2_OB:
8609       s = "ldc2";
8610       fmt = COP12_FMT;
8611       offbits = (mips_opts.micromips ? 12 : 16);
8612       /* Itbl support may require additional care here.  */
8613       coproc = 1;
8614       goto ld_st;
8615     case M_LQC2_AB:
8616       ab = 1;
8617       s = "lqc2";
8618       fmt = "E,o(b)";
8619       /* Itbl support may require additional care here.  */
8620       coproc = 1;
8621       goto ld_st;
8622     case M_LDC3_AB:
8623       ab = 1;
8624       s = "ldc3";
8625       fmt = "E,o(b)";
8626       /* Itbl support may require additional care here.  */
8627       coproc = 1;
8628       goto ld_st;
8629     case M_LDL_AB:
8630       ab = 1;
8631     case M_LDL_OB:
8632       s = "ldl";
8633       fmt = MEM12_FMT;
8634       offbits = (mips_opts.micromips ? 12 : 16);
8635       goto ld_st;
8636     case M_LDR_AB:
8637       ab = 1;
8638     case M_LDR_OB:
8639       s = "ldr";
8640       fmt = MEM12_FMT;
8641       offbits = (mips_opts.micromips ? 12 : 16);
8642       goto ld_st;
8643     case M_LL_AB:
8644       ab = 1;
8645     case M_LL_OB:
8646       s = "ll";
8647       fmt = MEM12_FMT;
8648       offbits = (mips_opts.micromips ? 12 : 16);
8649       goto ld;
8650     case M_LLD_AB:
8651       ab = 1;
8652     case M_LLD_OB:
8653       s = "lld";
8654       fmt = MEM12_FMT;
8655       offbits = (mips_opts.micromips ? 12 : 16);
8656       goto ld;
8657     case M_LWU_AB:
8658       ab = 1;
8659     case M_LWU_OB:
8660       s = "lwu";
8661       fmt = MEM12_FMT;
8662       offbits = (mips_opts.micromips ? 12 : 16);
8663       goto ld;
8664     case M_LWP_AB:
8665       ab = 1;
8666     case M_LWP_OB:
8667       gas_assert (mips_opts.micromips);
8668       s = "lwp";
8669       fmt = "t,~(b)";
8670       offbits = 12;
8671       lp = 1;
8672       goto ld;
8673     case M_LDP_AB:
8674       ab = 1;
8675     case M_LDP_OB:
8676       gas_assert (mips_opts.micromips);
8677       s = "ldp";
8678       fmt = "t,~(b)";
8679       offbits = 12;
8680       lp = 1;
8681       goto ld;
8682     case M_LWM_AB:
8683       ab = 1;
8684     case M_LWM_OB:
8685       gas_assert (mips_opts.micromips);
8686       s = "lwm";
8687       fmt = "n,~(b)";
8688       offbits = 12;
8689       goto ld_st;
8690     case M_LDM_AB:
8691       ab = 1;
8692     case M_LDM_OB:
8693       gas_assert (mips_opts.micromips);
8694       s = "ldm";
8695       fmt = "n,~(b)";
8696       offbits = 12;
8697       goto ld_st;
8698
8699     ld:
8700       /* We don't want to use $0 as tempreg.  */
8701       if (breg == treg + lp || treg + lp == ZERO)
8702         goto ld_st;
8703       else
8704         tempreg = treg + lp;
8705       goto ld_noat;
8706
8707     case M_SB_AB:
8708       ab = 1;
8709       s = "sb";
8710       fmt = "t,o(b)";
8711       goto ld_st;
8712     case M_SH_AB:
8713       ab = 1;
8714       s = "sh";
8715       fmt = "t,o(b)";
8716       goto ld_st;
8717     case M_SW_AB:
8718       ab = 1;
8719       s = "sw";
8720       fmt = "t,o(b)";
8721       goto ld_st;
8722     case M_SWC0_AB:
8723       ab = 1;
8724       gas_assert (!mips_opts.micromips);
8725       s = "swc0";
8726       fmt = "E,o(b)";
8727       /* Itbl support may require additional care here.  */
8728       coproc = 1;
8729       goto ld_st;
8730     case M_SWC1_AB:
8731       ab = 1;
8732       s = "swc1";
8733       fmt = "T,o(b)";
8734       /* Itbl support may require additional care here.  */
8735       coproc = 1;
8736       goto ld_st;
8737     case M_SWC2_AB:
8738       ab = 1;
8739     case M_SWC2_OB:
8740       s = "swc2";
8741       fmt = COP12_FMT;
8742       offbits = (mips_opts.micromips ? 12 : 16);
8743       /* Itbl support may require additional care here.  */
8744       coproc = 1;
8745       goto ld_st;
8746     case M_SWC3_AB:
8747       ab = 1;
8748       gas_assert (!mips_opts.micromips);
8749       s = "swc3";
8750       fmt = "E,o(b)";
8751       /* Itbl support may require additional care here.  */
8752       coproc = 1;
8753       goto ld_st;
8754     case M_SWL_AB:
8755       ab = 1;
8756     case M_SWL_OB:
8757       s = "swl";
8758       fmt = MEM12_FMT;
8759       offbits = (mips_opts.micromips ? 12 : 16);
8760       goto ld_st;
8761     case M_SWR_AB:
8762       ab = 1;
8763     case M_SWR_OB:
8764       s = "swr";
8765       fmt = MEM12_FMT;
8766       offbits = (mips_opts.micromips ? 12 : 16);
8767       goto ld_st;
8768     case M_SC_AB:
8769       ab = 1;
8770     case M_SC_OB:
8771       s = "sc";
8772       fmt = MEM12_FMT;
8773       offbits = (mips_opts.micromips ? 12 : 16);
8774       goto ld_st;
8775     case M_SCD_AB:
8776       ab = 1;
8777     case M_SCD_OB:
8778       s = "scd";
8779       fmt = MEM12_FMT;
8780       offbits = (mips_opts.micromips ? 12 : 16);
8781       goto ld_st;
8782     case M_CACHE_AB:
8783       ab = 1;
8784     case M_CACHE_OB:
8785       s = "cache";
8786       fmt = mips_opts.micromips ? "k,~(b)" : "k,o(b)";
8787       offbits = (mips_opts.micromips ? 12 : 16);
8788       goto ld_st;
8789     case M_CACHEE_AB:
8790       ab = 1;
8791     case M_CACHEE_OB:
8792       s = "cachee";
8793       fmt = "k,+j(b)";
8794       offbits = 9;
8795       goto ld_st;
8796     case M_PREF_AB:
8797       ab = 1;
8798     case M_PREF_OB:
8799       s = "pref";
8800       fmt = !mips_opts.micromips ? "k,o(b)" : "k,~(b)";
8801       offbits = (mips_opts.micromips ? 12 : 16);
8802       goto ld_st;
8803     case M_PREFE_AB:
8804       ab = 1;
8805     case M_PREFE_OB:
8806       s = "prefe";
8807       fmt = "k,+j(b)";
8808       offbits = 9;
8809       goto ld_st;
8810     case M_SDC1_AB:
8811       ab = 1;
8812       s = "sdc1";
8813       fmt = "T,o(b)";
8814       coproc = 1;
8815       /* Itbl support may require additional care here.  */
8816       goto ld_st;
8817     case M_SDC2_AB:
8818       ab = 1;
8819     case M_SDC2_OB:
8820       s = "sdc2";
8821       fmt = COP12_FMT;
8822       offbits = (mips_opts.micromips ? 12 : 16);
8823       /* Itbl support may require additional care here.  */
8824       coproc = 1;
8825       goto ld_st;
8826     case M_SQC2_AB:
8827       ab = 1;
8828       s = "sqc2";
8829       fmt = "E,o(b)";
8830       /* Itbl support may require additional care here.  */
8831       coproc = 1;
8832       goto ld_st;
8833     case M_SDC3_AB:
8834       ab = 1;
8835       gas_assert (!mips_opts.micromips);
8836       s = "sdc3";
8837       fmt = "E,o(b)";
8838       /* Itbl support may require additional care here.  */
8839       coproc = 1;
8840       goto ld_st;
8841     case M_SDL_AB:
8842       ab = 1;
8843     case M_SDL_OB:
8844       s = "sdl";
8845       fmt = MEM12_FMT;
8846       offbits = (mips_opts.micromips ? 12 : 16);
8847       goto ld_st;
8848     case M_SDR_AB:
8849       ab = 1;
8850     case M_SDR_OB:
8851       s = "sdr";
8852       fmt = MEM12_FMT;
8853       offbits = (mips_opts.micromips ? 12 : 16);
8854       goto ld_st;
8855     case M_SWP_AB:
8856       ab = 1;
8857     case M_SWP_OB:
8858       gas_assert (mips_opts.micromips);
8859       s = "swp";
8860       fmt = "t,~(b)";
8861       offbits = 12;
8862       goto ld_st;
8863     case M_SDP_AB:
8864       ab = 1;
8865     case M_SDP_OB:
8866       gas_assert (mips_opts.micromips);
8867       s = "sdp";
8868       fmt = "t,~(b)";
8869       offbits = 12;
8870       goto ld_st;
8871     case M_SWM_AB:
8872       ab = 1;
8873     case M_SWM_OB:
8874       gas_assert (mips_opts.micromips);
8875       s = "swm";
8876       fmt = "n,~(b)";
8877       offbits = 12;
8878       goto ld_st;
8879     case M_SDM_AB:
8880       ab = 1;
8881     case M_SDM_OB:
8882       gas_assert (mips_opts.micromips);
8883       s = "sdm";
8884       fmt = "n,~(b)";
8885       offbits = 12;
8886
8887     ld_st:
8888       tempreg = AT;
8889       used_at = 1;
8890     ld_noat:
8891       if (offset_expr.X_op != O_constant
8892           && offset_expr.X_op != O_symbol)
8893         {
8894           as_bad (_("Expression too complex"));
8895           offset_expr.X_op = O_constant;
8896         }
8897
8898       if (HAVE_32BIT_ADDRESSES
8899           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
8900         {
8901           char value [32];
8902
8903           sprintf_vma (value, offset_expr.X_add_number);
8904           as_bad (_("Number (0x%s) larger than 32 bits"), value);
8905         }
8906
8907       /* A constant expression in PIC code can be handled just as it
8908          is in non PIC code.  */
8909       if (offset_expr.X_op == O_constant)
8910         {
8911           int hipart = 0;
8912
8913           expr1.X_add_number = offset_expr.X_add_number;
8914           normalize_address_expr (&expr1);
8915           if ((offbits == 0 || offbits == 16)
8916               && !IS_SEXT_16BIT_NUM (expr1.X_add_number))
8917             {
8918               expr1.X_add_number = ((expr1.X_add_number + 0x8000)
8919                                     & ~(bfd_vma) 0xffff);
8920               hipart = 1;
8921             }
8922           else if (offbits == 12 && !IS_SEXT_12BIT_NUM (expr1.X_add_number))
8923             {
8924               expr1.X_add_number = ((expr1.X_add_number + 0x800)
8925                                     & ~(bfd_vma) 0xfff);
8926               hipart = 1;
8927             }
8928           else if (offbits == 9 && !IS_SEXT_9BIT_NUM (expr1.X_add_number))
8929             {
8930               expr1.X_add_number = ((expr1.X_add_number + 0x100)
8931                                     & ~(bfd_vma) 0x1ff);
8932               hipart = 1;
8933             }
8934           if (hipart)
8935             {
8936               load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
8937               if (breg != 0)
8938                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8939                              tempreg, tempreg, breg);
8940               breg = tempreg;
8941             }
8942           if (offbits == 0)
8943             {
8944               if (offset_expr.X_add_number == 0)
8945                 tempreg = breg;
8946               else
8947                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
8948                              "t,r,j", tempreg, breg, BFD_RELOC_LO16);
8949               macro_build (NULL, s, fmt, treg, tempreg);
8950             }
8951           else if (offbits == 16)
8952             macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16, breg);
8953           else
8954             macro_build (NULL, s, fmt,
8955                          treg, (unsigned long) offset_expr.X_add_number, breg);
8956         }
8957       else if (offbits != 16)
8958         {
8959           /* The offset field is too narrow to be used for a low-part
8960              relocation, so load the whole address into the auxillary
8961              register.  In the case of "A(b)" addresses, we first load
8962              absolute address "A" into the register and then add base
8963              register "b".  In the case of "o(b)" addresses, we simply
8964              need to add 16-bit offset "o" to base register "b", and
8965              offset_reloc already contains the relocations associated
8966              with "o".  */
8967           if (ab)
8968             {
8969               load_address (tempreg, &offset_expr, &used_at);
8970               if (breg != 0)
8971                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8972                              tempreg, tempreg, breg);
8973             }
8974           else
8975             macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8976                          tempreg, breg, -1,
8977                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
8978           expr1.X_add_number = 0;
8979           if (offbits == 0)
8980             macro_build (NULL, s, fmt, treg, tempreg);
8981           else
8982             macro_build (NULL, s, fmt,
8983                          treg, (unsigned long) expr1.X_add_number, tempreg);
8984         }
8985       else if (mips_pic == NO_PIC)
8986         {
8987           /* If this is a reference to a GP relative symbol, and there
8988              is no base register, we want
8989                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
8990              Otherwise, if there is no base register, we want
8991                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
8992                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8993              If we have a constant, we need two instructions anyhow,
8994              so we always use the latter form.
8995
8996              If we have a base register, and this is a reference to a
8997              GP relative symbol, we want
8998                addu     $tempreg,$breg,$gp
8999                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_GPREL16)
9000              Otherwise we want
9001                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
9002                addu     $tempreg,$tempreg,$breg
9003                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9004              With a constant we always use the latter case.
9005
9006              With 64bit address space and no base register and $at usable,
9007              we want
9008                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9009                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9010                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9011                dsll32   $tempreg,0
9012                daddu    $tempreg,$at
9013                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9014              If we have a base register, we want
9015                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9016                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9017                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9018                daddu    $at,$breg
9019                dsll32   $tempreg,0
9020                daddu    $tempreg,$at
9021                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9022
9023              Without $at we can't generate the optimal path for superscalar
9024              processors here since this would require two temporary registers.
9025                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9026                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9027                dsll     $tempreg,16
9028                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9029                dsll     $tempreg,16
9030                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9031              If we have a base register, we want
9032                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9033                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9034                dsll     $tempreg,16
9035                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9036                dsll     $tempreg,16
9037                daddu    $tempreg,$tempreg,$breg
9038                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9039
9040              For GP relative symbols in 64bit address space we can use
9041              the same sequence as in 32bit address space.  */
9042           if (HAVE_64BIT_SYMBOLS)
9043             {
9044               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9045                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9046                 {
9047                   relax_start (offset_expr.X_add_symbol);
9048                   if (breg == 0)
9049                     {
9050                       macro_build (&offset_expr, s, fmt, treg,
9051                                    BFD_RELOC_GPREL16, mips_gp_register);
9052                     }
9053                   else
9054                     {
9055                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9056                                    tempreg, breg, mips_gp_register);
9057                       macro_build (&offset_expr, s, fmt, treg,
9058                                    BFD_RELOC_GPREL16, tempreg);
9059                     }
9060                   relax_switch ();
9061                 }
9062
9063               if (used_at == 0 && mips_opts.at)
9064                 {
9065                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
9066                                BFD_RELOC_MIPS_HIGHEST);
9067                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
9068                                BFD_RELOC_HI16_S);
9069                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
9070                                tempreg, BFD_RELOC_MIPS_HIGHER);
9071                   if (breg != 0)
9072                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
9073                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
9074                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
9075                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16,
9076                                tempreg);
9077                   used_at = 1;
9078                 }
9079               else
9080                 {
9081                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
9082                                BFD_RELOC_MIPS_HIGHEST);
9083                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
9084                                tempreg, BFD_RELOC_MIPS_HIGHER);
9085                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9086                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
9087                                tempreg, BFD_RELOC_HI16_S);
9088                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9089                   if (breg != 0)
9090                     macro_build (NULL, "daddu", "d,v,t",
9091                                  tempreg, tempreg, breg);
9092                   macro_build (&offset_expr, s, fmt, treg,
9093                                BFD_RELOC_LO16, tempreg);
9094                 }
9095
9096               if (mips_relax.sequence)
9097                 relax_end ();
9098               break;
9099             }
9100
9101           if (breg == 0)
9102             {
9103               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9104                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9105                 {
9106                   relax_start (offset_expr.X_add_symbol);
9107                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_GPREL16,
9108                                mips_gp_register);
9109                   relax_switch ();
9110                 }
9111               macro_build_lui (&offset_expr, tempreg);
9112               macro_build (&offset_expr, s, fmt, treg,
9113                            BFD_RELOC_LO16, tempreg);
9114               if (mips_relax.sequence)
9115                 relax_end ();
9116             }
9117           else
9118             {
9119               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9120                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9121                 {
9122                   relax_start (offset_expr.X_add_symbol);
9123                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9124                                tempreg, breg, mips_gp_register);
9125                   macro_build (&offset_expr, s, fmt, treg,
9126                                BFD_RELOC_GPREL16, tempreg);
9127                   relax_switch ();
9128                 }
9129               macro_build_lui (&offset_expr, tempreg);
9130               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9131                            tempreg, tempreg, breg);
9132               macro_build (&offset_expr, s, fmt, treg,
9133                            BFD_RELOC_LO16, tempreg);
9134               if (mips_relax.sequence)
9135                 relax_end ();
9136             }
9137         }
9138       else if (!mips_big_got)
9139         {
9140           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
9141
9142           /* If this is a reference to an external symbol, we want
9143                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9144                nop
9145                <op>     $treg,0($tempreg)
9146              Otherwise we want
9147                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9148                nop
9149                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9150                <op>     $treg,0($tempreg)
9151
9152              For NewABI, we want
9153                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
9154                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
9155
9156              If there is a base register, we add it to $tempreg before
9157              the <op>.  If there is a constant, we stick it in the
9158              <op> instruction.  We don't handle constants larger than
9159              16 bits, because we have no way to load the upper 16 bits
9160              (actually, we could handle them for the subset of cases
9161              in which we are not using $at).  */
9162           gas_assert (offset_expr.X_op == O_symbol);
9163           if (HAVE_NEWABI)
9164             {
9165               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9166                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9167               if (breg != 0)
9168                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9169                              tempreg, tempreg, breg);
9170               macro_build (&offset_expr, s, fmt, treg,
9171                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
9172               break;
9173             }
9174           expr1.X_add_number = offset_expr.X_add_number;
9175           offset_expr.X_add_number = 0;
9176           if (expr1.X_add_number < -0x8000
9177               || expr1.X_add_number >= 0x8000)
9178             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9179           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9180                        lw_reloc_type, mips_gp_register);
9181           load_delay_nop ();
9182           relax_start (offset_expr.X_add_symbol);
9183           relax_switch ();
9184           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
9185                        tempreg, BFD_RELOC_LO16);
9186           relax_end ();
9187           if (breg != 0)
9188             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9189                          tempreg, tempreg, breg);
9190           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
9191         }
9192       else if (mips_big_got && !HAVE_NEWABI)
9193         {
9194           int gpdelay;
9195
9196           /* If this is a reference to an external symbol, we want
9197                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
9198                addu     $tempreg,$tempreg,$gp
9199                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
9200                <op>     $treg,0($tempreg)
9201              Otherwise we want
9202                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9203                nop
9204                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9205                <op>     $treg,0($tempreg)
9206              If there is a base register, we add it to $tempreg before
9207              the <op>.  If there is a constant, we stick it in the
9208              <op> instruction.  We don't handle constants larger than
9209              16 bits, because we have no way to load the upper 16 bits
9210              (actually, we could handle them for the subset of cases
9211              in which we are not using $at).  */
9212           gas_assert (offset_expr.X_op == O_symbol);
9213           expr1.X_add_number = offset_expr.X_add_number;
9214           offset_expr.X_add_number = 0;
9215           if (expr1.X_add_number < -0x8000
9216               || expr1.X_add_number >= 0x8000)
9217             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9218           gpdelay = reg_needs_delay (mips_gp_register);
9219           relax_start (offset_expr.X_add_symbol);
9220           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
9221                        BFD_RELOC_MIPS_GOT_HI16);
9222           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
9223                        mips_gp_register);
9224           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9225                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
9226           relax_switch ();
9227           if (gpdelay)
9228             macro_build (NULL, "nop", "");
9229           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9230                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9231           load_delay_nop ();
9232           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
9233                        tempreg, BFD_RELOC_LO16);
9234           relax_end ();
9235
9236           if (breg != 0)
9237             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9238                          tempreg, tempreg, breg);
9239           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
9240         }
9241       else if (mips_big_got && HAVE_NEWABI)
9242         {
9243           /* If this is a reference to an external symbol, we want
9244                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
9245                add      $tempreg,$tempreg,$gp
9246                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
9247                <op>     $treg,<ofst>($tempreg)
9248              Otherwise, for local symbols, we want:
9249                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
9250                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
9251           gas_assert (offset_expr.X_op == O_symbol);
9252           expr1.X_add_number = offset_expr.X_add_number;
9253           offset_expr.X_add_number = 0;
9254           if (expr1.X_add_number < -0x8000
9255               || expr1.X_add_number >= 0x8000)
9256             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9257           relax_start (offset_expr.X_add_symbol);
9258           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
9259                        BFD_RELOC_MIPS_GOT_HI16);
9260           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
9261                        mips_gp_register);
9262           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9263                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
9264           if (breg != 0)
9265             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9266                          tempreg, tempreg, breg);
9267           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
9268
9269           relax_switch ();
9270           offset_expr.X_add_number = expr1.X_add_number;
9271           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9272                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9273           if (breg != 0)
9274             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9275                          tempreg, tempreg, breg);
9276           macro_build (&offset_expr, s, fmt, treg,
9277                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
9278           relax_end ();
9279         }
9280       else
9281         abort ();
9282
9283       break;
9284
9285     case M_LI:
9286     case M_LI_S:
9287       load_register (treg, &imm_expr, 0);
9288       break;
9289
9290     case M_DLI:
9291       load_register (treg, &imm_expr, 1);
9292       break;
9293
9294     case M_LI_SS:
9295       if (imm_expr.X_op == O_constant)
9296         {
9297           used_at = 1;
9298           load_register (AT, &imm_expr, 0);
9299           macro_build (NULL, "mtc1", "t,G", AT, treg);
9300           break;
9301         }
9302       else
9303         {
9304           gas_assert (offset_expr.X_op == O_symbol
9305                       && strcmp (segment_name (S_GET_SEGMENT
9306                                                (offset_expr.X_add_symbol)),
9307                                  ".lit4") == 0
9308                       && offset_expr.X_add_number == 0);
9309           macro_build (&offset_expr, "lwc1", "T,o(b)", treg,
9310                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
9311           break;
9312         }
9313
9314     case M_LI_D:
9315       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
9316          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
9317          order 32 bits of the value and the low order 32 bits are either
9318          zero or in OFFSET_EXPR.  */
9319       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
9320         {
9321           if (HAVE_64BIT_GPRS)
9322             load_register (treg, &imm_expr, 1);
9323           else
9324             {
9325               int hreg, lreg;
9326
9327               if (target_big_endian)
9328                 {
9329                   hreg = treg;
9330                   lreg = treg + 1;
9331                 }
9332               else
9333                 {
9334                   hreg = treg + 1;
9335                   lreg = treg;
9336                 }
9337
9338               if (hreg <= 31)
9339                 load_register (hreg, &imm_expr, 0);
9340               if (lreg <= 31)
9341                 {
9342                   if (offset_expr.X_op == O_absent)
9343                     move_register (lreg, 0);
9344                   else
9345                     {
9346                       gas_assert (offset_expr.X_op == O_constant);
9347                       load_register (lreg, &offset_expr, 0);
9348                     }
9349                 }
9350             }
9351           break;
9352         }
9353
9354       /* We know that sym is in the .rdata section.  First we get the
9355          upper 16 bits of the address.  */
9356       if (mips_pic == NO_PIC)
9357         {
9358           macro_build_lui (&offset_expr, AT);
9359           used_at = 1;
9360         }
9361       else
9362         {
9363           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
9364                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9365           used_at = 1;
9366         }
9367
9368       /* Now we load the register(s).  */
9369       if (HAVE_64BIT_GPRS)
9370         {
9371           used_at = 1;
9372           macro_build (&offset_expr, "ld", "t,o(b)", treg, BFD_RELOC_LO16, AT);
9373         }
9374       else
9375         {
9376           used_at = 1;
9377           macro_build (&offset_expr, "lw", "t,o(b)", treg, BFD_RELOC_LO16, AT);
9378           if (treg != RA)
9379             {
9380               /* FIXME: How in the world do we deal with the possible
9381                  overflow here?  */
9382               offset_expr.X_add_number += 4;
9383               macro_build (&offset_expr, "lw", "t,o(b)",
9384                            treg + 1, BFD_RELOC_LO16, AT);
9385             }
9386         }
9387       break;
9388
9389     case M_LI_DD:
9390       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
9391          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
9392          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
9393          the value and the low order 32 bits are either zero or in
9394          OFFSET_EXPR.  */
9395       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
9396         {
9397           used_at = 1;
9398           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
9399           if (HAVE_64BIT_FPRS)
9400             {
9401               gas_assert (HAVE_64BIT_GPRS);
9402               macro_build (NULL, "dmtc1", "t,S", AT, treg);
9403             }
9404           else
9405             {
9406               macro_build (NULL, "mtc1", "t,G", AT, treg + 1);
9407               if (offset_expr.X_op == O_absent)
9408                 macro_build (NULL, "mtc1", "t,G", 0, treg);
9409               else
9410                 {
9411                   gas_assert (offset_expr.X_op == O_constant);
9412                   load_register (AT, &offset_expr, 0);
9413                   macro_build (NULL, "mtc1", "t,G", AT, treg);
9414                 }
9415             }
9416           break;
9417         }
9418
9419       gas_assert (offset_expr.X_op == O_symbol
9420                   && offset_expr.X_add_number == 0);
9421       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
9422       if (strcmp (s, ".lit8") == 0)
9423         {
9424           if (CPU_HAS_LDC1_SDC1 (mips_opts.arch) || mips_opts.micromips)
9425             {
9426               macro_build (&offset_expr, "ldc1", "T,o(b)", treg,
9427                            BFD_RELOC_MIPS_LITERAL, mips_gp_register);
9428               break;
9429             }
9430           breg = mips_gp_register;
9431           r = BFD_RELOC_MIPS_LITERAL;
9432           goto dob;
9433         }
9434       else
9435         {
9436           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
9437           used_at = 1;
9438           if (mips_pic != NO_PIC)
9439             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
9440                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
9441           else
9442             {
9443               /* FIXME: This won't work for a 64 bit address.  */
9444               macro_build_lui (&offset_expr, AT);
9445             }
9446
9447           if (CPU_HAS_LDC1_SDC1 (mips_opts.arch) || mips_opts.micromips)
9448             {
9449               macro_build (&offset_expr, "ldc1", "T,o(b)",
9450                            treg, BFD_RELOC_LO16, AT);
9451               break;
9452             }
9453           breg = AT;
9454           r = BFD_RELOC_LO16;
9455           goto dob;
9456         }
9457
9458     case M_L_DOB:
9459       /* Even on a big endian machine $fn comes before $fn+1.  We have
9460          to adjust when loading from memory.  */
9461       r = BFD_RELOC_LO16;
9462     dob:
9463       gas_assert (!mips_opts.micromips);
9464       gas_assert (!CPU_HAS_LDC1_SDC1 (mips_opts.arch));
9465       macro_build (&offset_expr, "lwc1", "T,o(b)",
9466                    target_big_endian ? treg + 1 : treg, r, breg);
9467       /* FIXME: A possible overflow which I don't know how to deal
9468          with.  */
9469       offset_expr.X_add_number += 4;
9470       macro_build (&offset_expr, "lwc1", "T,o(b)",
9471                    target_big_endian ? treg : treg + 1, r, breg);
9472       break;
9473
9474     case M_S_DOB:
9475       gas_assert (!mips_opts.micromips);
9476       gas_assert (!CPU_HAS_LDC1_SDC1 (mips_opts.arch));
9477       /* Even on a big endian machine $fn comes before $fn+1.  We have
9478          to adjust when storing to memory.  */
9479       macro_build (&offset_expr, "swc1", "T,o(b)",
9480                    target_big_endian ? treg + 1 : treg, BFD_RELOC_LO16, breg);
9481       offset_expr.X_add_number += 4;
9482       macro_build (&offset_expr, "swc1", "T,o(b)",
9483                    target_big_endian ? treg : treg + 1, BFD_RELOC_LO16, breg);
9484       break;
9485
9486     case M_L_DAB:
9487       gas_assert (!mips_opts.micromips);
9488       /*
9489        * The MIPS assembler seems to check for X_add_number not
9490        * being double aligned and generating:
9491        *        lui     at,%hi(foo+1)
9492        *        addu    at,at,v1
9493        *        addiu   at,at,%lo(foo+1)
9494        *        lwc1    f2,0(at)
9495        *        lwc1    f3,4(at)
9496        * But, the resulting address is the same after relocation so why
9497        * generate the extra instruction?
9498        */
9499       /* Itbl support may require additional care here.  */
9500       coproc = 1;
9501       fmt = "T,o(b)";
9502       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
9503         {
9504           s = "ldc1";
9505           goto ld_st;
9506         }
9507       s = "lwc1";
9508       goto ldd_std;
9509
9510     case M_S_DAB:
9511       gas_assert (!mips_opts.micromips);
9512       /* Itbl support may require additional care here.  */
9513       coproc = 1;
9514       fmt = "T,o(b)";
9515       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
9516         {
9517           s = "sdc1";
9518           goto ld_st;
9519         }
9520       s = "swc1";
9521       goto ldd_std;
9522
9523     case M_LQ_AB:
9524       fmt = "t,o(b)";
9525       s = "lq";
9526       goto ld;
9527
9528     case M_SQ_AB:
9529       fmt = "t,o(b)";
9530       s = "sq";
9531       goto ld_st;
9532
9533     case M_LD_AB:
9534       fmt = "t,o(b)";
9535       if (HAVE_64BIT_GPRS)
9536         {
9537           s = "ld";
9538           goto ld;
9539         }
9540       s = "lw";
9541       goto ldd_std;
9542
9543     case M_SD_AB:
9544       fmt = "t,o(b)";
9545       if (HAVE_64BIT_GPRS)
9546         {
9547           s = "sd";
9548           goto ld_st;
9549         }
9550       s = "sw";
9551
9552     ldd_std:
9553       if (offset_expr.X_op != O_symbol
9554           && offset_expr.X_op != O_constant)
9555         {
9556           as_bad (_("Expression too complex"));
9557           offset_expr.X_op = O_constant;
9558         }
9559
9560       if (HAVE_32BIT_ADDRESSES
9561           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
9562         {
9563           char value [32];
9564
9565           sprintf_vma (value, offset_expr.X_add_number);
9566           as_bad (_("Number (0x%s) larger than 32 bits"), value);
9567         }
9568
9569       /* Even on a big endian machine $fn comes before $fn+1.  We have
9570          to adjust when loading from memory.  We set coproc if we must
9571          load $fn+1 first.  */
9572       /* Itbl support may require additional care here.  */
9573       if (!target_big_endian)
9574         coproc = 0;
9575
9576       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
9577         {
9578           /* If this is a reference to a GP relative symbol, we want
9579                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
9580                <op>     $treg+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
9581              If we have a base register, we use this
9582                addu     $at,$breg,$gp
9583                <op>     $treg,<sym>($at)        (BFD_RELOC_GPREL16)
9584                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
9585              If this is not a GP relative symbol, we want
9586                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9587                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
9588                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
9589              If there is a base register, we add it to $at after the
9590              lui instruction.  If there is a constant, we always use
9591              the last case.  */
9592           if (offset_expr.X_op == O_symbol
9593               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9594               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9595             {
9596               relax_start (offset_expr.X_add_symbol);
9597               if (breg == 0)
9598                 {
9599                   tempreg = mips_gp_register;
9600                 }
9601               else
9602                 {
9603                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9604                                AT, breg, mips_gp_register);
9605                   tempreg = AT;
9606                   used_at = 1;
9607                 }
9608
9609               /* Itbl support may require additional care here.  */
9610               macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
9611                            BFD_RELOC_GPREL16, tempreg);
9612               offset_expr.X_add_number += 4;
9613
9614               /* Set mips_optimize to 2 to avoid inserting an
9615                  undesired nop.  */
9616               hold_mips_optimize = mips_optimize;
9617               mips_optimize = 2;
9618               /* Itbl support may require additional care here.  */
9619               macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
9620                            BFD_RELOC_GPREL16, tempreg);
9621               mips_optimize = hold_mips_optimize;
9622
9623               relax_switch ();
9624
9625               offset_expr.X_add_number -= 4;
9626             }
9627           used_at = 1;
9628           macro_build_lui (&offset_expr, AT);
9629           if (breg != 0)
9630             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
9631           /* Itbl support may require additional care here.  */
9632           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
9633                        BFD_RELOC_LO16, AT);
9634           /* FIXME: How do we handle overflow here?  */
9635           offset_expr.X_add_number += 4;
9636           /* Itbl support may require additional care here.  */
9637           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
9638                        BFD_RELOC_LO16, AT);
9639           if (mips_relax.sequence)
9640             relax_end ();
9641         }
9642       else if (!mips_big_got)
9643         {
9644           /* If this is a reference to an external symbol, we want
9645                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
9646                nop
9647                <op>     $treg,0($at)
9648                <op>     $treg+1,4($at)
9649              Otherwise we want
9650                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
9651                nop
9652                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
9653                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
9654              If there is a base register we add it to $at before the
9655              lwc1 instructions.  If there is a constant we include it
9656              in the lwc1 instructions.  */
9657           used_at = 1;
9658           expr1.X_add_number = offset_expr.X_add_number;
9659           if (expr1.X_add_number < -0x8000
9660               || expr1.X_add_number >= 0x8000 - 4)
9661             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9662           load_got_offset (AT, &offset_expr);
9663           load_delay_nop ();
9664           if (breg != 0)
9665             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
9666
9667           /* Set mips_optimize to 2 to avoid inserting an undesired
9668              nop.  */
9669           hold_mips_optimize = mips_optimize;
9670           mips_optimize = 2;
9671
9672           /* Itbl support may require additional care here.  */
9673           relax_start (offset_expr.X_add_symbol);
9674           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
9675                        BFD_RELOC_LO16, AT);
9676           expr1.X_add_number += 4;
9677           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
9678                        BFD_RELOC_LO16, AT);
9679           relax_switch ();
9680           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
9681                        BFD_RELOC_LO16, AT);
9682           offset_expr.X_add_number += 4;
9683           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
9684                        BFD_RELOC_LO16, AT);
9685           relax_end ();
9686
9687           mips_optimize = hold_mips_optimize;
9688         }
9689       else if (mips_big_got)
9690         {
9691           int gpdelay;
9692
9693           /* If this is a reference to an external symbol, we want
9694                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
9695                addu     $at,$at,$gp
9696                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
9697                nop
9698                <op>     $treg,0($at)
9699                <op>     $treg+1,4($at)
9700              Otherwise we want
9701                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
9702                nop
9703                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
9704                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
9705              If there is a base register we add it to $at before the
9706              lwc1 instructions.  If there is a constant we include it
9707              in the lwc1 instructions.  */
9708           used_at = 1;
9709           expr1.X_add_number = offset_expr.X_add_number;
9710           offset_expr.X_add_number = 0;
9711           if (expr1.X_add_number < -0x8000
9712               || expr1.X_add_number >= 0x8000 - 4)
9713             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9714           gpdelay = reg_needs_delay (mips_gp_register);
9715           relax_start (offset_expr.X_add_symbol);
9716           macro_build (&offset_expr, "lui", LUI_FMT,
9717                        AT, BFD_RELOC_MIPS_GOT_HI16);
9718           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9719                        AT, AT, mips_gp_register);
9720           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9721                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
9722           load_delay_nop ();
9723           if (breg != 0)
9724             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
9725           /* Itbl support may require additional care here.  */
9726           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
9727                        BFD_RELOC_LO16, AT);
9728           expr1.X_add_number += 4;
9729
9730           /* Set mips_optimize to 2 to avoid inserting an undesired
9731              nop.  */
9732           hold_mips_optimize = mips_optimize;
9733           mips_optimize = 2;
9734           /* Itbl support may require additional care here.  */
9735           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
9736                        BFD_RELOC_LO16, AT);
9737           mips_optimize = hold_mips_optimize;
9738           expr1.X_add_number -= 4;
9739
9740           relax_switch ();
9741           offset_expr.X_add_number = expr1.X_add_number;
9742           if (gpdelay)
9743             macro_build (NULL, "nop", "");
9744           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
9745                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9746           load_delay_nop ();
9747           if (breg != 0)
9748             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
9749           /* Itbl support may require additional care here.  */
9750           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
9751                        BFD_RELOC_LO16, AT);
9752           offset_expr.X_add_number += 4;
9753
9754           /* Set mips_optimize to 2 to avoid inserting an undesired
9755              nop.  */
9756           hold_mips_optimize = mips_optimize;
9757           mips_optimize = 2;
9758           /* Itbl support may require additional care here.  */
9759           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
9760                        BFD_RELOC_LO16, AT);
9761           mips_optimize = hold_mips_optimize;
9762           relax_end ();
9763         }
9764       else
9765         abort ();
9766
9767       break;
9768
9769     case M_LD_OB:
9770       s = HAVE_64BIT_GPRS ? "ld" : "lw";
9771       goto sd_ob;
9772     case M_SD_OB:
9773       s = HAVE_64BIT_GPRS ? "sd" : "sw";
9774     sd_ob:
9775       macro_build (&offset_expr, s, "t,o(b)", treg,
9776                    -1, offset_reloc[0], offset_reloc[1], offset_reloc[2],
9777                    breg);
9778       if (!HAVE_64BIT_GPRS)
9779         {
9780           offset_expr.X_add_number += 4;
9781           macro_build (&offset_expr, s, "t,o(b)", treg + 1,
9782                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2],
9783                        breg);
9784         }
9785       break;
9786
9787         
9788     case M_SAA_AB:
9789       ab = 1;
9790     case M_SAA_OB:
9791       s = "saa";
9792       offbits = 0;
9793       fmt = "t,(b)";
9794       goto ld_st;
9795     case M_SAAD_AB:
9796       ab = 1;
9797     case M_SAAD_OB:
9798       s = "saad";
9799       offbits = 0;
9800       fmt = "t,(b)";
9801       goto ld_st;
9802
9803    /* New code added to support COPZ instructions.
9804       This code builds table entries out of the macros in mip_opcodes.
9805       R4000 uses interlocks to handle coproc delays.
9806       Other chips (like the R3000) require nops to be inserted for delays.
9807
9808       FIXME: Currently, we require that the user handle delays.
9809       In order to fill delay slots for non-interlocked chips,
9810       we must have a way to specify delays based on the coprocessor.
9811       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
9812       What are the side-effects of the cop instruction?
9813       What cache support might we have and what are its effects?
9814       Both coprocessor & memory require delays. how long???
9815       What registers are read/set/modified?
9816
9817       If an itbl is provided to interpret cop instructions,
9818       this knowledge can be encoded in the itbl spec.  */
9819
9820     case M_COP0:
9821       s = "c0";
9822       goto copz;
9823     case M_COP1:
9824       s = "c1";
9825       goto copz;
9826     case M_COP2:
9827       s = "c2";
9828       goto copz;
9829     case M_COP3:
9830       s = "c3";
9831     copz:
9832       gas_assert (!mips_opts.micromips);
9833       /* For now we just do C (same as Cz).  The parameter will be
9834          stored in insn_opcode by mips_ip.  */
9835       macro_build (NULL, s, "C", ip->insn_opcode);
9836       break;
9837
9838     case M_MOVE:
9839       move_register (dreg, sreg);
9840       break;
9841
9842     case M_DMUL:
9843       dbl = 1;
9844     case M_MUL:
9845       if (mips_opts.arch == CPU_R5900)
9846         {
9847           macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", dreg, sreg, treg);
9848         }
9849       else
9850         {
9851       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", sreg, treg);
9852       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9853         }
9854       break;
9855
9856     case M_DMUL_I:
9857       dbl = 1;
9858     case M_MUL_I:
9859       /* The MIPS assembler some times generates shifts and adds.  I'm
9860          not trying to be that fancy. GCC should do this for us
9861          anyway.  */
9862       used_at = 1;
9863       load_register (AT, &imm_expr, dbl);
9864       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, AT);
9865       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9866       break;
9867
9868     case M_DMULO_I:
9869       dbl = 1;
9870     case M_MULO_I:
9871       imm = 1;
9872       goto do_mulo;
9873
9874     case M_DMULO:
9875       dbl = 1;
9876     case M_MULO:
9877     do_mulo:
9878       start_noreorder ();
9879       used_at = 1;
9880       if (imm)
9881         load_register (AT, &imm_expr, dbl);
9882       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, imm ? AT : treg);
9883       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9884       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, dreg, dreg, RA);
9885       macro_build (NULL, "mfhi", MFHL_FMT, AT);
9886       if (mips_trap)
9887         macro_build (NULL, "tne", TRAP_FMT, dreg, AT, 6);
9888       else
9889         {
9890           if (mips_opts.micromips)
9891             micromips_label_expr (&label_expr);
9892           else
9893             label_expr.X_add_number = 8;
9894           macro_build (&label_expr, "beq", "s,t,p", dreg, AT);
9895           macro_build (NULL, "nop", "");
9896           macro_build (NULL, "break", BRK_FMT, 6);
9897           if (mips_opts.micromips)
9898             micromips_add_label ();
9899         }
9900       end_noreorder ();
9901       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9902       break;
9903
9904     case M_DMULOU_I:
9905       dbl = 1;
9906     case M_MULOU_I:
9907       imm = 1;
9908       goto do_mulou;
9909
9910     case M_DMULOU:
9911       dbl = 1;
9912     case M_MULOU:
9913     do_mulou:
9914       start_noreorder ();
9915       used_at = 1;
9916       if (imm)
9917         load_register (AT, &imm_expr, dbl);
9918       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
9919                    sreg, imm ? AT : treg);
9920       macro_build (NULL, "mfhi", MFHL_FMT, AT);
9921       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9922       if (mips_trap)
9923         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
9924       else
9925         {
9926           if (mips_opts.micromips)
9927             micromips_label_expr (&label_expr);
9928           else
9929             label_expr.X_add_number = 8;
9930           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
9931           macro_build (NULL, "nop", "");
9932           macro_build (NULL, "break", BRK_FMT, 6);
9933           if (mips_opts.micromips)
9934             micromips_add_label ();
9935         }
9936       end_noreorder ();
9937       break;
9938
9939     case M_DROL:
9940       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
9941         {
9942           if (dreg == sreg)
9943             {
9944               tempreg = AT;
9945               used_at = 1;
9946             }
9947           else
9948             {
9949               tempreg = dreg;
9950             }
9951           macro_build (NULL, "dnegu", "d,w", tempreg, treg);
9952           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, tempreg);
9953           break;
9954         }
9955       used_at = 1;
9956       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
9957       macro_build (NULL, "dsrlv", "d,t,s", AT, sreg, AT);
9958       macro_build (NULL, "dsllv", "d,t,s", dreg, sreg, treg);
9959       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9960       break;
9961
9962     case M_ROL:
9963       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
9964         {
9965           if (dreg == sreg)
9966             {
9967               tempreg = AT;
9968               used_at = 1;
9969             }
9970           else
9971             {
9972               tempreg = dreg;
9973             }
9974           macro_build (NULL, "negu", "d,w", tempreg, treg);
9975           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, tempreg);
9976           break;
9977         }
9978       used_at = 1;
9979       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
9980       macro_build (NULL, "srlv", "d,t,s", AT, sreg, AT);
9981       macro_build (NULL, "sllv", "d,t,s", dreg, sreg, treg);
9982       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9983       break;
9984
9985     case M_DROL_I:
9986       {
9987         unsigned int rot;
9988         char *l;
9989         char *rr;
9990
9991         if (imm_expr.X_op != O_constant)
9992           as_bad (_("Improper rotate count"));
9993         rot = imm_expr.X_add_number & 0x3f;
9994         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
9995           {
9996             rot = (64 - rot) & 0x3f;
9997             if (rot >= 32)
9998               macro_build (NULL, "dror32", SHFT_FMT, dreg, sreg, rot - 32);
9999             else
10000               macro_build (NULL, "dror", SHFT_FMT, dreg, sreg, rot);
10001             break;
10002           }
10003         if (rot == 0)
10004           {
10005             macro_build (NULL, "dsrl", SHFT_FMT, dreg, sreg, 0);
10006             break;
10007           }
10008         l = (rot < 0x20) ? "dsll" : "dsll32";
10009         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
10010         rot &= 0x1f;
10011         used_at = 1;
10012         macro_build (NULL, l, SHFT_FMT, AT, sreg, rot);
10013         macro_build (NULL, rr, SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10014         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10015       }
10016       break;
10017
10018     case M_ROL_I:
10019       {
10020         unsigned int rot;
10021
10022         if (imm_expr.X_op != O_constant)
10023           as_bad (_("Improper rotate count"));
10024         rot = imm_expr.X_add_number & 0x1f;
10025         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
10026           {
10027             macro_build (NULL, "ror", SHFT_FMT, dreg, sreg, (32 - rot) & 0x1f);
10028             break;
10029           }
10030         if (rot == 0)
10031           {
10032             macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, 0);
10033             break;
10034           }
10035         used_at = 1;
10036         macro_build (NULL, "sll", SHFT_FMT, AT, sreg, rot);
10037         macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10038         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10039       }
10040       break;
10041
10042     case M_DROR:
10043       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
10044         {
10045           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, treg);
10046           break;
10047         }
10048       used_at = 1;
10049       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
10050       macro_build (NULL, "dsllv", "d,t,s", AT, sreg, AT);
10051       macro_build (NULL, "dsrlv", "d,t,s", dreg, sreg, treg);
10052       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10053       break;
10054
10055     case M_ROR:
10056       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
10057         {
10058           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, treg);
10059           break;
10060         }
10061       used_at = 1;
10062       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
10063       macro_build (NULL, "sllv", "d,t,s", AT, sreg, AT);
10064       macro_build (NULL, "srlv", "d,t,s", dreg, sreg, treg);
10065       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10066       break;
10067
10068     case M_DROR_I:
10069       {
10070         unsigned int rot;
10071         char *l;
10072         char *rr;
10073
10074         if (imm_expr.X_op != O_constant)
10075           as_bad (_("Improper rotate count"));
10076         rot = imm_expr.X_add_number & 0x3f;
10077         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
10078           {
10079             if (rot >= 32)
10080               macro_build (NULL, "dror32", SHFT_FMT, dreg, sreg, rot - 32);
10081             else
10082               macro_build (NULL, "dror", SHFT_FMT, dreg, sreg, rot);
10083             break;
10084           }
10085         if (rot == 0)
10086           {
10087             macro_build (NULL, "dsrl", SHFT_FMT, dreg, sreg, 0);
10088             break;
10089           }
10090         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
10091         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
10092         rot &= 0x1f;
10093         used_at = 1;
10094         macro_build (NULL, rr, SHFT_FMT, AT, sreg, rot);
10095         macro_build (NULL, l, SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10096         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10097       }
10098       break;
10099
10100     case M_ROR_I:
10101       {
10102         unsigned int rot;
10103
10104         if (imm_expr.X_op != O_constant)
10105           as_bad (_("Improper rotate count"));
10106         rot = imm_expr.X_add_number & 0x1f;
10107         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
10108           {
10109             macro_build (NULL, "ror", SHFT_FMT, dreg, sreg, rot);
10110             break;
10111           }
10112         if (rot == 0)
10113           {
10114             macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, 0);
10115             break;
10116           }
10117         used_at = 1;
10118         macro_build (NULL, "srl", SHFT_FMT, AT, sreg, rot);
10119         macro_build (NULL, "sll", SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10120         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10121       }
10122       break;
10123
10124     case M_SEQ:
10125       if (sreg == 0)
10126         macro_build (&expr1, "sltiu", "t,r,j", dreg, treg, BFD_RELOC_LO16);
10127       else if (treg == 0)
10128         macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10129       else
10130         {
10131           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
10132           macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
10133         }
10134       break;
10135
10136     case M_SEQ_I:
10137       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
10138         {
10139           macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10140           break;
10141         }
10142       if (sreg == 0)
10143         {
10144           as_warn (_("Instruction %s: result is always false"),
10145                    ip->insn_mo->name);
10146           move_register (dreg, 0);
10147           break;
10148         }
10149       if (CPU_HAS_SEQ (mips_opts.arch)
10150           && -512 <= imm_expr.X_add_number
10151           && imm_expr.X_add_number < 512)
10152         {
10153           macro_build (NULL, "seqi", "t,r,+Q", dreg, sreg,
10154                        (int) imm_expr.X_add_number);
10155           break;
10156         }
10157       if (imm_expr.X_op == O_constant
10158           && imm_expr.X_add_number >= 0
10159           && imm_expr.X_add_number < 0x10000)
10160         {
10161           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
10162         }
10163       else if (imm_expr.X_op == O_constant
10164                && imm_expr.X_add_number > -0x8000
10165                && imm_expr.X_add_number < 0)
10166         {
10167           imm_expr.X_add_number = -imm_expr.X_add_number;
10168           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
10169                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10170         }
10171       else if (CPU_HAS_SEQ (mips_opts.arch))
10172         {
10173           used_at = 1;
10174           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10175           macro_build (NULL, "seq", "d,v,t", dreg, sreg, AT);
10176           break;
10177         }
10178       else
10179         {
10180           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10181           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
10182           used_at = 1;
10183         }
10184       macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
10185       break;
10186
10187     case M_SGE:         /* sreg >= treg <==> not (sreg < treg) */
10188       s = "slt";
10189       goto sge;
10190     case M_SGEU:
10191       s = "sltu";
10192     sge:
10193       macro_build (NULL, s, "d,v,t", dreg, sreg, treg);
10194       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
10195       break;
10196
10197     case M_SGE_I:               /* sreg >= I <==> not (sreg < I) */
10198     case M_SGEU_I:
10199       if (imm_expr.X_op == O_constant
10200           && imm_expr.X_add_number >= -0x8000
10201           && imm_expr.X_add_number < 0x8000)
10202         {
10203           macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
10204                        dreg, sreg, BFD_RELOC_LO16);
10205         }
10206       else
10207         {
10208           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10209           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
10210                        dreg, sreg, AT);
10211           used_at = 1;
10212         }
10213       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
10214       break;
10215
10216     case M_SGT:         /* sreg > treg  <==>  treg < sreg */
10217       s = "slt";
10218       goto sgt;
10219     case M_SGTU:
10220       s = "sltu";
10221     sgt:
10222       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
10223       break;
10224
10225     case M_SGT_I:               /* sreg > I  <==>  I < sreg */
10226       s = "slt";
10227       goto sgti;
10228     case M_SGTU_I:
10229       s = "sltu";
10230     sgti:
10231       used_at = 1;
10232       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10233       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
10234       break;
10235
10236     case M_SLE: /* sreg <= treg  <==>  treg >= sreg  <==>  not (treg < sreg) */
10237       s = "slt";
10238       goto sle;
10239     case M_SLEU:
10240       s = "sltu";
10241     sle:
10242       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
10243       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
10244       break;
10245
10246     case M_SLE_I:       /* sreg <= I <==> I >= sreg <==> not (I < sreg) */
10247       s = "slt";
10248       goto slei;
10249     case M_SLEU_I:
10250       s = "sltu";
10251     slei:
10252       used_at = 1;
10253       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10254       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
10255       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
10256       break;
10257
10258     case M_SLT_I:
10259       if (imm_expr.X_op == O_constant
10260           && imm_expr.X_add_number >= -0x8000
10261           && imm_expr.X_add_number < 0x8000)
10262         {
10263           macro_build (&imm_expr, "slti", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10264           break;
10265         }
10266       used_at = 1;
10267       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10268       macro_build (NULL, "slt", "d,v,t", dreg, sreg, AT);
10269       break;
10270
10271     case M_SLTU_I:
10272       if (imm_expr.X_op == O_constant
10273           && imm_expr.X_add_number >= -0x8000
10274           && imm_expr.X_add_number < 0x8000)
10275         {
10276           macro_build (&imm_expr, "sltiu", "t,r,j", dreg, sreg,
10277                        BFD_RELOC_LO16);
10278           break;
10279         }
10280       used_at = 1;
10281       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10282       macro_build (NULL, "sltu", "d,v,t", dreg, sreg, AT);
10283       break;
10284
10285     case M_SNE:
10286       if (sreg == 0)
10287         macro_build (NULL, "sltu", "d,v,t", dreg, 0, treg);
10288       else if (treg == 0)
10289         macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
10290       else
10291         {
10292           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
10293           macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
10294         }
10295       break;
10296
10297     case M_SNE_I:
10298       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
10299         {
10300           macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
10301           break;
10302         }
10303       if (sreg == 0)
10304         {
10305           as_warn (_("Instruction %s: result is always true"),
10306                    ip->insn_mo->name);
10307           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
10308                        dreg, 0, BFD_RELOC_LO16);
10309           break;
10310         }
10311       if (CPU_HAS_SEQ (mips_opts.arch)
10312           && -512 <= imm_expr.X_add_number
10313           && imm_expr.X_add_number < 512)
10314         {
10315           macro_build (NULL, "snei", "t,r,+Q", dreg, sreg,
10316                        (int) imm_expr.X_add_number);
10317           break;
10318         }
10319       if (imm_expr.X_op == O_constant
10320           && imm_expr.X_add_number >= 0
10321           && imm_expr.X_add_number < 0x10000)
10322         {
10323           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
10324         }
10325       else if (imm_expr.X_op == O_constant
10326                && imm_expr.X_add_number > -0x8000
10327                && imm_expr.X_add_number < 0)
10328         {
10329           imm_expr.X_add_number = -imm_expr.X_add_number;
10330           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
10331                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10332         }
10333       else if (CPU_HAS_SEQ (mips_opts.arch))
10334         {
10335           used_at = 1;
10336           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10337           macro_build (NULL, "sne", "d,v,t", dreg, sreg, AT);
10338           break;
10339         }
10340       else
10341         {
10342           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10343           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
10344           used_at = 1;
10345         }
10346       macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
10347       break;
10348
10349     case M_SUB_I:
10350       s = "addi";
10351       s2 = "sub";
10352       goto do_subi;
10353     case M_SUBU_I:
10354       s = "addiu";
10355       s2 = "subu";
10356       goto do_subi;
10357     case M_DSUB_I:
10358       dbl = 1;
10359       s = "daddi";
10360       s2 = "dsub";
10361       if (!mips_opts.micromips)
10362         goto do_subi;
10363       if (imm_expr.X_op == O_constant
10364           && imm_expr.X_add_number > -0x200
10365           && imm_expr.X_add_number <= 0x200)
10366         {
10367           macro_build (NULL, s, "t,r,.", dreg, sreg, -imm_expr.X_add_number);
10368           break;
10369         }
10370       goto do_subi_i;
10371     case M_DSUBU_I:
10372       dbl = 1;
10373       s = "daddiu";
10374       s2 = "dsubu";
10375     do_subi:
10376       if (imm_expr.X_op == O_constant
10377           && imm_expr.X_add_number > -0x8000
10378           && imm_expr.X_add_number <= 0x8000)
10379         {
10380           imm_expr.X_add_number = -imm_expr.X_add_number;
10381           macro_build (&imm_expr, s, "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10382           break;
10383         }
10384     do_subi_i:
10385       used_at = 1;
10386       load_register (AT, &imm_expr, dbl);
10387       macro_build (NULL, s2, "d,v,t", dreg, sreg, AT);
10388       break;
10389
10390     case M_TEQ_I:
10391       s = "teq";
10392       goto trap;
10393     case M_TGE_I:
10394       s = "tge";
10395       goto trap;
10396     case M_TGEU_I:
10397       s = "tgeu";
10398       goto trap;
10399     case M_TLT_I:
10400       s = "tlt";
10401       goto trap;
10402     case M_TLTU_I:
10403       s = "tltu";
10404       goto trap;
10405     case M_TNE_I:
10406       s = "tne";
10407     trap:
10408       used_at = 1;
10409       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10410       macro_build (NULL, s, "s,t", sreg, AT);
10411       break;
10412
10413     case M_TRUNCWS:
10414     case M_TRUNCWD:
10415       gas_assert (!mips_opts.micromips);
10416       gas_assert (mips_opts.isa == ISA_MIPS1);
10417       used_at = 1;
10418       sreg = (ip->insn_opcode >> 11) & 0x1f;    /* floating reg */
10419       dreg = (ip->insn_opcode >> 06) & 0x1f;    /* floating reg */
10420
10421       /*
10422        * Is the double cfc1 instruction a bug in the mips assembler;
10423        * or is there a reason for it?
10424        */
10425       start_noreorder ();
10426       macro_build (NULL, "cfc1", "t,G", treg, RA);
10427       macro_build (NULL, "cfc1", "t,G", treg, RA);
10428       macro_build (NULL, "nop", "");
10429       expr1.X_add_number = 3;
10430       macro_build (&expr1, "ori", "t,r,i", AT, treg, BFD_RELOC_LO16);
10431       expr1.X_add_number = 2;
10432       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
10433       macro_build (NULL, "ctc1", "t,G", AT, RA);
10434       macro_build (NULL, "nop", "");
10435       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
10436                    dreg, sreg);
10437       macro_build (NULL, "ctc1", "t,G", treg, RA);
10438       macro_build (NULL, "nop", "");
10439       end_noreorder ();
10440       break;
10441
10442     case M_ULH_A:
10443       ab = 1;
10444     case M_ULH:
10445       s = "lb";
10446       s2 = "lbu";
10447       off = 1;
10448       goto uld_st;
10449     case M_ULHU_A:
10450       ab = 1;
10451     case M_ULHU:
10452       s = "lbu";
10453       s2 = "lbu";
10454       off = 1;
10455       goto uld_st;
10456     case M_ULW_A:
10457       ab = 1;
10458     case M_ULW:
10459       s = "lwl";
10460       s2 = "lwr";
10461       offbits = (mips_opts.micromips ? 12 : 16);
10462       off = 3;
10463       goto uld_st;
10464     case M_ULD_A:
10465       ab = 1;
10466     case M_ULD:
10467       s = "ldl";
10468       s2 = "ldr";
10469       offbits = (mips_opts.micromips ? 12 : 16);
10470       off = 7;
10471       goto uld_st;
10472     case M_USH_A:
10473       ab = 1;
10474     case M_USH:
10475       s = "sb";
10476       s2 = "sb";
10477       off = 1;
10478       ust = 1;
10479       goto uld_st;
10480     case M_USW_A:
10481       ab = 1;
10482     case M_USW:
10483       s = "swl";
10484       s2 = "swr";
10485       offbits = (mips_opts.micromips ? 12 : 16);
10486       off = 3;
10487       ust = 1;
10488       goto uld_st;
10489     case M_USD_A:
10490       ab = 1;
10491     case M_USD:
10492       s = "sdl";
10493       s2 = "sdr";
10494       offbits = (mips_opts.micromips ? 12 : 16);
10495       off = 7;
10496       ust = 1;
10497
10498     uld_st:
10499       if (!ab && offset_expr.X_add_number >= 0x8000 - off)
10500         as_bad (_("Operand overflow"));
10501
10502       ep = &offset_expr;
10503       expr1.X_add_number = 0;
10504       if (ab)
10505         {
10506           used_at = 1;
10507           tempreg = AT;
10508           load_address (tempreg, ep, &used_at);
10509           if (breg != 0)
10510             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10511                          tempreg, tempreg, breg);
10512           breg = tempreg;
10513           tempreg = treg;
10514           ep = &expr1;
10515         }
10516       else if (offbits == 12
10517                && (offset_expr.X_op != O_constant
10518                    || !IS_SEXT_12BIT_NUM (offset_expr.X_add_number)
10519                    || !IS_SEXT_12BIT_NUM (offset_expr.X_add_number + off)))
10520         {
10521           used_at = 1;
10522           tempreg = AT;
10523           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg,
10524                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
10525           breg = tempreg;
10526           tempreg = treg;
10527           ep = &expr1;
10528         }
10529       else if (!ust && treg == breg)
10530         {
10531           used_at = 1;
10532           tempreg = AT;
10533         }
10534       else
10535         tempreg = treg;
10536
10537       if (off == 1)
10538         goto ulh_sh;
10539
10540       if (!target_big_endian)
10541         ep->X_add_number += off;
10542       if (offbits != 12)
10543         macro_build (ep, s, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
10544       else
10545         macro_build (NULL, s, "t,~(b)",
10546                      tempreg, (unsigned long) ep->X_add_number, breg);
10547
10548       if (!target_big_endian)
10549         ep->X_add_number -= off;
10550       else
10551         ep->X_add_number += off;
10552       if (offbits != 12)
10553         macro_build (ep, s2, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
10554       else
10555         macro_build (NULL, s2, "t,~(b)",
10556                      tempreg, (unsigned long) ep->X_add_number, breg);
10557
10558       /* If necessary, move the result in tempreg to the final destination.  */
10559       if (!ust && treg != tempreg)
10560         {
10561           /* Protect second load's delay slot.  */
10562           load_delay_nop ();
10563           move_register (treg, tempreg);
10564         }
10565       break;
10566
10567     ulh_sh:
10568       used_at = 1;
10569       if (target_big_endian == ust)
10570         ep->X_add_number += off;
10571       tempreg = ust || ab ? treg : AT;
10572       macro_build (ep, s, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
10573
10574       /* For halfword transfers we need a temporary register to shuffle
10575          bytes.  Unfortunately for M_USH_A we have none available before
10576          the next store as AT holds the base address.  We deal with this
10577          case by clobbering TREG and then restoring it as with ULH.  */
10578       tempreg = ust == ab ? treg : AT;
10579       if (ust)
10580         macro_build (NULL, "srl", SHFT_FMT, tempreg, treg, 8);
10581
10582       if (target_big_endian == ust)
10583         ep->X_add_number -= off;
10584       else
10585         ep->X_add_number += off;
10586       macro_build (ep, s2, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
10587
10588       /* For M_USH_A re-retrieve the LSB.  */
10589       if (ust && ab)
10590         {
10591           if (target_big_endian)
10592             ep->X_add_number += off;
10593           else
10594             ep->X_add_number -= off;
10595           macro_build (&expr1, "lbu", "t,o(b)", AT, BFD_RELOC_LO16, AT);
10596         }
10597       /* For ULH and M_USH_A OR the LSB in.  */
10598       if (!ust || ab)
10599         {
10600           tempreg = !ab ? AT : treg;
10601           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
10602           macro_build (NULL, "or", "d,v,t", treg, treg, AT);
10603         }
10604       break;
10605
10606     default:
10607       /* FIXME: Check if this is one of the itbl macros, since they
10608          are added dynamically.  */
10609       as_bad (_("Macro %s not implemented yet"), ip->insn_mo->name);
10610       break;
10611     }
10612   if (!mips_opts.at && used_at)
10613     as_bad (_("Macro used $at after \".set noat\""));
10614 }
10615
10616 /* Implement macros in mips16 mode.  */
10617
10618 static void
10619 mips16_macro (struct mips_cl_insn *ip)
10620 {
10621   int mask;
10622   int xreg, yreg, zreg, tmp;
10623   expressionS expr1;
10624   int dbl;
10625   const char *s, *s2, *s3;
10626
10627   mask = ip->insn_mo->mask;
10628
10629   xreg = MIPS16_EXTRACT_OPERAND (RX, *ip);
10630   yreg = MIPS16_EXTRACT_OPERAND (RY, *ip);
10631   zreg = MIPS16_EXTRACT_OPERAND (RZ, *ip);
10632
10633   expr1.X_op = O_constant;
10634   expr1.X_op_symbol = NULL;
10635   expr1.X_add_symbol = NULL;
10636   expr1.X_add_number = 1;
10637
10638   dbl = 0;
10639
10640   switch (mask)
10641     {
10642     default:
10643       abort ();
10644
10645     case M_DDIV_3:
10646       dbl = 1;
10647     case M_DIV_3:
10648       s = "mflo";
10649       goto do_div3;
10650     case M_DREM_3:
10651       dbl = 1;
10652     case M_REM_3:
10653       s = "mfhi";
10654     do_div3:
10655       start_noreorder ();
10656       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", xreg, yreg);
10657       expr1.X_add_number = 2;
10658       macro_build (&expr1, "bnez", "x,p", yreg);
10659       macro_build (NULL, "break", "6", 7);
10660
10661       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
10662          since that causes an overflow.  We should do that as well,
10663          but I don't see how to do the comparisons without a temporary
10664          register.  */
10665       end_noreorder ();
10666       macro_build (NULL, s, "x", zreg);
10667       break;
10668
10669     case M_DIVU_3:
10670       s = "divu";
10671       s2 = "mflo";
10672       goto do_divu3;
10673     case M_REMU_3:
10674       s = "divu";
10675       s2 = "mfhi";
10676       goto do_divu3;
10677     case M_DDIVU_3:
10678       s = "ddivu";
10679       s2 = "mflo";
10680       goto do_divu3;
10681     case M_DREMU_3:
10682       s = "ddivu";
10683       s2 = "mfhi";
10684     do_divu3:
10685       start_noreorder ();
10686       macro_build (NULL, s, "0,x,y", xreg, yreg);
10687       expr1.X_add_number = 2;
10688       macro_build (&expr1, "bnez", "x,p", yreg);
10689       macro_build (NULL, "break", "6", 7);
10690       end_noreorder ();
10691       macro_build (NULL, s2, "x", zreg);
10692       break;
10693
10694     case M_DMUL:
10695       dbl = 1;
10696     case M_MUL:
10697       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", xreg, yreg);
10698       macro_build (NULL, "mflo", "x", zreg);
10699       break;
10700
10701     case M_DSUBU_I:
10702       dbl = 1;
10703       goto do_subu;
10704     case M_SUBU_I:
10705     do_subu:
10706       if (imm_expr.X_op != O_constant)
10707         as_bad (_("Unsupported large constant"));
10708       imm_expr.X_add_number = -imm_expr.X_add_number;
10709       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", yreg, xreg);
10710       break;
10711
10712     case M_SUBU_I_2:
10713       if (imm_expr.X_op != O_constant)
10714         as_bad (_("Unsupported large constant"));
10715       imm_expr.X_add_number = -imm_expr.X_add_number;
10716       macro_build (&imm_expr, "addiu", "x,k", xreg);
10717       break;
10718
10719     case M_DSUBU_I_2:
10720       if (imm_expr.X_op != O_constant)
10721         as_bad (_("Unsupported large constant"));
10722       imm_expr.X_add_number = -imm_expr.X_add_number;
10723       macro_build (&imm_expr, "daddiu", "y,j", yreg);
10724       break;
10725
10726     case M_BEQ:
10727       s = "cmp";
10728       s2 = "bteqz";
10729       goto do_branch;
10730     case M_BNE:
10731       s = "cmp";
10732       s2 = "btnez";
10733       goto do_branch;
10734     case M_BLT:
10735       s = "slt";
10736       s2 = "btnez";
10737       goto do_branch;
10738     case M_BLTU:
10739       s = "sltu";
10740       s2 = "btnez";
10741       goto do_branch;
10742     case M_BLE:
10743       s = "slt";
10744       s2 = "bteqz";
10745       goto do_reverse_branch;
10746     case M_BLEU:
10747       s = "sltu";
10748       s2 = "bteqz";
10749       goto do_reverse_branch;
10750     case M_BGE:
10751       s = "slt";
10752       s2 = "bteqz";
10753       goto do_branch;
10754     case M_BGEU:
10755       s = "sltu";
10756       s2 = "bteqz";
10757       goto do_branch;
10758     case M_BGT:
10759       s = "slt";
10760       s2 = "btnez";
10761       goto do_reverse_branch;
10762     case M_BGTU:
10763       s = "sltu";
10764       s2 = "btnez";
10765
10766     do_reverse_branch:
10767       tmp = xreg;
10768       xreg = yreg;
10769       yreg = tmp;
10770
10771     do_branch:
10772       macro_build (NULL, s, "x,y", xreg, yreg);
10773       macro_build (&offset_expr, s2, "p");
10774       break;
10775
10776     case M_BEQ_I:
10777       s = "cmpi";
10778       s2 = "bteqz";
10779       s3 = "x,U";
10780       goto do_branch_i;
10781     case M_BNE_I:
10782       s = "cmpi";
10783       s2 = "btnez";
10784       s3 = "x,U";
10785       goto do_branch_i;
10786     case M_BLT_I:
10787       s = "slti";
10788       s2 = "btnez";
10789       s3 = "x,8";
10790       goto do_branch_i;
10791     case M_BLTU_I:
10792       s = "sltiu";
10793       s2 = "btnez";
10794       s3 = "x,8";
10795       goto do_branch_i;
10796     case M_BLE_I:
10797       s = "slti";
10798       s2 = "btnez";
10799       s3 = "x,8";
10800       goto do_addone_branch_i;
10801     case M_BLEU_I:
10802       s = "sltiu";
10803       s2 = "btnez";
10804       s3 = "x,8";
10805       goto do_addone_branch_i;
10806     case M_BGE_I:
10807       s = "slti";
10808       s2 = "bteqz";
10809       s3 = "x,8";
10810       goto do_branch_i;
10811     case M_BGEU_I:
10812       s = "sltiu";
10813       s2 = "bteqz";
10814       s3 = "x,8";
10815       goto do_branch_i;
10816     case M_BGT_I:
10817       s = "slti";
10818       s2 = "bteqz";
10819       s3 = "x,8";
10820       goto do_addone_branch_i;
10821     case M_BGTU_I:
10822       s = "sltiu";
10823       s2 = "bteqz";
10824       s3 = "x,8";
10825
10826     do_addone_branch_i:
10827       if (imm_expr.X_op != O_constant)
10828         as_bad (_("Unsupported large constant"));
10829       ++imm_expr.X_add_number;
10830
10831     do_branch_i:
10832       macro_build (&imm_expr, s, s3, xreg);
10833       macro_build (&offset_expr, s2, "p");
10834       break;
10835
10836     case M_ABS:
10837       expr1.X_add_number = 0;
10838       macro_build (&expr1, "slti", "x,8", yreg);
10839       if (xreg != yreg)
10840         move_register (xreg, yreg);
10841       expr1.X_add_number = 2;
10842       macro_build (&expr1, "bteqz", "p");
10843       macro_build (NULL, "neg", "x,w", xreg, xreg);
10844     }
10845 }
10846
10847 /* For consistency checking, verify that all bits are specified either
10848    by the match/mask part of the instruction definition, or by the
10849    operand list.  */
10850 static int
10851 validate_mips_insn (const struct mips_opcode *opc)
10852 {
10853   const char *p = opc->args;
10854   char c;
10855   unsigned long used_bits = opc->mask;
10856
10857   if ((used_bits & opc->match) != opc->match)
10858     {
10859       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
10860               opc->name, opc->args);
10861       return 0;
10862     }
10863 #define USE_BITS(mask,shift)    (used_bits |= ((mask) << (shift)))
10864   while (*p)
10865     switch (c = *p++)
10866       {
10867       case ',': break;
10868       case '(': break;
10869       case ')': break;
10870       case '+':
10871         switch (c = *p++)
10872           {
10873           case '1': USE_BITS (OP_MASK_UDI1,     OP_SH_UDI1);    break;
10874           case '2': USE_BITS (OP_MASK_UDI2,     OP_SH_UDI2);    break;
10875           case '3': USE_BITS (OP_MASK_UDI3,     OP_SH_UDI3);    break;
10876           case '4': USE_BITS (OP_MASK_UDI4,     OP_SH_UDI4);    break;
10877           case 'A': USE_BITS (OP_MASK_SHAMT,    OP_SH_SHAMT);   break;
10878           case 'B': USE_BITS (OP_MASK_INSMSB,   OP_SH_INSMSB);  break;
10879           case 'C': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
10880           case 'D': USE_BITS (OP_MASK_RD,       OP_SH_RD);
10881                     USE_BITS (OP_MASK_SEL,      OP_SH_SEL);     break;
10882           case 'E': USE_BITS (OP_MASK_SHAMT,    OP_SH_SHAMT);   break;
10883           case 'F': USE_BITS (OP_MASK_INSMSB,   OP_SH_INSMSB);  break;
10884           case 'G': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
10885           case 'H': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
10886           case 'I': break;
10887           case 'J': USE_BITS (OP_MASK_CODE10,   OP_SH_CODE10);  break;
10888           case 't': USE_BITS (OP_MASK_RT,       OP_SH_RT);      break;
10889           case 'T': USE_BITS (OP_MASK_RT,       OP_SH_RT);
10890                     USE_BITS (OP_MASK_SEL,      OP_SH_SEL);     break;
10891           case 'x': USE_BITS (OP_MASK_BBITIND,  OP_SH_BBITIND); break;
10892           case 'X': USE_BITS (OP_MASK_BBITIND,  OP_SH_BBITIND); break;
10893           case 'p': USE_BITS (OP_MASK_CINSPOS,  OP_SH_CINSPOS); break;
10894           case 'P': USE_BITS (OP_MASK_CINSPOS,  OP_SH_CINSPOS); break;
10895           case 'Q': USE_BITS (OP_MASK_SEQI,     OP_SH_SEQI);    break;
10896           case 's': USE_BITS (OP_MASK_CINSLM1,  OP_SH_CINSLM1); break;
10897           case 'S': USE_BITS (OP_MASK_CINSLM1,  OP_SH_CINSLM1); break;
10898           case 'z': USE_BITS (OP_MASK_RZ,       OP_SH_RZ);      break;
10899           case 'Z': USE_BITS (OP_MASK_FZ,       OP_SH_FZ);      break;
10900           case 'a': USE_BITS (OP_MASK_OFFSET_A, OP_SH_OFFSET_A); break;
10901           case 'b': USE_BITS (OP_MASK_OFFSET_B, OP_SH_OFFSET_B); break;
10902           case 'c': USE_BITS (OP_MASK_OFFSET_C, OP_SH_OFFSET_C); break;
10903           case 'j': USE_BITS (OP_MASK_EVAOFFSET, OP_SH_EVAOFFSET); break;
10904
10905           default:
10906             as_bad (_("internal: bad mips opcode (unknown extension operand type `+%c'): %s %s"),
10907                     c, opc->name, opc->args);
10908             return 0;
10909           }
10910         break;
10911       case '<': USE_BITS (OP_MASK_SHAMT,        OP_SH_SHAMT);   break;
10912       case '>': USE_BITS (OP_MASK_SHAMT,        OP_SH_SHAMT);   break;
10913       case 'A': break;
10914       case 'B': USE_BITS (OP_MASK_CODE20,       OP_SH_CODE20);  break;
10915       case 'C': USE_BITS (OP_MASK_COPZ,         OP_SH_COPZ);    break;
10916       case 'D': USE_BITS (OP_MASK_FD,           OP_SH_FD);      break;
10917       case 'E': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
10918       case 'F': break;
10919       case 'G': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
10920       case 'H': USE_BITS (OP_MASK_SEL,          OP_SH_SEL);     break;
10921       case 'I': break;
10922       case 'J': USE_BITS (OP_MASK_CODE19,       OP_SH_CODE19);  break;
10923       case 'K': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
10924       case 'L': break;
10925       case 'M': USE_BITS (OP_MASK_CCC,          OP_SH_CCC);     break;
10926       case 'N': USE_BITS (OP_MASK_BCC,          OP_SH_BCC);     break;
10927       case 'O': USE_BITS (OP_MASK_ALN,          OP_SH_ALN);     break;
10928       case 'Q': USE_BITS (OP_MASK_VSEL,         OP_SH_VSEL);
10929                 USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
10930       case 'R': USE_BITS (OP_MASK_FR,           OP_SH_FR);      break;
10931       case 'S': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
10932       case 'T': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
10933       case 'V': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
10934       case 'W': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
10935       case 'X': USE_BITS (OP_MASK_FD,           OP_SH_FD);      break;
10936       case 'Y': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
10937       case 'Z': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
10938       case 'a': USE_BITS (OP_MASK_TARGET,       OP_SH_TARGET);  break;
10939       case 'b': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
10940       case 'c': USE_BITS (OP_MASK_CODE,         OP_SH_CODE);    break;
10941       case 'd': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
10942       case 'f': break;
10943       case 'h': USE_BITS (OP_MASK_PREFX,        OP_SH_PREFX);   break;
10944       case 'i': USE_BITS (OP_MASK_IMMEDIATE,    OP_SH_IMMEDIATE); break;
10945       case 'j': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
10946       case 'k': USE_BITS (OP_MASK_CACHE,        OP_SH_CACHE);   break;
10947       case 'l': break;
10948       case 'o': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
10949       case 'p': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
10950       case 'q': USE_BITS (OP_MASK_CODE2,        OP_SH_CODE2);   break;
10951       case 'r': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
10952       case 's': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
10953       case 't': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
10954       case 'u': USE_BITS (OP_MASK_IMMEDIATE,    OP_SH_IMMEDIATE); break;
10955       case 'v': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
10956       case 'w': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
10957       case 'x': break;
10958       case 'z': break;
10959       case 'P': USE_BITS (OP_MASK_PERFREG,      OP_SH_PERFREG); break;
10960       case 'U': USE_BITS (OP_MASK_RD,           OP_SH_RD);
10961                 USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
10962       case 'e': USE_BITS (OP_MASK_VECBYTE,      OP_SH_VECBYTE); break;
10963       case '%': USE_BITS (OP_MASK_VECALIGN,     OP_SH_VECALIGN); break;
10964       case '[': break;
10965       case ']': break;
10966       case '1': USE_BITS (OP_MASK_SHAMT,        OP_SH_SHAMT);   break;
10967       case '2': USE_BITS (OP_MASK_BP,           OP_SH_BP);      break;
10968       case '3': USE_BITS (OP_MASK_SA3,          OP_SH_SA3);     break;
10969       case '4': USE_BITS (OP_MASK_SA4,          OP_SH_SA4);     break;
10970       case '5': USE_BITS (OP_MASK_IMM8,         OP_SH_IMM8);    break;
10971       case '6': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
10972       case '7': USE_BITS (OP_MASK_DSPACC,       OP_SH_DSPACC);  break;
10973       case '8': USE_BITS (OP_MASK_WRDSP,        OP_SH_WRDSP);   break;
10974       case '9': USE_BITS (OP_MASK_DSPACC_S,     OP_SH_DSPACC_S);break;
10975       case '0': USE_BITS (OP_MASK_DSPSFT,       OP_SH_DSPSFT);  break;
10976       case '\'': USE_BITS (OP_MASK_RDDSP,       OP_SH_RDDSP);   break;
10977       case ':': USE_BITS (OP_MASK_DSPSFT_7,     OP_SH_DSPSFT_7);break;
10978       case '@': USE_BITS (OP_MASK_IMM10,        OP_SH_IMM10);   break;
10979       case '!': USE_BITS (OP_MASK_MT_U,         OP_SH_MT_U);    break;
10980       case '$': USE_BITS (OP_MASK_MT_H,         OP_SH_MT_H);    break;
10981       case '*': USE_BITS (OP_MASK_MTACC_T,      OP_SH_MTACC_T); break;
10982       case '&': USE_BITS (OP_MASK_MTACC_D,      OP_SH_MTACC_D); break;
10983       case '\\': USE_BITS (OP_MASK_3BITPOS,     OP_SH_3BITPOS); break;
10984       case '~': USE_BITS (OP_MASK_OFFSET12,     OP_SH_OFFSET12); break;
10985       case 'g': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
10986       default:
10987         as_bad (_("internal: bad mips opcode (unknown operand type `%c'): %s %s"),
10988                 c, opc->name, opc->args);
10989         return 0;
10990       }
10991 #undef USE_BITS
10992   if (used_bits != 0xffffffff)
10993     {
10994       as_bad (_("internal: bad mips opcode (bits 0x%lx undefined): %s %s"),
10995               ~used_bits & 0xffffffff, opc->name, opc->args);
10996       return 0;
10997     }
10998   return 1;
10999 }
11000
11001 /* For consistency checking, verify that the length implied matches the
11002    major opcode and that all bits are specified either by the match/mask
11003    part of the instruction definition, or by the operand list.  */
11004
11005 static int
11006 validate_micromips_insn (const struct mips_opcode *opc)
11007 {
11008   unsigned long match = opc->match;
11009   unsigned long mask = opc->mask;
11010   const char *p = opc->args;
11011   unsigned long insn_bits;
11012   unsigned long used_bits;
11013   unsigned long major;
11014   unsigned int length;
11015   char e;
11016   char c;
11017
11018   if ((mask & match) != match)
11019     {
11020       as_bad (_("Internal error: bad microMIPS opcode (mask error): %s %s"),
11021               opc->name, opc->args);
11022       return 0;
11023     }
11024   length = micromips_insn_length (opc);
11025   if (length != 2 && length != 4)
11026     {
11027       as_bad (_("Internal error: bad microMIPS opcode (incorrect length: %u): "
11028                 "%s %s"), length, opc->name, opc->args);
11029       return 0;
11030     }
11031   major = match >> (10 + 8 * (length - 2));
11032   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
11033       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
11034     {
11035       as_bad (_("Internal error: bad microMIPS opcode "
11036                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
11037       return 0;
11038     }
11039
11040   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
11041   insn_bits = 1 << 4 * length;
11042   insn_bits <<= 4 * length;
11043   insn_bits -= 1;
11044   used_bits = mask;
11045 #define USE_BITS(field) \
11046   (used_bits |= MICROMIPSOP_MASK_##field << MICROMIPSOP_SH_##field)
11047   while (*p)
11048     switch (c = *p++)
11049       {
11050       case ',': break;
11051       case '(': break;
11052       case ')': break;
11053       case '+':
11054         e = c;
11055         switch (c = *p++)
11056           {
11057           case 'A': USE_BITS (EXTLSB);  break;
11058           case 'B': USE_BITS (INSMSB);  break;
11059           case 'C': USE_BITS (EXTMSBD); break;
11060           case 'D': USE_BITS (RS);      USE_BITS (SEL); break;
11061           case 'E': USE_BITS (EXTLSB);  break;
11062           case 'F': USE_BITS (INSMSB);  break;
11063           case 'G': USE_BITS (EXTMSBD); break;
11064           case 'H': USE_BITS (EXTMSBD); break;
11065           case 'j': USE_BITS (EVAOFFSET);       break;
11066           default:
11067             as_bad (_("Internal error: bad mips opcode "
11068                       "(unknown extension operand type `%c%c'): %s %s"),
11069                     e, c, opc->name, opc->args);
11070             return 0;
11071           }
11072         break;
11073       case 'm':
11074         e = c;
11075         switch (c = *p++)
11076           {
11077           case 'A': USE_BITS (IMMA);    break;
11078           case 'B': USE_BITS (IMMB);    break;
11079           case 'C': USE_BITS (IMMC);    break;
11080           case 'D': USE_BITS (IMMD);    break;
11081           case 'E': USE_BITS (IMME);    break;
11082           case 'F': USE_BITS (IMMF);    break;
11083           case 'G': USE_BITS (IMMG);    break;
11084           case 'H': USE_BITS (IMMH);    break;
11085           case 'I': USE_BITS (IMMI);    break;
11086           case 'J': USE_BITS (IMMJ);    break;
11087           case 'L': USE_BITS (IMML);    break;
11088           case 'M': USE_BITS (IMMM);    break;
11089           case 'N': USE_BITS (IMMN);    break;
11090           case 'O': USE_BITS (IMMO);    break;
11091           case 'P': USE_BITS (IMMP);    break;
11092           case 'Q': USE_BITS (IMMQ);    break;
11093           case 'U': USE_BITS (IMMU);    break;
11094           case 'W': USE_BITS (IMMW);    break;
11095           case 'X': USE_BITS (IMMX);    break;
11096           case 'Y': USE_BITS (IMMY);    break;
11097           case 'Z': break;
11098           case 'a': break;
11099           case 'b': USE_BITS (MB);      break;
11100           case 'c': USE_BITS (MC);      break;
11101           case 'd': USE_BITS (MD);      break;
11102           case 'e': USE_BITS (ME);      break;
11103           case 'f': USE_BITS (MF);      break;
11104           case 'g': USE_BITS (MG);      break;
11105           case 'h': USE_BITS (MH);      break;
11106           case 'i': USE_BITS (MI);      break;
11107           case 'j': USE_BITS (MJ);      break;
11108           case 'l': USE_BITS (ML);      break;
11109           case 'm': USE_BITS (MM);      break;
11110           case 'n': USE_BITS (MN);      break;
11111           case 'p': USE_BITS (MP);      break;
11112           case 'q': USE_BITS (MQ);      break;
11113           case 'r': break;
11114           case 's': break;
11115           case 't': break;
11116           case 'x': break;
11117           case 'y': break;
11118           case 'z': break;
11119           default:
11120             as_bad (_("Internal error: bad mips opcode "
11121                       "(unknown extension operand type `%c%c'): %s %s"),
11122                     e, c, opc->name, opc->args);
11123             return 0;
11124           }
11125         break;
11126       case '.': USE_BITS (OFFSET10);    break;
11127       case '1': USE_BITS (STYPE);       break;
11128       case '2': USE_BITS (BP);          break;
11129       case '3': USE_BITS (SA3);         break;
11130       case '4': USE_BITS (SA4);         break;
11131       case '5': USE_BITS (IMM8);        break;
11132       case '6': USE_BITS (RS);          break;
11133       case '7': USE_BITS (DSPACC);      break;
11134       case '8': USE_BITS (WRDSP);       break;
11135       case '0': USE_BITS (DSPSFT);      break;
11136       case '<': USE_BITS (SHAMT);       break;
11137       case '>': USE_BITS (SHAMT);       break;
11138       case '@': USE_BITS (IMM10);       break;
11139       case 'B': USE_BITS (CODE10);      break;
11140       case 'C': USE_BITS (COPZ);        break;
11141       case 'D': USE_BITS (FD);          break;
11142       case 'E': USE_BITS (RT);          break;
11143       case 'G': USE_BITS (RS);          break;
11144       case 'H': USE_BITS (SEL);         break;
11145       case 'K': USE_BITS (RS);          break;
11146       case 'M': USE_BITS (CCC);         break;
11147       case 'N': USE_BITS (BCC);         break;
11148       case 'R': USE_BITS (FR);          break;
11149       case 'S': USE_BITS (FS);          break;
11150       case 'T': USE_BITS (FT);          break;
11151       case 'V': USE_BITS (FS);          break;
11152       case '\\': USE_BITS (3BITPOS);    break;
11153       case '^': USE_BITS (RD);          break;
11154       case 'a': USE_BITS (TARGET);      break;
11155       case 'b': USE_BITS (RS);          break;
11156       case 'c': USE_BITS (CODE);        break;
11157       case 'd': USE_BITS (RD);          break;
11158       case 'h': USE_BITS (PREFX);       break;
11159       case 'i': USE_BITS (IMMEDIATE);   break;
11160       case 'j': USE_BITS (DELTA);       break;
11161       case 'k': USE_BITS (CACHE);       break;
11162       case 'n': USE_BITS (RT);          break;
11163       case 'o': USE_BITS (DELTA);       break;
11164       case 'p': USE_BITS (DELTA);       break;
11165       case 'q': USE_BITS (CODE2);       break;
11166       case 'r': USE_BITS (RS);          break;
11167       case 's': USE_BITS (RS);          break;
11168       case 't': USE_BITS (RT);          break;
11169       case 'u': USE_BITS (IMMEDIATE);   break;
11170       case 'v': USE_BITS (RS);          break;
11171       case 'w': USE_BITS (RT);          break;
11172       case 'y': USE_BITS (RS3);         break;
11173       case 'z': break;
11174       case '|': USE_BITS (TRAP);        break;
11175       case '~': USE_BITS (OFFSET12);    break;
11176       default:
11177         as_bad (_("Internal error: bad microMIPS opcode "
11178                   "(unknown operand type `%c'): %s %s"),
11179                 c, opc->name, opc->args);
11180         return 0;
11181       }
11182 #undef USE_BITS
11183   if (used_bits != insn_bits)
11184     {
11185       if (~used_bits & insn_bits)
11186         as_bad (_("Internal error: bad microMIPS opcode "
11187                   "(bits 0x%lx undefined): %s %s"),
11188                 ~used_bits & insn_bits, opc->name, opc->args);
11189       if (used_bits & ~insn_bits)
11190         as_bad (_("Internal error: bad microMIPS opcode "
11191                   "(bits 0x%lx defined): %s %s"),
11192                 used_bits & ~insn_bits, opc->name, opc->args);
11193       return 0;
11194     }
11195   return 1;
11196 }
11197
11198 /* UDI immediates.  */
11199 struct mips_immed {
11200   char          type;
11201   unsigned int  shift;
11202   unsigned long mask;
11203   const char *  desc;
11204 };
11205
11206 static const struct mips_immed mips_immed[] = {
11207   { '1',        OP_SH_UDI1,     OP_MASK_UDI1,           0},
11208   { '2',        OP_SH_UDI2,     OP_MASK_UDI2,           0},
11209   { '3',        OP_SH_UDI3,     OP_MASK_UDI3,           0},
11210   { '4',        OP_SH_UDI4,     OP_MASK_UDI4,           0},
11211   { 0,0,0,0 }
11212 };
11213
11214 /* Check whether an odd floating-point register is allowed.  */
11215 static int
11216 mips_oddfpreg_ok (const struct mips_opcode *insn, int argnum)
11217 {
11218   const char *s = insn->name;
11219
11220   if (insn->pinfo == INSN_MACRO)
11221     /* Let a macro pass, we'll catch it later when it is expanded.  */
11222     return 1;
11223
11224   if (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa) || (mips_opts.arch == CPU_R5900))
11225     {
11226       /* Allow odd registers for single-precision ops.  */
11227       switch (insn->pinfo & (FP_S | FP_D))
11228         {
11229         case FP_S:
11230         case 0:
11231           return 1;     /* both single precision - ok */
11232         case FP_D:
11233           return 0;     /* both double precision - fail */
11234         default:
11235           break;
11236         }
11237
11238       /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
11239       s = strchr (insn->name, '.');
11240       if (argnum == 2)
11241         s = s != NULL ? strchr (s + 1, '.') : NULL;
11242       return (s != NULL && (s[1] == 'w' || s[1] == 's'));
11243     } 
11244
11245   /* Single-precision coprocessor loads and moves are OK too.  */
11246   if ((insn->pinfo & FP_S)
11247       && (insn->pinfo & (INSN_COPROC_MEMORY_DELAY | INSN_STORE_MEMORY
11248                          | INSN_LOAD_COPROC_DELAY | INSN_COPROC_MOVE_DELAY)))
11249     return 1;
11250
11251   return 0;
11252 }
11253
11254 /* Check if EXPR is a constant between MIN (inclusive) and MAX (exclusive)
11255    taking bits from BIT up.  */
11256 static int
11257 expr_const_in_range (expressionS *ep, offsetT min, offsetT max, int bit)
11258 {
11259   return (ep->X_op == O_constant
11260           && (ep->X_add_number & ((1 << bit) - 1)) == 0
11261           && ep->X_add_number >= min << bit
11262           && ep->X_add_number < max << bit);
11263 }
11264
11265 /* This routine assembles an instruction into its binary format.  As a
11266    side effect, it sets one of the global variables imm_reloc or
11267    offset_reloc to the type of relocation to do if one of the operands
11268    is an address expression.  */
11269
11270 static void
11271 mips_ip (char *str, struct mips_cl_insn *ip)
11272 {
11273   bfd_boolean wrong_delay_slot_insns = FALSE;
11274   bfd_boolean need_delay_slot_ok = TRUE;
11275   struct mips_opcode *firstinsn = NULL;
11276   const struct mips_opcode *past;
11277   struct hash_control *hash;
11278   char *s;
11279   const char *args;
11280   char c = 0;
11281   struct mips_opcode *insn;
11282   char *argsStart;
11283   unsigned int regno;
11284   unsigned int lastregno;
11285   unsigned int destregno = 0;
11286   unsigned int lastpos = 0;
11287   unsigned int limlo, limhi;
11288   int sizelo;
11289   char *s_reset;
11290   offsetT min_range, max_range;
11291   long opend;
11292   char *name;
11293   int argnum;
11294   unsigned int rtype;
11295   char *dot;
11296   long end;
11297
11298   insn_error = NULL;
11299
11300   if (mips_opts.micromips)
11301     {
11302       hash = micromips_op_hash;
11303       past = &micromips_opcodes[bfd_micromips_num_opcodes];
11304     }
11305   else
11306     {
11307       hash = op_hash;
11308       past = &mips_opcodes[NUMOPCODES];
11309     }
11310   forced_insn_length = 0;
11311   insn = NULL;
11312
11313   /* We first try to match an instruction up to a space or to the end.  */
11314   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
11315     continue;
11316
11317   /* Make a copy of the instruction so that we can fiddle with it.  */
11318   name = alloca (end + 1);
11319   memcpy (name, str, end);
11320   name[end] = '\0';
11321
11322   for (;;)
11323     {
11324       insn = (struct mips_opcode *) hash_find (hash, name);
11325
11326       if (insn != NULL || !mips_opts.micromips)
11327         break;
11328       if (forced_insn_length)
11329         break;
11330
11331       /* See if there's an instruction size override suffix,
11332          either `16' or `32', at the end of the mnemonic proper,
11333          that defines the operation, i.e. before the first `.'
11334          character if any.  Strip it and retry.  */
11335       dot = strchr (name, '.');
11336       opend = dot != NULL ? dot - name : end;
11337       if (opend < 3)
11338         break;
11339       if (name[opend - 2] == '1' && name[opend - 1] == '6')
11340         forced_insn_length = 2;
11341       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
11342         forced_insn_length = 4;
11343       else
11344         break;
11345       memcpy (name + opend - 2, name + opend, end - opend + 1);
11346     }
11347   if (insn == NULL)
11348     {
11349       insn_error = _("Unrecognized opcode");
11350       return;
11351     }
11352
11353   /* For microMIPS instructions placed in a fixed-length branch delay slot
11354      we make up to two passes over the relevant fragment of the opcode
11355      table.  First we try instructions that meet the delay slot's length
11356      requirement.  If none matched, then we retry with the remaining ones
11357      and if one matches, then we use it and then issue an appropriate
11358      warning later on.  */
11359   argsStart = s = str + end;
11360   for (;;)
11361     {
11362       bfd_boolean delay_slot_ok;
11363       bfd_boolean size_ok;
11364       bfd_boolean ok;
11365
11366       gas_assert (strcmp (insn->name, name) == 0);
11367
11368       ok = is_opcode_valid (insn);
11369       size_ok = is_size_valid (insn);
11370       delay_slot_ok = is_delay_slot_valid (insn);
11371       if (!delay_slot_ok && !wrong_delay_slot_insns)
11372         {
11373           firstinsn = insn;
11374           wrong_delay_slot_insns = TRUE;
11375         }
11376       if (!ok || !size_ok || delay_slot_ok != need_delay_slot_ok)
11377         {
11378           static char buf[256];
11379
11380           if (insn + 1 < past && strcmp (insn->name, insn[1].name) == 0)
11381             {
11382               ++insn;
11383               continue;
11384             }
11385           if (wrong_delay_slot_insns && need_delay_slot_ok)
11386             {
11387               gas_assert (firstinsn);
11388               need_delay_slot_ok = FALSE;
11389               past = insn + 1;
11390               insn = firstinsn;
11391               continue;
11392             }
11393
11394           if (insn_error)
11395             return;
11396
11397           if (!ok)
11398             sprintf (buf, _("Opcode not supported on this processor: %s (%s)"),
11399                      mips_cpu_info_from_arch (mips_opts.arch)->name,
11400                      mips_cpu_info_from_isa (mips_opts.isa)->name);
11401           else
11402             sprintf (buf, _("Unrecognized %u-bit version of microMIPS opcode"),
11403                      8 * forced_insn_length);
11404           insn_error = buf;
11405
11406           return;
11407         }
11408
11409       create_insn (ip, insn);
11410       insn_error = NULL;
11411       argnum = 1;
11412       lastregno = 0xffffffff;
11413       for (args = insn->args;; ++args)
11414         {
11415           int is_mdmx;
11416
11417           s += strspn (s, " \t");
11418           is_mdmx = 0;
11419           switch (*args)
11420             {
11421             case '\0':          /* end of args */
11422               if (*s == '\0')
11423                 return;
11424               break;
11425
11426             case '2':
11427               /* DSP 2-bit unsigned immediate in bit 11 (for standard MIPS
11428                  code) or 14 (for microMIPS code).  */
11429               my_getExpression (&imm_expr, s);
11430               check_absolute_expr (ip, &imm_expr);
11431               if ((unsigned long) imm_expr.X_add_number != 1
11432                   && (unsigned long) imm_expr.X_add_number != 3)
11433                 {
11434                   as_bad (_("BALIGN immediate not 1 or 3 (%lu)"),
11435                           (unsigned long) imm_expr.X_add_number);
11436                 }
11437               INSERT_OPERAND (mips_opts.micromips,
11438                               BP, *ip, imm_expr.X_add_number);
11439               imm_expr.X_op = O_absent;
11440               s = expr_end;
11441               continue;
11442
11443             case '3':
11444               /* DSP 3-bit unsigned immediate in bit 13 (for standard MIPS
11445                  code) or 21 (for microMIPS code).  */
11446               {
11447                 unsigned long mask = (mips_opts.micromips
11448                                       ? MICROMIPSOP_MASK_SA3 : OP_MASK_SA3);
11449
11450                 my_getExpression (&imm_expr, s);
11451                 check_absolute_expr (ip, &imm_expr);
11452                 if ((unsigned long) imm_expr.X_add_number > mask)
11453                   as_bad (_("DSP immediate not in range 0..%lu (%lu)"),
11454                           mask, (unsigned long) imm_expr.X_add_number);
11455                 INSERT_OPERAND (mips_opts.micromips,
11456                                 SA3, *ip, imm_expr.X_add_number);
11457                 imm_expr.X_op = O_absent;
11458                 s = expr_end;
11459               }
11460               continue;
11461
11462             case '4':
11463               /* DSP 4-bit unsigned immediate in bit 12 (for standard MIPS
11464                  code) or 21 (for microMIPS code).  */
11465               {
11466                 unsigned long mask = (mips_opts.micromips
11467                                       ? MICROMIPSOP_MASK_SA4 : OP_MASK_SA4);
11468
11469                 my_getExpression (&imm_expr, s);
11470                 check_absolute_expr (ip, &imm_expr);
11471                 if ((unsigned long) imm_expr.X_add_number > mask)
11472                   as_bad (_("DSP immediate not in range 0..%lu (%lu)"),
11473                           mask, (unsigned long) imm_expr.X_add_number);
11474                 INSERT_OPERAND (mips_opts.micromips,
11475                                 SA4, *ip, imm_expr.X_add_number);
11476                 imm_expr.X_op = O_absent;
11477                 s = expr_end;
11478               }
11479               continue;
11480
11481             case '5':
11482               /* DSP 8-bit unsigned immediate in bit 13 (for standard MIPS
11483                  code) or 16 (for microMIPS code).  */
11484               {
11485                 unsigned long mask = (mips_opts.micromips
11486                                       ? MICROMIPSOP_MASK_IMM8 : OP_MASK_IMM8);
11487
11488                 my_getExpression (&imm_expr, s);
11489                 check_absolute_expr (ip, &imm_expr);
11490                 if ((unsigned long) imm_expr.X_add_number > mask)
11491                   as_bad (_("DSP immediate not in range 0..%lu (%lu)"),
11492                           mask, (unsigned long) imm_expr.X_add_number);
11493                 INSERT_OPERAND (mips_opts.micromips,
11494                                 IMM8, *ip, imm_expr.X_add_number);
11495                 imm_expr.X_op = O_absent;
11496                 s = expr_end;
11497               }
11498               continue;
11499
11500             case '6':
11501               /* DSP 5-bit unsigned immediate in bit 16 (for standard MIPS
11502                  code) or 21 (for microMIPS code).  */
11503               {
11504                 unsigned long mask = (mips_opts.micromips
11505                                       ? MICROMIPSOP_MASK_RS : OP_MASK_RS);
11506
11507                 my_getExpression (&imm_expr, s);
11508                 check_absolute_expr (ip, &imm_expr);
11509                 if ((unsigned long) imm_expr.X_add_number > mask)
11510                   as_bad (_("DSP immediate not in range 0..%lu (%lu)"),
11511                           mask, (unsigned long) imm_expr.X_add_number);
11512                 INSERT_OPERAND (mips_opts.micromips,
11513                                 RS, *ip, imm_expr.X_add_number);
11514                 imm_expr.X_op = O_absent;
11515                 s = expr_end;
11516               }
11517               continue;
11518
11519             case '7': /* Four DSP accumulators in bits 11,12.  */
11520               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c'
11521                   && s[3] >= '0' && s[3] <= '3')
11522                 {
11523                   regno = s[3] - '0';
11524                   s += 4;
11525                   INSERT_OPERAND (mips_opts.micromips, DSPACC, *ip, regno);
11526                   continue;
11527                 }
11528               else
11529                 as_bad (_("Invalid dsp acc register"));
11530               break;
11531
11532             case '8':
11533               /* DSP 6-bit unsigned immediate in bit 11 (for standard MIPS
11534                  code) or 14 (for microMIPS code).  */
11535               {
11536                 unsigned long mask = (mips_opts.micromips
11537                                       ? MICROMIPSOP_MASK_WRDSP
11538                                       : OP_MASK_WRDSP);
11539
11540                 my_getExpression (&imm_expr, s);
11541                 check_absolute_expr (ip, &imm_expr);
11542                 if ((unsigned long) imm_expr.X_add_number > mask)
11543                   as_bad (_("DSP immediate not in range 0..%lu (%lu)"),
11544                           mask, (unsigned long) imm_expr.X_add_number);
11545                 INSERT_OPERAND (mips_opts.micromips,
11546                                 WRDSP, *ip, imm_expr.X_add_number);
11547                 imm_expr.X_op = O_absent;
11548                 s = expr_end;
11549               }
11550               continue;
11551
11552             case '9': /* Four DSP accumulators in bits 21,22.  */
11553               gas_assert (!mips_opts.micromips);
11554               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c'
11555                   && s[3] >= '0' && s[3] <= '3')
11556                 {
11557                   regno = s[3] - '0';
11558                   s += 4;
11559                   INSERT_OPERAND (0, DSPACC_S, *ip, regno);
11560                   continue;
11561                 }
11562               else
11563                 as_bad (_("Invalid dsp acc register"));
11564               break;
11565
11566             case '0':
11567               /* DSP 6-bit signed immediate in bit 16 (for standard MIPS
11568                  code) or 20 (for microMIPS code).  */
11569               {
11570                 long mask = (mips_opts.micromips
11571                              ? MICROMIPSOP_MASK_DSPSFT : OP_MASK_DSPSFT);
11572
11573                 my_getExpression (&imm_expr, s);
11574                 check_absolute_expr (ip, &imm_expr);
11575                 min_range = -((mask + 1) >> 1);
11576                 max_range = ((mask + 1) >> 1) - 1;
11577                 if (imm_expr.X_add_number < min_range
11578                     || imm_expr.X_add_number > max_range)
11579                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
11580                           (long) min_range, (long) max_range,
11581                           (long) imm_expr.X_add_number);
11582                 INSERT_OPERAND (mips_opts.micromips,
11583                                 DSPSFT, *ip, imm_expr.X_add_number);
11584                 imm_expr.X_op = O_absent;
11585                 s = expr_end;
11586               }
11587               continue;
11588
11589             case '\'': /* DSP 6-bit unsigned immediate in bit 16.  */
11590               gas_assert (!mips_opts.micromips);
11591               my_getExpression (&imm_expr, s);
11592               check_absolute_expr (ip, &imm_expr);
11593               if (imm_expr.X_add_number & ~OP_MASK_RDDSP)
11594                 {
11595                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
11596                           OP_MASK_RDDSP,
11597                           (unsigned long) imm_expr.X_add_number);
11598                 }
11599               INSERT_OPERAND (0, RDDSP, *ip, imm_expr.X_add_number);
11600               imm_expr.X_op = O_absent;
11601               s = expr_end;
11602               continue;
11603
11604             case ':': /* DSP 7-bit signed immediate in bit 19.  */
11605               gas_assert (!mips_opts.micromips);
11606               my_getExpression (&imm_expr, s);
11607               check_absolute_expr (ip, &imm_expr);
11608               min_range = -((OP_MASK_DSPSFT_7 + 1) >> 1);
11609               max_range = ((OP_MASK_DSPSFT_7 + 1) >> 1) - 1;
11610               if (imm_expr.X_add_number < min_range ||
11611                   imm_expr.X_add_number > max_range)
11612                 {
11613                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
11614                           (long) min_range, (long) max_range,
11615                           (long) imm_expr.X_add_number);
11616                 }
11617               INSERT_OPERAND (0, DSPSFT_7, *ip, imm_expr.X_add_number);
11618               imm_expr.X_op = O_absent;
11619               s = expr_end;
11620               continue;
11621
11622             case '@': /* DSP 10-bit signed immediate in bit 16.  */
11623               {
11624                 long mask = (mips_opts.micromips
11625                              ? MICROMIPSOP_MASK_IMM10 : OP_MASK_IMM10);
11626
11627                 my_getExpression (&imm_expr, s);
11628                 check_absolute_expr (ip, &imm_expr);
11629                 min_range = -((mask + 1) >> 1);
11630                 max_range = ((mask + 1) >> 1) - 1;
11631                 if (imm_expr.X_add_number < min_range
11632                     || imm_expr.X_add_number > max_range)
11633                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
11634                           (long) min_range, (long) max_range,
11635                           (long) imm_expr.X_add_number);
11636                 INSERT_OPERAND (mips_opts.micromips,
11637                                 IMM10, *ip, imm_expr.X_add_number);
11638                 imm_expr.X_op = O_absent;
11639                 s = expr_end;
11640               }
11641               continue;
11642
11643             case '^': /* DSP 5-bit unsigned immediate in bit 11.  */
11644               gas_assert (mips_opts.micromips);
11645               my_getExpression (&imm_expr, s);
11646               check_absolute_expr (ip, &imm_expr);
11647               if (imm_expr.X_add_number & ~MICROMIPSOP_MASK_RD)
11648                 as_bad (_("DSP immediate not in range 0..%d (%lu)"),
11649                         MICROMIPSOP_MASK_RD,
11650                         (unsigned long) imm_expr.X_add_number);
11651               INSERT_OPERAND (1, RD, *ip, imm_expr.X_add_number);
11652               imm_expr.X_op = O_absent;
11653               s = expr_end;
11654               continue;
11655
11656             case '!': /* MT usermode flag bit.  */
11657               gas_assert (!mips_opts.micromips);
11658               my_getExpression (&imm_expr, s);
11659               check_absolute_expr (ip, &imm_expr);
11660               if (imm_expr.X_add_number & ~OP_MASK_MT_U)
11661                 as_bad (_("MT usermode bit not 0 or 1 (%lu)"),
11662                         (unsigned long) imm_expr.X_add_number);
11663               INSERT_OPERAND (0, MT_U, *ip, imm_expr.X_add_number);
11664               imm_expr.X_op = O_absent;
11665               s = expr_end;
11666               continue;
11667
11668             case '$': /* MT load high flag bit.  */
11669               gas_assert (!mips_opts.micromips);
11670               my_getExpression (&imm_expr, s);
11671               check_absolute_expr (ip, &imm_expr);
11672               if (imm_expr.X_add_number & ~OP_MASK_MT_H)
11673                 as_bad (_("MT load high bit not 0 or 1 (%lu)"),
11674                         (unsigned long) imm_expr.X_add_number);
11675               INSERT_OPERAND (0, MT_H, *ip, imm_expr.X_add_number);
11676               imm_expr.X_op = O_absent;
11677               s = expr_end;
11678               continue;
11679
11680             case '*': /* Four DSP accumulators in bits 18,19.  */
11681               gas_assert (!mips_opts.micromips);
11682               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
11683                   s[3] >= '0' && s[3] <= '3')
11684                 {
11685                   regno = s[3] - '0';
11686                   s += 4;
11687                   INSERT_OPERAND (0, MTACC_T, *ip, regno);
11688                   continue;
11689                 }
11690               else
11691                 as_bad (_("Invalid dsp/smartmips acc register"));
11692               break;
11693
11694             case '&': /* Four DSP accumulators in bits 13,14.  */
11695               gas_assert (!mips_opts.micromips);
11696               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
11697                   s[3] >= '0' && s[3] <= '3')
11698                 {
11699                   regno = s[3] - '0';
11700                   s += 4;
11701                   INSERT_OPERAND (0, MTACC_D, *ip, regno);
11702                   continue;
11703                 }
11704               else
11705                 as_bad (_("Invalid dsp/smartmips acc register"));
11706               break;
11707
11708             case '\\':          /* 3-bit bit position.  */
11709               {
11710                 unsigned long mask = (mips_opts.micromips
11711                                       ? MICROMIPSOP_MASK_3BITPOS
11712                                       : OP_MASK_3BITPOS);
11713
11714                 my_getExpression (&imm_expr, s);
11715                 check_absolute_expr (ip, &imm_expr);
11716                 if ((unsigned long) imm_expr.X_add_number > mask)
11717                   as_warn (_("Bit position for %s not in range 0..%lu (%lu)"),
11718                            ip->insn_mo->name,
11719                            mask, (unsigned long) imm_expr.X_add_number);
11720                 INSERT_OPERAND (mips_opts.micromips,
11721                                 3BITPOS, *ip, imm_expr.X_add_number);
11722                 imm_expr.X_op = O_absent;
11723                 s = expr_end;
11724               }
11725               continue;
11726
11727             case ',':
11728               ++argnum;
11729               if (*s++ == *args)
11730                 continue;
11731               s--;
11732               switch (*++args)
11733                 {
11734                 case 'r':
11735                 case 'v':
11736                   INSERT_OPERAND (mips_opts.micromips, RS, *ip, lastregno);
11737                   continue;
11738
11739                 case 'w':
11740                   INSERT_OPERAND (mips_opts.micromips, RT, *ip, lastregno);
11741                   continue;
11742
11743                 case 'W':
11744                   gas_assert (!mips_opts.micromips);
11745                   INSERT_OPERAND (0, FT, *ip, lastregno);
11746                   continue;
11747
11748                 case 'V':
11749                   INSERT_OPERAND (mips_opts.micromips, FS, *ip, lastregno);
11750                   continue;
11751                 }
11752               break;
11753
11754             case '(':
11755               /* Handle optional base register.
11756                  Either the base register is omitted or
11757                  we must have a left paren.  */
11758               /* This is dependent on the next operand specifier
11759                  is a base register specification.  */
11760               gas_assert (args[1] == 'b'
11761                           || (mips_opts.micromips
11762                               && args[1] == 'm'
11763                               && (args[2] == 'l' || args[2] == 'n'
11764                                   || args[2] == 's' || args[2] == 'a')));
11765               if (*s == '\0' && args[1] == 'b')
11766                 return;
11767               /* Fall through.  */
11768
11769             case ')':           /* These must match exactly.  */
11770               if (*s++ == *args)
11771                 continue;
11772               break;
11773
11774             case '[':           /* These must match exactly.  */
11775             case ']':
11776               gas_assert (!mips_opts.micromips);
11777               if (*s++ == *args)
11778                 continue;
11779               break;
11780
11781             case '+':           /* Opcode extension character.  */
11782               switch (*++args)
11783                 {
11784                 case '1':       /* UDI immediates.  */
11785                 case '2':
11786                 case '3':
11787                 case '4':
11788                   gas_assert (!mips_opts.micromips);
11789                   {
11790                     const struct mips_immed *imm = mips_immed;
11791
11792                     while (imm->type && imm->type != *args)
11793                       ++imm;
11794                     if (! imm->type)
11795                       abort ();
11796                     my_getExpression (&imm_expr, s);
11797                     check_absolute_expr (ip, &imm_expr);
11798                     if ((unsigned long) imm_expr.X_add_number & ~imm->mask)
11799                       {
11800                         as_warn (_("Illegal %s number (%lu, 0x%lx)"),
11801                                  imm->desc ? imm->desc : ip->insn_mo->name,
11802                                  (unsigned long) imm_expr.X_add_number,
11803                                  (unsigned long) imm_expr.X_add_number);
11804                         imm_expr.X_add_number &= imm->mask;
11805                       }
11806                     ip->insn_opcode |= ((unsigned long) imm_expr.X_add_number
11807                                         << imm->shift);
11808                     imm_expr.X_op = O_absent;
11809                     s = expr_end;
11810                   }
11811                   continue;
11812
11813                 case 'J':               /* 10-bit hypcall code.  */
11814                   gas_assert (!mips_opts.micromips);
11815                   {
11816                     unsigned long mask = OP_MASK_CODE10;
11817
11818                     my_getExpression (&imm_expr, s);
11819                     check_absolute_expr (ip, &imm_expr);
11820                     if ((unsigned long) imm_expr.X_add_number > mask)
11821                       as_warn (_("Code for %s not in range 0..%lu (%lu)"),
11822                                ip->insn_mo->name,
11823                                mask, (unsigned long) imm_expr.X_add_number);
11824                     INSERT_OPERAND (0, CODE10, *ip, imm_expr.X_add_number);
11825                     imm_expr.X_op = O_absent;
11826                     s = expr_end;
11827                   }
11828                   continue;
11829
11830                 case 'A':               /* ins/ext position, becomes LSB.  */
11831                   limlo = 0;
11832                   limhi = 31;
11833                   goto do_lsb;
11834                 case 'E':
11835                   limlo = 32;
11836                   limhi = 63;
11837                   goto do_lsb;
11838                 do_lsb:
11839                   my_getExpression (&imm_expr, s);
11840                   check_absolute_expr (ip, &imm_expr);
11841                   if ((unsigned long) imm_expr.X_add_number < limlo
11842                       || (unsigned long) imm_expr.X_add_number > limhi)
11843                     {
11844                       as_bad (_("Improper position (%lu)"),
11845                               (unsigned long) imm_expr.X_add_number);
11846                       imm_expr.X_add_number = limlo;
11847                     }
11848                   lastpos = imm_expr.X_add_number;
11849                   INSERT_OPERAND (mips_opts.micromips,
11850                                   EXTLSB, *ip, imm_expr.X_add_number);
11851                   imm_expr.X_op = O_absent;
11852                   s = expr_end;
11853                   continue;
11854
11855                 case 'B':               /* ins size, becomes MSB.  */
11856                   limlo = 1;
11857                   limhi = 32;
11858                   goto do_msb;
11859                 case 'F':
11860                   limlo = 33;
11861                   limhi = 64;
11862                   goto do_msb;
11863                 do_msb:
11864                   my_getExpression (&imm_expr, s);
11865                   check_absolute_expr (ip, &imm_expr);
11866                   /* Check for negative input so that small negative numbers
11867                      will not succeed incorrectly.  The checks against
11868                      (pos+size) transitively check "size" itself,
11869                      assuming that "pos" is reasonable.  */
11870                   if ((long) imm_expr.X_add_number < 0
11871                       || ((unsigned long) imm_expr.X_add_number
11872                           + lastpos) < limlo
11873                       || ((unsigned long) imm_expr.X_add_number
11874                           + lastpos) > limhi)
11875                     {
11876                       as_bad (_("Improper insert size (%lu, position %lu)"),
11877                               (unsigned long) imm_expr.X_add_number,
11878                               (unsigned long) lastpos);
11879                       imm_expr.X_add_number = limlo - lastpos;
11880                     }
11881                   INSERT_OPERAND (mips_opts.micromips, INSMSB, *ip,
11882                                   lastpos + imm_expr.X_add_number - 1);
11883                   imm_expr.X_op = O_absent;
11884                   s = expr_end;
11885                   continue;
11886
11887                 case 'C':               /* ext size, becomes MSBD.  */
11888                   limlo = 1;
11889                   limhi = 32;
11890                   sizelo = 1;
11891                   goto do_msbd;
11892                 case 'G':
11893                   limlo = 33;
11894                   limhi = 64;
11895                   sizelo = 33;
11896                   goto do_msbd;
11897                 case 'H':
11898                   limlo = 33;
11899                   limhi = 64;
11900                   sizelo = 1;
11901                   goto do_msbd;
11902                 do_msbd:
11903                   my_getExpression (&imm_expr, s);
11904                   check_absolute_expr (ip, &imm_expr);
11905                   /* The checks against (pos+size) don't transitively check
11906                      "size" itself, assuming that "pos" is reasonable.
11907                      We also need to check the lower bound of "size".  */
11908                   if ((long) imm_expr.X_add_number < sizelo
11909                       || ((unsigned long) imm_expr.X_add_number
11910                           + lastpos) < limlo
11911                       || ((unsigned long) imm_expr.X_add_number
11912                           + lastpos) > limhi)
11913                     {
11914                       as_bad (_("Improper extract size (%lu, position %lu)"),
11915                               (unsigned long) imm_expr.X_add_number,
11916                               (unsigned long) lastpos);
11917                       imm_expr.X_add_number = limlo - lastpos;
11918                     }
11919                   INSERT_OPERAND (mips_opts.micromips,
11920                                   EXTMSBD, *ip, imm_expr.X_add_number - 1);
11921                   imm_expr.X_op = O_absent;
11922                   s = expr_end;
11923                   continue;
11924
11925                 case 'D':
11926                   /* +D is for disassembly only; never match.  */
11927                   break;
11928
11929                 case 'I':
11930                   /* "+I" is like "I", except that imm2_expr is used.  */
11931                   my_getExpression (&imm2_expr, s);
11932                   if (imm2_expr.X_op != O_big
11933                       && imm2_expr.X_op != O_constant)
11934                   insn_error = _("absolute expression required");
11935                   if (HAVE_32BIT_GPRS)
11936                     normalize_constant_expr (&imm2_expr);
11937                   s = expr_end;
11938                   continue;
11939
11940                 case 'T': /* Coprocessor register.  */
11941                   gas_assert (!mips_opts.micromips);
11942                   /* +T is for disassembly only; never match.  */
11943                   break;
11944
11945                 case 't': /* Coprocessor register number.  */
11946                   gas_assert (!mips_opts.micromips);
11947                   if (s[0] == '$' && ISDIGIT (s[1]))
11948                     {
11949                       ++s;
11950                       regno = 0;
11951                       do
11952                         {
11953                           regno *= 10;
11954                           regno += *s - '0';
11955                           ++s;
11956                         }
11957                       while (ISDIGIT (*s));
11958                       if (regno > 31)
11959                         as_bad (_("Invalid register number (%d)"), regno);
11960                       else
11961                         {
11962                           INSERT_OPERAND (0, RT, *ip, regno);
11963                           continue;
11964                         }
11965                     }
11966                   else
11967                     as_bad (_("Invalid coprocessor 0 register number"));
11968                   break;
11969
11970                 case 'x':
11971                   /* bbit[01] and bbit[01]32 bit index.  Give error if index
11972                      is not in the valid range.  */
11973                   gas_assert (!mips_opts.micromips);
11974                   my_getExpression (&imm_expr, s);
11975                   check_absolute_expr (ip, &imm_expr);
11976                   if ((unsigned) imm_expr.X_add_number > 31)
11977                     {
11978                       as_bad (_("Improper bit index (%lu)"),
11979                               (unsigned long) imm_expr.X_add_number);
11980                       imm_expr.X_add_number = 0;
11981                     }
11982                   INSERT_OPERAND (0, BBITIND, *ip, imm_expr.X_add_number);
11983                   imm_expr.X_op = O_absent;
11984                   s = expr_end;
11985                   continue;
11986
11987                 case 'X':
11988                   /* bbit[01] bit index when bbit is used but we generate
11989                      bbit[01]32 because the index is over 32.  Move to the
11990                      next candidate if index is not in the valid range.  */
11991                   gas_assert (!mips_opts.micromips);
11992                   my_getExpression (&imm_expr, s);
11993                   check_absolute_expr (ip, &imm_expr);
11994                   if ((unsigned) imm_expr.X_add_number < 32
11995                       || (unsigned) imm_expr.X_add_number > 63)
11996                     break;
11997                   INSERT_OPERAND (0, BBITIND, *ip, imm_expr.X_add_number - 32);
11998                   imm_expr.X_op = O_absent;
11999                   s = expr_end;
12000                   continue;
12001
12002                 case 'p':
12003                   /* cins, cins32, exts and exts32 position field.  Give error
12004                      if it's not in the valid range.  */
12005                   gas_assert (!mips_opts.micromips);
12006                   my_getExpression (&imm_expr, s);
12007                   check_absolute_expr (ip, &imm_expr);
12008                   if ((unsigned) imm_expr.X_add_number > 31)
12009                     {
12010                       as_bad (_("Improper position (%lu)"),
12011                               (unsigned long) imm_expr.X_add_number);
12012                       imm_expr.X_add_number = 0;
12013                     }
12014                   /* Make the pos explicit to simplify +S.  */
12015                   lastpos = imm_expr.X_add_number + 32;
12016                   INSERT_OPERAND (0, CINSPOS, *ip, imm_expr.X_add_number);
12017                   imm_expr.X_op = O_absent;
12018                   s = expr_end;
12019                   continue;
12020
12021                 case 'P':
12022                   /* cins, cins32, exts and exts32 position field.  Move to
12023                      the next candidate if it's not in the valid range.  */
12024                   gas_assert (!mips_opts.micromips);
12025                   my_getExpression (&imm_expr, s);
12026                   check_absolute_expr (ip, &imm_expr);
12027                   if ((unsigned) imm_expr.X_add_number < 32
12028                       || (unsigned) imm_expr.X_add_number > 63)
12029                     break;
12030                   lastpos = imm_expr.X_add_number;
12031                   INSERT_OPERAND (0, CINSPOS, *ip, imm_expr.X_add_number - 32);
12032                   imm_expr.X_op = O_absent;
12033                   s = expr_end;
12034                   continue;
12035
12036                 case 's':
12037                   /* cins and exts length-minus-one field.  */
12038                   gas_assert (!mips_opts.micromips);
12039                   my_getExpression (&imm_expr, s);
12040                   check_absolute_expr (ip, &imm_expr);
12041                   if ((unsigned long) imm_expr.X_add_number > 31)
12042                     {
12043                       as_bad (_("Improper size (%lu)"),
12044                               (unsigned long) imm_expr.X_add_number);
12045                       imm_expr.X_add_number = 0;
12046                     }
12047                   INSERT_OPERAND (0, CINSLM1, *ip, imm_expr.X_add_number);
12048                   imm_expr.X_op = O_absent;
12049                   s = expr_end;
12050                   continue;
12051
12052                 case 'S':
12053                   /* cins32/exts32 and cins/exts aliasing cint32/exts32
12054                      length-minus-one field.  */
12055                   gas_assert (!mips_opts.micromips);
12056                   my_getExpression (&imm_expr, s);
12057                   check_absolute_expr (ip, &imm_expr);
12058                   if ((long) imm_expr.X_add_number < 0
12059                       || (unsigned long) imm_expr.X_add_number + lastpos > 63)
12060                     {
12061                       as_bad (_("Improper size (%lu)"),
12062                               (unsigned long) imm_expr.X_add_number);
12063                       imm_expr.X_add_number = 0;
12064                     }
12065                   INSERT_OPERAND (0, CINSLM1, *ip, imm_expr.X_add_number);
12066                   imm_expr.X_op = O_absent;
12067                   s = expr_end;
12068                   continue;
12069
12070                 case 'Q':
12071                   /* seqi/snei immediate field.  */
12072                   gas_assert (!mips_opts.micromips);
12073                   my_getExpression (&imm_expr, s);
12074                   check_absolute_expr (ip, &imm_expr);
12075                   if ((long) imm_expr.X_add_number < -512
12076                       || (long) imm_expr.X_add_number >= 512)
12077                     {
12078                       as_bad (_("Improper immediate (%ld)"),
12079                                (long) imm_expr.X_add_number);
12080                       imm_expr.X_add_number = 0;
12081                     }
12082                   INSERT_OPERAND (0, SEQI, *ip, imm_expr.X_add_number);
12083                   imm_expr.X_op = O_absent;
12084                   s = expr_end;
12085                   continue;
12086
12087                 case 'a': /* 8-bit signed offset in bit 6 */
12088                   gas_assert (!mips_opts.micromips);
12089                   my_getExpression (&imm_expr, s);
12090                   check_absolute_expr (ip, &imm_expr);
12091                   min_range = -((OP_MASK_OFFSET_A + 1) >> 1);
12092                   max_range = ((OP_MASK_OFFSET_A + 1) >> 1) - 1;
12093                   if (imm_expr.X_add_number < min_range
12094                       || imm_expr.X_add_number > max_range)
12095                     {
12096                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
12097                               (long) min_range, (long) max_range,
12098                               (long) imm_expr.X_add_number);
12099                     }
12100                   INSERT_OPERAND (0, OFFSET_A, *ip, imm_expr.X_add_number);
12101                   imm_expr.X_op = O_absent;
12102                   s = expr_end;
12103                   continue;
12104
12105                 case 'b': /* 8-bit signed offset in bit 3 */
12106                   gas_assert (!mips_opts.micromips);
12107                   my_getExpression (&imm_expr, s);
12108                   check_absolute_expr (ip, &imm_expr);
12109                   min_range = -((OP_MASK_OFFSET_B + 1) >> 1);
12110                   max_range = ((OP_MASK_OFFSET_B + 1) >> 1) - 1;
12111                   if (imm_expr.X_add_number < min_range
12112                       || imm_expr.X_add_number > max_range)
12113                     {
12114                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
12115                               (long) min_range, (long) max_range,
12116                               (long) imm_expr.X_add_number);
12117                     }
12118                   INSERT_OPERAND (0, OFFSET_B, *ip, imm_expr.X_add_number);
12119                   imm_expr.X_op = O_absent;
12120                   s = expr_end;
12121                   continue;
12122
12123                 case 'c': /* 9-bit signed offset in bit 6 */
12124                   gas_assert (!mips_opts.micromips);
12125                   my_getExpression (&imm_expr, s);
12126                   check_absolute_expr (ip, &imm_expr);
12127                   min_range = -((OP_MASK_OFFSET_C + 1) >> 1);
12128                   max_range = ((OP_MASK_OFFSET_C + 1) >> 1) - 1;
12129                   /* We check the offset range before adjusted.  */
12130                   min_range <<= 4;
12131                   max_range <<= 4;
12132                   if (imm_expr.X_add_number < min_range
12133                       || imm_expr.X_add_number > max_range)
12134                     {
12135                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
12136                               (long) min_range, (long) max_range,
12137                               (long) imm_expr.X_add_number);
12138                     }
12139                   if (imm_expr.X_add_number & 0xf)
12140                     {
12141                       as_bad (_("Offset not 16 bytes alignment (%ld)"),
12142                               (long) imm_expr.X_add_number);
12143                     }
12144                   /* Right shift 4 bits to adjust the offset operand.  */
12145                   INSERT_OPERAND (0, OFFSET_C, *ip,
12146                                   imm_expr.X_add_number >> 4);
12147                   imm_expr.X_op = O_absent;
12148                   s = expr_end;
12149                   continue;
12150
12151                 case 'z':
12152                   gas_assert (!mips_opts.micromips);
12153                   if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno))
12154                     break;
12155                   if (regno == AT && mips_opts.at)
12156                     {
12157                       if (mips_opts.at == ATREG)
12158                         as_warn (_("used $at without \".set noat\""));
12159                       else
12160                         as_warn (_("used $%u with \".set at=$%u\""),
12161                                  regno, mips_opts.at);
12162                     }
12163                   INSERT_OPERAND (0, RZ, *ip, regno);
12164                   continue;
12165
12166                 case 'Z':
12167                   gas_assert (!mips_opts.micromips);
12168                   if (!reg_lookup (&s, RTYPE_FPU, &regno))
12169                     break;
12170                   INSERT_OPERAND (0, FZ, *ip, regno);
12171                   continue;
12172
12173                 case 'j':
12174                   {
12175                     int shift = 8;
12176                     size_t i;
12177                     /* Check whether there is only a single bracketed expression
12178                        left.  If so, it must be the base register and the
12179                        constant must be zero.  */
12180                     if (*s == '(' && strchr (s + 1, '(') == 0)
12181                       continue;
12182
12183                     /* If this value won't fit into the offset, then go find
12184                        a macro that will generate a 16- or 32-bit offset code
12185                        pattern.  */
12186                     i = my_getSmallExpression (&imm_expr, imm_reloc, s);
12187                     if ((i == 0 && (imm_expr.X_op != O_constant
12188                                     || imm_expr.X_add_number >= 1 << shift
12189                                     || imm_expr.X_add_number < -1 << shift))
12190                         || i > 0)
12191                       {
12192                         imm_expr.X_op = O_absent;
12193                         break;
12194                       }
12195                     INSERT_OPERAND (mips_opts.micromips, EVAOFFSET, *ip,
12196                                     imm_expr.X_add_number);
12197                     imm_expr.X_op = O_absent;
12198                     s = expr_end;
12199                   }
12200                   continue;
12201
12202                 default:
12203                   as_bad (_("Internal error: bad %s opcode "
12204                             "(unknown extension operand type `+%c'): %s %s"),
12205                           mips_opts.micromips ? "microMIPS" : "MIPS",
12206                           *args, insn->name, insn->args);
12207                   /* Further processing is fruitless.  */
12208                   return;
12209                 }
12210               break;
12211
12212             case '.':           /* 10-bit offset.  */
12213               gas_assert (mips_opts.micromips);
12214             case '~':           /* 12-bit offset.  */
12215               {
12216                 int shift = *args == '.' ? 9 : 11;
12217                 size_t i;
12218
12219                 /* Check whether there is only a single bracketed expression
12220                    left.  If so, it must be the base register and the
12221                    constant must be zero.  */
12222                 if (*s == '(' && strchr (s + 1, '(') == 0)
12223                   continue;
12224
12225                 /* If this value won't fit into the offset, then go find
12226                    a macro that will generate a 16- or 32-bit offset code
12227                    pattern.  */
12228                 i = my_getSmallExpression (&imm_expr, imm_reloc, s);
12229                 if ((i == 0 && (imm_expr.X_op != O_constant
12230                                 || imm_expr.X_add_number >= 1 << shift
12231                                 || imm_expr.X_add_number < -1 << shift))
12232                     || i > 0)
12233                   {
12234                     imm_expr.X_op = O_absent;
12235                     break;
12236                   }
12237                 if (shift == 9)
12238                   INSERT_OPERAND (1, OFFSET10, *ip, imm_expr.X_add_number);
12239                 else
12240                   INSERT_OPERAND (mips_opts.micromips,
12241                                   OFFSET12, *ip, imm_expr.X_add_number);
12242                 imm_expr.X_op = O_absent;
12243                 s = expr_end;
12244               }
12245               continue;
12246
12247             case '<':           /* must be at least one digit */
12248               /*
12249                * According to the manual, if the shift amount is greater
12250                * than 31 or less than 0, then the shift amount should be
12251                * mod 32.  In reality the mips assembler issues an error.
12252                * We issue a warning and mask out all but the low 5 bits.
12253                */
12254               my_getExpression (&imm_expr, s);
12255               check_absolute_expr (ip, &imm_expr);
12256               if ((unsigned long) imm_expr.X_add_number > 31)
12257                 as_warn (_("Improper shift amount (%lu)"),
12258                          (unsigned long) imm_expr.X_add_number);
12259               INSERT_OPERAND (mips_opts.micromips,
12260                               SHAMT, *ip, imm_expr.X_add_number);
12261               imm_expr.X_op = O_absent;
12262               s = expr_end;
12263               continue;
12264
12265             case '>':           /* shift amount minus 32 */
12266               my_getExpression (&imm_expr, s);
12267               check_absolute_expr (ip, &imm_expr);
12268               if ((unsigned long) imm_expr.X_add_number < 32
12269                   || (unsigned long) imm_expr.X_add_number > 63)
12270                 break;
12271               INSERT_OPERAND (mips_opts.micromips,
12272                               SHAMT, *ip, imm_expr.X_add_number - 32);
12273               imm_expr.X_op = O_absent;
12274               s = expr_end;
12275               continue;
12276
12277             case 'k':           /* CACHE code.  */
12278             case 'h':           /* PREFX code.  */
12279             case '1':           /* SYNC type.  */
12280               my_getExpression (&imm_expr, s);
12281               check_absolute_expr (ip, &imm_expr);
12282               if ((unsigned long) imm_expr.X_add_number > 31)
12283                 as_warn (_("Invalid value for `%s' (%lu)"),
12284                          ip->insn_mo->name,
12285                          (unsigned long) imm_expr.X_add_number);
12286               switch (*args)
12287                 {
12288                 case 'k':
12289                   if (mips_fix_cn63xxp1
12290                       && !mips_opts.micromips
12291                       && strcmp ("pref", insn->name) == 0)
12292                     switch (imm_expr.X_add_number)
12293                       {
12294                       case 5:
12295                       case 25:
12296                       case 26:
12297                       case 27:
12298                       case 28:
12299                       case 29:
12300                       case 30:
12301                       case 31:  /* These are ok.  */
12302                         break;
12303
12304                       default:  /* The rest must be changed to 28.  */
12305                         imm_expr.X_add_number = 28;
12306                         break;
12307                       }
12308                   INSERT_OPERAND (mips_opts.micromips,
12309                                   CACHE, *ip, imm_expr.X_add_number);
12310                   break;
12311                 case 'h':
12312                   INSERT_OPERAND (mips_opts.micromips,
12313                                   PREFX, *ip, imm_expr.X_add_number);
12314                   break;
12315                 case '1':
12316                   INSERT_OPERAND (mips_opts.micromips,
12317                                   STYPE, *ip, imm_expr.X_add_number);
12318                   break;
12319                 }
12320               imm_expr.X_op = O_absent;
12321               s = expr_end;
12322               continue;
12323
12324             case 'c':           /* BREAK code.  */
12325               {
12326                 unsigned long mask = (mips_opts.micromips
12327                                       ? MICROMIPSOP_MASK_CODE
12328                                       : OP_MASK_CODE);
12329
12330                 my_getExpression (&imm_expr, s);
12331                 check_absolute_expr (ip, &imm_expr);
12332                 if ((unsigned long) imm_expr.X_add_number > mask)
12333                   as_warn (_("Code for %s not in range 0..%lu (%lu)"),
12334                            ip->insn_mo->name,
12335                            mask, (unsigned long) imm_expr.X_add_number);
12336                 INSERT_OPERAND (mips_opts.micromips,
12337                                 CODE, *ip, imm_expr.X_add_number);
12338                 imm_expr.X_op = O_absent;
12339                 s = expr_end;
12340               }
12341               continue;
12342
12343             case 'q':           /* Lower BREAK code.  */
12344               {
12345                 unsigned long mask = (mips_opts.micromips
12346                                       ? MICROMIPSOP_MASK_CODE2
12347                                       : OP_MASK_CODE2);
12348
12349                 my_getExpression (&imm_expr, s);
12350                 check_absolute_expr (ip, &imm_expr);
12351                 if ((unsigned long) imm_expr.X_add_number > mask)
12352                   as_warn (_("Lower code for %s not in range 0..%lu (%lu)"),
12353                            ip->insn_mo->name,
12354                            mask, (unsigned long) imm_expr.X_add_number);
12355                 INSERT_OPERAND (mips_opts.micromips,
12356                                 CODE2, *ip, imm_expr.X_add_number);
12357                 imm_expr.X_op = O_absent;
12358                 s = expr_end;
12359               }
12360               continue;
12361
12362             case 'B':           /* 20- or 10-bit syscall/break/wait code.  */
12363               {
12364                 unsigned long mask = (mips_opts.micromips
12365                                       ? MICROMIPSOP_MASK_CODE10
12366                                       : OP_MASK_CODE20);
12367
12368                 my_getExpression (&imm_expr, s);
12369                 check_absolute_expr (ip, &imm_expr);
12370                 if ((unsigned long) imm_expr.X_add_number > mask)
12371                   as_warn (_("Code for %s not in range 0..%lu (%lu)"),
12372                            ip->insn_mo->name,
12373                            mask, (unsigned long) imm_expr.X_add_number);
12374                 if (mips_opts.micromips)
12375                   INSERT_OPERAND (1, CODE10, *ip, imm_expr.X_add_number);
12376                 else
12377                   INSERT_OPERAND (0, CODE20, *ip, imm_expr.X_add_number);
12378                 imm_expr.X_op = O_absent;
12379                 s = expr_end;
12380               }
12381               continue;
12382
12383             case 'C':           /* 25- or 23-bit coprocessor code.  */
12384               {
12385                 unsigned long mask = (mips_opts.micromips
12386                                       ? MICROMIPSOP_MASK_COPZ
12387                                       : OP_MASK_COPZ);
12388
12389                 my_getExpression (&imm_expr, s);
12390                 check_absolute_expr (ip, &imm_expr);
12391                 if ((unsigned long) imm_expr.X_add_number > mask)
12392                   as_warn (_("Coproccesor code > %u bits (%lu)"),
12393                            mips_opts.micromips ? 23U : 25U,
12394                            (unsigned long) imm_expr.X_add_number);
12395                 INSERT_OPERAND (mips_opts.micromips,
12396                                 COPZ, *ip, imm_expr.X_add_number);
12397                 imm_expr.X_op = O_absent;
12398                 s = expr_end;
12399               }
12400               continue;
12401
12402             case 'J':           /* 19-bit WAIT code.  */
12403               gas_assert (!mips_opts.micromips);
12404               my_getExpression (&imm_expr, s);
12405               check_absolute_expr (ip, &imm_expr);
12406               if ((unsigned long) imm_expr.X_add_number > OP_MASK_CODE19)
12407                 {
12408                   as_warn (_("Illegal 19-bit code (%lu)"),
12409                            (unsigned long) imm_expr.X_add_number);
12410                   imm_expr.X_add_number &= OP_MASK_CODE19;
12411                 }
12412               INSERT_OPERAND (0, CODE19, *ip, imm_expr.X_add_number);
12413               imm_expr.X_op = O_absent;
12414               s = expr_end;
12415               continue;
12416
12417             case 'P':           /* Performance register.  */
12418               gas_assert (!mips_opts.micromips);
12419               my_getExpression (&imm_expr, s);
12420               check_absolute_expr (ip, &imm_expr);
12421               if (imm_expr.X_add_number != 0 && imm_expr.X_add_number != 1)
12422                 as_warn (_("Invalid performance register (%lu)"),
12423                          (unsigned long) imm_expr.X_add_number);
12424               if (imm_expr.X_add_number != 0 && mips_opts.arch == CPU_R5900
12425                 && (!strcmp(insn->name,"mfps") || !strcmp(insn->name,"mtps")))
12426                 as_warn (_("Invalid performance register (%lu)"),
12427                   (unsigned long) imm_expr.X_add_number);
12428               INSERT_OPERAND (0, PERFREG, *ip, imm_expr.X_add_number);
12429               imm_expr.X_op = O_absent;
12430               s = expr_end;
12431               continue;
12432
12433             case 'G':           /* Coprocessor destination register.  */
12434               {
12435                 unsigned long opcode = ip->insn_opcode;
12436                 unsigned long mask;
12437                 unsigned int types;
12438                 int cop0;
12439
12440                 if (mips_opts.micromips)
12441                   {
12442                     mask = ~((MICROMIPSOP_MASK_RT << MICROMIPSOP_SH_RT)
12443                              | (MICROMIPSOP_MASK_RS << MICROMIPSOP_SH_RS)
12444                              | (MICROMIPSOP_MASK_SEL << MICROMIPSOP_SH_SEL));
12445                     opcode &= mask;
12446                     switch (opcode)
12447                       {
12448                       case 0x000000fc:                          /* mfc0  */
12449                       case 0x000002fc:                          /* mtc0  */
12450                       case 0x580000fc:                          /* dmfc0 */
12451                       case 0x580002fc:                          /* dmtc0 */
12452                         cop0 = 1;
12453                         break;
12454                       default:
12455                         cop0 = 0;
12456                         break;
12457                       }
12458                   }
12459                 else
12460                   {
12461                     opcode = (opcode >> OP_SH_OP) & OP_MASK_OP;
12462                     cop0 = opcode == OP_OP_COP0;
12463                   }
12464                 types = RTYPE_NUM | (cop0 ? RTYPE_CP0 : RTYPE_GP);
12465                 ok = reg_lookup (&s, types, &regno);
12466                 if (mips_opts.micromips)
12467                   INSERT_OPERAND (1, RS, *ip, regno);
12468                 else
12469                   INSERT_OPERAND (0, RD, *ip, regno);
12470                 if (ok)
12471                   {
12472                     lastregno = regno;
12473                     continue;
12474                   }
12475               }
12476               break;
12477
12478             case 'y':           /* ALNV.PS source register.  */
12479               gas_assert (mips_opts.micromips);
12480               goto do_reg;
12481             case 'x':           /* Ignore register name.  */
12482             case 'U':           /* Destination register (CLO/CLZ).  */
12483             case 'g':           /* Coprocessor destination register.  */
12484               gas_assert (!mips_opts.micromips);
12485             case 'b':           /* Base register.  */
12486             case 'd':           /* Destination register.  */
12487             case 's':           /* Source register.  */
12488             case 't':           /* Target register.  */
12489             case 'r':           /* Both target and source.  */
12490             case 'v':           /* Both dest and source.  */
12491             case 'w':           /* Both dest and target.  */
12492             case 'E':           /* Coprocessor target register.  */
12493             case 'K':           /* RDHWR destination register.  */
12494             case 'z':           /* Must be zero register.  */
12495             do_reg:
12496               s_reset = s;
12497               if (*args == 'E' || *args == 'K')
12498                 ok = reg_lookup (&s, RTYPE_NUM, &regno);
12499               else
12500                 {
12501                   ok = reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno);
12502                   if (regno == AT && mips_opts.at)
12503                     {
12504                       if (mips_opts.at == ATREG)
12505                         as_warn (_("Used $at without \".set noat\""));
12506                       else
12507                         as_warn (_("Used $%u with \".set at=$%u\""),
12508                                  regno, mips_opts.at);
12509                     }
12510                 }
12511               if (ok)
12512                 {
12513                   c = *args;
12514                   if (*s == ' ')
12515                     ++s;
12516                   if (args[1] != *s)
12517                     {
12518                       if (c == 'r' || c == 'v' || c == 'w')
12519                         {
12520                           regno = lastregno;
12521                           s = s_reset;
12522                           ++args;
12523                         }
12524                     }
12525                   /* 'z' only matches $0.  */
12526                   if (c == 'z' && regno != 0)
12527                     break;
12528
12529                   if (c == 's' && !strncmp (ip->insn_mo->name, "jalr", 4))
12530                     {
12531                       if (regno == lastregno)
12532                         {
12533                           insn_error
12534                             = _("Source and destination must be different");
12535                           continue;
12536                         }
12537                       if (regno == 31 && lastregno == 0xffffffff)
12538                         {
12539                           insn_error
12540                             = _("A destination register must be supplied");
12541                           continue;
12542                         }
12543                     }
12544                   /* Now that we have assembled one operand, we use the args
12545                      string to figure out where it goes in the instruction.  */
12546                   switch (c)
12547                     {
12548                     case 'r':
12549                     case 's':
12550                     case 'v':
12551                     case 'b':
12552                       INSERT_OPERAND (mips_opts.micromips, RS, *ip, regno);
12553                       break;
12554
12555                     case 'K':
12556                       if (mips_opts.micromips)
12557                         INSERT_OPERAND (1, RS, *ip, regno);
12558                       else
12559                         INSERT_OPERAND (0, RD, *ip, regno);
12560                       break;
12561
12562                     case 'd':
12563                     case 'g':
12564                       INSERT_OPERAND (mips_opts.micromips, RD, *ip, regno);
12565                       break;
12566
12567                     case 'U':
12568                       gas_assert (!mips_opts.micromips);
12569                       INSERT_OPERAND (0, RD, *ip, regno);
12570                       INSERT_OPERAND (0, RT, *ip, regno);
12571                       break;
12572
12573                     case 'w':
12574                     case 't':
12575                     case 'E':
12576                       INSERT_OPERAND (mips_opts.micromips, RT, *ip, regno);
12577                       break;
12578
12579                     case 'y':
12580                       gas_assert (mips_opts.micromips);
12581                       INSERT_OPERAND (1, RS3, *ip, regno);
12582                       break;
12583
12584                     case 'x':
12585                       /* This case exists because on the r3000 trunc
12586                          expands into a macro which requires a gp
12587                          register.  On the r6000 or r4000 it is
12588                          assembled into a single instruction which
12589                          ignores the register.  Thus the insn version
12590                          is MIPS_ISA2 and uses 'x', and the macro
12591                          version is MIPS_ISA1 and uses 't'.  */
12592                       break;
12593
12594                     case 'z':
12595                       /* This case is for the div instruction, which
12596                          acts differently if the destination argument
12597                          is $0.  This only matches $0, and is checked
12598                          outside the switch.  */
12599                       break;
12600                     }
12601                   lastregno = regno;
12602                   continue;
12603                 }
12604               switch (*args++)
12605                 {
12606                 case 'r':
12607                 case 'v':
12608                   INSERT_OPERAND (mips_opts.micromips, RS, *ip, lastregno);
12609                   continue;
12610
12611                 case 'w':
12612                   INSERT_OPERAND (mips_opts.micromips, RT, *ip, lastregno);
12613                   continue;
12614                 }
12615               break;
12616
12617             case 'O':           /* MDMX alignment immediate constant.  */
12618               gas_assert (!mips_opts.micromips);
12619               my_getExpression (&imm_expr, s);
12620               check_absolute_expr (ip, &imm_expr);
12621               if ((unsigned long) imm_expr.X_add_number > OP_MASK_ALN)
12622                 as_warn (_("Improper align amount (%ld), using low bits"),
12623                          (long) imm_expr.X_add_number);
12624               INSERT_OPERAND (0, ALN, *ip, imm_expr.X_add_number);
12625               imm_expr.X_op = O_absent;
12626               s = expr_end;
12627               continue;
12628
12629             case 'Q':           /* MDMX vector, element sel, or const.  */
12630               if (s[0] != '$')
12631                 {
12632                   /* MDMX Immediate.  */
12633                   gas_assert (!mips_opts.micromips);
12634                   my_getExpression (&imm_expr, s);
12635                   check_absolute_expr (ip, &imm_expr);
12636                   if ((unsigned long) imm_expr.X_add_number > OP_MASK_FT)
12637                     as_warn (_("Invalid MDMX Immediate (%ld)"),
12638                              (long) imm_expr.X_add_number);
12639                   INSERT_OPERAND (0, FT, *ip, imm_expr.X_add_number);
12640                   if (ip->insn_opcode & (OP_MASK_VSEL << OP_SH_VSEL))
12641                     ip->insn_opcode |= MDMX_FMTSEL_IMM_QH << OP_SH_VSEL;
12642                   else
12643                     ip->insn_opcode |= MDMX_FMTSEL_IMM_OB << OP_SH_VSEL;
12644                   imm_expr.X_op = O_absent;
12645                   s = expr_end;
12646                   continue;
12647                 }
12648               /* Not MDMX Immediate.  Fall through.  */
12649             case 'X':           /* MDMX destination register.  */
12650             case 'Y':           /* MDMX source register.  */
12651             case 'Z':           /* MDMX target register.  */
12652               is_mdmx = 1;
12653             case 'W':
12654               gas_assert (!mips_opts.micromips);
12655             case 'D':           /* Floating point destination register.  */
12656             case 'S':           /* Floating point source register.  */
12657             case 'T':           /* Floating point target register.  */
12658             case 'R':           /* Floating point source register.  */
12659             case 'V':
12660               rtype = RTYPE_FPU;
12661               if (is_mdmx
12662                   || ((mips_opts.ase & ASE_MDMX)
12663                       && (ip->insn_mo->pinfo & FP_D)
12664                       && (ip->insn_mo->pinfo & (INSN_COPROC_MOVE_DELAY
12665                                                 | INSN_COPROC_MEMORY_DELAY
12666                                                 | INSN_LOAD_COPROC_DELAY
12667                                                 | INSN_LOAD_MEMORY_DELAY
12668                                                 | INSN_STORE_MEMORY))))
12669                 rtype |= RTYPE_VEC;
12670               s_reset = s;
12671               if (reg_lookup (&s, rtype, &regno))
12672                 {
12673                   if ((regno & 1) != 0
12674                       && HAVE_32BIT_FPRS
12675                       && !mips_oddfpreg_ok (ip->insn_mo, argnum))
12676                     as_warn (_("Float register should be even, was %d"),
12677                              regno);
12678
12679                   c = *args;
12680                   if (*s == ' ')
12681                     ++s;
12682                   if (args[1] != *s)
12683                     {
12684                       if (c == 'V' || c == 'W')
12685                         {
12686                           regno = lastregno;
12687                           s = s_reset;
12688                           ++args;
12689                         }
12690                     }
12691                   switch (c)
12692                     {
12693                     case 'D':
12694                     case 'X':
12695                       INSERT_OPERAND (mips_opts.micromips, FD, *ip, regno);
12696                       break;
12697
12698                     case 'V':
12699                     case 'S':
12700                     case 'Y':
12701                       INSERT_OPERAND (mips_opts.micromips, FS, *ip, regno);
12702                       break;
12703
12704                     case 'Q':
12705                       /* This is like 'Z', but also needs to fix the MDMX
12706                          vector/scalar select bits.  Note that the
12707                          scalar immediate case is handled above.  */
12708                       if (*s == '[')
12709                         {
12710                           int is_qh = (ip->insn_opcode & (1 << OP_SH_VSEL));
12711                           int max_el = (is_qh ? 3 : 7);
12712                           s++;
12713                           my_getExpression(&imm_expr, s);
12714                           check_absolute_expr (ip, &imm_expr);
12715                           s = expr_end;
12716                           if (imm_expr.X_add_number > max_el)
12717                             as_bad (_("Bad element selector %ld"),
12718                                     (long) imm_expr.X_add_number);
12719                           imm_expr.X_add_number &= max_el;
12720                           ip->insn_opcode |= (imm_expr.X_add_number
12721                                               << (OP_SH_VSEL +
12722                                                   (is_qh ? 2 : 1)));
12723                           imm_expr.X_op = O_absent;
12724                           if (*s != ']')
12725                             as_warn (_("Expecting ']' found '%s'"), s);
12726                           else
12727                             s++;
12728                         }
12729                       else
12730                         {
12731                           if (ip->insn_opcode & (OP_MASK_VSEL << OP_SH_VSEL))
12732                             ip->insn_opcode |= (MDMX_FMTSEL_VEC_QH
12733                                                 << OP_SH_VSEL);
12734                           else
12735                             ip->insn_opcode |= (MDMX_FMTSEL_VEC_OB <<
12736                                                 OP_SH_VSEL);
12737                         }
12738                       /* Fall through.  */
12739                     case 'W':
12740                     case 'T':
12741                     case 'Z':
12742                       INSERT_OPERAND (mips_opts.micromips, FT, *ip, regno);
12743                       break;
12744
12745                     case 'R':
12746                       INSERT_OPERAND (mips_opts.micromips, FR, *ip, regno);
12747                       break;
12748                     }
12749                   lastregno = regno;
12750                   continue;
12751                 }
12752
12753               switch (*args++)
12754                 {
12755                 case 'V':
12756                   INSERT_OPERAND (mips_opts.micromips, FS, *ip, lastregno);
12757                   continue;
12758
12759                 case 'W':
12760                   INSERT_OPERAND (mips_opts.micromips, FT, *ip, lastregno);
12761                   continue;
12762                 }
12763               break;
12764
12765             case 'I':
12766               my_getExpression (&imm_expr, s);
12767               if (imm_expr.X_op != O_big
12768                   && imm_expr.X_op != O_constant)
12769                 insn_error = _("absolute expression required");
12770               if (HAVE_32BIT_GPRS)
12771                 normalize_constant_expr (&imm_expr);
12772               s = expr_end;
12773               continue;
12774
12775             case 'A':
12776               my_getExpression (&offset_expr, s);
12777               normalize_address_expr (&offset_expr);
12778               *imm_reloc = BFD_RELOC_32;
12779               s = expr_end;
12780               continue;
12781
12782             case 'F':
12783             case 'L':
12784             case 'f':
12785             case 'l':
12786               {
12787                 int f64;
12788                 int using_gprs;
12789                 char *save_in;
12790                 char *err;
12791                 unsigned char temp[8];
12792                 int len;
12793                 unsigned int length;
12794                 segT seg;
12795                 subsegT subseg;
12796                 char *p;
12797
12798                 /* These only appear as the last operand in an
12799                    instruction, and every instruction that accepts
12800                    them in any variant accepts them in all variants.
12801                    This means we don't have to worry about backing out
12802                    any changes if the instruction does not match.
12803
12804                    The difference between them is the size of the
12805                    floating point constant and where it goes.  For 'F'
12806                    and 'L' the constant is 64 bits; for 'f' and 'l' it
12807                    is 32 bits.  Where the constant is placed is based
12808                    on how the MIPS assembler does things:
12809                     F -- .rdata
12810                     L -- .lit8
12811                     f -- immediate value
12812                     l -- .lit4
12813
12814                     The .lit4 and .lit8 sections are only used if
12815                     permitted by the -G argument.
12816
12817                     The code below needs to know whether the target register
12818                     is 32 or 64 bits wide.  It relies on the fact 'f' and
12819                     'F' are used with GPR-based instructions and 'l' and
12820                     'L' are used with FPR-based instructions.  */
12821
12822                 f64 = *args == 'F' || *args == 'L';
12823                 using_gprs = *args == 'F' || *args == 'f';
12824
12825                 save_in = input_line_pointer;
12826                 input_line_pointer = s;
12827                 err = md_atof (f64 ? 'd' : 'f', (char *) temp, &len);
12828                 length = len;
12829                 s = input_line_pointer;
12830                 input_line_pointer = save_in;
12831                 if (err != NULL && *err != '\0')
12832                   {
12833                     as_bad (_("Bad floating point constant: %s"), err);
12834                     memset (temp, '\0', sizeof temp);
12835                     length = f64 ? 8 : 4;
12836                   }
12837
12838                 gas_assert (length == (unsigned) (f64 ? 8 : 4));
12839
12840                 if (*args == 'f'
12841                     || (*args == 'l'
12842                         && (g_switch_value < 4
12843                             || (temp[0] == 0 && temp[1] == 0)
12844                             || (temp[2] == 0 && temp[3] == 0))))
12845                   {
12846                     imm_expr.X_op = O_constant;
12847                     if (!target_big_endian)
12848                       imm_expr.X_add_number = bfd_getl32 (temp);
12849                     else
12850                       imm_expr.X_add_number = bfd_getb32 (temp);
12851                   }
12852                 else if (length > 4
12853                          && !mips_disable_float_construction
12854                          /* Constants can only be constructed in GPRs and
12855                             copied to FPRs if the GPRs are at least as wide
12856                             as the FPRs.  Force the constant into memory if
12857                             we are using 64-bit FPRs but the GPRs are only
12858                             32 bits wide.  */
12859                          && (using_gprs
12860                              || !(HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
12861                          && ((temp[0] == 0 && temp[1] == 0)
12862                              || (temp[2] == 0 && temp[3] == 0))
12863                          && ((temp[4] == 0 && temp[5] == 0)
12864                              || (temp[6] == 0 && temp[7] == 0)))
12865                   {
12866                     /* The value is simple enough to load with a couple of
12867                        instructions.  If using 32-bit registers, set
12868                        imm_expr to the high order 32 bits and offset_expr to
12869                        the low order 32 bits.  Otherwise, set imm_expr to
12870                        the entire 64 bit constant.  */
12871                     if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
12872                       {
12873                         imm_expr.X_op = O_constant;
12874                         offset_expr.X_op = O_constant;
12875                         if (!target_big_endian)
12876                           {
12877                             imm_expr.X_add_number = bfd_getl32 (temp + 4);
12878                             offset_expr.X_add_number = bfd_getl32 (temp);
12879                           }
12880                         else
12881                           {
12882                             imm_expr.X_add_number = bfd_getb32 (temp);
12883                             offset_expr.X_add_number = bfd_getb32 (temp + 4);
12884                           }
12885                         if (offset_expr.X_add_number == 0)
12886                           offset_expr.X_op = O_absent;
12887                       }
12888                     else if (sizeof (imm_expr.X_add_number) > 4)
12889                       {
12890                         imm_expr.X_op = O_constant;
12891                         if (!target_big_endian)
12892                           imm_expr.X_add_number = bfd_getl64 (temp);
12893                         else
12894                           imm_expr.X_add_number = bfd_getb64 (temp);
12895                       }
12896                     else
12897                       {
12898                         imm_expr.X_op = O_big;
12899                         imm_expr.X_add_number = 4;
12900                         if (!target_big_endian)
12901                           {
12902                             generic_bignum[0] = bfd_getl16 (temp);
12903                             generic_bignum[1] = bfd_getl16 (temp + 2);
12904                             generic_bignum[2] = bfd_getl16 (temp + 4);
12905                             generic_bignum[3] = bfd_getl16 (temp + 6);
12906                           }
12907                         else
12908                           {
12909                             generic_bignum[0] = bfd_getb16 (temp + 6);
12910                             generic_bignum[1] = bfd_getb16 (temp + 4);
12911                             generic_bignum[2] = bfd_getb16 (temp + 2);
12912                             generic_bignum[3] = bfd_getb16 (temp);
12913                           }
12914                       }
12915                   }
12916                 else
12917                   {
12918                     const char *newname;
12919                     segT new_seg;
12920
12921                     /* Switch to the right section.  */
12922                     seg = now_seg;
12923                     subseg = now_subseg;
12924                     switch (*args)
12925                       {
12926                       default: /* unused default case avoids warnings.  */
12927                       case 'L':
12928                         newname = RDATA_SECTION_NAME;
12929                         if (g_switch_value >= 8)
12930                           newname = ".lit8";
12931                         break;
12932                       case 'F':
12933                         newname = RDATA_SECTION_NAME;
12934                         break;
12935                       case 'l':
12936                         gas_assert (g_switch_value >= 4);
12937                         newname = ".lit4";
12938                         break;
12939                       }
12940                     new_seg = subseg_new (newname, (subsegT) 0);
12941                     if (IS_ELF)
12942                       bfd_set_section_flags (stdoutput, new_seg,
12943                                              (SEC_ALLOC
12944                                               | SEC_LOAD
12945                                               | SEC_READONLY
12946                                               | SEC_DATA));
12947                     frag_align (*args == 'l' ? 2 : 3, 0, 0);
12948                     if (IS_ELF && strncmp (TARGET_OS, "elf", 3) != 0)
12949                       record_alignment (new_seg, 4);
12950                     else
12951                       record_alignment (new_seg, *args == 'l' ? 2 : 3);
12952                     if (seg == now_seg)
12953                       as_bad (_("Can't use floating point insn in this section"));
12954
12955                     /* Set the argument to the current address in the
12956                        section.  */
12957                     offset_expr.X_op = O_symbol;
12958                     offset_expr.X_add_symbol = symbol_temp_new_now ();
12959                     offset_expr.X_add_number = 0;
12960
12961                     /* Put the floating point number into the section.  */
12962                     p = frag_more ((int) length);
12963                     memcpy (p, temp, length);
12964
12965                     /* Switch back to the original section.  */
12966                     subseg_set (seg, subseg);
12967                   }
12968               }
12969               continue;
12970
12971             case 'i':           /* 16-bit unsigned immediate.  */
12972             case 'j':           /* 16-bit signed immediate.  */
12973               *imm_reloc = BFD_RELOC_LO16;
12974               if (my_getSmallExpression (&imm_expr, imm_reloc, s) == 0)
12975                 {
12976                   int more;
12977                   offsetT minval, maxval;
12978
12979                   more = (insn + 1 < past
12980                           && strcmp (insn->name, insn[1].name) == 0);
12981
12982                   /* If the expression was written as an unsigned number,
12983                      only treat it as signed if there are no more
12984                      alternatives.  */
12985                   if (more
12986                       && *args == 'j'
12987                       && sizeof (imm_expr.X_add_number) <= 4
12988                       && imm_expr.X_op == O_constant
12989                       && imm_expr.X_add_number < 0
12990                       && imm_expr.X_unsigned
12991                       && HAVE_64BIT_GPRS)
12992                     break;
12993
12994                   /* For compatibility with older assemblers, we accept
12995                      0x8000-0xffff as signed 16-bit numbers when only
12996                      signed numbers are allowed.  */
12997                   if (*args == 'i')
12998                     minval = 0, maxval = 0xffff;
12999                   else if (more)
13000                     minval = -0x8000, maxval = 0x7fff;
13001                   else
13002                     minval = -0x8000, maxval = 0xffff;
13003
13004                   if (imm_expr.X_op != O_constant
13005                       || imm_expr.X_add_number < minval
13006                       || imm_expr.X_add_number > maxval)
13007                     {
13008                       if (more)
13009                         break;
13010                       if (imm_expr.X_op == O_constant
13011                           || imm_expr.X_op == O_big)
13012                         as_bad (_("Expression out of range"));
13013                     }
13014                 }
13015               s = expr_end;
13016               continue;
13017
13018             case 'o':           /* 16-bit offset.  */
13019               offset_reloc[0] = BFD_RELOC_LO16;
13020               offset_reloc[1] = BFD_RELOC_UNUSED;
13021               offset_reloc[2] = BFD_RELOC_UNUSED;
13022
13023               /* Check whether there is only a single bracketed expression
13024                  left.  If so, it must be the base register and the
13025                  constant must be zero.  */
13026               if (*s == '(' && strchr (s + 1, '(') == 0)
13027                 {
13028                   offset_expr.X_op = O_constant;
13029                   offset_expr.X_add_number = 0;
13030                   continue;
13031                 }
13032
13033               /* If this value won't fit into a 16 bit offset, then go
13034                  find a macro that will generate the 32 bit offset
13035                  code pattern.  */
13036               if (my_getSmallExpression (&offset_expr, offset_reloc, s) == 0
13037                   && (offset_expr.X_op != O_constant
13038                       || offset_expr.X_add_number >= 0x8000
13039                       || offset_expr.X_add_number < -0x8000))
13040                 break;
13041
13042               s = expr_end;
13043               continue;
13044
13045             case 'p':           /* PC-relative offset.  */
13046               *offset_reloc = BFD_RELOC_16_PCREL_S2;
13047               my_getExpression (&offset_expr, s);
13048               s = expr_end;
13049               continue;
13050
13051             case 'u':           /* Upper 16 bits.  */
13052               *imm_reloc = BFD_RELOC_LO16;
13053               if (my_getSmallExpression (&imm_expr, imm_reloc, s) == 0
13054                   && imm_expr.X_op == O_constant
13055                   && (imm_expr.X_add_number < 0
13056                       || imm_expr.X_add_number >= 0x10000))
13057                 as_bad (_("lui expression (%lu) not in range 0..65535"),
13058                         (unsigned long) imm_expr.X_add_number);
13059               s = expr_end;
13060               continue;
13061
13062             case 'a':           /* 26-bit address.  */
13063               *offset_reloc = BFD_RELOC_MIPS_JMP;
13064               my_getExpression (&offset_expr, s);
13065               s = expr_end;
13066               continue;
13067
13068             case 'N':           /* 3-bit branch condition code.  */
13069             case 'M':           /* 3-bit compare condition code.  */
13070               rtype = RTYPE_CCC;
13071               if (ip->insn_mo->pinfo & (FP_D | FP_S))
13072                 rtype |= RTYPE_FCC;
13073               if (!reg_lookup (&s, rtype, &regno))
13074                 break;
13075               if ((strcmp (str + strlen (str) - 3, ".ps") == 0
13076                    || strcmp (str + strlen (str) - 5, "any2f") == 0
13077                    || strcmp (str + strlen (str) - 5, "any2t") == 0)
13078                   && (regno & 1) != 0)
13079                 as_warn (_("Condition code register should be even for %s, "
13080                            "was %d"),
13081                          str, regno);
13082               if ((strcmp (str + strlen (str) - 5, "any4f") == 0
13083                    || strcmp (str + strlen (str) - 5, "any4t") == 0)
13084                   && (regno & 3) != 0)
13085                 as_warn (_("Condition code register should be 0 or 4 for %s, "
13086                            "was %d"),
13087                          str, regno);
13088               if (*args == 'N')
13089                 INSERT_OPERAND (mips_opts.micromips, BCC, *ip, regno);
13090               else
13091                 INSERT_OPERAND (mips_opts.micromips, CCC, *ip, regno);
13092               continue;
13093
13094             case 'H':
13095               if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
13096                 s += 2;
13097               if (ISDIGIT (*s))
13098                 {
13099                   c = 0;
13100                   do
13101                     {
13102                       c *= 10;
13103                       c += *s - '0';
13104                       ++s;
13105                     }
13106                   while (ISDIGIT (*s));
13107                 }
13108               else
13109                 c = 8; /* Invalid sel value.  */
13110
13111               if (c > 7)
13112                 as_bad (_("Invalid coprocessor sub-selection value (0-7)"));
13113               INSERT_OPERAND (mips_opts.micromips, SEL, *ip, c);
13114               continue;
13115
13116             case 'e':
13117               gas_assert (!mips_opts.micromips);
13118               /* Must be at least one digit.  */
13119               my_getExpression (&imm_expr, s);
13120               check_absolute_expr (ip, &imm_expr);
13121
13122               if ((unsigned long) imm_expr.X_add_number
13123                   > (unsigned long) OP_MASK_VECBYTE)
13124                 {
13125                   as_bad (_("bad byte vector index (%ld)"),
13126                            (long) imm_expr.X_add_number);
13127                   imm_expr.X_add_number = 0;
13128                 }
13129
13130               INSERT_OPERAND (0, VECBYTE, *ip, imm_expr.X_add_number);
13131               imm_expr.X_op = O_absent;
13132               s = expr_end;
13133               continue;
13134
13135             case '%':
13136               gas_assert (!mips_opts.micromips);
13137               my_getExpression (&imm_expr, s);
13138               check_absolute_expr (ip, &imm_expr);
13139
13140               if ((unsigned long) imm_expr.X_add_number
13141                   > (unsigned long) OP_MASK_VECALIGN)
13142                 {
13143                   as_bad (_("bad byte vector index (%ld)"),
13144                            (long) imm_expr.X_add_number);
13145                   imm_expr.X_add_number = 0;
13146                 }
13147
13148               INSERT_OPERAND (0, VECALIGN, *ip, imm_expr.X_add_number);
13149               imm_expr.X_op = O_absent;
13150               s = expr_end;
13151               continue;
13152
13153             case 'm':           /* Opcode extension character.  */
13154               gas_assert (mips_opts.micromips);
13155               c = *++args;
13156               switch (c)
13157                 {
13158                 case 'r':
13159                   if (strncmp (s, "$pc", 3) == 0)
13160                     {
13161                       s += 3;
13162                       continue;
13163                     }
13164                   break;
13165
13166                 case 'a':
13167                 case 'b':
13168                 case 'c':
13169                 case 'd':
13170                 case 'e':
13171                 case 'f':
13172                 case 'g':
13173                 case 'h':
13174                 case 'i':
13175                 case 'j':
13176                 case 'l':
13177                 case 'm':
13178                 case 'n':
13179                 case 'p':
13180                 case 'q':
13181                 case 's':
13182                 case 't':
13183                 case 'x':
13184                 case 'y':
13185                 case 'z':
13186                   s_reset = s;
13187                   ok = reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno);
13188                   if (regno == AT && mips_opts.at)
13189                     {
13190                       if (mips_opts.at == ATREG)
13191                         as_warn (_("Used $at without \".set noat\""));
13192                       else
13193                         as_warn (_("Used $%u with \".set at=$%u\""),
13194                                  regno, mips_opts.at);
13195                     }
13196                   if (!ok)
13197                     {
13198                       if (c == 'c')
13199                         {
13200                           gas_assert (args[1] == ',');
13201                           regno = lastregno;
13202                           ++args;
13203                         }
13204                       else if (c == 't')
13205                         {
13206                           gas_assert (args[1] == ',');
13207                           ++args;
13208                           continue;                     /* Nothing to do.  */
13209                         }
13210                       else
13211                         break;
13212                     }
13213
13214                   if (c == 'j' && !strncmp (ip->insn_mo->name, "jalr", 4))
13215                     {
13216                       if (regno == lastregno)
13217                         {
13218                           insn_error
13219                             = _("Source and destination must be different");
13220                           continue;
13221                         }
13222                       if (regno == 31 && lastregno == 0xffffffff)
13223                         {
13224                           insn_error
13225                             = _("A destination register must be supplied");
13226                           continue;
13227                         }
13228                     }
13229
13230                   if (*s == ' ')
13231                     ++s;
13232                   if (args[1] != *s)
13233                     {
13234                       if (c == 'e')
13235                         {
13236                           gas_assert (args[1] == ',');
13237                           regno = lastregno;
13238                           s = s_reset;
13239                           ++args;
13240                         }
13241                       else if (c == 't')
13242                         {
13243                           gas_assert (args[1] == ',');
13244                           s = s_reset;
13245                           ++args;
13246                           continue;                     /* Nothing to do.  */
13247                         }
13248                     }
13249
13250                   /* Make sure regno is the same as lastregno.  */
13251                   if (c == 't' && regno != lastregno)
13252                     break;
13253
13254                   /* Make sure regno is the same as destregno.  */
13255                   if (c == 'x' && regno != destregno)
13256                     break;
13257
13258                   /* We need to save regno, before regno maps to the
13259                      microMIPS register encoding.  */
13260                   lastregno = regno;
13261
13262                   if (c == 'f')
13263                     destregno = regno;
13264
13265                   switch (c)
13266                     {
13267                       case 'a':
13268                         if (regno != GP)
13269                           regno = ILLEGAL_REG;
13270                         break;
13271
13272                       case 'b':
13273                         regno = mips32_to_micromips_reg_b_map[regno];
13274                         break;
13275
13276                       case 'c':
13277                         regno = mips32_to_micromips_reg_c_map[regno];
13278                         break;
13279
13280                       case 'd':
13281                         regno = mips32_to_micromips_reg_d_map[regno];
13282                         break;
13283
13284                       case 'e':
13285                         regno = mips32_to_micromips_reg_e_map[regno];
13286                         break;
13287
13288                       case 'f':
13289                         regno = mips32_to_micromips_reg_f_map[regno];
13290                         break;
13291
13292                       case 'g':
13293                         regno = mips32_to_micromips_reg_g_map[regno];
13294                         break;
13295
13296                       case 'h':
13297                         regno = mips32_to_micromips_reg_h_map[regno];
13298                         break;
13299
13300                       case 'i':
13301                         switch (EXTRACT_OPERAND (1, MI, *ip))
13302                           {
13303                             case 4:
13304                               if (regno == 21)
13305                                 regno = 3;
13306                               else if (regno == 22)
13307                                 regno = 4;
13308                               else if (regno == 5)
13309                                 regno = 5;
13310                               else if (regno == 6)
13311                                 regno = 6;
13312                               else if (regno == 7)
13313                                 regno = 7;
13314                               else
13315                                 regno = ILLEGAL_REG;
13316                               break;
13317
13318                             case 5:
13319                               if (regno == 6)
13320                                 regno = 0;
13321                               else if (regno == 7)
13322                                 regno = 1;
13323                               else
13324                                 regno = ILLEGAL_REG;
13325                               break;
13326
13327                             case 6:
13328                               if (regno == 7)
13329                                 regno = 2;
13330                               else
13331                                 regno = ILLEGAL_REG;
13332                               break;
13333
13334                             default:
13335                               regno = ILLEGAL_REG;
13336                               break;
13337                           }
13338                         break;
13339
13340                       case 'l':
13341                         regno = mips32_to_micromips_reg_l_map[regno];
13342                         break;
13343
13344                       case 'm':
13345                         regno = mips32_to_micromips_reg_m_map[regno];
13346                         break;
13347
13348                       case 'n':
13349                         regno = mips32_to_micromips_reg_n_map[regno];
13350                         break;
13351
13352                       case 'q':
13353                         regno = mips32_to_micromips_reg_q_map[regno];
13354                         break;
13355
13356                       case 's':
13357                         if (regno != SP)
13358                           regno = ILLEGAL_REG;
13359                         break;
13360
13361                       case 'y':
13362                         if (regno != 31)
13363                           regno = ILLEGAL_REG;
13364                         break;
13365
13366                       case 'z':
13367                         if (regno != ZERO)
13368                           regno = ILLEGAL_REG;
13369                         break;
13370
13371                       case 'j': /* Do nothing.  */
13372                       case 'p':
13373                       case 't':
13374                       case 'x':
13375                         break;
13376
13377                       default:
13378                         abort ();
13379                     }
13380
13381                   if (regno == ILLEGAL_REG)
13382                     break;
13383
13384                   switch (c)
13385                     {
13386                       case 'b':
13387                         INSERT_OPERAND (1, MB, *ip, regno);
13388                         break;
13389
13390                       case 'c':
13391                         INSERT_OPERAND (1, MC, *ip, regno);
13392                         break;
13393
13394                       case 'd':
13395                         INSERT_OPERAND (1, MD, *ip, regno);
13396                         break;
13397
13398                       case 'e':
13399                         INSERT_OPERAND (1, ME, *ip, regno);
13400                         break;
13401
13402                       case 'f':
13403                         INSERT_OPERAND (1, MF, *ip, regno);
13404                         break;
13405
13406                       case 'g':
13407                         INSERT_OPERAND (1, MG, *ip, regno);
13408                         break;
13409
13410                       case 'h':
13411                         INSERT_OPERAND (1, MH, *ip, regno);
13412                         break;
13413
13414                       case 'i':
13415                         INSERT_OPERAND (1, MI, *ip, regno);
13416                         break;
13417
13418                       case 'j':
13419                         INSERT_OPERAND (1, MJ, *ip, regno);
13420                         break;
13421
13422                       case 'l':
13423                         INSERT_OPERAND (1, ML, *ip, regno);
13424                         break;
13425
13426                       case 'm':
13427                         INSERT_OPERAND (1, MM, *ip, regno);
13428                         break;
13429
13430                       case 'n':
13431                         INSERT_OPERAND (1, MN, *ip, regno);
13432                         break;
13433
13434                       case 'p':
13435                         INSERT_OPERAND (1, MP, *ip, regno);
13436                         break;
13437
13438                       case 'q':
13439                         INSERT_OPERAND (1, MQ, *ip, regno);
13440                         break;
13441
13442                       case 'a': /* Do nothing.  */
13443                       case 's': /* Do nothing.  */
13444                       case 't': /* Do nothing.  */
13445                       case 'x': /* Do nothing.  */
13446                       case 'y': /* Do nothing.  */
13447                       case 'z': /* Do nothing.  */
13448                         break;
13449
13450                       default:
13451                         abort ();
13452                     }
13453                   continue;
13454
13455                 case 'A':
13456                   {
13457                     bfd_reloc_code_real_type r[3];
13458                     expressionS ep;
13459                     int imm;
13460
13461                     /* Check whether there is only a single bracketed
13462                        expression left.  If so, it must be the base register
13463                        and the constant must be zero.  */
13464                     if (*s == '(' && strchr (s + 1, '(') == 0)
13465                       {
13466                         INSERT_OPERAND (1, IMMA, *ip, 0);
13467                         continue;
13468                       }
13469
13470                     if (my_getSmallExpression (&ep, r, s) > 0
13471                         || !expr_const_in_range (&ep, -64, 64, 2))
13472                       break;
13473
13474                     imm = ep.X_add_number >> 2;
13475                     INSERT_OPERAND (1, IMMA, *ip, imm);
13476                   }
13477                   s = expr_end;
13478                   continue;
13479
13480                 case 'B':
13481                   {
13482                     bfd_reloc_code_real_type r[3];
13483                     expressionS ep;
13484                     int imm;
13485
13486                     if (my_getSmallExpression (&ep, r, s) > 0
13487                         || ep.X_op != O_constant)
13488                       break;
13489
13490                     for (imm = 0; imm < 8; imm++)
13491                       if (micromips_imm_b_map[imm] == ep.X_add_number)
13492                         break;
13493                     if (imm >= 8)
13494                       break;
13495
13496                     INSERT_OPERAND (1, IMMB, *ip, imm);
13497                   }
13498                   s = expr_end;
13499                   continue;
13500
13501                 case 'C':
13502                   {
13503                     bfd_reloc_code_real_type r[3];
13504                     expressionS ep;
13505                     int imm;
13506
13507                     if (my_getSmallExpression (&ep, r, s) > 0
13508                         || ep.X_op != O_constant)
13509                       break;
13510
13511                     for (imm = 0; imm < 16; imm++)
13512                       if (micromips_imm_c_map[imm] == ep.X_add_number)
13513                         break;
13514                     if (imm >= 16)
13515                       break;
13516
13517                     INSERT_OPERAND (1, IMMC, *ip, imm);
13518                   }
13519                   s = expr_end;
13520                   continue;
13521
13522                 case 'D':       /* pc relative offset */
13523                 case 'E':       /* pc relative offset */
13524                   my_getExpression (&offset_expr, s);
13525                   if (offset_expr.X_op == O_register)
13526                     break;
13527
13528                   if (!forced_insn_length)
13529                     *offset_reloc = (int) BFD_RELOC_UNUSED + c;
13530                   else if (c == 'D')
13531                     *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
13532                   else
13533                     *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
13534                   s = expr_end;
13535                   continue;
13536
13537                 case 'F':
13538                   {
13539                     bfd_reloc_code_real_type r[3];
13540                     expressionS ep;
13541                     int imm;
13542
13543                     if (my_getSmallExpression (&ep, r, s) > 0
13544                         || !expr_const_in_range (&ep, 0, 16, 0))
13545                       break;
13546
13547                     imm = ep.X_add_number;
13548                     INSERT_OPERAND (1, IMMF, *ip, imm);
13549                   }
13550                   s = expr_end;
13551                   continue;
13552
13553                 case 'G':
13554                   {
13555                     bfd_reloc_code_real_type r[3];
13556                     expressionS ep;
13557                     int imm;
13558
13559                     /* Check whether there is only a single bracketed
13560                        expression left.  If so, it must be the base register
13561                        and the constant must be zero.  */
13562                     if (*s == '(' && strchr (s + 1, '(') == 0)
13563                       {
13564                         INSERT_OPERAND (1, IMMG, *ip, 0);
13565                         continue;
13566                       }
13567
13568                     if (my_getSmallExpression (&ep, r, s) > 0
13569                         || !expr_const_in_range (&ep, -1, 15, 0))
13570                       break;
13571
13572                     imm = ep.X_add_number & 15;
13573                     INSERT_OPERAND (1, IMMG, *ip, imm);
13574                   }
13575                   s = expr_end;
13576                   continue;
13577
13578                 case 'H':
13579                   {
13580                     bfd_reloc_code_real_type r[3];
13581                     expressionS ep;
13582                     int imm;
13583
13584                     /* Check whether there is only a single bracketed
13585                        expression left.  If so, it must be the base register
13586                        and the constant must be zero.  */
13587                     if (*s == '(' && strchr (s + 1, '(') == 0)
13588                       {
13589                         INSERT_OPERAND (1, IMMH, *ip, 0);
13590                         continue;
13591                       }
13592
13593                     if (my_getSmallExpression (&ep, r, s) > 0
13594                         || !expr_const_in_range (&ep, 0, 16, 1))
13595                       break;
13596
13597                     imm = ep.X_add_number >> 1;
13598                     INSERT_OPERAND (1, IMMH, *ip, imm);
13599                   }
13600                   s = expr_end;
13601                   continue;
13602
13603                 case 'I':
13604                   {
13605                     bfd_reloc_code_real_type r[3];
13606                     expressionS ep;
13607                     int imm;
13608
13609                     if (my_getSmallExpression (&ep, r, s) > 0
13610                         || !expr_const_in_range (&ep, -1, 127, 0))
13611                       break;
13612
13613                     imm = ep.X_add_number & 127;
13614                     INSERT_OPERAND (1, IMMI, *ip, imm);
13615                   }
13616                   s = expr_end;
13617                   continue;
13618
13619                 case 'J':
13620                   {
13621                     bfd_reloc_code_real_type r[3];
13622                     expressionS ep;
13623                     int imm;
13624
13625                     /* Check whether there is only a single bracketed
13626                        expression left.  If so, it must be the base register
13627                        and the constant must be zero.  */
13628                     if (*s == '(' && strchr (s + 1, '(') == 0)
13629                       {
13630                         INSERT_OPERAND (1, IMMJ, *ip, 0);
13631                         continue;
13632                       }
13633
13634                     if (my_getSmallExpression (&ep, r, s) > 0
13635                         || !expr_const_in_range (&ep, 0, 16, 2))
13636                       break;
13637
13638                     imm = ep.X_add_number >> 2;
13639                     INSERT_OPERAND (1, IMMJ, *ip, imm);
13640                   }
13641                   s = expr_end;
13642                   continue;
13643
13644                 case 'L':
13645                   {
13646                     bfd_reloc_code_real_type r[3];
13647                     expressionS ep;
13648                     int imm;
13649
13650                     /* Check whether there is only a single bracketed
13651                        expression left.  If so, it must be the base register
13652                        and the constant must be zero.  */
13653                     if (*s == '(' && strchr (s + 1, '(') == 0)
13654                       {
13655                         INSERT_OPERAND (1, IMML, *ip, 0);
13656                         continue;
13657                       }
13658
13659                     if (my_getSmallExpression (&ep, r, s) > 0
13660                         || !expr_const_in_range (&ep, 0, 16, 0))
13661                       break;
13662
13663                     imm = ep.X_add_number;
13664                     INSERT_OPERAND (1, IMML, *ip, imm);
13665                   }
13666                   s = expr_end;
13667                   continue;
13668
13669                 case 'M':
13670                   {
13671                     bfd_reloc_code_real_type r[3];
13672                     expressionS ep;
13673                     int imm;
13674
13675                     if (my_getSmallExpression (&ep, r, s) > 0
13676                         || !expr_const_in_range (&ep, 1, 9, 0))
13677                       break;
13678
13679                     imm = ep.X_add_number & 7;
13680                     INSERT_OPERAND (1, IMMM, *ip, imm);
13681                   }
13682                   s = expr_end;
13683                   continue;
13684
13685                 case 'N':       /* Register list for lwm and swm.  */
13686                   {
13687                     /* A comma-separated list of registers and/or
13688                        dash-separated contiguous ranges including
13689                        both ra and a set of one or more registers
13690                        starting at s0 up to s3 which have to be
13691                        consecutive, e.g.:
13692
13693                        s0, ra
13694                        s0, s1, ra, s2, s3
13695                        s0-s2, ra
13696
13697                        and any permutations of these.  */
13698                     unsigned int reglist;
13699                     int imm;
13700
13701                     if (!reglist_lookup (&s, RTYPE_NUM | RTYPE_GP, &reglist))
13702                       break;
13703
13704                     if ((reglist & 0xfff1ffff) != 0x80010000)
13705                       break;
13706
13707                     reglist = (reglist >> 17) & 7;
13708                     reglist += 1;
13709                     if ((reglist & -reglist) != reglist)
13710                       break;
13711
13712                     imm = ffs (reglist) - 1;
13713                     INSERT_OPERAND (1, IMMN, *ip, imm);
13714                   }
13715                   continue;
13716
13717                 case 'O':       /* sdbbp 4-bit code.  */
13718                   {
13719                     bfd_reloc_code_real_type r[3];
13720                     expressionS ep;
13721                     int imm;
13722
13723                     if (my_getSmallExpression (&ep, r, s) > 0
13724                         || !expr_const_in_range (&ep, 0, 16, 0))
13725                       break;
13726
13727                     imm = ep.X_add_number;
13728                     INSERT_OPERAND (1, IMMO, *ip, imm);
13729                   }
13730                   s = expr_end;
13731                   continue;
13732
13733                 case 'P':
13734                   {
13735                     bfd_reloc_code_real_type r[3];
13736                     expressionS ep;
13737                     int imm;
13738
13739                     if (my_getSmallExpression (&ep, r, s) > 0
13740                         || !expr_const_in_range (&ep, 0, 32, 2))
13741                       break;
13742
13743                     imm = ep.X_add_number >> 2;
13744                     INSERT_OPERAND (1, IMMP, *ip, imm);
13745                   }
13746                   s = expr_end;
13747                   continue;
13748
13749                 case 'Q':
13750                   {
13751                     bfd_reloc_code_real_type r[3];
13752                     expressionS ep;
13753                     int imm;
13754
13755                     if (my_getSmallExpression (&ep, r, s) > 0
13756                         || !expr_const_in_range (&ep, -0x400000, 0x400000, 2))
13757                       break;
13758
13759                     imm = ep.X_add_number >> 2;
13760                     INSERT_OPERAND (1, IMMQ, *ip, imm);
13761                   }
13762                   s = expr_end;
13763                   continue;
13764
13765                 case 'U':
13766                   {
13767                     bfd_reloc_code_real_type r[3];
13768                     expressionS ep;
13769                     int imm;
13770
13771                     /* Check whether there is only a single bracketed
13772                        expression left.  If so, it must be the base register
13773                        and the constant must be zero.  */
13774                     if (*s == '(' && strchr (s + 1, '(') == 0)
13775                       {
13776                         INSERT_OPERAND (1, IMMU, *ip, 0);
13777                         continue;
13778                       }
13779
13780                     if (my_getSmallExpression (&ep, r, s) > 0
13781                         || !expr_const_in_range (&ep, 0, 32, 2))
13782                       break;
13783
13784                     imm = ep.X_add_number >> 2;
13785                     INSERT_OPERAND (1, IMMU, *ip, imm);
13786                   }
13787                   s = expr_end;
13788                   continue;
13789
13790                 case 'W':
13791                   {
13792                     bfd_reloc_code_real_type r[3];
13793                     expressionS ep;
13794                     int imm;
13795
13796                     if (my_getSmallExpression (&ep, r, s) > 0
13797                         || !expr_const_in_range (&ep, 0, 64, 2))
13798                       break;
13799
13800                     imm = ep.X_add_number >> 2;
13801                     INSERT_OPERAND (1, IMMW, *ip, imm);
13802                   }
13803                   s = expr_end;
13804                   continue;
13805
13806                 case 'X':
13807                   {
13808                     bfd_reloc_code_real_type r[3];
13809                     expressionS ep;
13810                     int imm;
13811
13812                     if (my_getSmallExpression (&ep, r, s) > 0
13813                         || !expr_const_in_range (&ep, -8, 8, 0))
13814                       break;
13815
13816                     imm = ep.X_add_number;
13817                     INSERT_OPERAND (1, IMMX, *ip, imm);
13818                   }
13819                   s = expr_end;
13820                   continue;
13821
13822                 case 'Y':
13823                   {
13824                     bfd_reloc_code_real_type r[3];
13825                     expressionS ep;
13826                     int imm;
13827
13828                     if (my_getSmallExpression (&ep, r, s) > 0
13829                         || expr_const_in_range (&ep, -2, 2, 2)
13830                         || !expr_const_in_range (&ep, -258, 258, 2))
13831                       break;
13832
13833                     imm = ep.X_add_number >> 2;
13834                     imm = ((imm >> 1) & ~0xff) | (imm & 0xff);
13835                     INSERT_OPERAND (1, IMMY, *ip, imm);
13836                   }
13837                   s = expr_end;
13838                   continue;
13839
13840                 case 'Z':
13841                   {
13842                     bfd_reloc_code_real_type r[3];
13843                     expressionS ep;
13844
13845                     if (my_getSmallExpression (&ep, r, s) > 0
13846                         || !expr_const_in_range (&ep, 0, 1, 0))
13847                       break;
13848                   }
13849                   s = expr_end;
13850                   continue;
13851
13852                 default:
13853                   as_bad (_("Internal error: bad microMIPS opcode "
13854                             "(unknown extension operand type `m%c'): %s %s"),
13855                           *args, insn->name, insn->args);
13856                   /* Further processing is fruitless.  */
13857                   return;
13858                 }
13859               break;
13860
13861             case 'n':           /* Register list for 32-bit lwm and swm.  */
13862               gas_assert (mips_opts.micromips);
13863               {
13864                 /* A comma-separated list of registers and/or
13865                    dash-separated contiguous ranges including
13866                    at least one of ra and a set of one or more
13867                    registers starting at s0 up to s7 and then
13868                    s8 which have to be consecutive, e.g.:
13869
13870                    ra
13871                    s0
13872                    ra, s0, s1, s2
13873                    s0-s8
13874                    s0-s5, ra
13875
13876                    and any permutations of these.  */
13877                 unsigned int reglist;
13878                 int imm;
13879                 int ra;
13880
13881                 if (!reglist_lookup (&s, RTYPE_NUM | RTYPE_GP, &reglist))
13882                   break;
13883
13884                 if ((reglist & 0x3f00ffff) != 0)
13885                   break;
13886
13887                 ra = (reglist >> 27) & 0x10;
13888                 reglist = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
13889                 reglist += 1;
13890                 if ((reglist & -reglist) != reglist)
13891                   break;
13892
13893                 imm = (ffs (reglist) - 1) | ra;
13894                 INSERT_OPERAND (1, RT, *ip, imm);
13895                 imm_expr.X_op = O_absent;
13896               }
13897               continue;
13898
13899             case '|':           /* 4-bit trap code.  */
13900               gas_assert (mips_opts.micromips);
13901               my_getExpression (&imm_expr, s);
13902               check_absolute_expr (ip, &imm_expr);
13903               if ((unsigned long) imm_expr.X_add_number
13904                   > MICROMIPSOP_MASK_TRAP)
13905                 as_bad (_("Trap code (%lu) for %s not in 0..15 range"),
13906                         (unsigned long) imm_expr.X_add_number,
13907                         ip->insn_mo->name);
13908               INSERT_OPERAND (1, TRAP, *ip, imm_expr.X_add_number);
13909               imm_expr.X_op = O_absent;
13910               s = expr_end;
13911               continue;
13912
13913             default:
13914               as_bad (_("Bad char = '%c'\n"), *args);
13915               abort ();
13916             }
13917           break;
13918         }
13919       /* Args don't match.  */
13920       s = argsStart;
13921       insn_error = _("Illegal operands");
13922       if (insn + 1 < past && !strcmp (insn->name, insn[1].name))
13923         {
13924           ++insn;
13925           continue;
13926         }
13927       else if (wrong_delay_slot_insns && need_delay_slot_ok)
13928         {
13929           gas_assert (firstinsn);
13930           need_delay_slot_ok = FALSE;
13931           past = insn + 1;
13932           insn = firstinsn;
13933           continue;
13934         }
13935       return;
13936     }
13937 }
13938
13939 #define SKIP_SPACE_TABS(S) { while (*(S) == ' ' || *(S) == '\t') ++(S); }
13940
13941 /* This routine assembles an instruction into its binary format when
13942    assembling for the mips16.  As a side effect, it sets one of the
13943    global variables imm_reloc or offset_reloc to the type of relocation
13944    to do if one of the operands is an address expression.  It also sets
13945    forced_insn_length to the resulting instruction size in bytes if the
13946    user explicitly requested a small or extended instruction.  */
13947
13948 static void
13949 mips16_ip (char *str, struct mips_cl_insn *ip)
13950 {
13951   char *s;
13952   const char *args;
13953   struct mips_opcode *insn;
13954   char *argsstart;
13955   unsigned int regno;
13956   unsigned int lastregno = 0;
13957   char *s_reset;
13958   size_t i;
13959
13960   insn_error = NULL;
13961
13962   forced_insn_length = 0;
13963
13964   for (s = str; ISLOWER (*s); ++s)
13965     ;
13966   switch (*s)
13967     {
13968     case '\0':
13969       break;
13970
13971     case ' ':
13972       *s++ = '\0';
13973       break;
13974
13975     case '.':
13976       if (s[1] == 't' && s[2] == ' ')
13977         {
13978           *s = '\0';
13979           forced_insn_length = 2;
13980           s += 3;
13981           break;
13982         }
13983       else if (s[1] == 'e' && s[2] == ' ')
13984         {
13985           *s = '\0';
13986           forced_insn_length = 4;
13987           s += 3;
13988           break;
13989         }
13990       /* Fall through.  */
13991     default:
13992       insn_error = _("unknown opcode");
13993       return;
13994     }
13995
13996   if (mips_opts.noautoextend && !forced_insn_length)
13997     forced_insn_length = 2;
13998
13999   if ((insn = (struct mips_opcode *) hash_find (mips16_op_hash, str)) == NULL)
14000     {
14001       insn_error = _("unrecognized opcode");
14002       return;
14003     }
14004
14005   argsstart = s;
14006   for (;;)
14007     {
14008       bfd_boolean ok;
14009
14010       gas_assert (strcmp (insn->name, str) == 0);
14011
14012       ok = is_opcode_valid_16 (insn);
14013       if (! ok)
14014         {
14015           if (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes]
14016               && strcmp (insn->name, insn[1].name) == 0)
14017             {
14018               ++insn;
14019               continue;
14020             }
14021           else
14022             {
14023               if (!insn_error)
14024                 {
14025                   static char buf[100];
14026                   sprintf (buf,
14027                            _("Opcode not supported on this processor: %s (%s)"),
14028                            mips_cpu_info_from_arch (mips_opts.arch)->name,
14029                            mips_cpu_info_from_isa (mips_opts.isa)->name);
14030                   insn_error = buf;
14031                 }
14032               return;
14033             }
14034         }
14035
14036       create_insn (ip, insn);
14037       imm_expr.X_op = O_absent;
14038       imm_reloc[0] = BFD_RELOC_UNUSED;
14039       imm_reloc[1] = BFD_RELOC_UNUSED;
14040       imm_reloc[2] = BFD_RELOC_UNUSED;
14041       imm2_expr.X_op = O_absent;
14042       offset_expr.X_op = O_absent;
14043       offset_reloc[0] = BFD_RELOC_UNUSED;
14044       offset_reloc[1] = BFD_RELOC_UNUSED;
14045       offset_reloc[2] = BFD_RELOC_UNUSED;
14046       for (args = insn->args; 1; ++args)
14047         {
14048           int c;
14049
14050           if (*s == ' ')
14051             ++s;
14052
14053           /* In this switch statement we call break if we did not find
14054              a match, continue if we did find a match, or return if we
14055              are done.  */
14056
14057           c = *args;
14058           switch (c)
14059             {
14060             case '\0':
14061               if (*s == '\0')
14062                 {
14063                   offsetT value;
14064
14065                   /* Stuff the immediate value in now, if we can.  */
14066                   if (imm_expr.X_op == O_constant
14067                       && *imm_reloc > BFD_RELOC_UNUSED
14068                       && insn->pinfo != INSN_MACRO
14069                       && calculate_reloc (*offset_reloc,
14070                                           imm_expr.X_add_number, &value))
14071                     {
14072                       mips16_immed (NULL, 0, *imm_reloc - BFD_RELOC_UNUSED,
14073                                     *offset_reloc, value, forced_insn_length,
14074                                     &ip->insn_opcode);
14075                       imm_expr.X_op = O_absent;
14076                       *imm_reloc = BFD_RELOC_UNUSED;
14077                       *offset_reloc = BFD_RELOC_UNUSED;
14078                     }
14079
14080                   return;
14081                 }
14082               break;
14083
14084             case ',':
14085               if (*s++ == c)
14086                 continue;
14087               s--;
14088               switch (*++args)
14089                 {
14090                 case 'v':
14091                   MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
14092                   continue;
14093                 case 'w':
14094                   MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
14095                   continue;
14096                 }
14097               break;
14098
14099             case '(':
14100             case ')':
14101               if (*s++ == c)
14102                 continue;
14103               break;
14104
14105             case 'v':
14106             case 'w':
14107               if (s[0] != '$')
14108                 {
14109                   if (c == 'v')
14110                     MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
14111                   else
14112                     MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
14113                   ++args;
14114                   continue;
14115                 }
14116               /* Fall through.  */
14117             case 'x':
14118             case 'y':
14119             case 'z':
14120             case 'Z':
14121             case '0':
14122             case 'S':
14123             case 'R':
14124             case 'X':
14125             case 'Y':
14126               s_reset = s;
14127               if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno))
14128                 {
14129                   if (c == 'v' || c == 'w')
14130                     {
14131                       if (c == 'v')
14132                         MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
14133                       else
14134                         MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
14135                       ++args;
14136                       continue;
14137                     }
14138                   break;
14139                 }
14140
14141               if (*s == ' ')
14142                 ++s;
14143               if (args[1] != *s)
14144                 {
14145                   if (c == 'v' || c == 'w')
14146                     {
14147                       regno = mips16_to_32_reg_map[lastregno];
14148                       s = s_reset;
14149                       ++args;
14150                     }
14151                 }
14152
14153               switch (c)
14154                 {
14155                 case 'x':
14156                 case 'y':
14157                 case 'z':
14158                 case 'v':
14159                 case 'w':
14160                 case 'Z':
14161                   regno = mips32_to_16_reg_map[regno];
14162                   break;
14163
14164                 case '0':
14165                   if (regno != 0)
14166                     regno = ILLEGAL_REG;
14167                   break;
14168
14169                 case 'S':
14170                   if (regno != SP)
14171                     regno = ILLEGAL_REG;
14172                   break;
14173
14174                 case 'R':
14175                   if (regno != RA)
14176                     regno = ILLEGAL_REG;
14177                   break;
14178
14179                 case 'X':
14180                 case 'Y':
14181                   if (regno == AT && mips_opts.at)
14182                     {
14183                       if (mips_opts.at == ATREG)
14184                         as_warn (_("used $at without \".set noat\""));
14185                       else
14186                         as_warn (_("used $%u with \".set at=$%u\""),
14187                                  regno, mips_opts.at);
14188                     }
14189                   break;
14190
14191                 default:
14192                   abort ();
14193                 }
14194
14195               if (regno == ILLEGAL_REG)
14196                 break;
14197
14198               switch (c)
14199                 {
14200                 case 'x':
14201                 case 'v':
14202                   MIPS16_INSERT_OPERAND (RX, *ip, regno);
14203                   break;
14204                 case 'y':
14205                 case 'w':
14206                   MIPS16_INSERT_OPERAND (RY, *ip, regno);
14207                   break;
14208                 case 'z':
14209                   MIPS16_INSERT_OPERAND (RZ, *ip, regno);
14210                   break;
14211                 case 'Z':
14212                   MIPS16_INSERT_OPERAND (MOVE32Z, *ip, regno);
14213                 case '0':
14214                 case 'S':
14215                 case 'R':
14216                   break;
14217                 case 'X':
14218                   MIPS16_INSERT_OPERAND (REGR32, *ip, regno);
14219                   break;
14220                 case 'Y':
14221                   regno = ((regno & 7) << 2) | ((regno & 0x18) >> 3);
14222                   MIPS16_INSERT_OPERAND (REG32R, *ip, regno);
14223                   break;
14224                 default:
14225                   abort ();
14226                 }
14227
14228               lastregno = regno;
14229               continue;
14230
14231             case 'P':
14232               if (strncmp (s, "$pc", 3) == 0)
14233                 {
14234                   s += 3;
14235                   continue;
14236                 }
14237               break;
14238
14239             case '5':
14240             case 'H':
14241             case 'W':
14242             case 'D':
14243             case 'j':
14244             case 'V':
14245             case 'C':
14246             case 'U':
14247             case 'k':
14248             case 'K':
14249               i = my_getSmallExpression (&imm_expr, imm_reloc, s);
14250               if (i > 0)
14251                 {
14252                   if (imm_expr.X_op != O_constant)
14253                     {
14254                       forced_insn_length = 4;
14255                       ip->insn_opcode |= MIPS16_EXTEND;
14256                     }
14257                   else
14258                     {
14259                       /* We need to relax this instruction.  */
14260                       *offset_reloc = *imm_reloc;
14261                       *imm_reloc = (int) BFD_RELOC_UNUSED + c;
14262                     }
14263                   s = expr_end;
14264                   continue;
14265                 }
14266               *imm_reloc = BFD_RELOC_UNUSED;
14267               /* Fall through.  */
14268             case '<':
14269             case '>':
14270             case '[':
14271             case ']':
14272             case '4':
14273             case '8':
14274               my_getExpression (&imm_expr, s);
14275               if (imm_expr.X_op == O_register)
14276                 {
14277                   /* What we thought was an expression turned out to
14278                      be a register.  */
14279
14280                   if (s[0] == '(' && args[1] == '(')
14281                     {
14282                       /* It looks like the expression was omitted
14283                          before a register indirection, which means
14284                          that the expression is implicitly zero.  We
14285                          still set up imm_expr, so that we handle
14286                          explicit extensions correctly.  */
14287                       imm_expr.X_op = O_constant;
14288                       imm_expr.X_add_number = 0;
14289                       *imm_reloc = (int) BFD_RELOC_UNUSED + c;
14290                       continue;
14291                     }
14292
14293                   break;
14294                 }
14295
14296               /* We need to relax this instruction.  */
14297               *imm_reloc = (int) BFD_RELOC_UNUSED + c;
14298               s = expr_end;
14299               continue;
14300
14301             case 'p':
14302             case 'q':
14303             case 'A':
14304             case 'B':
14305             case 'E':
14306               /* We use offset_reloc rather than imm_reloc for the PC
14307                  relative operands.  This lets macros with both
14308                  immediate and address operands work correctly.  */
14309               my_getExpression (&offset_expr, s);
14310
14311               if (offset_expr.X_op == O_register)
14312                 break;
14313
14314               /* We need to relax this instruction.  */
14315               *offset_reloc = (int) BFD_RELOC_UNUSED + c;
14316               s = expr_end;
14317               continue;
14318
14319             case '6':           /* break code */
14320               my_getExpression (&imm_expr, s);
14321               check_absolute_expr (ip, &imm_expr);
14322               if ((unsigned long) imm_expr.X_add_number > 63)
14323                 as_warn (_("Invalid value for `%s' (%lu)"),
14324                          ip->insn_mo->name,
14325                          (unsigned long) imm_expr.X_add_number);
14326               MIPS16_INSERT_OPERAND (IMM6, *ip, imm_expr.X_add_number);
14327               imm_expr.X_op = O_absent;
14328               s = expr_end;
14329               continue;
14330
14331             case 'a':           /* 26 bit address */
14332               my_getExpression (&offset_expr, s);
14333               s = expr_end;
14334               *offset_reloc = BFD_RELOC_MIPS16_JMP;
14335               ip->insn_opcode <<= 16;
14336               continue;
14337
14338             case 'l':           /* register list for entry macro */
14339             case 'L':           /* register list for exit macro */
14340               {
14341                 int mask;
14342
14343                 if (c == 'l')
14344                   mask = 0;
14345                 else
14346                   mask = 7 << 3;
14347                 while (*s != '\0')
14348                   {
14349                     unsigned int freg, reg1, reg2;
14350
14351                     while (*s == ' ' || *s == ',')
14352                       ++s;
14353                     if (reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg1))
14354                       freg = 0;
14355                     else if (reg_lookup (&s, RTYPE_FPU, &reg1))
14356                       freg = 1;
14357                     else
14358                       {
14359                         as_bad (_("can't parse register list"));
14360                         break;
14361                       }
14362                     if (*s == ' ')
14363                       ++s;
14364                     if (*s != '-')
14365                       reg2 = reg1;
14366                     else
14367                       {
14368                         ++s;
14369                         if (!reg_lookup (&s, freg ? RTYPE_FPU 
14370                                          : (RTYPE_GP | RTYPE_NUM), &reg2))
14371                           {
14372                             as_bad (_("invalid register list"));
14373                             break;
14374                           }
14375                       }
14376                     if (freg && reg1 == 0 && reg2 == 0 && c == 'L')
14377                       {
14378                         mask &= ~ (7 << 3);
14379                         mask |= 5 << 3;
14380                       }
14381                     else if (freg && reg1 == 0 && reg2 == 1 && c == 'L')
14382                       {
14383                         mask &= ~ (7 << 3);
14384                         mask |= 6 << 3;
14385                       }
14386                     else if (reg1 == 4 && reg2 >= 4 && reg2 <= 7 && c != 'L')
14387                       mask |= (reg2 - 3) << 3;
14388                     else if (reg1 == 16 && reg2 >= 16 && reg2 <= 17)
14389                       mask |= (reg2 - 15) << 1;
14390                     else if (reg1 == RA && reg2 == RA)
14391                       mask |= 1;
14392                     else
14393                       {
14394                         as_bad (_("invalid register list"));
14395                         break;
14396                       }
14397                   }
14398                 /* The mask is filled in in the opcode table for the
14399                    benefit of the disassembler.  We remove it before
14400                    applying the actual mask.  */
14401                 ip->insn_opcode &= ~ ((7 << 3) << MIPS16OP_SH_IMM6);
14402                 ip->insn_opcode |= mask << MIPS16OP_SH_IMM6;
14403               }
14404             continue;
14405
14406             case 'm':           /* Register list for save insn.  */
14407             case 'M':           /* Register list for restore insn.  */
14408               {
14409                 int opcode = ip->insn_opcode;
14410                 int framesz = 0, seen_framesz = 0;
14411                 int nargs = 0, statics = 0, sregs = 0;
14412
14413                 while (*s != '\0')
14414                   {
14415                     unsigned int reg1, reg2;
14416
14417                     SKIP_SPACE_TABS (s);
14418                     while (*s == ',')
14419                       ++s;
14420                     SKIP_SPACE_TABS (s);
14421
14422                     my_getExpression (&imm_expr, s);
14423                     if (imm_expr.X_op == O_constant)
14424                       {
14425                         /* Handle the frame size.  */
14426                         if (seen_framesz)
14427                           {
14428                             as_bad (_("more than one frame size in list"));
14429                             break;
14430                           }
14431                         seen_framesz = 1;
14432                         framesz = imm_expr.X_add_number;
14433                         imm_expr.X_op = O_absent;
14434                         s = expr_end;
14435                         continue;
14436                       }
14437
14438                     if (! reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg1))
14439                       {
14440                         as_bad (_("can't parse register list"));
14441                         break;
14442                       }
14443
14444                     while (*s == ' ')
14445                       ++s;
14446
14447                     if (*s != '-')
14448                       reg2 = reg1;
14449                     else
14450                       {
14451                         ++s;
14452                         if (! reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg2)
14453                             || reg2 < reg1)
14454                           {
14455                             as_bad (_("can't parse register list"));
14456                             break;
14457                           }
14458                       }
14459
14460                     while (reg1 <= reg2)
14461                       {
14462                         if (reg1 >= 4 && reg1 <= 7)
14463                           {
14464                             if (!seen_framesz)
14465                                 /* args $a0-$a3 */
14466                                 nargs |= 1 << (reg1 - 4);
14467                             else
14468                                 /* statics $a0-$a3 */
14469                                 statics |= 1 << (reg1 - 4);
14470                           }
14471                         else if ((reg1 >= 16 && reg1 <= 23) || reg1 == 30)
14472                           {
14473                             /* $s0-$s8 */
14474                             sregs |= 1 << ((reg1 == 30) ? 8 : (reg1 - 16));
14475                           }
14476                         else if (reg1 == 31)
14477                           {
14478                             /* Add $ra to insn.  */
14479                             opcode |= 0x40;
14480                           }
14481                         else
14482                           {
14483                             as_bad (_("unexpected register in list"));
14484                             break;
14485                           }
14486                         if (++reg1 == 24)
14487                           reg1 = 30;
14488                       }
14489                   }
14490
14491                 /* Encode args/statics combination.  */
14492                 if (nargs & statics)
14493                   as_bad (_("arg/static registers overlap"));
14494                 else if (nargs == 0xf)
14495                   /* All $a0-$a3 are args.  */
14496                   opcode |= MIPS16_ALL_ARGS << 16;
14497                 else if (statics == 0xf)
14498                   /* All $a0-$a3 are statics.  */
14499                   opcode |= MIPS16_ALL_STATICS << 16;
14500                 else 
14501                   {
14502                     int narg = 0, nstat = 0;
14503
14504                     /* Count arg registers.  */
14505                     while (nargs & 0x1)
14506                       {
14507                         nargs >>= 1;
14508                         narg++;
14509                       }
14510                     if (nargs != 0)
14511                       as_bad (_("invalid arg register list"));
14512
14513                     /* Count static registers.  */
14514                     while (statics & 0x8)
14515                       {
14516                         statics = (statics << 1) & 0xf;
14517                         nstat++;
14518                       }
14519                     if (statics != 0) 
14520                       as_bad (_("invalid static register list"));
14521
14522                     /* Encode args/statics.  */
14523                     opcode |= ((narg << 2) | nstat) << 16;
14524                   }
14525
14526                 /* Encode $s0/$s1.  */
14527                 if (sregs & (1 << 0))           /* $s0 */
14528                   opcode |= 0x20;
14529                 if (sregs & (1 << 1))           /* $s1 */
14530                   opcode |= 0x10;
14531                 sregs >>= 2;
14532
14533                 if (sregs != 0)
14534                   {
14535                     /* Count regs $s2-$s8.  */
14536                     int nsreg = 0;
14537                     while (sregs & 1)
14538                       {
14539                         sregs >>= 1;
14540                         nsreg++;
14541                       }
14542                     if (sregs != 0)
14543                       as_bad (_("invalid static register list"));
14544                     /* Encode $s2-$s8. */
14545                     opcode |= nsreg << 24;
14546                   }
14547
14548                 /* Encode frame size.  */
14549                 if (!seen_framesz)
14550                   as_bad (_("missing frame size"));
14551                 else if ((framesz & 7) != 0 || framesz < 0
14552                          || framesz > 0xff * 8)
14553                   as_bad (_("invalid frame size"));
14554                 else if (framesz != 128 || (opcode >> 16) != 0)
14555                   {
14556                     framesz /= 8;
14557                     opcode |= (((framesz & 0xf0) << 16)
14558                              | (framesz & 0x0f));
14559                   }
14560
14561                 /* Finally build the instruction.  */
14562                 if ((opcode >> 16) != 0 || framesz == 0)
14563                   opcode |= MIPS16_EXTEND;
14564                 ip->insn_opcode = opcode;
14565               }
14566             continue;
14567
14568             case 'e':           /* extend code */
14569               my_getExpression (&imm_expr, s);
14570               check_absolute_expr (ip, &imm_expr);
14571               if ((unsigned long) imm_expr.X_add_number > 0x7ff)
14572                 {
14573                   as_warn (_("Invalid value for `%s' (%lu)"),
14574                            ip->insn_mo->name,
14575                            (unsigned long) imm_expr.X_add_number);
14576                   imm_expr.X_add_number &= 0x7ff;
14577                 }
14578               ip->insn_opcode |= imm_expr.X_add_number;
14579               imm_expr.X_op = O_absent;
14580               s = expr_end;
14581               continue;
14582
14583             default:
14584               abort ();
14585             }
14586           break;
14587         }
14588
14589       /* Args don't match.  */
14590       if (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes] &&
14591           strcmp (insn->name, insn[1].name) == 0)
14592         {
14593           ++insn;
14594           s = argsstart;
14595           continue;
14596         }
14597
14598       insn_error = _("illegal operands");
14599
14600       return;
14601     }
14602 }
14603
14604 /* This structure holds information we know about a mips16 immediate
14605    argument type.  */
14606
14607 struct mips16_immed_operand
14608 {
14609   /* The type code used in the argument string in the opcode table.  */
14610   int type;
14611   /* The number of bits in the short form of the opcode.  */
14612   int nbits;
14613   /* The number of bits in the extended form of the opcode.  */
14614   int extbits;
14615   /* The amount by which the short form is shifted when it is used;
14616      for example, the sw instruction has a shift count of 2.  */
14617   int shift;
14618   /* The amount by which the short form is shifted when it is stored
14619      into the instruction code.  */
14620   int op_shift;
14621   /* Non-zero if the short form is unsigned.  */
14622   int unsp;
14623   /* Non-zero if the extended form is unsigned.  */
14624   int extu;
14625   /* Non-zero if the value is PC relative.  */
14626   int pcrel;
14627 };
14628
14629 /* The mips16 immediate operand types.  */
14630
14631 static const struct mips16_immed_operand mips16_immed_operands[] =
14632 {
14633   { '<',  3,  5, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
14634   { '>',  3,  5, 0, MIPS16OP_SH_RX,   1, 1, 0 },
14635   { '[',  3,  6, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
14636   { ']',  3,  6, 0, MIPS16OP_SH_RX,   1, 1, 0 },
14637   { '4',  4, 15, 0, MIPS16OP_SH_IMM4, 0, 0, 0 },
14638   { '5',  5, 16, 0, MIPS16OP_SH_IMM5, 1, 0, 0 },
14639   { 'H',  5, 16, 1, MIPS16OP_SH_IMM5, 1, 0, 0 },
14640   { 'W',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 0 },
14641   { 'D',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 0 },
14642   { 'j',  5, 16, 0, MIPS16OP_SH_IMM5, 0, 0, 0 },
14643   { '8',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 0, 0 },
14644   { 'V',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 0 },
14645   { 'C',  8, 16, 3, MIPS16OP_SH_IMM8, 1, 0, 0 },
14646   { 'U',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 1, 0 },
14647   { 'k',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 0 },
14648   { 'K',  8, 16, 3, MIPS16OP_SH_IMM8, 0, 0, 0 },
14649   { 'p',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
14650   { 'q', 11, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
14651   { 'A',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 1 },
14652   { 'B',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 1 },
14653   { 'E',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 1 }
14654 };
14655
14656 #define MIPS16_NUM_IMMED \
14657   (sizeof mips16_immed_operands / sizeof mips16_immed_operands[0])
14658
14659 /* Marshal immediate value VAL for an extended MIPS16 instruction.
14660    NBITS is the number of significant bits in VAL.  */
14661
14662 static unsigned long
14663 mips16_immed_extend (offsetT val, unsigned int nbits)
14664 {
14665   int extval;
14666   if (nbits == 16)
14667     {
14668       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
14669       val &= 0x1f;
14670     }
14671   else if (nbits == 15)
14672     {
14673       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
14674       val &= 0xf;
14675     }
14676   else
14677     {
14678       extval = ((val & 0x1f) << 6) | (val & 0x20);
14679       val = 0;
14680     }
14681   return (extval << 16) | val;
14682 }
14683
14684 /* Install immediate value VAL into MIPS16 instruction *INSN,
14685    extending it if necessary.  The instruction in *INSN may
14686    already be extended.
14687
14688    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
14689    if none.  In the former case, VAL is a 16-bit number with no
14690    defined signedness.
14691
14692    TYPE is the type of the immediate field.  USER_INSN_LENGTH
14693    is the length that the user requested, or 0 if none.  */
14694
14695 static void
14696 mips16_immed (char *file, unsigned int line, int type,
14697               bfd_reloc_code_real_type reloc, offsetT val,
14698               unsigned int user_insn_length, unsigned long *insn)
14699 {
14700   const struct mips16_immed_operand *op;
14701   int mintiny, maxtiny;
14702
14703   op = mips16_immed_operands;
14704   while (op->type != type)
14705     {
14706       ++op;
14707       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
14708     }
14709
14710   if (op->unsp)
14711     {
14712       if (type == '<' || type == '>' || type == '[' || type == ']')
14713         {
14714           mintiny = 1;
14715           maxtiny = 1 << op->nbits;
14716         }
14717       else
14718         {
14719           mintiny = 0;
14720           maxtiny = (1 << op->nbits) - 1;
14721         }
14722       if (reloc != BFD_RELOC_UNUSED)
14723         val &= 0xffff;
14724     }
14725   else
14726     {
14727       mintiny = - (1 << (op->nbits - 1));
14728       maxtiny = (1 << (op->nbits - 1)) - 1;
14729       if (reloc != BFD_RELOC_UNUSED)
14730         val = SEXT_16BIT (val);
14731     }
14732
14733   /* Branch offsets have an implicit 0 in the lowest bit.  */
14734   if (type == 'p' || type == 'q')
14735     val /= 2;
14736
14737   if ((val & ((1 << op->shift) - 1)) != 0
14738       || val < (mintiny << op->shift)
14739       || val > (maxtiny << op->shift))
14740     {
14741       /* We need an extended instruction.  */
14742       if (user_insn_length == 2)
14743         as_bad_where (file, line, _("invalid unextended operand value"));
14744       else
14745         *insn |= MIPS16_EXTEND;
14746     }
14747   else if (user_insn_length == 4)
14748     {
14749       /* The operand doesn't force an unextended instruction to be extended.
14750          Warn if the user wanted an extended instruction anyway.  */
14751       *insn |= MIPS16_EXTEND;
14752       as_warn_where (file, line,
14753                      _("extended operand requested but not required"));
14754     }
14755
14756   if (mips16_opcode_length (*insn) == 2)
14757     {
14758       int insnval;
14759
14760       insnval = ((val >> op->shift) & ((1 << op->nbits) - 1));
14761       insnval <<= op->op_shift;
14762       *insn |= insnval;
14763     }
14764   else
14765     {
14766       long minext, maxext;
14767
14768       if (reloc == BFD_RELOC_UNUSED)
14769         {
14770           if (op->extu)
14771             {
14772               minext = 0;
14773               maxext = (1 << op->extbits) - 1;
14774             }
14775           else
14776             {
14777               minext = - (1 << (op->extbits - 1));
14778               maxext = (1 << (op->extbits - 1)) - 1;
14779             }
14780           if (val < minext || val > maxext)
14781             as_bad_where (file, line,
14782                           _("operand value out of range for instruction"));
14783         }
14784
14785       *insn |= mips16_immed_extend (val, op->extbits);
14786     }
14787 }
14788 \f
14789 struct percent_op_match
14790 {
14791   const char *str;
14792   bfd_reloc_code_real_type reloc;
14793 };
14794
14795 static const struct percent_op_match mips_percent_op[] =
14796 {
14797   {"%lo", BFD_RELOC_LO16},
14798 #ifdef OBJ_ELF
14799   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
14800   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
14801   {"%call16", BFD_RELOC_MIPS_CALL16},
14802   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
14803   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
14804   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
14805   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
14806   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
14807   {"%got", BFD_RELOC_MIPS_GOT16},
14808   {"%gp_rel", BFD_RELOC_GPREL16},
14809   {"%half", BFD_RELOC_16},
14810   {"%highest", BFD_RELOC_MIPS_HIGHEST},
14811   {"%higher", BFD_RELOC_MIPS_HIGHER},
14812   {"%neg", BFD_RELOC_MIPS_SUB},
14813   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
14814   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
14815   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
14816   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
14817   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
14818   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
14819   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
14820 #endif
14821   {"%hi", BFD_RELOC_HI16_S}
14822 };
14823
14824 static const struct percent_op_match mips16_percent_op[] =
14825 {
14826   {"%lo", BFD_RELOC_MIPS16_LO16},
14827   {"%gprel", BFD_RELOC_MIPS16_GPREL},
14828   {"%got", BFD_RELOC_MIPS16_GOT16},
14829   {"%call16", BFD_RELOC_MIPS16_CALL16},
14830   {"%hi", BFD_RELOC_MIPS16_HI16_S},
14831   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
14832   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
14833   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
14834   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
14835   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
14836   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
14837   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
14838 };
14839
14840
14841 /* Return true if *STR points to a relocation operator.  When returning true,
14842    move *STR over the operator and store its relocation code in *RELOC.
14843    Leave both *STR and *RELOC alone when returning false.  */
14844
14845 static bfd_boolean
14846 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
14847 {
14848   const struct percent_op_match *percent_op;
14849   size_t limit, i;
14850
14851   if (mips_opts.mips16)
14852     {
14853       percent_op = mips16_percent_op;
14854       limit = ARRAY_SIZE (mips16_percent_op);
14855     }
14856   else
14857     {
14858       percent_op = mips_percent_op;
14859       limit = ARRAY_SIZE (mips_percent_op);
14860     }
14861
14862   for (i = 0; i < limit; i++)
14863     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
14864       {
14865         int len = strlen (percent_op[i].str);
14866
14867         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
14868           continue;
14869
14870         *str += strlen (percent_op[i].str);
14871         *reloc = percent_op[i].reloc;
14872
14873         /* Check whether the output BFD supports this relocation.
14874            If not, issue an error and fall back on something safe.  */
14875         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
14876           {
14877             as_bad (_("relocation %s isn't supported by the current ABI"),
14878                     percent_op[i].str);
14879             *reloc = BFD_RELOC_UNUSED;
14880           }
14881         return TRUE;
14882       }
14883   return FALSE;
14884 }
14885
14886
14887 /* Parse string STR as a 16-bit relocatable operand.  Store the
14888    expression in *EP and the relocations in the array starting
14889    at RELOC.  Return the number of relocation operators used.
14890
14891    On exit, EXPR_END points to the first character after the expression.  */
14892
14893 static size_t
14894 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
14895                        char *str)
14896 {
14897   bfd_reloc_code_real_type reversed_reloc[3];
14898   size_t reloc_index, i;
14899   int crux_depth, str_depth;
14900   char *crux;
14901
14902   /* Search for the start of the main expression, recoding relocations
14903      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
14904      of the main expression and with CRUX_DEPTH containing the number
14905      of open brackets at that point.  */
14906   reloc_index = -1;
14907   str_depth = 0;
14908   do
14909     {
14910       reloc_index++;
14911       crux = str;
14912       crux_depth = str_depth;
14913
14914       /* Skip over whitespace and brackets, keeping count of the number
14915          of brackets.  */
14916       while (*str == ' ' || *str == '\t' || *str == '(')
14917         if (*str++ == '(')
14918           str_depth++;
14919     }
14920   while (*str == '%'
14921          && reloc_index < (HAVE_NEWABI ? 3 : 1)
14922          && parse_relocation (&str, &reversed_reloc[reloc_index]));
14923
14924   my_getExpression (ep, crux);
14925   str = expr_end;
14926
14927   /* Match every open bracket.  */
14928   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
14929     if (*str++ == ')')
14930       crux_depth--;
14931
14932   if (crux_depth > 0)
14933     as_bad (_("unclosed '('"));
14934
14935   expr_end = str;
14936
14937   if (reloc_index != 0)
14938     {
14939       prev_reloc_op_frag = frag_now;
14940       for (i = 0; i < reloc_index; i++)
14941         reloc[i] = reversed_reloc[reloc_index - 1 - i];
14942     }
14943
14944   return reloc_index;
14945 }
14946
14947 static void
14948 my_getExpression (expressionS *ep, char *str)
14949 {
14950   char *save_in;
14951
14952   save_in = input_line_pointer;
14953   input_line_pointer = str;
14954   expression (ep);
14955   expr_end = input_line_pointer;
14956   input_line_pointer = save_in;
14957 }
14958
14959 char *
14960 md_atof (int type, char *litP, int *sizeP)
14961 {
14962   return ieee_md_atof (type, litP, sizeP, target_big_endian);
14963 }
14964
14965 void
14966 md_number_to_chars (char *buf, valueT val, int n)
14967 {
14968   if (target_big_endian)
14969     number_to_chars_bigendian (buf, val, n);
14970   else
14971     number_to_chars_littleendian (buf, val, n);
14972 }
14973 \f
14974 #ifdef OBJ_ELF
14975 static int support_64bit_objects(void)
14976 {
14977   const char **list, **l;
14978   int yes;
14979
14980   list = bfd_target_list ();
14981   for (l = list; *l != NULL; l++)
14982     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
14983         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
14984       break;
14985   yes = (*l != NULL);
14986   free (list);
14987   return yes;
14988 }
14989 #endif /* OBJ_ELF */
14990
14991 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
14992    NEW_VALUE.  Warn if another value was already specified.  Note:
14993    we have to defer parsing the -march and -mtune arguments in order
14994    to handle 'from-abi' correctly, since the ABI might be specified
14995    in a later argument.  */
14996
14997 static void
14998 mips_set_option_string (const char **string_ptr, const char *new_value)
14999 {
15000   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
15001     as_warn (_("A different %s was already specified, is now %s"),
15002              string_ptr == &mips_arch_string ? "-march" : "-mtune",
15003              new_value);
15004
15005   *string_ptr = new_value;
15006 }
15007
15008 int
15009 md_parse_option (int c, char *arg)
15010 {
15011   unsigned int i;
15012
15013   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
15014     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
15015       {
15016         file_ase_explicit |= mips_set_ase (&mips_ases[i],
15017                                            c == mips_ases[i].option_on);
15018         return 1;
15019       }
15020
15021   switch (c)
15022     {
15023     case OPTION_CONSTRUCT_FLOATS:
15024       mips_disable_float_construction = 0;
15025       break;
15026
15027     case OPTION_NO_CONSTRUCT_FLOATS:
15028       mips_disable_float_construction = 1;
15029       break;
15030
15031     case OPTION_TRAP:
15032       mips_trap = 1;
15033       break;
15034
15035     case OPTION_BREAK:
15036       mips_trap = 0;
15037       break;
15038
15039     case OPTION_EB:
15040       target_big_endian = 1;
15041       break;
15042
15043     case OPTION_EL:
15044       target_big_endian = 0;
15045       break;
15046
15047     case 'O':
15048       if (arg == NULL)
15049         mips_optimize = 1;
15050       else if (arg[0] == '0')
15051         mips_optimize = 0;
15052       else if (arg[0] == '1')
15053         mips_optimize = 1;
15054       else
15055         mips_optimize = 2;
15056       break;
15057
15058     case 'g':
15059       if (arg == NULL)
15060         mips_debug = 2;
15061       else
15062         mips_debug = atoi (arg);
15063       break;
15064
15065     case OPTION_MIPS1:
15066       file_mips_isa = ISA_MIPS1;
15067       break;
15068
15069     case OPTION_MIPS2:
15070       file_mips_isa = ISA_MIPS2;
15071       break;
15072
15073     case OPTION_MIPS3:
15074       file_mips_isa = ISA_MIPS3;
15075       break;
15076
15077     case OPTION_MIPS4:
15078       file_mips_isa = ISA_MIPS4;
15079       break;
15080
15081     case OPTION_MIPS5:
15082       file_mips_isa = ISA_MIPS5;
15083       break;
15084
15085     case OPTION_MIPS32:
15086       file_mips_isa = ISA_MIPS32;
15087       break;
15088
15089     case OPTION_MIPS32R2:
15090       file_mips_isa = ISA_MIPS32R2;
15091       break;
15092
15093     case OPTION_MIPS64R2:
15094       file_mips_isa = ISA_MIPS64R2;
15095       break;
15096
15097     case OPTION_MIPS64:
15098       file_mips_isa = ISA_MIPS64;
15099       break;
15100
15101     case OPTION_MTUNE:
15102       mips_set_option_string (&mips_tune_string, arg);
15103       break;
15104
15105     case OPTION_MARCH:
15106       mips_set_option_string (&mips_arch_string, arg);
15107       break;
15108
15109     case OPTION_M4650:
15110       mips_set_option_string (&mips_arch_string, "4650");
15111       mips_set_option_string (&mips_tune_string, "4650");
15112       break;
15113
15114     case OPTION_NO_M4650:
15115       break;
15116
15117     case OPTION_M4010:
15118       mips_set_option_string (&mips_arch_string, "4010");
15119       mips_set_option_string (&mips_tune_string, "4010");
15120       break;
15121
15122     case OPTION_NO_M4010:
15123       break;
15124
15125     case OPTION_M4100:
15126       mips_set_option_string (&mips_arch_string, "4100");
15127       mips_set_option_string (&mips_tune_string, "4100");
15128       break;
15129
15130     case OPTION_NO_M4100:
15131       break;
15132
15133     case OPTION_M3900:
15134       mips_set_option_string (&mips_arch_string, "3900");
15135       mips_set_option_string (&mips_tune_string, "3900");
15136       break;
15137
15138     case OPTION_NO_M3900:
15139       break;
15140
15141     case OPTION_MICROMIPS:
15142       if (mips_opts.mips16 == 1)
15143         {
15144           as_bad (_("-mmicromips cannot be used with -mips16"));
15145           return 0;
15146         }
15147       mips_opts.micromips = 1;
15148       mips_no_prev_insn ();
15149       break;
15150
15151     case OPTION_NO_MICROMIPS:
15152       mips_opts.micromips = 0;
15153       mips_no_prev_insn ();
15154       break;
15155
15156     case OPTION_MIPS16:
15157       if (mips_opts.micromips == 1)
15158         {
15159           as_bad (_("-mips16 cannot be used with -micromips"));
15160           return 0;
15161         }
15162       mips_opts.mips16 = 1;
15163       mips_no_prev_insn ();
15164       break;
15165
15166     case OPTION_NO_MIPS16:
15167       mips_opts.mips16 = 0;
15168       mips_no_prev_insn ();
15169       break;
15170
15171     case OPTION_FIX_24K:
15172       mips_fix_24k = 1;
15173       break;
15174
15175     case OPTION_NO_FIX_24K:
15176       mips_fix_24k = 0;
15177       break;
15178
15179     case OPTION_FIX_LOONGSON2F_JUMP:
15180       mips_fix_loongson2f_jump = TRUE;
15181       break;
15182
15183     case OPTION_NO_FIX_LOONGSON2F_JUMP:
15184       mips_fix_loongson2f_jump = FALSE;
15185       break;
15186
15187     case OPTION_FIX_LOONGSON2F_NOP:
15188       mips_fix_loongson2f_nop = TRUE;
15189       break;
15190
15191     case OPTION_NO_FIX_LOONGSON2F_NOP:
15192       mips_fix_loongson2f_nop = FALSE;
15193       break;
15194
15195     case OPTION_FIX_VR4120:
15196       mips_fix_vr4120 = 1;
15197       break;
15198
15199     case OPTION_NO_FIX_VR4120:
15200       mips_fix_vr4120 = 0;
15201       break;
15202
15203     case OPTION_FIX_VR4130:
15204       mips_fix_vr4130 = 1;
15205       break;
15206
15207     case OPTION_NO_FIX_VR4130:
15208       mips_fix_vr4130 = 0;
15209       break;
15210
15211     case OPTION_FIX_CN63XXP1:
15212       mips_fix_cn63xxp1 = TRUE;
15213       break;
15214
15215     case OPTION_NO_FIX_CN63XXP1:
15216       mips_fix_cn63xxp1 = FALSE;
15217       break;
15218
15219     case OPTION_RELAX_BRANCH:
15220       mips_relax_branch = 1;
15221       break;
15222
15223     case OPTION_NO_RELAX_BRANCH:
15224       mips_relax_branch = 0;
15225       break;
15226
15227     case OPTION_MSHARED:
15228       mips_in_shared = TRUE;
15229       break;
15230
15231     case OPTION_MNO_SHARED:
15232       mips_in_shared = FALSE;
15233       break;
15234
15235     case OPTION_MSYM32:
15236       mips_opts.sym32 = TRUE;
15237       break;
15238
15239     case OPTION_MNO_SYM32:
15240       mips_opts.sym32 = FALSE;
15241       break;
15242
15243 #ifdef OBJ_ELF
15244       /* When generating ELF code, we permit -KPIC and -call_shared to
15245          select SVR4_PIC, and -non_shared to select no PIC.  This is
15246          intended to be compatible with Irix 5.  */
15247     case OPTION_CALL_SHARED:
15248       if (!IS_ELF)
15249         {
15250           as_bad (_("-call_shared is supported only for ELF format"));
15251           return 0;
15252         }
15253       mips_pic = SVR4_PIC;
15254       mips_abicalls = TRUE;
15255       break;
15256
15257     case OPTION_CALL_NONPIC:
15258       if (!IS_ELF)
15259         {
15260           as_bad (_("-call_nonpic is supported only for ELF format"));
15261           return 0;
15262         }
15263       mips_pic = NO_PIC;
15264       mips_abicalls = TRUE;
15265       break;
15266
15267     case OPTION_NON_SHARED:
15268       if (!IS_ELF)
15269         {
15270           as_bad (_("-non_shared is supported only for ELF format"));
15271           return 0;
15272         }
15273       mips_pic = NO_PIC;
15274       mips_abicalls = FALSE;
15275       break;
15276
15277       /* The -xgot option tells the assembler to use 32 bit offsets
15278          when accessing the got in SVR4_PIC mode.  It is for Irix
15279          compatibility.  */
15280     case OPTION_XGOT:
15281       mips_big_got = 1;
15282       break;
15283 #endif /* OBJ_ELF */
15284
15285     case 'G':
15286       g_switch_value = atoi (arg);
15287       g_switch_seen = 1;
15288       break;
15289
15290       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
15291          and -mabi=64.  */
15292     case OPTION_32:
15293       if (IS_ELF)
15294         mips_abi = O32_ABI;
15295       /* We silently ignore -32 for non-ELF targets.  This greatly
15296          simplifies the construction of the MIPS GAS test cases.  */
15297       break;
15298
15299 #ifdef OBJ_ELF
15300     case OPTION_N32:
15301       if (!IS_ELF)
15302         {
15303           as_bad (_("-n32 is supported for ELF format only"));
15304           return 0;
15305         }
15306       mips_abi = N32_ABI;
15307       break;
15308
15309     case OPTION_64:
15310       if (!IS_ELF)
15311         {
15312           as_bad (_("-64 is supported for ELF format only"));
15313           return 0;
15314         }
15315       mips_abi = N64_ABI;
15316       if (!support_64bit_objects())
15317         as_fatal (_("No compiled in support for 64 bit object file format"));
15318       break;
15319 #endif /* OBJ_ELF */
15320
15321     case OPTION_GP32:
15322       file_mips_gp32 = 1;
15323       break;
15324
15325     case OPTION_GP64:
15326       file_mips_gp32 = 0;
15327       break;
15328
15329     case OPTION_FP32:
15330       file_mips_fp32 = 1;
15331       break;
15332
15333     case OPTION_FP64:
15334       file_mips_fp32 = 0;
15335       break;
15336
15337     case OPTION_SINGLE_FLOAT:
15338       file_mips_single_float = 1;
15339       break;
15340
15341     case OPTION_DOUBLE_FLOAT:
15342       file_mips_single_float = 0;
15343       break;
15344
15345     case OPTION_SOFT_FLOAT:
15346       file_mips_soft_float = 1;
15347       break;
15348
15349     case OPTION_HARD_FLOAT:
15350       file_mips_soft_float = 0;
15351       break;
15352
15353 #ifdef OBJ_ELF
15354     case OPTION_MABI:
15355       if (!IS_ELF)
15356         {
15357           as_bad (_("-mabi is supported for ELF format only"));
15358           return 0;
15359         }
15360       if (strcmp (arg, "32") == 0)
15361         mips_abi = O32_ABI;
15362       else if (strcmp (arg, "o64") == 0)
15363         mips_abi = O64_ABI;
15364       else if (strcmp (arg, "n32") == 0)
15365         mips_abi = N32_ABI;
15366       else if (strcmp (arg, "64") == 0)
15367         {
15368           mips_abi = N64_ABI;
15369           if (! support_64bit_objects())
15370             as_fatal (_("No compiled in support for 64 bit object file "
15371                         "format"));
15372         }
15373       else if (strcmp (arg, "eabi") == 0)
15374         mips_abi = EABI_ABI;
15375       else
15376         {
15377           as_fatal (_("invalid abi -mabi=%s"), arg);
15378           return 0;
15379         }
15380       break;
15381 #endif /* OBJ_ELF */
15382
15383     case OPTION_M7000_HILO_FIX:
15384       mips_7000_hilo_fix = TRUE;
15385       break;
15386
15387     case OPTION_MNO_7000_HILO_FIX:
15388       mips_7000_hilo_fix = FALSE;
15389       break;
15390
15391 #ifdef OBJ_ELF
15392     case OPTION_MDEBUG:
15393       mips_flag_mdebug = TRUE;
15394       break;
15395
15396     case OPTION_NO_MDEBUG:
15397       mips_flag_mdebug = FALSE;
15398       break;
15399
15400     case OPTION_PDR:
15401       mips_flag_pdr = TRUE;
15402       break;
15403
15404     case OPTION_NO_PDR:
15405       mips_flag_pdr = FALSE;
15406       break;
15407
15408     case OPTION_MVXWORKS_PIC:
15409       mips_pic = VXWORKS_PIC;
15410       break;
15411 #endif /* OBJ_ELF */
15412
15413     default:
15414       return 0;
15415     }
15416
15417     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
15418
15419   return 1;
15420 }
15421 \f
15422 /* Set up globals to generate code for the ISA or processor
15423    described by INFO.  */
15424
15425 static void
15426 mips_set_architecture (const struct mips_cpu_info *info)
15427 {
15428   if (info != 0)
15429     {
15430       file_mips_arch = info->cpu;
15431       mips_opts.arch = info->cpu;
15432       mips_opts.isa = info->isa;
15433     }
15434 }
15435
15436
15437 /* Likewise for tuning.  */
15438
15439 static void
15440 mips_set_tune (const struct mips_cpu_info *info)
15441 {
15442   if (info != 0)
15443     mips_tune = info->cpu;
15444 }
15445
15446
15447 void
15448 mips_after_parse_args (void)
15449 {
15450   const struct mips_cpu_info *arch_info = 0;
15451   const struct mips_cpu_info *tune_info = 0;
15452
15453   /* GP relative stuff not working for PE */
15454   if (strncmp (TARGET_OS, "pe", 2) == 0)
15455     {
15456       if (g_switch_seen && g_switch_value != 0)
15457         as_bad (_("-G not supported in this configuration."));
15458       g_switch_value = 0;
15459     }
15460
15461   if (mips_abi == NO_ABI)
15462     mips_abi = MIPS_DEFAULT_ABI;
15463
15464   /* The following code determines the architecture and register size.
15465      Similar code was added to GCC 3.3 (see override_options() in
15466      config/mips/mips.c).  The GAS and GCC code should be kept in sync
15467      as much as possible.  */
15468
15469   if (mips_arch_string != 0)
15470     arch_info = mips_parse_cpu ("-march", mips_arch_string);
15471
15472   if (file_mips_isa != ISA_UNKNOWN)
15473     {
15474       /* Handle -mipsN.  At this point, file_mips_isa contains the
15475          ISA level specified by -mipsN, while arch_info->isa contains
15476          the -march selection (if any).  */
15477       if (arch_info != 0)
15478         {
15479           /* -march takes precedence over -mipsN, since it is more descriptive.
15480              There's no harm in specifying both as long as the ISA levels
15481              are the same.  */
15482           if (file_mips_isa != arch_info->isa)
15483             as_bad (_("-%s conflicts with the other architecture options, which imply -%s"),
15484                     mips_cpu_info_from_isa (file_mips_isa)->name,
15485                     mips_cpu_info_from_isa (arch_info->isa)->name);
15486         }
15487       else
15488         arch_info = mips_cpu_info_from_isa (file_mips_isa);
15489     }
15490
15491   if (arch_info == 0)
15492     {
15493       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
15494       gas_assert (arch_info);
15495     }
15496
15497   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
15498     as_bad (_("-march=%s is not compatible with the selected ABI"),
15499             arch_info->name);
15500
15501   mips_set_architecture (arch_info);
15502
15503   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
15504   if (mips_tune_string != 0)
15505     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
15506
15507   if (tune_info == 0)
15508     mips_set_tune (arch_info);
15509   else
15510     mips_set_tune (tune_info);
15511
15512   if (file_mips_gp32 >= 0)
15513     {
15514       /* The user specified the size of the integer registers.  Make sure
15515          it agrees with the ABI and ISA.  */
15516       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
15517         as_bad (_("-mgp64 used with a 32-bit processor"));
15518       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
15519         as_bad (_("-mgp32 used with a 64-bit ABI"));
15520       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
15521         as_bad (_("-mgp64 used with a 32-bit ABI"));
15522     }
15523   else
15524     {
15525       /* Infer the integer register size from the ABI and processor.
15526          Restrict ourselves to 32-bit registers if that's all the
15527          processor has, or if the ABI cannot handle 64-bit registers.  */
15528       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
15529                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
15530     }
15531
15532   switch (file_mips_fp32)
15533     {
15534     default:
15535     case -1:
15536       /* No user specified float register size.
15537          ??? GAS treats single-float processors as though they had 64-bit
15538          float registers (although it complains when double-precision
15539          instructions are used).  As things stand, saying they have 32-bit
15540          registers would lead to spurious "register must be even" messages.
15541          So here we assume float registers are never smaller than the
15542          integer ones.  */
15543       if (file_mips_gp32 == 0)
15544         /* 64-bit integer registers implies 64-bit float registers.  */
15545         file_mips_fp32 = 0;
15546       else if ((mips_opts.ase & FP64_ASES)
15547                && ISA_HAS_64BIT_FPRS (mips_opts.isa))
15548         /* -mips3d and -mdmx imply 64-bit float registers, if possible.  */
15549         file_mips_fp32 = 0;
15550       else
15551         /* 32-bit float registers.  */
15552         file_mips_fp32 = 1;
15553       break;
15554
15555     /* The user specified the size of the float registers.  Check if it
15556        agrees with the ABI and ISA.  */
15557     case 0:
15558       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
15559         as_bad (_("-mfp64 used with a 32-bit fpu"));
15560       else if (ABI_NEEDS_32BIT_REGS (mips_abi)
15561                && !ISA_HAS_MXHC1 (mips_opts.isa))
15562         as_warn (_("-mfp64 used with a 32-bit ABI"));
15563       break;
15564     case 1:
15565       if (ABI_NEEDS_64BIT_REGS (mips_abi))
15566         as_warn (_("-mfp32 used with a 64-bit ABI"));
15567       break;
15568     }
15569
15570   /* End of GCC-shared inference code.  */
15571
15572   /* This flag is set when we have a 64-bit capable CPU but use only
15573      32-bit wide registers.  Note that EABI does not use it.  */
15574   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
15575       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
15576           || mips_abi == O32_ABI))
15577     mips_32bitmode = 1;
15578
15579   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
15580     as_bad (_("trap exception not supported at ISA 1"));
15581
15582   /* If the selected architecture includes support for ASEs, enable
15583      generation of code for them.  */
15584   if (mips_opts.mips16 == -1)
15585     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
15586   if (mips_opts.micromips == -1)
15587     mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_arch)) ? 1 : 0;
15588
15589   /* MIPS3D and MDMX require 64-bit FPRs, so -mfp32 should stop those
15590      ASEs from being selected implicitly.  */
15591   if (file_mips_fp32 == 1)
15592     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX;
15593
15594   /* If the user didn't explicitly select or deselect a particular ASE,
15595      use the default setting for the CPU.  */
15596   mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
15597
15598   file_mips_isa = mips_opts.isa;
15599   file_ase = mips_opts.ase;
15600   mips_opts.gp32 = file_mips_gp32;
15601   mips_opts.fp32 = file_mips_fp32;
15602   mips_opts.soft_float = file_mips_soft_float;
15603   mips_opts.single_float = file_mips_single_float;
15604
15605   mips_check_isa_supports_ases ();
15606
15607   if (mips_flag_mdebug < 0)
15608     mips_flag_mdebug = 0;
15609 }
15610 \f
15611 void
15612 mips_init_after_args (void)
15613 {
15614   /* initialize opcodes */
15615   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
15616   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
15617 }
15618
15619 long
15620 md_pcrel_from (fixS *fixP)
15621 {
15622   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
15623   switch (fixP->fx_r_type)
15624     {
15625     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15626     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15627       /* Return the address of the delay slot.  */
15628       return addr + 2;
15629
15630     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15631     case BFD_RELOC_MICROMIPS_JMP:
15632     case BFD_RELOC_16_PCREL_S2:
15633     case BFD_RELOC_MIPS_JMP:
15634       /* Return the address of the delay slot.  */
15635       return addr + 4;
15636
15637     case BFD_RELOC_32_PCREL:
15638       return addr;
15639
15640     default:
15641       /* We have no relocation type for PC relative MIPS16 instructions.  */
15642       if (fixP->fx_addsy && S_GET_SEGMENT (fixP->fx_addsy) != now_seg)
15643         as_bad_where (fixP->fx_file, fixP->fx_line,
15644                       _("PC relative MIPS16 instruction references a different section"));
15645       return addr;
15646     }
15647 }
15648
15649 /* This is called before the symbol table is processed.  In order to
15650    work with gcc when using mips-tfile, we must keep all local labels.
15651    However, in other cases, we want to discard them.  If we were
15652    called with -g, but we didn't see any debugging information, it may
15653    mean that gcc is smuggling debugging information through to
15654    mips-tfile, in which case we must generate all local labels.  */
15655
15656 void
15657 mips_frob_file_before_adjust (void)
15658 {
15659 #ifndef NO_ECOFF_DEBUGGING
15660   if (ECOFF_DEBUGGING
15661       && mips_debug != 0
15662       && ! ecoff_debugging_seen)
15663     flag_keep_locals = 1;
15664 #endif
15665 }
15666
15667 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
15668    the corresponding LO16 reloc.  This is called before md_apply_fix and
15669    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
15670    relocation operators.
15671
15672    For our purposes, a %lo() expression matches a %got() or %hi()
15673    expression if:
15674
15675       (a) it refers to the same symbol; and
15676       (b) the offset applied in the %lo() expression is no lower than
15677           the offset applied in the %got() or %hi().
15678
15679    (b) allows us to cope with code like:
15680
15681         lui     $4,%hi(foo)
15682         lh      $4,%lo(foo+2)($4)
15683
15684    ...which is legal on RELA targets, and has a well-defined behaviour
15685    if the user knows that adding 2 to "foo" will not induce a carry to
15686    the high 16 bits.
15687
15688    When several %lo()s match a particular %got() or %hi(), we use the
15689    following rules to distinguish them:
15690
15691      (1) %lo()s with smaller offsets are a better match than %lo()s with
15692          higher offsets.
15693
15694      (2) %lo()s with no matching %got() or %hi() are better than those
15695          that already have a matching %got() or %hi().
15696
15697      (3) later %lo()s are better than earlier %lo()s.
15698
15699    These rules are applied in order.
15700
15701    (1) means, among other things, that %lo()s with identical offsets are
15702    chosen if they exist.
15703
15704    (2) means that we won't associate several high-part relocations with
15705    the same low-part relocation unless there's no alternative.  Having
15706    several high parts for the same low part is a GNU extension; this rule
15707    allows careful users to avoid it.
15708
15709    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
15710    with the last high-part relocation being at the front of the list.
15711    It therefore makes sense to choose the last matching low-part
15712    relocation, all other things being equal.  It's also easier
15713    to code that way.  */
15714
15715 void
15716 mips_frob_file (void)
15717 {
15718   struct mips_hi_fixup *l;
15719   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
15720
15721   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
15722     {
15723       segment_info_type *seginfo;
15724       bfd_boolean matched_lo_p;
15725       fixS **hi_pos, **lo_pos, **pos;
15726
15727       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
15728
15729       /* If a GOT16 relocation turns out to be against a global symbol,
15730          there isn't supposed to be a matching LO.  Ignore %gots against
15731          constants; we'll report an error for those later.  */
15732       if (got16_reloc_p (l->fixp->fx_r_type)
15733           && !(l->fixp->fx_addsy
15734                && pic_need_relax (l->fixp->fx_addsy, l->seg)))
15735         continue;
15736
15737       /* Check quickly whether the next fixup happens to be a matching %lo.  */
15738       if (fixup_has_matching_lo_p (l->fixp))
15739         continue;
15740
15741       seginfo = seg_info (l->seg);
15742
15743       /* Set HI_POS to the position of this relocation in the chain.
15744          Set LO_POS to the position of the chosen low-part relocation.
15745          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
15746          relocation that matches an immediately-preceding high-part
15747          relocation.  */
15748       hi_pos = NULL;
15749       lo_pos = NULL;
15750       matched_lo_p = FALSE;
15751       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
15752
15753       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
15754         {
15755           if (*pos == l->fixp)
15756             hi_pos = pos;
15757
15758           if ((*pos)->fx_r_type == looking_for_rtype
15759               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
15760               && (*pos)->fx_offset >= l->fixp->fx_offset
15761               && (lo_pos == NULL
15762                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
15763                   || (!matched_lo_p
15764                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
15765             lo_pos = pos;
15766
15767           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
15768                           && fixup_has_matching_lo_p (*pos));
15769         }
15770
15771       /* If we found a match, remove the high-part relocation from its
15772          current position and insert it before the low-part relocation.
15773          Make the offsets match so that fixup_has_matching_lo_p()
15774          will return true.
15775
15776          We don't warn about unmatched high-part relocations since some
15777          versions of gcc have been known to emit dead "lui ...%hi(...)"
15778          instructions.  */
15779       if (lo_pos != NULL)
15780         {
15781           l->fixp->fx_offset = (*lo_pos)->fx_offset;
15782           if (l->fixp->fx_next != *lo_pos)
15783             {
15784               *hi_pos = l->fixp->fx_next;
15785               l->fixp->fx_next = *lo_pos;
15786               *lo_pos = l->fixp;
15787             }
15788         }
15789     }
15790 }
15791
15792 int
15793 mips_force_relocation (fixS *fixp)
15794 {
15795   if (generic_force_reloc (fixp))
15796     return 1;
15797
15798   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
15799      so that the linker relaxation can update targets.  */
15800   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
15801       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
15802       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
15803     return 1;
15804
15805   return 0;
15806 }
15807
15808 /* Read the instruction associated with RELOC from BUF.  */
15809
15810 static unsigned int
15811 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
15812 {
15813   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
15814     return read_compressed_insn (buf, 4);
15815   else
15816     return read_insn (buf);
15817 }
15818
15819 /* Write instruction INSN to BUF, given that it has been relocated
15820    by RELOC.  */
15821
15822 static void
15823 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
15824                   unsigned long insn)
15825 {
15826   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
15827     write_compressed_insn (buf, insn, 4);
15828   else
15829     write_insn (buf, insn);
15830 }
15831
15832 /* Apply a fixup to the object file.  */
15833
15834 void
15835 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
15836 {
15837   char *buf;
15838   unsigned long insn;
15839   reloc_howto_type *howto;
15840
15841   /* We ignore generic BFD relocations we don't know about.  */
15842   howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
15843   if (! howto)
15844     return;
15845
15846   gas_assert (fixP->fx_size == 2
15847               || fixP->fx_size == 4
15848               || fixP->fx_r_type == BFD_RELOC_16
15849               || fixP->fx_r_type == BFD_RELOC_64
15850               || fixP->fx_r_type == BFD_RELOC_CTOR
15851               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
15852               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
15853               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
15854               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
15855               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
15856
15857   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15858
15859   gas_assert (!fixP->fx_pcrel || fixP->fx_r_type == BFD_RELOC_16_PCREL_S2
15860               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
15861               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
15862               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
15863               || fixP->fx_r_type == BFD_RELOC_32_PCREL);
15864
15865   /* Don't treat parts of a composite relocation as done.  There are two
15866      reasons for this:
15867
15868      (1) The second and third parts will be against 0 (RSS_UNDEF) but
15869          should nevertheless be emitted if the first part is.
15870
15871      (2) In normal usage, composite relocations are never assembly-time
15872          constants.  The easiest way of dealing with the pathological
15873          exceptions is to generate a relocation against STN_UNDEF and
15874          leave everything up to the linker.  */
15875   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
15876     fixP->fx_done = 1;
15877
15878   switch (fixP->fx_r_type)
15879     {
15880     case BFD_RELOC_MIPS_TLS_GD:
15881     case BFD_RELOC_MIPS_TLS_LDM:
15882     case BFD_RELOC_MIPS_TLS_DTPREL32:
15883     case BFD_RELOC_MIPS_TLS_DTPREL64:
15884     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
15885     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
15886     case BFD_RELOC_MIPS_TLS_GOTTPREL:
15887     case BFD_RELOC_MIPS_TLS_TPREL32:
15888     case BFD_RELOC_MIPS_TLS_TPREL64:
15889     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
15890     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
15891     case BFD_RELOC_MICROMIPS_TLS_GD:
15892     case BFD_RELOC_MICROMIPS_TLS_LDM:
15893     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
15894     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
15895     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
15896     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
15897     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
15898     case BFD_RELOC_MIPS16_TLS_GD:
15899     case BFD_RELOC_MIPS16_TLS_LDM:
15900     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
15901     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
15902     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
15903     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
15904     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
15905       if (!fixP->fx_addsy)
15906         {
15907           as_bad_where (fixP->fx_file, fixP->fx_line,
15908                         _("TLS relocation against a constant"));
15909           break;
15910         }
15911       S_SET_THREAD_LOCAL (fixP->fx_addsy);
15912       /* fall through */
15913
15914     case BFD_RELOC_MIPS_JMP:
15915     case BFD_RELOC_MIPS_SHIFT5:
15916     case BFD_RELOC_MIPS_SHIFT6:
15917     case BFD_RELOC_MIPS_GOT_DISP:
15918     case BFD_RELOC_MIPS_GOT_PAGE:
15919     case BFD_RELOC_MIPS_GOT_OFST:
15920     case BFD_RELOC_MIPS_SUB:
15921     case BFD_RELOC_MIPS_INSERT_A:
15922     case BFD_RELOC_MIPS_INSERT_B:
15923     case BFD_RELOC_MIPS_DELETE:
15924     case BFD_RELOC_MIPS_HIGHEST:
15925     case BFD_RELOC_MIPS_HIGHER:
15926     case BFD_RELOC_MIPS_SCN_DISP:
15927     case BFD_RELOC_MIPS_REL16:
15928     case BFD_RELOC_MIPS_RELGOT:
15929     case BFD_RELOC_MIPS_JALR:
15930     case BFD_RELOC_HI16:
15931     case BFD_RELOC_HI16_S:
15932     case BFD_RELOC_LO16:
15933     case BFD_RELOC_GPREL16:
15934     case BFD_RELOC_MIPS_LITERAL:
15935     case BFD_RELOC_MIPS_CALL16:
15936     case BFD_RELOC_MIPS_GOT16:
15937     case BFD_RELOC_GPREL32:
15938     case BFD_RELOC_MIPS_GOT_HI16:
15939     case BFD_RELOC_MIPS_GOT_LO16:
15940     case BFD_RELOC_MIPS_CALL_HI16:
15941     case BFD_RELOC_MIPS_CALL_LO16:
15942     case BFD_RELOC_MIPS16_GPREL:
15943     case BFD_RELOC_MIPS16_GOT16:
15944     case BFD_RELOC_MIPS16_CALL16:
15945     case BFD_RELOC_MIPS16_HI16:
15946     case BFD_RELOC_MIPS16_HI16_S:
15947     case BFD_RELOC_MIPS16_LO16:
15948     case BFD_RELOC_MIPS16_JMP:
15949     case BFD_RELOC_MICROMIPS_JMP:
15950     case BFD_RELOC_MICROMIPS_GOT_DISP:
15951     case BFD_RELOC_MICROMIPS_GOT_PAGE:
15952     case BFD_RELOC_MICROMIPS_GOT_OFST:
15953     case BFD_RELOC_MICROMIPS_SUB:
15954     case BFD_RELOC_MICROMIPS_HIGHEST:
15955     case BFD_RELOC_MICROMIPS_HIGHER:
15956     case BFD_RELOC_MICROMIPS_SCN_DISP:
15957     case BFD_RELOC_MICROMIPS_JALR:
15958     case BFD_RELOC_MICROMIPS_HI16:
15959     case BFD_RELOC_MICROMIPS_HI16_S:
15960     case BFD_RELOC_MICROMIPS_LO16:
15961     case BFD_RELOC_MICROMIPS_GPREL16:
15962     case BFD_RELOC_MICROMIPS_LITERAL:
15963     case BFD_RELOC_MICROMIPS_CALL16:
15964     case BFD_RELOC_MICROMIPS_GOT16:
15965     case BFD_RELOC_MICROMIPS_GOT_HI16:
15966     case BFD_RELOC_MICROMIPS_GOT_LO16:
15967     case BFD_RELOC_MICROMIPS_CALL_HI16:
15968     case BFD_RELOC_MICROMIPS_CALL_LO16:
15969     case BFD_RELOC_MIPS_EH:
15970       if (fixP->fx_done)
15971         {
15972           offsetT value;
15973
15974           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
15975             {
15976               insn = read_reloc_insn (buf, fixP->fx_r_type);
15977               if (mips16_reloc_p (fixP->fx_r_type))
15978                 insn |= mips16_immed_extend (value, 16);
15979               else
15980                 insn |= (value & 0xffff);
15981               write_reloc_insn (buf, fixP->fx_r_type, insn);
15982             }
15983           else
15984             as_bad_where (fixP->fx_file, fixP->fx_line,
15985                           _("Unsupported constant in relocation"));
15986         }
15987       break;
15988
15989     case BFD_RELOC_64:
15990       /* This is handled like BFD_RELOC_32, but we output a sign
15991          extended value if we are only 32 bits.  */
15992       if (fixP->fx_done)
15993         {
15994           if (8 <= sizeof (valueT))
15995             md_number_to_chars (buf, *valP, 8);
15996           else
15997             {
15998               valueT hiv;
15999
16000               if ((*valP & 0x80000000) != 0)
16001                 hiv = 0xffffffff;
16002               else
16003                 hiv = 0;
16004               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
16005               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
16006             }
16007         }
16008       break;
16009
16010     case BFD_RELOC_RVA:
16011     case BFD_RELOC_32:
16012     case BFD_RELOC_32_PCREL:
16013     case BFD_RELOC_16:
16014       /* If we are deleting this reloc entry, we must fill in the
16015          value now.  This can happen if we have a .word which is not
16016          resolved when it appears but is later defined.  */
16017       if (fixP->fx_done)
16018         md_number_to_chars (buf, *valP, fixP->fx_size);
16019       break;
16020
16021     case BFD_RELOC_16_PCREL_S2:
16022       if ((*valP & 0x3) != 0)
16023         as_bad_where (fixP->fx_file, fixP->fx_line,
16024                       _("Branch to misaligned address (%lx)"), (long) *valP);
16025
16026       /* We need to save the bits in the instruction since fixup_segment()
16027          might be deleting the relocation entry (i.e., a branch within
16028          the current segment).  */
16029       if (! fixP->fx_done)
16030         break;
16031
16032       /* Update old instruction data.  */
16033       insn = read_insn (buf);
16034
16035       if (*valP + 0x20000 <= 0x3ffff)
16036         {
16037           insn |= (*valP >> 2) & 0xffff;
16038           write_insn (buf, insn);
16039         }
16040       else if (mips_pic == NO_PIC
16041                && fixP->fx_done
16042                && fixP->fx_frag->fr_address >= text_section->vma
16043                && (fixP->fx_frag->fr_address
16044                    < text_section->vma + bfd_get_section_size (text_section))
16045                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
16046                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
16047                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
16048         {
16049           /* The branch offset is too large.  If this is an
16050              unconditional branch, and we are not generating PIC code,
16051              we can convert it to an absolute jump instruction.  */
16052           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
16053             insn = 0x0c000000;  /* jal */
16054           else
16055             insn = 0x08000000;  /* j */
16056           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
16057           fixP->fx_done = 0;
16058           fixP->fx_addsy = section_symbol (text_section);
16059           *valP += md_pcrel_from (fixP);
16060           write_insn (buf, insn);
16061         }
16062       else
16063         {
16064           /* If we got here, we have branch-relaxation disabled,
16065              and there's nothing we can do to fix this instruction
16066              without turning it into a longer sequence.  */
16067           as_bad_where (fixP->fx_file, fixP->fx_line,
16068                         _("Branch out of range"));
16069         }
16070       break;
16071
16072     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
16073     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
16074     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
16075       /* We adjust the offset back to even.  */
16076       if ((*valP & 0x1) != 0)
16077         --(*valP);
16078
16079       if (! fixP->fx_done)
16080         break;
16081
16082       /* Should never visit here, because we keep the relocation.  */
16083       abort ();
16084       break;
16085
16086     case BFD_RELOC_VTABLE_INHERIT:
16087       fixP->fx_done = 0;
16088       if (fixP->fx_addsy
16089           && !S_IS_DEFINED (fixP->fx_addsy)
16090           && !S_IS_WEAK (fixP->fx_addsy))
16091         S_SET_WEAK (fixP->fx_addsy);
16092       break;
16093
16094     case BFD_RELOC_VTABLE_ENTRY:
16095       fixP->fx_done = 0;
16096       break;
16097
16098     default:
16099       abort ();
16100     }
16101
16102   /* Remember value for tc_gen_reloc.  */
16103   fixP->fx_addnumber = *valP;
16104 }
16105
16106 static symbolS *
16107 get_symbol (void)
16108 {
16109   int c;
16110   char *name;
16111   symbolS *p;
16112
16113   name = input_line_pointer;
16114   c = get_symbol_end ();
16115   p = (symbolS *) symbol_find_or_make (name);
16116   *input_line_pointer = c;
16117   return p;
16118 }
16119
16120 /* Align the current frag to a given power of two.  If a particular
16121    fill byte should be used, FILL points to an integer that contains
16122    that byte, otherwise FILL is null.
16123
16124    This function used to have the comment:
16125
16126       The MIPS assembler also automatically adjusts any preceding label.
16127
16128    The implementation therefore applied the adjustment to a maximum of
16129    one label.  However, other label adjustments are applied to batches
16130    of labels, and adjusting just one caused problems when new labels
16131    were added for the sake of debugging or unwind information.
16132    We therefore adjust all preceding labels (given as LABELS) instead.  */
16133
16134 static void
16135 mips_align (int to, int *fill, struct insn_label_list *labels)
16136 {
16137   mips_emit_delays ();
16138   mips_record_compressed_mode ();
16139   if (fill == NULL && subseg_text_p (now_seg))
16140     frag_align_code (to, 0);
16141   else
16142     frag_align (to, fill ? *fill : 0, 0);
16143   record_alignment (now_seg, to);
16144   mips_move_labels (labels, FALSE);
16145 }
16146
16147 /* Align to a given power of two.  .align 0 turns off the automatic
16148    alignment used by the data creating pseudo-ops.  */
16149
16150 static void
16151 s_align (int x ATTRIBUTE_UNUSED)
16152 {
16153   int temp, fill_value, *fill_ptr;
16154   long max_alignment = 28;
16155
16156   /* o Note that the assembler pulls down any immediately preceding label
16157        to the aligned address.
16158      o It's not documented but auto alignment is reinstated by
16159        a .align pseudo instruction.
16160      o Note also that after auto alignment is turned off the mips assembler
16161        issues an error on attempt to assemble an improperly aligned data item.
16162        We don't.  */
16163
16164   temp = get_absolute_expression ();
16165   if (temp > max_alignment)
16166     as_bad (_("Alignment too large: %d. assumed."), temp = max_alignment);
16167   else if (temp < 0)
16168     {
16169       as_warn (_("Alignment negative: 0 assumed."));
16170       temp = 0;
16171     }
16172   if (*input_line_pointer == ',')
16173     {
16174       ++input_line_pointer;
16175       fill_value = get_absolute_expression ();
16176       fill_ptr = &fill_value;
16177     }
16178   else
16179     fill_ptr = 0;
16180   if (temp)
16181     {
16182       segment_info_type *si = seg_info (now_seg);
16183       struct insn_label_list *l = si->label_list;
16184       /* Auto alignment should be switched on by next section change.  */
16185       auto_align = 1;
16186       mips_align (temp, fill_ptr, l);
16187     }
16188   else
16189     {
16190       auto_align = 0;
16191     }
16192
16193   demand_empty_rest_of_line ();
16194 }
16195
16196 static void
16197 s_change_sec (int sec)
16198 {
16199   segT seg;
16200
16201 #ifdef OBJ_ELF
16202   /* The ELF backend needs to know that we are changing sections, so
16203      that .previous works correctly.  We could do something like check
16204      for an obj_section_change_hook macro, but that might be confusing
16205      as it would not be appropriate to use it in the section changing
16206      functions in read.c, since obj-elf.c intercepts those.  FIXME:
16207      This should be cleaner, somehow.  */
16208   if (IS_ELF)
16209     obj_elf_section_change_hook ();
16210 #endif
16211
16212   mips_emit_delays ();
16213
16214   switch (sec)
16215     {
16216     case 't':
16217       s_text (0);
16218       break;
16219     case 'd':
16220       s_data (0);
16221       break;
16222     case 'b':
16223       subseg_set (bss_section, (subsegT) get_absolute_expression ());
16224       demand_empty_rest_of_line ();
16225       break;
16226
16227     case 'r':
16228       seg = subseg_new (RDATA_SECTION_NAME,
16229                         (subsegT) get_absolute_expression ());
16230       if (IS_ELF)
16231         {
16232           bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
16233                                                   | SEC_READONLY | SEC_RELOC
16234                                                   | SEC_DATA));
16235           if (strncmp (TARGET_OS, "elf", 3) != 0)
16236             record_alignment (seg, 4);
16237         }
16238       demand_empty_rest_of_line ();
16239       break;
16240
16241     case 's':
16242       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
16243       if (IS_ELF)
16244         {
16245           bfd_set_section_flags (stdoutput, seg,
16246                                  SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
16247           if (strncmp (TARGET_OS, "elf", 3) != 0)
16248             record_alignment (seg, 4);
16249         }
16250       demand_empty_rest_of_line ();
16251       break;
16252
16253     case 'B':
16254       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
16255       if (IS_ELF)
16256         {
16257           bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
16258           if (strncmp (TARGET_OS, "elf", 3) != 0)
16259             record_alignment (seg, 4);
16260         }
16261       demand_empty_rest_of_line ();
16262       break;
16263     }
16264
16265   auto_align = 1;
16266 }
16267
16268 void
16269 s_change_section (int ignore ATTRIBUTE_UNUSED)
16270 {
16271 #ifdef OBJ_ELF
16272   char *section_name;
16273   char c;
16274   char next_c = 0;
16275   int section_type;
16276   int section_flag;
16277   int section_entry_size;
16278   int section_alignment;
16279
16280   if (!IS_ELF)
16281     return;
16282
16283   section_name = input_line_pointer;
16284   c = get_symbol_end ();
16285   if (c)
16286     next_c = *(input_line_pointer + 1);
16287
16288   /* Do we have .section Name<,"flags">?  */
16289   if (c != ',' || (c == ',' && next_c == '"'))
16290     {
16291       /* just after name is now '\0'.  */
16292       *input_line_pointer = c;
16293       input_line_pointer = section_name;
16294       obj_elf_section (ignore);
16295       return;
16296     }
16297   input_line_pointer++;
16298
16299   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
16300   if (c == ',')
16301     section_type = get_absolute_expression ();
16302   else
16303     section_type = 0;
16304   if (*input_line_pointer++ == ',')
16305     section_flag = get_absolute_expression ();
16306   else
16307     section_flag = 0;
16308   if (*input_line_pointer++ == ',')
16309     section_entry_size = get_absolute_expression ();
16310   else
16311     section_entry_size = 0;
16312   if (*input_line_pointer++ == ',')
16313     section_alignment = get_absolute_expression ();
16314   else
16315     section_alignment = 0;
16316   /* FIXME: really ignore?  */
16317   (void) section_alignment;
16318
16319   section_name = xstrdup (section_name);
16320
16321   /* When using the generic form of .section (as implemented by obj-elf.c),
16322      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
16323      traditionally had to fall back on the more common @progbits instead.
16324
16325      There's nothing really harmful in this, since bfd will correct
16326      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
16327      means that, for backwards compatibility, the special_section entries
16328      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
16329
16330      Even so, we shouldn't force users of the MIPS .section syntax to
16331      incorrectly label the sections as SHT_PROGBITS.  The best compromise
16332      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
16333      generic type-checking code.  */
16334   if (section_type == SHT_MIPS_DWARF)
16335     section_type = SHT_PROGBITS;
16336
16337   obj_elf_change_section (section_name, section_type, section_flag,
16338                           section_entry_size, 0, 0, 0);
16339
16340   if (now_seg->name != section_name)
16341     free (section_name);
16342 #endif /* OBJ_ELF */
16343 }
16344
16345 void
16346 mips_enable_auto_align (void)
16347 {
16348   auto_align = 1;
16349 }
16350
16351 static void
16352 s_cons (int log_size)
16353 {
16354   segment_info_type *si = seg_info (now_seg);
16355   struct insn_label_list *l = si->label_list;
16356
16357   mips_emit_delays ();
16358   if (log_size > 0 && auto_align)
16359     mips_align (log_size, 0, l);
16360   cons (1 << log_size);
16361   mips_clear_insn_labels ();
16362 }
16363
16364 static void
16365 s_float_cons (int type)
16366 {
16367   segment_info_type *si = seg_info (now_seg);
16368   struct insn_label_list *l = si->label_list;
16369
16370   mips_emit_delays ();
16371
16372   if (auto_align)
16373     {
16374       if (type == 'd')
16375         mips_align (3, 0, l);
16376       else
16377         mips_align (2, 0, l);
16378     }
16379
16380   float_cons (type);
16381   mips_clear_insn_labels ();
16382 }
16383
16384 /* Handle .globl.  We need to override it because on Irix 5 you are
16385    permitted to say
16386        .globl foo .text
16387    where foo is an undefined symbol, to mean that foo should be
16388    considered to be the address of a function.  */
16389
16390 static void
16391 s_mips_globl (int x ATTRIBUTE_UNUSED)
16392 {
16393   char *name;
16394   int c;
16395   symbolS *symbolP;
16396   flagword flag;
16397
16398   do
16399     {
16400       name = input_line_pointer;
16401       c = get_symbol_end ();
16402       symbolP = symbol_find_or_make (name);
16403       S_SET_EXTERNAL (symbolP);
16404
16405       *input_line_pointer = c;
16406       SKIP_WHITESPACE ();
16407
16408       /* On Irix 5, every global symbol that is not explicitly labelled as
16409          being a function is apparently labelled as being an object.  */
16410       flag = BSF_OBJECT;
16411
16412       if (!is_end_of_line[(unsigned char) *input_line_pointer]
16413           && (*input_line_pointer != ','))
16414         {
16415           char *secname;
16416           asection *sec;
16417
16418           secname = input_line_pointer;
16419           c = get_symbol_end ();
16420           sec = bfd_get_section_by_name (stdoutput, secname);
16421           if (sec == NULL)
16422             as_bad (_("%s: no such section"), secname);
16423           *input_line_pointer = c;
16424
16425           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
16426             flag = BSF_FUNCTION;
16427         }
16428
16429       symbol_get_bfdsym (symbolP)->flags |= flag;
16430
16431       c = *input_line_pointer;
16432       if (c == ',')
16433         {
16434           input_line_pointer++;
16435           SKIP_WHITESPACE ();
16436           if (is_end_of_line[(unsigned char) *input_line_pointer])
16437             c = '\n';
16438         }
16439     }
16440   while (c == ',');
16441
16442   demand_empty_rest_of_line ();
16443 }
16444
16445 static void
16446 s_option (int x ATTRIBUTE_UNUSED)
16447 {
16448   char *opt;
16449   char c;
16450
16451   opt = input_line_pointer;
16452   c = get_symbol_end ();
16453
16454   if (*opt == 'O')
16455     {
16456       /* FIXME: What does this mean?  */
16457     }
16458   else if (strncmp (opt, "pic", 3) == 0)
16459     {
16460       int i;
16461
16462       i = atoi (opt + 3);
16463       if (i == 0)
16464         mips_pic = NO_PIC;
16465       else if (i == 2)
16466         {
16467           mips_pic = SVR4_PIC;
16468           mips_abicalls = TRUE;
16469         }
16470       else
16471         as_bad (_(".option pic%d not supported"), i);
16472
16473       if (mips_pic == SVR4_PIC)
16474         {
16475           if (g_switch_seen && g_switch_value != 0)
16476             as_warn (_("-G may not be used with SVR4 PIC code"));
16477           g_switch_value = 0;
16478           bfd_set_gp_size (stdoutput, 0);
16479         }
16480     }
16481   else
16482     as_warn (_("Unrecognized option \"%s\""), opt);
16483
16484   *input_line_pointer = c;
16485   demand_empty_rest_of_line ();
16486 }
16487
16488 /* This structure is used to hold a stack of .set values.  */
16489
16490 struct mips_option_stack
16491 {
16492   struct mips_option_stack *next;
16493   struct mips_set_options options;
16494 };
16495
16496 static struct mips_option_stack *mips_opts_stack;
16497
16498 /* Handle the .set pseudo-op.  */
16499
16500 static void
16501 s_mipsset (int x ATTRIBUTE_UNUSED)
16502 {
16503   char *name = input_line_pointer, ch;
16504   const struct mips_ase *ase;
16505
16506   while (!is_end_of_line[(unsigned char) *input_line_pointer])
16507     ++input_line_pointer;
16508   ch = *input_line_pointer;
16509   *input_line_pointer = '\0';
16510
16511   if (strcmp (name, "reorder") == 0)
16512     {
16513       if (mips_opts.noreorder)
16514         end_noreorder ();
16515     }
16516   else if (strcmp (name, "noreorder") == 0)
16517     {
16518       if (!mips_opts.noreorder)
16519         start_noreorder ();
16520     }
16521   else if (strncmp (name, "at=", 3) == 0)
16522     {
16523       char *s = name + 3;
16524
16525       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
16526         as_bad (_("Unrecognized register name `%s'"), s);
16527     }
16528   else if (strcmp (name, "at") == 0)
16529     {
16530       mips_opts.at = ATREG;
16531     }
16532   else if (strcmp (name, "noat") == 0)
16533     {
16534       mips_opts.at = ZERO;
16535     }
16536   else if (strcmp (name, "macro") == 0)
16537     {
16538       mips_opts.warn_about_macros = 0;
16539     }
16540   else if (strcmp (name, "nomacro") == 0)
16541     {
16542       if (mips_opts.noreorder == 0)
16543         as_bad (_("`noreorder' must be set before `nomacro'"));
16544       mips_opts.warn_about_macros = 1;
16545     }
16546   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
16547     {
16548       mips_opts.nomove = 0;
16549     }
16550   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
16551     {
16552       mips_opts.nomove = 1;
16553     }
16554   else if (strcmp (name, "bopt") == 0)
16555     {
16556       mips_opts.nobopt = 0;
16557     }
16558   else if (strcmp (name, "nobopt") == 0)
16559     {
16560       mips_opts.nobopt = 1;
16561     }
16562   else if (strcmp (name, "gp=default") == 0)
16563     mips_opts.gp32 = file_mips_gp32;
16564   else if (strcmp (name, "gp=32") == 0)
16565     mips_opts.gp32 = 1;
16566   else if (strcmp (name, "gp=64") == 0)
16567     {
16568       if (!ISA_HAS_64BIT_REGS (mips_opts.isa))
16569         as_warn (_("%s isa does not support 64-bit registers"),
16570                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16571       mips_opts.gp32 = 0;
16572     }
16573   else if (strcmp (name, "fp=default") == 0)
16574     mips_opts.fp32 = file_mips_fp32;
16575   else if (strcmp (name, "fp=32") == 0)
16576     mips_opts.fp32 = 1;
16577   else if (strcmp (name, "fp=64") == 0)
16578     {
16579       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
16580         as_warn (_("%s isa does not support 64-bit floating point registers"),
16581                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16582       mips_opts.fp32 = 0;
16583     }
16584   else if (strcmp (name, "softfloat") == 0)
16585     mips_opts.soft_float = 1;
16586   else if (strcmp (name, "hardfloat") == 0)
16587     mips_opts.soft_float = 0;
16588   else if (strcmp (name, "singlefloat") == 0)
16589     mips_opts.single_float = 1;
16590   else if (strcmp (name, "doublefloat") == 0)
16591     mips_opts.single_float = 0;
16592   else if (strcmp (name, "mips16") == 0
16593            || strcmp (name, "MIPS-16") == 0)
16594     {
16595       if (mips_opts.micromips == 1)
16596         as_fatal (_("`mips16' cannot be used with `micromips'"));
16597       mips_opts.mips16 = 1;
16598     }
16599   else if (strcmp (name, "nomips16") == 0
16600            || strcmp (name, "noMIPS-16") == 0)
16601     mips_opts.mips16 = 0;
16602   else if (strcmp (name, "micromips") == 0)
16603     {
16604       if (mips_opts.mips16 == 1)
16605         as_fatal (_("`micromips' cannot be used with `mips16'"));
16606       mips_opts.micromips = 1;
16607     }
16608   else if (strcmp (name, "nomicromips") == 0)
16609     mips_opts.micromips = 0;
16610   else if (name[0] == 'n'
16611            && name[1] == 'o'
16612            && (ase = mips_lookup_ase (name + 2)))
16613     mips_set_ase (ase, FALSE);
16614   else if ((ase = mips_lookup_ase (name)))
16615     mips_set_ase (ase, TRUE);
16616   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
16617     {
16618       int reset = 0;
16619
16620       /* Permit the user to change the ISA and architecture on the fly.
16621          Needless to say, misuse can cause serious problems.  */
16622       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
16623         {
16624           reset = 1;
16625           mips_opts.isa = file_mips_isa;
16626           mips_opts.arch = file_mips_arch;
16627         }
16628       else if (strncmp (name, "arch=", 5) == 0)
16629         {
16630           const struct mips_cpu_info *p;
16631
16632           p = mips_parse_cpu("internal use", name + 5);
16633           if (!p)
16634             as_bad (_("unknown architecture %s"), name + 5);
16635           else
16636             {
16637               mips_opts.arch = p->cpu;
16638               mips_opts.isa = p->isa;
16639             }
16640         }
16641       else if (strncmp (name, "mips", 4) == 0)
16642         {
16643           const struct mips_cpu_info *p;
16644
16645           p = mips_parse_cpu("internal use", name);
16646           if (!p)
16647             as_bad (_("unknown ISA level %s"), name + 4);
16648           else
16649             {
16650               mips_opts.arch = p->cpu;
16651               mips_opts.isa = p->isa;
16652             }
16653         }
16654       else
16655         as_bad (_("unknown ISA or architecture %s"), name);
16656
16657       switch (mips_opts.isa)
16658         {
16659         case  0:
16660           break;
16661         case ISA_MIPS1:
16662         case ISA_MIPS2:
16663         case ISA_MIPS32:
16664         case ISA_MIPS32R2:
16665           mips_opts.gp32 = 1;
16666           mips_opts.fp32 = 1;
16667           break;
16668         case ISA_MIPS3:
16669         case ISA_MIPS4:
16670         case ISA_MIPS5:
16671         case ISA_MIPS64:
16672         case ISA_MIPS64R2:
16673           mips_opts.gp32 = 0;
16674           if (mips_opts.arch == CPU_R5900)
16675             {
16676                 mips_opts.fp32 = 1;
16677             }
16678           else
16679             {
16680           mips_opts.fp32 = 0;
16681             }
16682           break;
16683         default:
16684           as_bad (_("unknown ISA level %s"), name + 4);
16685           break;
16686         }
16687       if (reset)
16688         {
16689           mips_opts.gp32 = file_mips_gp32;
16690           mips_opts.fp32 = file_mips_fp32;
16691         }
16692     }
16693   else if (strcmp (name, "autoextend") == 0)
16694     mips_opts.noautoextend = 0;
16695   else if (strcmp (name, "noautoextend") == 0)
16696     mips_opts.noautoextend = 1;
16697   else if (strcmp (name, "push") == 0)
16698     {
16699       struct mips_option_stack *s;
16700
16701       s = (struct mips_option_stack *) xmalloc (sizeof *s);
16702       s->next = mips_opts_stack;
16703       s->options = mips_opts;
16704       mips_opts_stack = s;
16705     }
16706   else if (strcmp (name, "pop") == 0)
16707     {
16708       struct mips_option_stack *s;
16709
16710       s = mips_opts_stack;
16711       if (s == NULL)
16712         as_bad (_(".set pop with no .set push"));
16713       else
16714         {
16715           /* If we're changing the reorder mode we need to handle
16716              delay slots correctly.  */
16717           if (s->options.noreorder && ! mips_opts.noreorder)
16718             start_noreorder ();
16719           else if (! s->options.noreorder && mips_opts.noreorder)
16720             end_noreorder ();
16721
16722           mips_opts = s->options;
16723           mips_opts_stack = s->next;
16724           free (s);
16725         }
16726     }
16727   else if (strcmp (name, "sym32") == 0)
16728     mips_opts.sym32 = TRUE;
16729   else if (strcmp (name, "nosym32") == 0)
16730     mips_opts.sym32 = FALSE;
16731   else if (strchr (name, ','))
16732     {
16733       /* Generic ".set" directive; use the generic handler.  */
16734       *input_line_pointer = ch;
16735       input_line_pointer = name;
16736       s_set (0);
16737       return;
16738     }
16739   else
16740     {
16741       as_warn (_("Tried to set unrecognized symbol: %s\n"), name);
16742     }
16743   mips_check_isa_supports_ases ();
16744   *input_line_pointer = ch;
16745   demand_empty_rest_of_line ();
16746 }
16747
16748 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
16749    .option pic2.  It means to generate SVR4 PIC calls.  */
16750
16751 static void
16752 s_abicalls (int ignore ATTRIBUTE_UNUSED)
16753 {
16754   mips_pic = SVR4_PIC;
16755   mips_abicalls = TRUE;
16756
16757   if (g_switch_seen && g_switch_value != 0)
16758     as_warn (_("-G may not be used with SVR4 PIC code"));
16759   g_switch_value = 0;
16760
16761   bfd_set_gp_size (stdoutput, 0);
16762   demand_empty_rest_of_line ();
16763 }
16764
16765 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
16766    PIC code.  It sets the $gp register for the function based on the
16767    function address, which is in the register named in the argument.
16768    This uses a relocation against _gp_disp, which is handled specially
16769    by the linker.  The result is:
16770         lui     $gp,%hi(_gp_disp)
16771         addiu   $gp,$gp,%lo(_gp_disp)
16772         addu    $gp,$gp,.cpload argument
16773    The .cpload argument is normally $25 == $t9.
16774
16775    The -mno-shared option changes this to:
16776         lui     $gp,%hi(__gnu_local_gp)
16777         addiu   $gp,$gp,%lo(__gnu_local_gp)
16778    and the argument is ignored.  This saves an instruction, but the
16779    resulting code is not position independent; it uses an absolute
16780    address for __gnu_local_gp.  Thus code assembled with -mno-shared
16781    can go into an ordinary executable, but not into a shared library.  */
16782
16783 static void
16784 s_cpload (int ignore ATTRIBUTE_UNUSED)
16785 {
16786   expressionS ex;
16787   int reg;
16788   int in_shared;
16789
16790   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16791      .cpload is ignored.  */
16792   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16793     {
16794       s_ignore (0);
16795       return;
16796     }
16797
16798   if (mips_opts.mips16)
16799     {
16800       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
16801       ignore_rest_of_line ();
16802       return;
16803     }
16804
16805   /* .cpload should be in a .set noreorder section.  */
16806   if (mips_opts.noreorder == 0)
16807     as_warn (_(".cpload not in noreorder section"));
16808
16809   reg = tc_get_register (0);
16810
16811   /* If we need to produce a 64-bit address, we are better off using
16812      the default instruction sequence.  */
16813   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
16814
16815   ex.X_op = O_symbol;
16816   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
16817                                          "__gnu_local_gp");
16818   ex.X_op_symbol = NULL;
16819   ex.X_add_number = 0;
16820
16821   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16822   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16823
16824   mips_mark_labels ();
16825   mips_assembling_insn = TRUE;
16826
16827   macro_start ();
16828   macro_build_lui (&ex, mips_gp_register);
16829   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16830                mips_gp_register, BFD_RELOC_LO16);
16831   if (in_shared)
16832     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
16833                  mips_gp_register, reg);
16834   macro_end ();
16835
16836   mips_assembling_insn = FALSE;
16837   demand_empty_rest_of_line ();
16838 }
16839
16840 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
16841      .cpsetup $reg1, offset|$reg2, label
16842
16843    If offset is given, this results in:
16844      sd         $gp, offset($sp)
16845      lui        $gp, %hi(%neg(%gp_rel(label)))
16846      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16847      daddu      $gp, $gp, $reg1
16848
16849    If $reg2 is given, this results in:
16850      daddu      $reg2, $gp, $0
16851      lui        $gp, %hi(%neg(%gp_rel(label)))
16852      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16853      daddu      $gp, $gp, $reg1
16854    $reg1 is normally $25 == $t9.
16855
16856    The -mno-shared option replaces the last three instructions with
16857         lui     $gp,%hi(_gp)
16858         addiu   $gp,$gp,%lo(_gp)  */
16859
16860 static void
16861 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
16862 {
16863   expressionS ex_off;
16864   expressionS ex_sym;
16865   int reg1;
16866
16867   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
16868      We also need NewABI support.  */
16869   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16870     {
16871       s_ignore (0);
16872       return;
16873     }
16874
16875   if (mips_opts.mips16)
16876     {
16877       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
16878       ignore_rest_of_line ();
16879       return;
16880     }
16881
16882   reg1 = tc_get_register (0);
16883   SKIP_WHITESPACE ();
16884   if (*input_line_pointer != ',')
16885     {
16886       as_bad (_("missing argument separator ',' for .cpsetup"));
16887       return;
16888     }
16889   else
16890     ++input_line_pointer;
16891   SKIP_WHITESPACE ();
16892   if (*input_line_pointer == '$')
16893     {
16894       mips_cpreturn_register = tc_get_register (0);
16895       mips_cpreturn_offset = -1;
16896     }
16897   else
16898     {
16899       mips_cpreturn_offset = get_absolute_expression ();
16900       mips_cpreturn_register = -1;
16901     }
16902   SKIP_WHITESPACE ();
16903   if (*input_line_pointer != ',')
16904     {
16905       as_bad (_("missing argument separator ',' for .cpsetup"));
16906       return;
16907     }
16908   else
16909     ++input_line_pointer;
16910   SKIP_WHITESPACE ();
16911   expression (&ex_sym);
16912
16913   mips_mark_labels ();
16914   mips_assembling_insn = TRUE;
16915
16916   macro_start ();
16917   if (mips_cpreturn_register == -1)
16918     {
16919       ex_off.X_op = O_constant;
16920       ex_off.X_add_symbol = NULL;
16921       ex_off.X_op_symbol = NULL;
16922       ex_off.X_add_number = mips_cpreturn_offset;
16923
16924       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
16925                    BFD_RELOC_LO16, SP);
16926     }
16927   else
16928     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
16929                  mips_gp_register, 0);
16930
16931   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
16932     {
16933       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
16934                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
16935                    BFD_RELOC_HI16_S);
16936
16937       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
16938                    mips_gp_register, -1, BFD_RELOC_GPREL16,
16939                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
16940
16941       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
16942                    mips_gp_register, reg1);
16943     }
16944   else
16945     {
16946       expressionS ex;
16947
16948       ex.X_op = O_symbol;
16949       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
16950       ex.X_op_symbol = NULL;
16951       ex.X_add_number = 0;
16952
16953       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16954       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16955
16956       macro_build_lui (&ex, mips_gp_register);
16957       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16958                    mips_gp_register, BFD_RELOC_LO16);
16959     }
16960
16961   macro_end ();
16962
16963   mips_assembling_insn = FALSE;
16964   demand_empty_rest_of_line ();
16965 }
16966
16967 static void
16968 s_cplocal (int ignore ATTRIBUTE_UNUSED)
16969 {
16970   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
16971      .cplocal is ignored.  */
16972   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16973     {
16974       s_ignore (0);
16975       return;
16976     }
16977
16978   if (mips_opts.mips16)
16979     {
16980       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
16981       ignore_rest_of_line ();
16982       return;
16983     }
16984
16985   mips_gp_register = tc_get_register (0);
16986   demand_empty_rest_of_line ();
16987 }
16988
16989 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
16990    offset from $sp.  The offset is remembered, and after making a PIC
16991    call $gp is restored from that location.  */
16992
16993 static void
16994 s_cprestore (int ignore ATTRIBUTE_UNUSED)
16995 {
16996   expressionS ex;
16997
16998   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16999      .cprestore is ignored.  */
17000   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
17001     {
17002       s_ignore (0);
17003       return;
17004     }
17005
17006   if (mips_opts.mips16)
17007     {
17008       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
17009       ignore_rest_of_line ();
17010       return;
17011     }
17012
17013   mips_cprestore_offset = get_absolute_expression ();
17014   mips_cprestore_valid = 1;
17015
17016   ex.X_op = O_constant;
17017   ex.X_add_symbol = NULL;
17018   ex.X_op_symbol = NULL;
17019   ex.X_add_number = mips_cprestore_offset;
17020
17021   mips_mark_labels ();
17022   mips_assembling_insn = TRUE;
17023
17024   macro_start ();
17025   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
17026                                 SP, HAVE_64BIT_ADDRESSES);
17027   macro_end ();
17028
17029   mips_assembling_insn = FALSE;
17030   demand_empty_rest_of_line ();
17031 }
17032
17033 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
17034    was given in the preceding .cpsetup, it results in:
17035      ld         $gp, offset($sp)
17036
17037    If a register $reg2 was given there, it results in:
17038      daddu      $gp, $reg2, $0  */
17039
17040 static void
17041 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
17042 {
17043   expressionS ex;
17044
17045   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
17046      We also need NewABI support.  */
17047   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
17048     {
17049       s_ignore (0);
17050       return;
17051     }
17052
17053   if (mips_opts.mips16)
17054     {
17055       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
17056       ignore_rest_of_line ();
17057       return;
17058     }
17059
17060   mips_mark_labels ();
17061   mips_assembling_insn = TRUE;
17062
17063   macro_start ();
17064   if (mips_cpreturn_register == -1)
17065     {
17066       ex.X_op = O_constant;
17067       ex.X_add_symbol = NULL;
17068       ex.X_op_symbol = NULL;
17069       ex.X_add_number = mips_cpreturn_offset;
17070
17071       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
17072     }
17073   else
17074     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
17075                  mips_cpreturn_register, 0);
17076   macro_end ();
17077
17078   mips_assembling_insn = FALSE;
17079   demand_empty_rest_of_line ();
17080 }
17081
17082 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
17083    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
17084    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
17085    debug information or MIPS16 TLS.  */
17086
17087 static void
17088 s_tls_rel_directive (const size_t bytes, const char *dirstr,
17089                      bfd_reloc_code_real_type rtype)
17090 {
17091   expressionS ex;
17092   char *p;
17093
17094   expression (&ex);
17095
17096   if (ex.X_op != O_symbol)
17097     {
17098       as_bad (_("Unsupported use of %s"), dirstr);
17099       ignore_rest_of_line ();
17100     }
17101
17102   p = frag_more (bytes);
17103   md_number_to_chars (p, 0, bytes);
17104   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
17105   demand_empty_rest_of_line ();
17106   mips_clear_insn_labels ();
17107 }
17108
17109 /* Handle .dtprelword.  */
17110
17111 static void
17112 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
17113 {
17114   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
17115 }
17116
17117 /* Handle .dtpreldword.  */
17118
17119 static void
17120 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
17121 {
17122   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
17123 }
17124
17125 /* Handle .tprelword.  */
17126
17127 static void
17128 s_tprelword (int ignore ATTRIBUTE_UNUSED)
17129 {
17130   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
17131 }
17132
17133 /* Handle .tpreldword.  */
17134
17135 static void
17136 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
17137 {
17138   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
17139 }
17140
17141 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
17142    code.  It sets the offset to use in gp_rel relocations.  */
17143
17144 static void
17145 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
17146 {
17147   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
17148      We also need NewABI support.  */
17149   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
17150     {
17151       s_ignore (0);
17152       return;
17153     }
17154
17155   mips_gprel_offset = get_absolute_expression ();
17156
17157   demand_empty_rest_of_line ();
17158 }
17159
17160 /* Handle the .gpword pseudo-op.  This is used when generating PIC
17161    code.  It generates a 32 bit GP relative reloc.  */
17162
17163 static void
17164 s_gpword (int ignore ATTRIBUTE_UNUSED)
17165 {
17166   segment_info_type *si;
17167   struct insn_label_list *l;
17168   expressionS ex;
17169   char *p;
17170
17171   /* When not generating PIC code, this is treated as .word.  */
17172   if (mips_pic != SVR4_PIC)
17173     {
17174       s_cons (2);
17175       return;
17176     }
17177
17178   si = seg_info (now_seg);
17179   l = si->label_list;
17180   mips_emit_delays ();
17181   if (auto_align)
17182     mips_align (2, 0, l);
17183
17184   expression (&ex);
17185   mips_clear_insn_labels ();
17186
17187   if (ex.X_op != O_symbol || ex.X_add_number != 0)
17188     {
17189       as_bad (_("Unsupported use of .gpword"));
17190       ignore_rest_of_line ();
17191     }
17192
17193   p = frag_more (4);
17194   md_number_to_chars (p, 0, 4);
17195   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
17196                BFD_RELOC_GPREL32);
17197
17198   demand_empty_rest_of_line ();
17199 }
17200
17201 static void
17202 s_gpdword (int ignore ATTRIBUTE_UNUSED)
17203 {
17204   segment_info_type *si;
17205   struct insn_label_list *l;
17206   expressionS ex;
17207   char *p;
17208
17209   /* When not generating PIC code, this is treated as .dword.  */
17210   if (mips_pic != SVR4_PIC)
17211     {
17212       s_cons (3);
17213       return;
17214     }
17215
17216   si = seg_info (now_seg);
17217   l = si->label_list;
17218   mips_emit_delays ();
17219   if (auto_align)
17220     mips_align (3, 0, l);
17221
17222   expression (&ex);
17223   mips_clear_insn_labels ();
17224
17225   if (ex.X_op != O_symbol || ex.X_add_number != 0)
17226     {
17227       as_bad (_("Unsupported use of .gpdword"));
17228       ignore_rest_of_line ();
17229     }
17230
17231   p = frag_more (8);
17232   md_number_to_chars (p, 0, 8);
17233   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
17234                BFD_RELOC_GPREL32)->fx_tcbit = 1;
17235
17236   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
17237   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
17238            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
17239
17240   demand_empty_rest_of_line ();
17241 }
17242
17243 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
17244    tables.  It generates a R_MIPS_EH reloc.  */
17245
17246 static void
17247 s_ehword (int ignore ATTRIBUTE_UNUSED)
17248 {
17249   expressionS ex;
17250   char *p;
17251
17252   mips_emit_delays ();
17253
17254   expression (&ex);
17255   mips_clear_insn_labels ();
17256
17257   if (ex.X_op != O_symbol || ex.X_add_number != 0)
17258     {
17259       as_bad (_("Unsupported use of .ehword"));
17260       ignore_rest_of_line ();
17261     }
17262
17263   p = frag_more (4);
17264   md_number_to_chars (p, 0, 4);
17265   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
17266                BFD_RELOC_MIPS_EH);
17267
17268   demand_empty_rest_of_line ();
17269 }
17270
17271 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
17272    tables in SVR4 PIC code.  */
17273
17274 static void
17275 s_cpadd (int ignore ATTRIBUTE_UNUSED)
17276 {
17277   int reg;
17278
17279   /* This is ignored when not generating SVR4 PIC code.  */
17280   if (mips_pic != SVR4_PIC)
17281     {
17282       s_ignore (0);
17283       return;
17284     }
17285
17286   mips_mark_labels ();
17287   mips_assembling_insn = TRUE;
17288
17289   /* Add $gp to the register named as an argument.  */
17290   macro_start ();
17291   reg = tc_get_register (0);
17292   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
17293   macro_end ();
17294
17295   mips_assembling_insn = FALSE;
17296   demand_empty_rest_of_line ();
17297 }
17298
17299 /* Handle the .insn pseudo-op.  This marks instruction labels in
17300    mips16/micromips mode.  This permits the linker to handle them specially,
17301    such as generating jalx instructions when needed.  We also make
17302    them odd for the duration of the assembly, in order to generate the
17303    right sort of code.  We will make them even in the adjust_symtab
17304    routine, while leaving them marked.  This is convenient for the
17305    debugger and the disassembler.  The linker knows to make them odd
17306    again.  */
17307
17308 static void
17309 s_insn (int ignore ATTRIBUTE_UNUSED)
17310 {
17311   mips_mark_labels ();
17312
17313   demand_empty_rest_of_line ();
17314 }
17315
17316 /* Handle a .stab[snd] directive.  Ideally these directives would be
17317    implemented in a transparent way, so that removing them would not
17318    have any effect on the generated instructions.  However, s_stab
17319    internally changes the section, so in practice we need to decide
17320    now whether the preceding label marks compressed code.  We do not
17321    support changing the compression mode of a label after a .stab*
17322    directive, such as in:
17323
17324    foo:
17325         .stabs ...
17326         .set mips16
17327
17328    so the current mode wins.  */
17329
17330 static void
17331 s_mips_stab (int type)
17332 {
17333   mips_mark_labels ();
17334   s_stab (type);
17335 }
17336
17337 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
17338
17339 static void
17340 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
17341 {
17342   char *name;
17343   int c;
17344   symbolS *symbolP;
17345   expressionS exp;
17346
17347   name = input_line_pointer;
17348   c = get_symbol_end ();
17349   symbolP = symbol_find_or_make (name);
17350   S_SET_WEAK (symbolP);
17351   *input_line_pointer = c;
17352
17353   SKIP_WHITESPACE ();
17354
17355   if (! is_end_of_line[(unsigned char) *input_line_pointer])
17356     {
17357       if (S_IS_DEFINED (symbolP))
17358         {
17359           as_bad (_("ignoring attempt to redefine symbol %s"),
17360                   S_GET_NAME (symbolP));
17361           ignore_rest_of_line ();
17362           return;
17363         }
17364
17365       if (*input_line_pointer == ',')
17366         {
17367           ++input_line_pointer;
17368           SKIP_WHITESPACE ();
17369         }
17370
17371       expression (&exp);
17372       if (exp.X_op != O_symbol)
17373         {
17374           as_bad (_("bad .weakext directive"));
17375           ignore_rest_of_line ();
17376           return;
17377         }
17378       symbol_set_value_expression (symbolP, &exp);
17379     }
17380
17381   demand_empty_rest_of_line ();
17382 }
17383
17384 /* Parse a register string into a number.  Called from the ECOFF code
17385    to parse .frame.  The argument is non-zero if this is the frame
17386    register, so that we can record it in mips_frame_reg.  */
17387
17388 int
17389 tc_get_register (int frame)
17390 {
17391   unsigned int reg;
17392
17393   SKIP_WHITESPACE ();
17394   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
17395     reg = 0;
17396   if (frame)
17397     {
17398       mips_frame_reg = reg != 0 ? reg : SP;
17399       mips_frame_reg_valid = 1;
17400       mips_cprestore_valid = 0;
17401     }
17402   return reg;
17403 }
17404
17405 valueT
17406 md_section_align (asection *seg, valueT addr)
17407 {
17408   int align = bfd_get_section_alignment (stdoutput, seg);
17409
17410   if (IS_ELF)
17411     {
17412       /* We don't need to align ELF sections to the full alignment.
17413          However, Irix 5 may prefer that we align them at least to a 16
17414          byte boundary.  We don't bother to align the sections if we
17415          are targeted for an embedded system.  */
17416       if (strncmp (TARGET_OS, "elf", 3) == 0)
17417         return addr;
17418       if (align > 4)
17419         align = 4;
17420     }
17421
17422   return ((addr + (1 << align) - 1) & (-1 << align));
17423 }
17424
17425 /* Utility routine, called from above as well.  If called while the
17426    input file is still being read, it's only an approximation.  (For
17427    example, a symbol may later become defined which appeared to be
17428    undefined earlier.)  */
17429
17430 static int
17431 nopic_need_relax (symbolS *sym, int before_relaxing)
17432 {
17433   if (sym == 0)
17434     return 0;
17435
17436   if (g_switch_value > 0)
17437     {
17438       const char *symname;
17439       int change;
17440
17441       /* Find out whether this symbol can be referenced off the $gp
17442          register.  It can be if it is smaller than the -G size or if
17443          it is in the .sdata or .sbss section.  Certain symbols can
17444          not be referenced off the $gp, although it appears as though
17445          they can.  */
17446       symname = S_GET_NAME (sym);
17447       if (symname != (const char *) NULL
17448           && (strcmp (symname, "eprol") == 0
17449               || strcmp (symname, "etext") == 0
17450               || strcmp (symname, "_gp") == 0
17451               || strcmp (symname, "edata") == 0
17452               || strcmp (symname, "_fbss") == 0
17453               || strcmp (symname, "_fdata") == 0
17454               || strcmp (symname, "_ftext") == 0
17455               || strcmp (symname, "end") == 0
17456               || strcmp (symname, "_gp_disp") == 0))
17457         change = 1;
17458       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
17459                && (0
17460 #ifndef NO_ECOFF_DEBUGGING
17461                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
17462                        && (symbol_get_obj (sym)->ecoff_extern_size
17463                            <= g_switch_value))
17464 #endif
17465                    /* We must defer this decision until after the whole
17466                       file has been read, since there might be a .extern
17467                       after the first use of this symbol.  */
17468                    || (before_relaxing
17469 #ifndef NO_ECOFF_DEBUGGING
17470                        && symbol_get_obj (sym)->ecoff_extern_size == 0
17471 #endif
17472                        && S_GET_VALUE (sym) == 0)
17473                    || (S_GET_VALUE (sym) != 0
17474                        && S_GET_VALUE (sym) <= g_switch_value)))
17475         change = 0;
17476       else
17477         {
17478           const char *segname;
17479
17480           segname = segment_name (S_GET_SEGMENT (sym));
17481           gas_assert (strcmp (segname, ".lit8") != 0
17482                   && strcmp (segname, ".lit4") != 0);
17483           change = (strcmp (segname, ".sdata") != 0
17484                     && strcmp (segname, ".sbss") != 0
17485                     && strncmp (segname, ".sdata.", 7) != 0
17486                     && strncmp (segname, ".sbss.", 6) != 0
17487                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
17488                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
17489         }
17490       return change;
17491     }
17492   else
17493     /* We are not optimizing for the $gp register.  */
17494     return 1;
17495 }
17496
17497
17498 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
17499
17500 static bfd_boolean
17501 pic_need_relax (symbolS *sym, asection *segtype)
17502 {
17503   asection *symsec;
17504
17505   /* Handle the case of a symbol equated to another symbol.  */
17506   while (symbol_equated_reloc_p (sym))
17507     {
17508       symbolS *n;
17509
17510       /* It's possible to get a loop here in a badly written program.  */
17511       n = symbol_get_value_expression (sym)->X_add_symbol;
17512       if (n == sym)
17513         break;
17514       sym = n;
17515     }
17516
17517   if (symbol_section_p (sym))
17518     return TRUE;
17519
17520   symsec = S_GET_SEGMENT (sym);
17521
17522   /* This must duplicate the test in adjust_reloc_syms.  */
17523   return (!bfd_is_und_section (symsec)
17524           && !bfd_is_abs_section (symsec)
17525           && !bfd_is_com_section (symsec)
17526           && !s_is_linkonce (sym, segtype)
17527 #ifdef OBJ_ELF
17528           /* A global or weak symbol is treated as external.  */
17529           && (!IS_ELF || (! S_IS_WEAK (sym) && ! S_IS_EXTERNAL (sym)))
17530 #endif
17531           );
17532 }
17533
17534
17535 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
17536    extended opcode.  SEC is the section the frag is in.  */
17537
17538 static int
17539 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
17540 {
17541   int type;
17542   const struct mips16_immed_operand *op;
17543   offsetT val;
17544   int mintiny, maxtiny;
17545   segT symsec;
17546   fragS *sym_frag;
17547
17548   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
17549     return 0;
17550   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17551     return 1;
17552
17553   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17554   op = mips16_immed_operands;
17555   while (op->type != type)
17556     {
17557       ++op;
17558       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
17559     }
17560
17561   if (op->unsp)
17562     {
17563       if (type == '<' || type == '>' || type == '[' || type == ']')
17564         {
17565           mintiny = 1;
17566           maxtiny = 1 << op->nbits;
17567         }
17568       else
17569         {
17570           mintiny = 0;
17571           maxtiny = (1 << op->nbits) - 1;
17572         }
17573     }
17574   else
17575     {
17576       mintiny = - (1 << (op->nbits - 1));
17577       maxtiny = (1 << (op->nbits - 1)) - 1;
17578     }
17579
17580   sym_frag = symbol_get_frag (fragp->fr_symbol);
17581   val = S_GET_VALUE (fragp->fr_symbol);
17582   symsec = S_GET_SEGMENT (fragp->fr_symbol);
17583
17584   if (op->pcrel)
17585     {
17586       addressT addr;
17587
17588       /* We won't have the section when we are called from
17589          mips_relax_frag.  However, we will always have been called
17590          from md_estimate_size_before_relax first.  If this is a
17591          branch to a different section, we mark it as such.  If SEC is
17592          NULL, and the frag is not marked, then it must be a branch to
17593          the same section.  */
17594       if (sec == NULL)
17595         {
17596           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
17597             return 1;
17598         }
17599       else
17600         {
17601           /* Must have been called from md_estimate_size_before_relax.  */
17602           if (symsec != sec)
17603             {
17604               fragp->fr_subtype =
17605                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17606
17607               /* FIXME: We should support this, and let the linker
17608                  catch branches and loads that are out of range.  */
17609               as_bad_where (fragp->fr_file, fragp->fr_line,
17610                             _("unsupported PC relative reference to different section"));
17611
17612               return 1;
17613             }
17614           if (fragp != sym_frag && sym_frag->fr_address == 0)
17615             /* Assume non-extended on the first relaxation pass.
17616                The address we have calculated will be bogus if this is
17617                a forward branch to another frag, as the forward frag
17618                will have fr_address == 0.  */
17619             return 0;
17620         }
17621
17622       /* In this case, we know for sure that the symbol fragment is in
17623          the same section.  If the relax_marker of the symbol fragment
17624          differs from the relax_marker of this fragment, we have not
17625          yet adjusted the symbol fragment fr_address.  We want to add
17626          in STRETCH in order to get a better estimate of the address.
17627          This particularly matters because of the shift bits.  */
17628       if (stretch != 0
17629           && sym_frag->relax_marker != fragp->relax_marker)
17630         {
17631           fragS *f;
17632
17633           /* Adjust stretch for any alignment frag.  Note that if have
17634              been expanding the earlier code, the symbol may be
17635              defined in what appears to be an earlier frag.  FIXME:
17636              This doesn't handle the fr_subtype field, which specifies
17637              a maximum number of bytes to skip when doing an
17638              alignment.  */
17639           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
17640             {
17641               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
17642                 {
17643                   if (stretch < 0)
17644                     stretch = - ((- stretch)
17645                                  & ~ ((1 << (int) f->fr_offset) - 1));
17646                   else
17647                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
17648                   if (stretch == 0)
17649                     break;
17650                 }
17651             }
17652           if (f != NULL)
17653             val += stretch;
17654         }
17655
17656       addr = fragp->fr_address + fragp->fr_fix;
17657
17658       /* The base address rules are complicated.  The base address of
17659          a branch is the following instruction.  The base address of a
17660          PC relative load or add is the instruction itself, but if it
17661          is in a delay slot (in which case it can not be extended) use
17662          the address of the instruction whose delay slot it is in.  */
17663       if (type == 'p' || type == 'q')
17664         {
17665           addr += 2;
17666
17667           /* If we are currently assuming that this frag should be
17668              extended, then, the current address is two bytes
17669              higher.  */
17670           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17671             addr += 2;
17672
17673           /* Ignore the low bit in the target, since it will be set
17674              for a text label.  */
17675           if ((val & 1) != 0)
17676             --val;
17677         }
17678       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17679         addr -= 4;
17680       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17681         addr -= 2;
17682
17683       val -= addr & ~ ((1 << op->shift) - 1);
17684
17685       /* Branch offsets have an implicit 0 in the lowest bit.  */
17686       if (type == 'p' || type == 'q')
17687         val /= 2;
17688
17689       /* If any of the shifted bits are set, we must use an extended
17690          opcode.  If the address depends on the size of this
17691          instruction, this can lead to a loop, so we arrange to always
17692          use an extended opcode.  We only check this when we are in
17693          the main relaxation loop, when SEC is NULL.  */
17694       if ((val & ((1 << op->shift) - 1)) != 0 && sec == NULL)
17695         {
17696           fragp->fr_subtype =
17697             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17698           return 1;
17699         }
17700
17701       /* If we are about to mark a frag as extended because the value
17702          is precisely maxtiny + 1, then there is a chance of an
17703          infinite loop as in the following code:
17704              la $4,foo
17705              .skip      1020
17706              .align     2
17707            foo:
17708          In this case when the la is extended, foo is 0x3fc bytes
17709          away, so the la can be shrunk, but then foo is 0x400 away, so
17710          the la must be extended.  To avoid this loop, we mark the
17711          frag as extended if it was small, and is about to become
17712          extended with a value of maxtiny + 1.  */
17713       if (val == ((maxtiny + 1) << op->shift)
17714           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
17715           && sec == NULL)
17716         {
17717           fragp->fr_subtype =
17718             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17719           return 1;
17720         }
17721     }
17722   else if (symsec != absolute_section && sec != NULL)
17723     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
17724
17725   if ((val & ((1 << op->shift) - 1)) != 0
17726       || val < (mintiny << op->shift)
17727       || val > (maxtiny << op->shift))
17728     return 1;
17729   else
17730     return 0;
17731 }
17732
17733 /* Compute the length of a branch sequence, and adjust the
17734    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
17735    worst-case length is computed, with UPDATE being used to indicate
17736    whether an unconditional (-1), branch-likely (+1) or regular (0)
17737    branch is to be computed.  */
17738 static int
17739 relaxed_branch_length (fragS *fragp, asection *sec, int update)
17740 {
17741   bfd_boolean toofar;
17742   int length;
17743
17744   if (fragp
17745       && S_IS_DEFINED (fragp->fr_symbol)
17746       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17747     {
17748       addressT addr;
17749       offsetT val;
17750
17751       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17752
17753       addr = fragp->fr_address + fragp->fr_fix + 4;
17754
17755       val -= addr;
17756
17757       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
17758     }
17759   else if (fragp)
17760     /* If the symbol is not defined or it's in a different segment,
17761        assume the user knows what's going on and emit a short
17762        branch.  */
17763     toofar = FALSE;
17764   else
17765     toofar = TRUE;
17766
17767   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
17768     fragp->fr_subtype
17769       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
17770                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
17771                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
17772                              RELAX_BRANCH_LINK (fragp->fr_subtype),
17773                              toofar);
17774
17775   length = 4;
17776   if (toofar)
17777     {
17778       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
17779         length += 8;
17780
17781       if (mips_pic != NO_PIC)
17782         {
17783           /* Additional space for PIC loading of target address.  */
17784           length += 8;
17785           if (mips_opts.isa == ISA_MIPS1)
17786             /* Additional space for $at-stabilizing nop.  */
17787             length += 4;
17788         }
17789
17790       /* If branch is conditional.  */
17791       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
17792         length += 8;
17793     }
17794
17795   return length;
17796 }
17797
17798 /* Compute the length of a branch sequence, and adjust the
17799    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
17800    worst-case length is computed, with UPDATE being used to indicate
17801    whether an unconditional (-1), or regular (0) branch is to be
17802    computed.  */
17803
17804 static int
17805 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
17806 {
17807   bfd_boolean toofar;
17808   int length;
17809
17810   if (fragp
17811       && S_IS_DEFINED (fragp->fr_symbol)
17812       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17813     {
17814       addressT addr;
17815       offsetT val;
17816
17817       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17818       /* Ignore the low bit in the target, since it will be set
17819          for a text label.  */
17820       if ((val & 1) != 0)
17821         --val;
17822
17823       addr = fragp->fr_address + fragp->fr_fix + 4;
17824
17825       val -= addr;
17826
17827       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
17828     }
17829   else if (fragp)
17830     /* If the symbol is not defined or it's in a different segment,
17831        assume the user knows what's going on and emit a short
17832        branch.  */
17833     toofar = FALSE;
17834   else
17835     toofar = TRUE;
17836
17837   if (fragp && update
17838       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17839     fragp->fr_subtype = (toofar
17840                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
17841                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
17842
17843   length = 4;
17844   if (toofar)
17845     {
17846       bfd_boolean compact_known = fragp != NULL;
17847       bfd_boolean compact = FALSE;
17848       bfd_boolean uncond;
17849
17850       if (compact_known)
17851         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
17852       if (fragp)
17853         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
17854       else
17855         uncond = update < 0;
17856
17857       /* If label is out of range, we turn branch <br>:
17858
17859                 <br>    label                   # 4 bytes
17860             0:
17861
17862          into:
17863
17864                 j       label                   # 4 bytes
17865                 nop                             # 2 bytes if compact && !PIC
17866             0:
17867        */
17868       if (mips_pic == NO_PIC && (!compact_known || compact))
17869         length += 2;
17870
17871       /* If assembling PIC code, we further turn:
17872
17873                         j       label                   # 4 bytes
17874
17875          into:
17876
17877                         lw/ld   at, %got(label)(gp)     # 4 bytes
17878                         d/addiu at, %lo(label)          # 4 bytes
17879                         jr/c    at                      # 2 bytes
17880        */
17881       if (mips_pic != NO_PIC)
17882         length += 6;
17883
17884       /* If branch <br> is conditional, we prepend negated branch <brneg>:
17885
17886                         <brneg> 0f                      # 4 bytes
17887                         nop                             # 2 bytes if !compact
17888        */
17889       if (!uncond)
17890         length += (compact_known && compact) ? 4 : 6;
17891     }
17892
17893   return length;
17894 }
17895
17896 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
17897    bit accordingly.  */
17898
17899 static int
17900 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
17901 {
17902   bfd_boolean toofar;
17903
17904   if (fragp
17905       && S_IS_DEFINED (fragp->fr_symbol)
17906       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17907     {
17908       addressT addr;
17909       offsetT val;
17910       int type;
17911
17912       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17913       /* Ignore the low bit in the target, since it will be set
17914          for a text label.  */
17915       if ((val & 1) != 0)
17916         --val;
17917
17918       /* Assume this is a 2-byte branch.  */
17919       addr = fragp->fr_address + fragp->fr_fix + 2;
17920
17921       /* We try to avoid the infinite loop by not adding 2 more bytes for
17922          long branches.  */
17923
17924       val -= addr;
17925
17926       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
17927       if (type == 'D')
17928         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
17929       else if (type == 'E')
17930         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
17931       else
17932         abort ();
17933     }
17934   else
17935     /* If the symbol is not defined or it's in a different segment,
17936        we emit a normal 32-bit branch.  */
17937     toofar = TRUE;
17938
17939   if (fragp && update
17940       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
17941     fragp->fr_subtype
17942       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
17943                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
17944
17945   if (toofar)
17946     return 4;
17947
17948   return 2;
17949 }
17950
17951 /* Estimate the size of a frag before relaxing.  Unless this is the
17952    mips16, we are not really relaxing here, and the final size is
17953    encoded in the subtype information.  For the mips16, we have to
17954    decide whether we are using an extended opcode or not.  */
17955
17956 int
17957 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
17958 {
17959   int change;
17960
17961   if (RELAX_BRANCH_P (fragp->fr_subtype))
17962     {
17963
17964       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
17965
17966       return fragp->fr_var;
17967     }
17968
17969   if (RELAX_MIPS16_P (fragp->fr_subtype))
17970     /* We don't want to modify the EXTENDED bit here; it might get us
17971        into infinite loops.  We change it only in mips_relax_frag().  */
17972     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
17973
17974   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17975     {
17976       int length = 4;
17977
17978       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
17979         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
17980       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
17981         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
17982       fragp->fr_var = length;
17983
17984       return length;
17985     }
17986
17987   if (mips_pic == NO_PIC)
17988     change = nopic_need_relax (fragp->fr_symbol, 0);
17989   else if (mips_pic == SVR4_PIC)
17990     change = pic_need_relax (fragp->fr_symbol, segtype);
17991   else if (mips_pic == VXWORKS_PIC)
17992     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
17993     change = 0;
17994   else
17995     abort ();
17996
17997   if (change)
17998     {
17999       fragp->fr_subtype |= RELAX_USE_SECOND;
18000       return -RELAX_FIRST (fragp->fr_subtype);
18001     }
18002   else
18003     return -RELAX_SECOND (fragp->fr_subtype);
18004 }
18005
18006 /* This is called to see whether a reloc against a defined symbol
18007    should be converted into a reloc against a section.  */
18008
18009 int
18010 mips_fix_adjustable (fixS *fixp)
18011 {
18012   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
18013       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
18014     return 0;
18015
18016   if (fixp->fx_addsy == NULL)
18017     return 1;
18018
18019   /* If symbol SYM is in a mergeable section, relocations of the form
18020      SYM + 0 can usually be made section-relative.  The mergeable data
18021      is then identified by the section offset rather than by the symbol.
18022
18023      However, if we're generating REL LO16 relocations, the offset is split
18024      between the LO16 and parterning high part relocation.  The linker will
18025      need to recalculate the complete offset in order to correctly identify
18026      the merge data.
18027
18028      The linker has traditionally not looked for the parterning high part
18029      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
18030      placed anywhere.  Rather than break backwards compatibility by changing
18031      this, it seems better not to force the issue, and instead keep the
18032      original symbol.  This will work with either linker behavior.  */
18033   if ((lo16_reloc_p (fixp->fx_r_type)
18034        || reloc_needs_lo_p (fixp->fx_r_type))
18035       && HAVE_IN_PLACE_ADDENDS
18036       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
18037     return 0;
18038
18039   /* There is no place to store an in-place offset for JALR relocations.
18040      Likewise an in-range offset of limited PC-relative relocations may
18041      overflow the in-place relocatable field if recalculated against the
18042      start address of the symbol's containing section.  */
18043   if (HAVE_IN_PLACE_ADDENDS
18044       && (limited_pcrel_reloc_p (fixp->fx_r_type)
18045           || jalr_reloc_p (fixp->fx_r_type)))
18046     return 0;
18047
18048 #ifdef OBJ_ELF
18049   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
18050      to a floating-point stub.  The same is true for non-R_MIPS16_26
18051      relocations against MIPS16 functions; in this case, the stub becomes
18052      the function's canonical address.
18053
18054      Floating-point stubs are stored in unique .mips16.call.* or
18055      .mips16.fn.* sections.  If a stub T for function F is in section S,
18056      the first relocation in section S must be against F; this is how the
18057      linker determines the target function.  All relocations that might
18058      resolve to T must also be against F.  We therefore have the following
18059      restrictions, which are given in an intentionally-redundant way:
18060
18061        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
18062           symbols.
18063
18064        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
18065           if that stub might be used.
18066
18067        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
18068           symbols.
18069
18070        4. We cannot reduce a stub's relocations against MIPS16 symbols if
18071           that stub might be used.
18072
18073      There is a further restriction:
18074
18075        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
18076           R_MICROMIPS_26_S1) against MIPS16 or microMIPS symbols on
18077           targets with in-place addends; the relocation field cannot
18078           encode the low bit.
18079
18080      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
18081      against a MIPS16 symbol.  We deal with (5) by by not reducing any
18082      such relocations on REL targets.
18083
18084      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
18085      relocation against some symbol R, no relocation against R may be
18086      reduced.  (Note that this deals with (2) as well as (1) because
18087      relocations against global symbols will never be reduced on ELF
18088      targets.)  This approach is a little simpler than trying to detect
18089      stub sections, and gives the "all or nothing" per-symbol consistency
18090      that we have for MIPS16 symbols.  */
18091   if (IS_ELF
18092       && fixp->fx_subsy == NULL
18093       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
18094           || *symbol_get_tc (fixp->fx_addsy)
18095           || (HAVE_IN_PLACE_ADDENDS
18096               && ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
18097               && jmp_reloc_p (fixp->fx_r_type))))
18098     return 0;
18099 #endif
18100
18101   return 1;
18102 }
18103
18104 /* Translate internal representation of relocation info to BFD target
18105    format.  */
18106
18107 arelent **
18108 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
18109 {
18110   static arelent *retval[4];
18111   arelent *reloc;
18112   bfd_reloc_code_real_type code;
18113
18114   memset (retval, 0, sizeof(retval));
18115   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
18116   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
18117   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
18118   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
18119
18120   if (fixp->fx_pcrel)
18121     {
18122       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
18123                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
18124                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
18125                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
18126                   || fixp->fx_r_type == BFD_RELOC_32_PCREL);
18127
18128       /* At this point, fx_addnumber is "symbol offset - pcrel address".
18129          Relocations want only the symbol offset.  */
18130       reloc->addend = fixp->fx_addnumber + reloc->address;
18131       if (!IS_ELF)
18132         {
18133           /* A gruesome hack which is a result of the gruesome gas
18134              reloc handling.  What's worse, for COFF (as opposed to
18135              ECOFF), we might need yet another copy of reloc->address.
18136              See bfd_install_relocation.  */
18137           reloc->addend += reloc->address;
18138         }
18139     }
18140   else
18141     reloc->addend = fixp->fx_addnumber;
18142
18143   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
18144      entry to be used in the relocation's section offset.  */
18145   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
18146     {
18147       reloc->address = reloc->addend;
18148       reloc->addend = 0;
18149     }
18150
18151   code = fixp->fx_r_type;
18152
18153   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
18154   if (reloc->howto == NULL)
18155     {
18156       as_bad_where (fixp->fx_file, fixp->fx_line,
18157                     _("Can not represent %s relocation in this object file format"),
18158                     bfd_get_reloc_code_name (code));
18159       retval[0] = NULL;
18160     }
18161
18162   return retval;
18163 }
18164
18165 /* Relax a machine dependent frag.  This returns the amount by which
18166    the current size of the frag should change.  */
18167
18168 int
18169 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
18170 {
18171   if (RELAX_BRANCH_P (fragp->fr_subtype))
18172     {
18173       offsetT old_var = fragp->fr_var;
18174
18175       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
18176
18177       return fragp->fr_var - old_var;
18178     }
18179
18180   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
18181     {
18182       offsetT old_var = fragp->fr_var;
18183       offsetT new_var = 4;
18184
18185       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
18186         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
18187       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
18188         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
18189       fragp->fr_var = new_var;
18190
18191       return new_var - old_var;
18192     }
18193
18194   if (! RELAX_MIPS16_P (fragp->fr_subtype))
18195     return 0;
18196
18197   if (mips16_extended_frag (fragp, NULL, stretch))
18198     {
18199       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
18200         return 0;
18201       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
18202       return 2;
18203     }
18204   else
18205     {
18206       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
18207         return 0;
18208       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
18209       return -2;
18210     }
18211
18212   return 0;
18213 }
18214
18215 /* Convert a machine dependent frag.  */
18216
18217 void
18218 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
18219 {
18220   if (RELAX_BRANCH_P (fragp->fr_subtype))
18221     {
18222       char *buf;
18223       unsigned long insn;
18224       expressionS exp;
18225       fixS *fixp;
18226
18227       buf = fragp->fr_literal + fragp->fr_fix;
18228       insn = read_insn (buf);
18229
18230       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
18231         {
18232           /* We generate a fixup instead of applying it right now
18233              because, if there are linker relaxations, we're going to
18234              need the relocations.  */
18235           exp.X_op = O_symbol;
18236           exp.X_add_symbol = fragp->fr_symbol;
18237           exp.X_add_number = fragp->fr_offset;
18238
18239           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
18240                               BFD_RELOC_16_PCREL_S2);
18241           fixp->fx_file = fragp->fr_file;
18242           fixp->fx_line = fragp->fr_line;
18243
18244           buf = write_insn (buf, insn);
18245         }
18246       else
18247         {
18248           int i;
18249
18250           as_warn_where (fragp->fr_file, fragp->fr_line,
18251                          _("Relaxed out-of-range branch into a jump"));
18252
18253           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
18254             goto uncond;
18255
18256           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18257             {
18258               /* Reverse the branch.  */
18259               switch ((insn >> 28) & 0xf)
18260                 {
18261                 case 4:
18262                   /* bc[0-3][tf]l? instructions can have the condition
18263                      reversed by tweaking a single TF bit, and their
18264                      opcodes all have 0x4???????.  */
18265                   gas_assert ((insn & 0xf3e00000) == 0x41000000);
18266                   insn ^= 0x00010000;
18267                   break;
18268
18269                 case 0:
18270                   /* bltz       0x04000000      bgez    0x04010000
18271                      bltzal     0x04100000      bgezal  0x04110000  */
18272                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
18273                   insn ^= 0x00010000;
18274                   break;
18275
18276                 case 1:
18277                   /* beq        0x10000000      bne     0x14000000
18278                      blez       0x18000000      bgtz    0x1c000000  */
18279                   insn ^= 0x04000000;
18280                   break;
18281
18282                 default:
18283                   abort ();
18284                 }
18285             }
18286
18287           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
18288             {
18289               /* Clear the and-link bit.  */
18290               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
18291
18292               /* bltzal         0x04100000      bgezal  0x04110000
18293                  bltzall        0x04120000      bgezall 0x04130000  */
18294               insn &= ~0x00100000;
18295             }
18296
18297           /* Branch over the branch (if the branch was likely) or the
18298              full jump (not likely case).  Compute the offset from the
18299              current instruction to branch to.  */
18300           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18301             i = 16;
18302           else
18303             {
18304               /* How many bytes in instructions we've already emitted?  */
18305               i = buf - fragp->fr_literal - fragp->fr_fix;
18306               /* How many bytes in instructions from here to the end?  */
18307               i = fragp->fr_var - i;
18308             }
18309           /* Convert to instruction count.  */
18310           i >>= 2;
18311           /* Branch counts from the next instruction.  */
18312           i--;
18313           insn |= i;
18314           /* Branch over the jump.  */
18315           buf = write_insn (buf, insn);
18316
18317           /* nop */
18318           buf = write_insn (buf, 0);
18319
18320           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18321             {
18322               /* beql $0, $0, 2f */
18323               insn = 0x50000000;
18324               /* Compute the PC offset from the current instruction to
18325                  the end of the variable frag.  */
18326               /* How many bytes in instructions we've already emitted?  */
18327               i = buf - fragp->fr_literal - fragp->fr_fix;
18328               /* How many bytes in instructions from here to the end?  */
18329               i = fragp->fr_var - i;
18330               /* Convert to instruction count.  */
18331               i >>= 2;
18332               /* Don't decrement i, because we want to branch over the
18333                  delay slot.  */
18334               insn |= i;
18335
18336               buf = write_insn (buf, insn);
18337               buf = write_insn (buf, 0);
18338             }
18339
18340         uncond:
18341           if (mips_pic == NO_PIC)
18342             {
18343               /* j or jal.  */
18344               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
18345                       ? 0x0c000000 : 0x08000000);
18346               exp.X_op = O_symbol;
18347               exp.X_add_symbol = fragp->fr_symbol;
18348               exp.X_add_number = fragp->fr_offset;
18349
18350               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
18351                                   FALSE, BFD_RELOC_MIPS_JMP);
18352               fixp->fx_file = fragp->fr_file;
18353               fixp->fx_line = fragp->fr_line;
18354
18355               buf = write_insn (buf, insn);
18356             }
18357           else
18358             {
18359               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
18360
18361               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
18362               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
18363               insn |= at << OP_SH_RT;
18364               exp.X_op = O_symbol;
18365               exp.X_add_symbol = fragp->fr_symbol;
18366               exp.X_add_number = fragp->fr_offset;
18367
18368               if (fragp->fr_offset)
18369                 {
18370                   exp.X_add_symbol = make_expr_symbol (&exp);
18371                   exp.X_add_number = 0;
18372                 }
18373
18374               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
18375                                   FALSE, BFD_RELOC_MIPS_GOT16);
18376               fixp->fx_file = fragp->fr_file;
18377               fixp->fx_line = fragp->fr_line;
18378
18379               buf = write_insn (buf, insn);
18380
18381               if (mips_opts.isa == ISA_MIPS1)
18382                 /* nop */
18383                 buf = write_insn (buf, 0);
18384
18385               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
18386               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
18387               insn |= at << OP_SH_RS | at << OP_SH_RT;
18388
18389               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
18390                                   FALSE, BFD_RELOC_LO16);
18391               fixp->fx_file = fragp->fr_file;
18392               fixp->fx_line = fragp->fr_line;
18393
18394               buf = write_insn (buf, insn);
18395
18396               /* j(al)r $at.  */
18397               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
18398                 insn = 0x0000f809;
18399               else
18400                 insn = 0x00000008;
18401               insn |= at << OP_SH_RS;
18402
18403               buf = write_insn (buf, insn);
18404             }
18405         }
18406
18407       fragp->fr_fix += fragp->fr_var;
18408       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18409       return;
18410     }
18411
18412   /* Relax microMIPS branches.  */
18413   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
18414     {
18415       char *buf = fragp->fr_literal + fragp->fr_fix;
18416       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
18417       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
18418       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
18419       bfd_boolean short_ds;
18420       unsigned long insn;
18421       expressionS exp;
18422       fixS *fixp;
18423
18424       exp.X_op = O_symbol;
18425       exp.X_add_symbol = fragp->fr_symbol;
18426       exp.X_add_number = fragp->fr_offset;
18427
18428       fragp->fr_fix += fragp->fr_var;
18429
18430       /* Handle 16-bit branches that fit or are forced to fit.  */
18431       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
18432         {
18433           /* We generate a fixup instead of applying it right now,
18434              because if there is linker relaxation, we're going to
18435              need the relocations.  */
18436           if (type == 'D')
18437             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
18438                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
18439           else if (type == 'E')
18440             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
18441                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
18442           else
18443             abort ();
18444
18445           fixp->fx_file = fragp->fr_file;
18446           fixp->fx_line = fragp->fr_line;
18447
18448           /* These relocations can have an addend that won't fit in
18449              2 octets.  */
18450           fixp->fx_no_overflow = 1;
18451
18452           return;
18453         }
18454
18455       /* Handle 32-bit branches that fit or are forced to fit.  */
18456       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
18457           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18458         {
18459           /* We generate a fixup instead of applying it right now,
18460              because if there is linker relaxation, we're going to
18461              need the relocations.  */
18462           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
18463                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
18464           fixp->fx_file = fragp->fr_file;
18465           fixp->fx_line = fragp->fr_line;
18466
18467           if (type == 0)
18468             return;
18469         }
18470
18471       /* Relax 16-bit branches to 32-bit branches.  */
18472       if (type != 0)
18473         {
18474           insn = read_compressed_insn (buf, 2);
18475
18476           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
18477             insn = 0x94000000;                          /* beq  */
18478           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
18479             {
18480               unsigned long regno;
18481
18482               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
18483               regno = micromips_to_32_reg_d_map [regno];
18484               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
18485               insn |= regno << MICROMIPSOP_SH_RS;
18486             }
18487           else
18488             abort ();
18489
18490           /* Nothing else to do, just write it out.  */
18491           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
18492               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18493             {
18494               buf = write_compressed_insn (buf, insn, 4);
18495               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18496               return;
18497             }
18498         }
18499       else
18500         insn = read_compressed_insn (buf, 4);
18501
18502       /* Relax 32-bit branches to a sequence of instructions.  */
18503       as_warn_where (fragp->fr_file, fragp->fr_line,
18504                      _("Relaxed out-of-range branch into a jump"));
18505
18506       /* Set the short-delay-slot bit.  */
18507       short_ds = al && (insn & 0x02000000) != 0;
18508
18509       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
18510         {
18511           symbolS *l;
18512
18513           /* Reverse the branch.  */
18514           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
18515               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
18516             insn ^= 0x20000000;
18517           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
18518                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
18519                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
18520                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
18521                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
18522                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
18523                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
18524                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
18525                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
18526                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
18527             insn ^= 0x00400000;
18528           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
18529                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
18530                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
18531                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
18532             insn ^= 0x00200000;
18533           else
18534             abort ();
18535
18536           if (al)
18537             {
18538               /* Clear the and-link and short-delay-slot bits.  */
18539               gas_assert ((insn & 0xfda00000) == 0x40200000);
18540
18541               /* bltzal  0x40200000     bgezal  0x40600000  */
18542               /* bltzals 0x42200000     bgezals 0x42600000  */
18543               insn &= ~0x02200000;
18544             }
18545
18546           /* Make a label at the end for use with the branch.  */
18547           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
18548           micromips_label_inc ();
18549 #if defined(OBJ_ELF) || defined(OBJ_MAYBE_ELF)
18550           if (IS_ELF)
18551             S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
18552 #endif
18553
18554           /* Refer to it.  */
18555           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
18556                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
18557           fixp->fx_file = fragp->fr_file;
18558           fixp->fx_line = fragp->fr_line;
18559
18560           /* Branch over the jump.  */
18561           buf = write_compressed_insn (buf, insn, 4);
18562           if (!compact)
18563             /* nop */
18564             buf = write_compressed_insn (buf, 0x0c00, 2);
18565         }
18566
18567       if (mips_pic == NO_PIC)
18568         {
18569           unsigned long jal = short_ds ? 0x74000000 : 0xf4000000; /* jal/s  */
18570
18571           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
18572           insn = al ? jal : 0xd4000000;
18573
18574           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18575                               BFD_RELOC_MICROMIPS_JMP);
18576           fixp->fx_file = fragp->fr_file;
18577           fixp->fx_line = fragp->fr_line;
18578
18579           buf = write_compressed_insn (buf, insn, 4);
18580           if (compact)
18581             /* nop */
18582             buf = write_compressed_insn (buf, 0x0c00, 2);
18583         }
18584       else
18585         {
18586           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
18587           unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;      /* jalr/s  */
18588           unsigned long jr = compact ? 0x45a0 : 0x4580;         /* jr/c  */
18589
18590           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
18591           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
18592           insn |= at << MICROMIPSOP_SH_RT;
18593
18594           if (exp.X_add_number)
18595             {
18596               exp.X_add_symbol = make_expr_symbol (&exp);
18597               exp.X_add_number = 0;
18598             }
18599
18600           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18601                               BFD_RELOC_MICROMIPS_GOT16);
18602           fixp->fx_file = fragp->fr_file;
18603           fixp->fx_line = fragp->fr_line;
18604
18605           buf = write_compressed_insn (buf, insn, 4);
18606
18607           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
18608           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
18609           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
18610
18611           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18612                               BFD_RELOC_MICROMIPS_LO16);
18613           fixp->fx_file = fragp->fr_file;
18614           fixp->fx_line = fragp->fr_line;
18615
18616           buf = write_compressed_insn (buf, insn, 4);
18617
18618           /* jr/jrc/jalr/jalrs $at  */
18619           insn = al ? jalr : jr;
18620           insn |= at << MICROMIPSOP_SH_MJ;
18621
18622           buf = write_compressed_insn (buf, insn, 2);
18623         }
18624
18625       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18626       return;
18627     }
18628
18629   if (RELAX_MIPS16_P (fragp->fr_subtype))
18630     {
18631       int type;
18632       const struct mips16_immed_operand *op;
18633       offsetT val;
18634       char *buf;
18635       unsigned int user_length, length;
18636       unsigned long insn;
18637       bfd_boolean ext;
18638
18639       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
18640       op = mips16_immed_operands;
18641       while (op->type != type)
18642         ++op;
18643
18644       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
18645       val = resolve_symbol_value (fragp->fr_symbol);
18646       if (op->pcrel)
18647         {
18648           addressT addr;
18649
18650           addr = fragp->fr_address + fragp->fr_fix;
18651
18652           /* The rules for the base address of a PC relative reloc are
18653              complicated; see mips16_extended_frag.  */
18654           if (type == 'p' || type == 'q')
18655             {
18656               addr += 2;
18657               if (ext)
18658                 addr += 2;
18659               /* Ignore the low bit in the target, since it will be
18660                  set for a text label.  */
18661               if ((val & 1) != 0)
18662                 --val;
18663             }
18664           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
18665             addr -= 4;
18666           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
18667             addr -= 2;
18668
18669           addr &= ~ (addressT) ((1 << op->shift) - 1);
18670           val -= addr;
18671
18672           /* Make sure the section winds up with the alignment we have
18673              assumed.  */
18674           if (op->shift > 0)
18675             record_alignment (asec, op->shift);
18676         }
18677
18678       if (ext
18679           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
18680               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
18681         as_warn_where (fragp->fr_file, fragp->fr_line,
18682                        _("extended instruction in delay slot"));
18683
18684       buf = fragp->fr_literal + fragp->fr_fix;
18685
18686       insn = read_compressed_insn (buf, 2);
18687       if (ext)
18688         insn |= MIPS16_EXTEND;
18689
18690       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
18691         user_length = 4;
18692       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
18693         user_length = 2;
18694       else
18695         user_length = 0;
18696
18697       mips16_immed (fragp->fr_file, fragp->fr_line, type,
18698                     BFD_RELOC_UNUSED, val, user_length, &insn);
18699
18700       length = (ext ? 4 : 2);
18701       gas_assert (mips16_opcode_length (insn) == length);
18702       write_compressed_insn (buf, insn, length);
18703       fragp->fr_fix += length;
18704     }
18705   else
18706     {
18707       relax_substateT subtype = fragp->fr_subtype;
18708       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
18709       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
18710       int first, second;
18711       fixS *fixp;
18712
18713       first = RELAX_FIRST (subtype);
18714       second = RELAX_SECOND (subtype);
18715       fixp = (fixS *) fragp->fr_opcode;
18716
18717       /* If the delay slot chosen does not match the size of the instruction,
18718          then emit a warning.  */
18719       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
18720            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
18721         {
18722           relax_substateT s;
18723           const char *msg;
18724
18725           s = subtype & (RELAX_DELAY_SLOT_16BIT
18726                          | RELAX_DELAY_SLOT_SIZE_FIRST
18727                          | RELAX_DELAY_SLOT_SIZE_SECOND);
18728           msg = macro_warning (s);
18729           if (msg != NULL)
18730             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18731           subtype &= ~s;
18732         }
18733
18734       /* Possibly emit a warning if we've chosen the longer option.  */
18735       if (use_second == second_longer)
18736         {
18737           relax_substateT s;
18738           const char *msg;
18739
18740           s = (subtype
18741                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
18742           msg = macro_warning (s);
18743           if (msg != NULL)
18744             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18745           subtype &= ~s;
18746         }
18747
18748       /* Go through all the fixups for the first sequence.  Disable them
18749          (by marking them as done) if we're going to use the second
18750          sequence instead.  */
18751       while (fixp
18752              && fixp->fx_frag == fragp
18753              && fixp->fx_where < fragp->fr_fix - second)
18754         {
18755           if (subtype & RELAX_USE_SECOND)
18756             fixp->fx_done = 1;
18757           fixp = fixp->fx_next;
18758         }
18759
18760       /* Go through the fixups for the second sequence.  Disable them if
18761          we're going to use the first sequence, otherwise adjust their
18762          addresses to account for the relaxation.  */
18763       while (fixp && fixp->fx_frag == fragp)
18764         {
18765           if (subtype & RELAX_USE_SECOND)
18766             fixp->fx_where -= first;
18767           else
18768             fixp->fx_done = 1;
18769           fixp = fixp->fx_next;
18770         }
18771
18772       /* Now modify the frag contents.  */
18773       if (subtype & RELAX_USE_SECOND)
18774         {
18775           char *start;
18776
18777           start = fragp->fr_literal + fragp->fr_fix - first - second;
18778           memmove (start, start + first, second);
18779           fragp->fr_fix -= first;
18780         }
18781       else
18782         fragp->fr_fix -= second;
18783     }
18784 }
18785
18786 #ifdef OBJ_ELF
18787
18788 /* This function is called after the relocs have been generated.
18789    We've been storing mips16 text labels as odd.  Here we convert them
18790    back to even for the convenience of the debugger.  */
18791
18792 void
18793 mips_frob_file_after_relocs (void)
18794 {
18795   asymbol **syms;
18796   unsigned int count, i;
18797
18798   if (!IS_ELF)
18799     return;
18800
18801   syms = bfd_get_outsymbols (stdoutput);
18802   count = bfd_get_symcount (stdoutput);
18803   for (i = 0; i < count; i++, syms++)
18804     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
18805         && ((*syms)->value & 1) != 0)
18806       {
18807         (*syms)->value &= ~1;
18808         /* If the symbol has an odd size, it was probably computed
18809            incorrectly, so adjust that as well.  */
18810         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
18811           ++elf_symbol (*syms)->internal_elf_sym.st_size;
18812       }
18813 }
18814
18815 #endif
18816
18817 /* This function is called whenever a label is defined, including fake
18818    labels instantiated off the dot special symbol.  It is used when
18819    handling branch delays; if a branch has a label, we assume we cannot
18820    move it.  This also bumps the value of the symbol by 1 in compressed
18821    code.  */
18822
18823 static void
18824 mips_record_label (symbolS *sym)
18825 {
18826   segment_info_type *si = seg_info (now_seg);
18827   struct insn_label_list *l;
18828
18829   if (free_insn_labels == NULL)
18830     l = (struct insn_label_list *) xmalloc (sizeof *l);
18831   else
18832     {
18833       l = free_insn_labels;
18834       free_insn_labels = l->next;
18835     }
18836
18837   l->label = sym;
18838   l->next = si->label_list;
18839   si->label_list = l;
18840 }
18841
18842 /* This function is called as tc_frob_label() whenever a label is defined
18843    and adds a DWARF-2 record we only want for true labels.  */
18844
18845 void
18846 mips_define_label (symbolS *sym)
18847 {
18848   mips_record_label (sym);
18849 #ifdef OBJ_ELF
18850   dwarf2_emit_label (sym);
18851 #endif
18852 }
18853
18854 /* This function is called by tc_new_dot_label whenever a new dot symbol
18855    is defined.  */
18856
18857 void
18858 mips_add_dot_label (symbolS *sym)
18859 {
18860   mips_record_label (sym);
18861   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
18862     mips_compressed_mark_label (sym);
18863 }
18864 \f
18865 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
18866
18867 /* Some special processing for a MIPS ELF file.  */
18868
18869 void
18870 mips_elf_final_processing (void)
18871 {
18872   /* Write out the register information.  */
18873   if (mips_abi != N64_ABI)
18874     {
18875       Elf32_RegInfo s;
18876
18877       s.ri_gprmask = mips_gprmask;
18878       s.ri_cprmask[0] = mips_cprmask[0];
18879       s.ri_cprmask[1] = mips_cprmask[1];
18880       s.ri_cprmask[2] = mips_cprmask[2];
18881       s.ri_cprmask[3] = mips_cprmask[3];
18882       /* The gp_value field is set by the MIPS ELF backend.  */
18883
18884       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
18885                                        ((Elf32_External_RegInfo *)
18886                                         mips_regmask_frag));
18887     }
18888   else
18889     {
18890       Elf64_Internal_RegInfo s;
18891
18892       s.ri_gprmask = mips_gprmask;
18893       s.ri_pad = 0;
18894       s.ri_cprmask[0] = mips_cprmask[0];
18895       s.ri_cprmask[1] = mips_cprmask[1];
18896       s.ri_cprmask[2] = mips_cprmask[2];
18897       s.ri_cprmask[3] = mips_cprmask[3];
18898       /* The gp_value field is set by the MIPS ELF backend.  */
18899
18900       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
18901                                        ((Elf64_External_RegInfo *)
18902                                         mips_regmask_frag));
18903     }
18904
18905   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
18906      sort of BFD interface for this.  */
18907   if (mips_any_noreorder)
18908     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
18909   if (mips_pic != NO_PIC)
18910     {
18911       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
18912       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
18913     }
18914   if (mips_abicalls)
18915     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
18916
18917   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
18918      defined at present; this might need to change in future.  */
18919   if (file_ase_mips16)
18920     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
18921   if (file_ase_micromips)
18922     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
18923   if (file_ase & ASE_MDMX)
18924     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
18925
18926   /* Set the MIPS ELF ABI flags.  */
18927   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
18928     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
18929   else if (mips_abi == O64_ABI)
18930     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
18931   else if (mips_abi == EABI_ABI)
18932     {
18933       if (!file_mips_gp32)
18934         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
18935       else
18936         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
18937     }
18938   else if (mips_abi == N32_ABI)
18939     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
18940
18941   /* Nothing to do for N64_ABI.  */
18942
18943   if (mips_32bitmode)
18944     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
18945
18946 #if 0 /* XXX FIXME */
18947   /* 32 bit code with 64 bit FP registers.  */
18948   if (!file_mips_fp32 && ABI_NEEDS_32BIT_REGS (mips_abi))
18949     elf_elfheader (stdoutput)->e_flags |= ???;
18950 #endif
18951 }
18952
18953 #endif /* OBJ_ELF || OBJ_MAYBE_ELF */
18954 \f
18955 typedef struct proc {
18956   symbolS *func_sym;
18957   symbolS *func_end_sym;
18958   unsigned long reg_mask;
18959   unsigned long reg_offset;
18960   unsigned long fpreg_mask;
18961   unsigned long fpreg_offset;
18962   unsigned long frame_offset;
18963   unsigned long frame_reg;
18964   unsigned long pc_reg;
18965 } procS;
18966
18967 static procS cur_proc;
18968 static procS *cur_proc_ptr;
18969 static int numprocs;
18970
18971 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
18972    as "2", and a normal nop as "0".  */
18973
18974 #define NOP_OPCODE_MIPS         0
18975 #define NOP_OPCODE_MIPS16       1
18976 #define NOP_OPCODE_MICROMIPS    2
18977
18978 char
18979 mips_nop_opcode (void)
18980 {
18981   if (seg_info (now_seg)->tc_segment_info_data.micromips)
18982     return NOP_OPCODE_MICROMIPS;
18983   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
18984     return NOP_OPCODE_MIPS16;
18985   else
18986     return NOP_OPCODE_MIPS;
18987 }
18988
18989 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
18990    32-bit microMIPS NOPs here (if applicable).  */
18991
18992 void
18993 mips_handle_align (fragS *fragp)
18994 {
18995   char nop_opcode;
18996   char *p;
18997   int bytes, size, excess;
18998   valueT opcode;
18999
19000   if (fragp->fr_type != rs_align_code)
19001     return;
19002
19003   p = fragp->fr_literal + fragp->fr_fix;
19004   nop_opcode = *p;
19005   switch (nop_opcode)
19006     {
19007     case NOP_OPCODE_MICROMIPS:
19008       opcode = micromips_nop32_insn.insn_opcode;
19009       size = 4;
19010       break;
19011     case NOP_OPCODE_MIPS16:
19012       opcode = mips16_nop_insn.insn_opcode;
19013       size = 2;
19014       break;
19015     case NOP_OPCODE_MIPS:
19016     default:
19017       opcode = nop_insn.insn_opcode;
19018       size = 4;
19019       break;
19020     }
19021
19022   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
19023   excess = bytes % size;
19024
19025   /* Handle the leading part if we're not inserting a whole number of
19026      instructions, and make it the end of the fixed part of the frag.
19027      Try to fit in a short microMIPS NOP if applicable and possible,
19028      and use zeroes otherwise.  */
19029   gas_assert (excess < 4);
19030   fragp->fr_fix += excess;
19031   switch (excess)
19032     {
19033     case 3:
19034       *p++ = '\0';
19035       /* Fall through.  */
19036     case 2:
19037       if (nop_opcode == NOP_OPCODE_MICROMIPS)
19038         {
19039           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
19040           break;
19041         }
19042       *p++ = '\0';
19043       /* Fall through.  */
19044     case 1:
19045       *p++ = '\0';
19046       /* Fall through.  */
19047     case 0:
19048       break;
19049     }
19050
19051   md_number_to_chars (p, opcode, size);
19052   fragp->fr_var = size;
19053 }
19054
19055 static void
19056 md_obj_begin (void)
19057 {
19058 }
19059
19060 static void
19061 md_obj_end (void)
19062 {
19063   /* Check for premature end, nesting errors, etc.  */
19064   if (cur_proc_ptr)
19065     as_warn (_("missing .end at end of assembly"));
19066 }
19067
19068 static long
19069 get_number (void)
19070 {
19071   int negative = 0;
19072   long val = 0;
19073
19074   if (*input_line_pointer == '-')
19075     {
19076       ++input_line_pointer;
19077       negative = 1;
19078     }
19079   if (!ISDIGIT (*input_line_pointer))
19080     as_bad (_("expected simple number"));
19081   if (input_line_pointer[0] == '0')
19082     {
19083       if (input_line_pointer[1] == 'x')
19084         {
19085           input_line_pointer += 2;
19086           while (ISXDIGIT (*input_line_pointer))
19087             {
19088               val <<= 4;
19089               val |= hex_value (*input_line_pointer++);
19090             }
19091           return negative ? -val : val;
19092         }
19093       else
19094         {
19095           ++input_line_pointer;
19096           while (ISDIGIT (*input_line_pointer))
19097             {
19098               val <<= 3;
19099               val |= *input_line_pointer++ - '0';
19100             }
19101           return negative ? -val : val;
19102         }
19103     }
19104   if (!ISDIGIT (*input_line_pointer))
19105     {
19106       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
19107               *input_line_pointer, *input_line_pointer);
19108       as_warn (_("invalid number"));
19109       return -1;
19110     }
19111   while (ISDIGIT (*input_line_pointer))
19112     {
19113       val *= 10;
19114       val += *input_line_pointer++ - '0';
19115     }
19116   return negative ? -val : val;
19117 }
19118
19119 /* The .file directive; just like the usual .file directive, but there
19120    is an initial number which is the ECOFF file index.  In the non-ECOFF
19121    case .file implies DWARF-2.  */
19122
19123 static void
19124 s_mips_file (int x ATTRIBUTE_UNUSED)
19125 {
19126   static int first_file_directive = 0;
19127
19128   if (ECOFF_DEBUGGING)
19129     {
19130       get_number ();
19131       s_app_file (0);
19132     }
19133   else
19134     {
19135       char *filename;
19136
19137       filename = dwarf2_directive_file (0);
19138
19139       /* Versions of GCC up to 3.1 start files with a ".file"
19140          directive even for stabs output.  Make sure that this
19141          ".file" is handled.  Note that you need a version of GCC
19142          after 3.1 in order to support DWARF-2 on MIPS.  */
19143       if (filename != NULL && ! first_file_directive)
19144         {
19145           (void) new_logical_line (filename, -1);
19146           s_app_file_string (filename, 0);
19147         }
19148       first_file_directive = 1;
19149     }
19150 }
19151
19152 /* The .loc directive, implying DWARF-2.  */
19153
19154 static void
19155 s_mips_loc (int x ATTRIBUTE_UNUSED)
19156 {
19157   if (!ECOFF_DEBUGGING)
19158     dwarf2_directive_loc (0);
19159 }
19160
19161 /* The .end directive.  */
19162
19163 static void
19164 s_mips_end (int x ATTRIBUTE_UNUSED)
19165 {
19166   symbolS *p;
19167
19168   /* Following functions need their own .frame and .cprestore directives.  */
19169   mips_frame_reg_valid = 0;
19170   mips_cprestore_valid = 0;
19171
19172   if (!is_end_of_line[(unsigned char) *input_line_pointer])
19173     {
19174       p = get_symbol ();
19175       demand_empty_rest_of_line ();
19176     }
19177   else
19178     p = NULL;
19179
19180   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
19181     as_warn (_(".end not in text section"));
19182
19183   if (!cur_proc_ptr)
19184     {
19185       as_warn (_(".end directive without a preceding .ent directive."));
19186       demand_empty_rest_of_line ();
19187       return;
19188     }
19189
19190   if (p != NULL)
19191     {
19192       gas_assert (S_GET_NAME (p));
19193       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
19194         as_warn (_(".end symbol does not match .ent symbol."));
19195
19196       if (debug_type == DEBUG_STABS)
19197         stabs_generate_asm_endfunc (S_GET_NAME (p),
19198                                     S_GET_NAME (p));
19199     }
19200   else
19201     as_warn (_(".end directive missing or unknown symbol"));
19202
19203 #ifdef OBJ_ELF
19204   /* Create an expression to calculate the size of the function.  */
19205   if (p && cur_proc_ptr)
19206     {
19207       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
19208       expressionS *exp = xmalloc (sizeof (expressionS));
19209
19210       obj->size = exp;
19211       exp->X_op = O_subtract;
19212       exp->X_add_symbol = symbol_temp_new_now ();
19213       exp->X_op_symbol = p;
19214       exp->X_add_number = 0;
19215
19216       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
19217     }
19218
19219   /* Generate a .pdr section.  */
19220   if (IS_ELF && !ECOFF_DEBUGGING && mips_flag_pdr)
19221     {
19222       segT saved_seg = now_seg;
19223       subsegT saved_subseg = now_subseg;
19224       expressionS exp;
19225       char *fragp;
19226
19227 #ifdef md_flush_pending_output
19228       md_flush_pending_output ();
19229 #endif
19230
19231       gas_assert (pdr_seg);
19232       subseg_set (pdr_seg, 0);
19233
19234       /* Write the symbol.  */
19235       exp.X_op = O_symbol;
19236       exp.X_add_symbol = p;
19237       exp.X_add_number = 0;
19238       emit_expr (&exp, 4);
19239
19240       fragp = frag_more (7 * 4);
19241
19242       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
19243       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
19244       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
19245       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
19246       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
19247       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
19248       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
19249
19250       subseg_set (saved_seg, saved_subseg);
19251     }
19252 #endif /* OBJ_ELF */
19253
19254   cur_proc_ptr = NULL;
19255 }
19256
19257 /* The .aent and .ent directives.  */
19258
19259 static void
19260 s_mips_ent (int aent)
19261 {
19262   symbolS *symbolP;
19263
19264   symbolP = get_symbol ();
19265   if (*input_line_pointer == ',')
19266     ++input_line_pointer;
19267   SKIP_WHITESPACE ();
19268   if (ISDIGIT (*input_line_pointer)
19269       || *input_line_pointer == '-')
19270     get_number ();
19271
19272   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
19273     as_warn (_(".ent or .aent not in text section."));
19274
19275   if (!aent && cur_proc_ptr)
19276     as_warn (_("missing .end"));
19277
19278   if (!aent)
19279     {
19280       /* This function needs its own .frame and .cprestore directives.  */
19281       mips_frame_reg_valid = 0;
19282       mips_cprestore_valid = 0;
19283
19284       cur_proc_ptr = &cur_proc;
19285       memset (cur_proc_ptr, '\0', sizeof (procS));
19286
19287       cur_proc_ptr->func_sym = symbolP;
19288
19289       ++numprocs;
19290
19291       if (debug_type == DEBUG_STABS)
19292         stabs_generate_asm_func (S_GET_NAME (symbolP),
19293                                  S_GET_NAME (symbolP));
19294     }
19295
19296   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
19297
19298   demand_empty_rest_of_line ();
19299 }
19300
19301 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
19302    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
19303    s_mips_frame is used so that we can set the PDR information correctly.
19304    We can't use the ecoff routines because they make reference to the ecoff
19305    symbol table (in the mdebug section).  */
19306
19307 static void
19308 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
19309 {
19310 #ifdef OBJ_ELF
19311   if (IS_ELF && !ECOFF_DEBUGGING)
19312     {
19313       long val;
19314
19315       if (cur_proc_ptr == (procS *) NULL)
19316         {
19317           as_warn (_(".frame outside of .ent"));
19318           demand_empty_rest_of_line ();
19319           return;
19320         }
19321
19322       cur_proc_ptr->frame_reg = tc_get_register (1);
19323
19324       SKIP_WHITESPACE ();
19325       if (*input_line_pointer++ != ','
19326           || get_absolute_expression_and_terminator (&val) != ',')
19327         {
19328           as_warn (_("Bad .frame directive"));
19329           --input_line_pointer;
19330           demand_empty_rest_of_line ();
19331           return;
19332         }
19333
19334       cur_proc_ptr->frame_offset = val;
19335       cur_proc_ptr->pc_reg = tc_get_register (0);
19336
19337       demand_empty_rest_of_line ();
19338     }
19339   else
19340 #endif /* OBJ_ELF */
19341     s_ignore (ignore);
19342 }
19343
19344 /* The .fmask and .mask directives. If the mdebug section is present
19345    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
19346    embedded targets, s_mips_mask is used so that we can set the PDR
19347    information correctly. We can't use the ecoff routines because they
19348    make reference to the ecoff symbol table (in the mdebug section).  */
19349
19350 static void
19351 s_mips_mask (int reg_type)
19352 {
19353 #ifdef OBJ_ELF
19354   if (IS_ELF && !ECOFF_DEBUGGING)
19355     {
19356       long mask, off;
19357
19358       if (cur_proc_ptr == (procS *) NULL)
19359         {
19360           as_warn (_(".mask/.fmask outside of .ent"));
19361           demand_empty_rest_of_line ();
19362           return;
19363         }
19364
19365       if (get_absolute_expression_and_terminator (&mask) != ',')
19366         {
19367           as_warn (_("Bad .mask/.fmask directive"));
19368           --input_line_pointer;
19369           demand_empty_rest_of_line ();
19370           return;
19371         }
19372
19373       off = get_absolute_expression ();
19374
19375       if (reg_type == 'F')
19376         {
19377           cur_proc_ptr->fpreg_mask = mask;
19378           cur_proc_ptr->fpreg_offset = off;
19379         }
19380       else
19381         {
19382           cur_proc_ptr->reg_mask = mask;
19383           cur_proc_ptr->reg_offset = off;
19384         }
19385
19386       demand_empty_rest_of_line ();
19387     }
19388   else
19389 #endif /* OBJ_ELF */
19390     s_ignore (reg_type);
19391 }
19392
19393 /* A table describing all the processors gas knows about.  Names are
19394    matched in the order listed.
19395
19396    To ease comparison, please keep this table in the same order as
19397    gcc's mips_cpu_info_table[].  */
19398 static const struct mips_cpu_info mips_cpu_info_table[] =
19399 {
19400   /* Entries for generic ISAs */
19401   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
19402   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
19403   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
19404   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
19405   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
19406   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
19407   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
19408   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
19409   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
19410
19411   /* MIPS I */
19412   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
19413   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
19414   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
19415
19416   /* MIPS II */
19417   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
19418
19419   /* MIPS III */
19420   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
19421   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
19422   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
19423   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
19424   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
19425   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
19426   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
19427   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
19428   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
19429   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
19430   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
19431   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
19432   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
19433   /* ST Microelectronics Loongson 2E and 2F cores */
19434   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
19435   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
19436
19437   /* MIPS IV */
19438   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
19439   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
19440   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
19441   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
19442   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
19443   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19444   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
19445   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
19446   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19447   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19448   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19449   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19450   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19451   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
19452   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
19453
19454   /* MIPS 32 */
19455   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19456   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19457   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19458   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
19459
19460   /* MIPS 32 Release 2 */
19461   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19462   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19463   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19464   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
19465   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19466   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19467   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
19468   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
19469   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
19470                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
19471   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
19472                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
19473   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19474   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19475   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19476   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19477   /* Deprecated forms of the above.  */
19478   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19479   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19480   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
19481   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19482   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19483   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19484   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19485   /* Deprecated forms of the above.  */
19486   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19487   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19488   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
19489   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19490   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19491   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19492   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19493   /* Deprecated forms of the above.  */
19494   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19495   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19496   /* 34Kn is a 34kc without DSP.  */
19497   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
19498   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
19499   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19500   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19501   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19502   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19503   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19504   /* Deprecated forms of the above.  */
19505   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19506   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19507   /* 1004K cores are multiprocessor versions of the 34K.  */
19508   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19509   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19510   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19511   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19512
19513   /* MIPS 64 */
19514   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
19515   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
19516   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
19517   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
19518
19519   /* Broadcom SB-1 CPU core */
19520   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
19521   /* Broadcom SB-1A CPU core */
19522   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
19523   
19524   { "loongson3a",     0, 0,                     ISA_MIPS64,   CPU_LOONGSON_3A },
19525
19526   /* MIPS 64 Release 2 */
19527
19528   /* Cavium Networks Octeon CPU core */
19529   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
19530   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
19531   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
19532
19533   /* RMI Xlr */
19534   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
19535
19536   /* Broadcom XLP.
19537      XLP is mostly like XLR, with the prominent exception that it is
19538      MIPS64R2 rather than MIPS64.  */
19539   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
19540
19541   /* End marker */
19542   { NULL, 0, 0, 0, 0 }
19543 };
19544
19545
19546 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
19547    with a final "000" replaced by "k".  Ignore case.
19548
19549    Note: this function is shared between GCC and GAS.  */
19550
19551 static bfd_boolean
19552 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
19553 {
19554   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
19555     given++, canonical++;
19556
19557   return ((*given == 0 && *canonical == 0)
19558           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
19559 }
19560
19561
19562 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
19563    CPU name.  We've traditionally allowed a lot of variation here.
19564
19565    Note: this function is shared between GCC and GAS.  */
19566
19567 static bfd_boolean
19568 mips_matching_cpu_name_p (const char *canonical, const char *given)
19569 {
19570   /* First see if the name matches exactly, or with a final "000"
19571      turned into "k".  */
19572   if (mips_strict_matching_cpu_name_p (canonical, given))
19573     return TRUE;
19574
19575   /* If not, try comparing based on numerical designation alone.
19576      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
19577   if (TOLOWER (*given) == 'r')
19578     given++;
19579   if (!ISDIGIT (*given))
19580     return FALSE;
19581
19582   /* Skip over some well-known prefixes in the canonical name,
19583      hoping to find a number there too.  */
19584   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
19585     canonical += 2;
19586   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
19587     canonical += 2;
19588   else if (TOLOWER (canonical[0]) == 'r')
19589     canonical += 1;
19590
19591   return mips_strict_matching_cpu_name_p (canonical, given);
19592 }
19593
19594
19595 /* Parse an option that takes the name of a processor as its argument.
19596    OPTION is the name of the option and CPU_STRING is the argument.
19597    Return the corresponding processor enumeration if the CPU_STRING is
19598    recognized, otherwise report an error and return null.
19599
19600    A similar function exists in GCC.  */
19601
19602 static const struct mips_cpu_info *
19603 mips_parse_cpu (const char *option, const char *cpu_string)
19604 {
19605   const struct mips_cpu_info *p;
19606
19607   /* 'from-abi' selects the most compatible architecture for the given
19608      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
19609      EABIs, we have to decide whether we're using the 32-bit or 64-bit
19610      version.  Look first at the -mgp options, if given, otherwise base
19611      the choice on MIPS_DEFAULT_64BIT.
19612
19613      Treat NO_ABI like the EABIs.  One reason to do this is that the
19614      plain 'mips' and 'mips64' configs have 'from-abi' as their default
19615      architecture.  This code picks MIPS I for 'mips' and MIPS III for
19616      'mips64', just as we did in the days before 'from-abi'.  */
19617   if (strcasecmp (cpu_string, "from-abi") == 0)
19618     {
19619       if (ABI_NEEDS_32BIT_REGS (mips_abi))
19620         return mips_cpu_info_from_isa (ISA_MIPS1);
19621
19622       if (ABI_NEEDS_64BIT_REGS (mips_abi))
19623         return mips_cpu_info_from_isa (ISA_MIPS3);
19624
19625       if (file_mips_gp32 >= 0)
19626         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
19627
19628       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
19629                                      ? ISA_MIPS3
19630                                      : ISA_MIPS1);
19631     }
19632
19633   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
19634   if (strcasecmp (cpu_string, "default") == 0)
19635     return 0;
19636
19637   for (p = mips_cpu_info_table; p->name != 0; p++)
19638     if (mips_matching_cpu_name_p (p->name, cpu_string))
19639       return p;
19640
19641   as_bad (_("Bad value (%s) for %s"), cpu_string, option);
19642   return 0;
19643 }
19644
19645 /* Return the canonical processor information for ISA (a member of the
19646    ISA_MIPS* enumeration).  */
19647
19648 static const struct mips_cpu_info *
19649 mips_cpu_info_from_isa (int isa)
19650 {
19651   int i;
19652
19653   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19654     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
19655         && isa == mips_cpu_info_table[i].isa)
19656       return (&mips_cpu_info_table[i]);
19657
19658   return NULL;
19659 }
19660
19661 static const struct mips_cpu_info *
19662 mips_cpu_info_from_arch (int arch)
19663 {
19664   int i;
19665
19666   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19667     if (arch == mips_cpu_info_table[i].cpu)
19668       return (&mips_cpu_info_table[i]);
19669
19670   return NULL;
19671 }
19672 \f
19673 static void
19674 show (FILE *stream, const char *string, int *col_p, int *first_p)
19675 {
19676   if (*first_p)
19677     {
19678       fprintf (stream, "%24s", "");
19679       *col_p = 24;
19680     }
19681   else
19682     {
19683       fprintf (stream, ", ");
19684       *col_p += 2;
19685     }
19686
19687   if (*col_p + strlen (string) > 72)
19688     {
19689       fprintf (stream, "\n%24s", "");
19690       *col_p = 24;
19691     }
19692
19693   fprintf (stream, "%s", string);
19694   *col_p += strlen (string);
19695
19696   *first_p = 0;
19697 }
19698
19699 void
19700 md_show_usage (FILE *stream)
19701 {
19702   int column, first;
19703   size_t i;
19704
19705   fprintf (stream, _("\
19706 MIPS options:\n\
19707 -EB                     generate big endian output\n\
19708 -EL                     generate little endian output\n\
19709 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
19710 -G NUM                  allow referencing objects up to NUM bytes\n\
19711                         implicitly with the gp register [default 8]\n"));
19712   fprintf (stream, _("\
19713 -mips1                  generate MIPS ISA I instructions\n\
19714 -mips2                  generate MIPS ISA II instructions\n\
19715 -mips3                  generate MIPS ISA III instructions\n\
19716 -mips4                  generate MIPS ISA IV instructions\n\
19717 -mips5                  generate MIPS ISA V instructions\n\
19718 -mips32                 generate MIPS32 ISA instructions\n\
19719 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
19720 -mips64                 generate MIPS64 ISA instructions\n\
19721 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
19722 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
19723
19724   first = 1;
19725
19726   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19727     show (stream, mips_cpu_info_table[i].name, &column, &first);
19728   show (stream, "from-abi", &column, &first);
19729   fputc ('\n', stream);
19730
19731   fprintf (stream, _("\
19732 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
19733 -no-mCPU                don't generate code specific to CPU.\n\
19734                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
19735
19736   first = 1;
19737
19738   show (stream, "3900", &column, &first);
19739   show (stream, "4010", &column, &first);
19740   show (stream, "4100", &column, &first);
19741   show (stream, "4650", &column, &first);
19742   fputc ('\n', stream);
19743
19744   fprintf (stream, _("\
19745 -mips16                 generate mips16 instructions\n\
19746 -no-mips16              do not generate mips16 instructions\n"));
19747   fprintf (stream, _("\
19748 -mmicromips             generate microMIPS instructions\n\
19749 -mno-micromips          do not generate microMIPS instructions\n"));
19750   fprintf (stream, _("\
19751 -msmartmips             generate smartmips instructions\n\
19752 -mno-smartmips          do not generate smartmips instructions\n"));  
19753   fprintf (stream, _("\
19754 -mdsp                   generate DSP instructions\n\
19755 -mno-dsp                do not generate DSP instructions\n"));
19756   fprintf (stream, _("\
19757 -mdspr2                 generate DSP R2 instructions\n\
19758 -mno-dspr2              do not generate DSP R2 instructions\n"));
19759   fprintf (stream, _("\
19760 -mmt                    generate MT instructions\n\
19761 -mno-mt                 do not generate MT instructions\n"));
19762   fprintf (stream, _("\
19763 -mmcu                   generate MCU instructions\n\
19764 -mno-mcu                do not generate MCU instructions\n"));
19765   fprintf (stream, _("\
19766 -mvirt                  generate Virtualization instructions\n\
19767 -mno-virt               do not generate Virtualization instructions\n"));
19768   fprintf (stream, _("\
19769 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
19770 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
19771 -mfix-vr4120            work around certain VR4120 errata\n\
19772 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
19773 -mfix-24k               insert a nop after ERET and DERET instructions\n\
19774 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
19775 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
19776 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
19777 -msym32                 assume all symbols have 32-bit values\n\
19778 -O0                     remove unneeded NOPs, do not swap branches\n\
19779 -O                      remove unneeded NOPs and swap branches\n\
19780 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
19781 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
19782   fprintf (stream, _("\
19783 -mhard-float            allow floating-point instructions\n\
19784 -msoft-float            do not allow floating-point instructions\n\
19785 -msingle-float          only allow 32-bit floating-point operations\n\
19786 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
19787 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
19788 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n"
19789                      ));
19790 #ifdef OBJ_ELF
19791   fprintf (stream, _("\
19792 -KPIC, -call_shared     generate SVR4 position independent code\n\
19793 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
19794 -mvxworks-pic           generate VxWorks position independent code\n\
19795 -non_shared             do not generate code that can operate with DSOs\n\
19796 -xgot                   assume a 32 bit GOT\n\
19797 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
19798 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
19799                         position dependent (non shared) code\n\
19800 -mabi=ABI               create ABI conformant object file for:\n"));
19801
19802   first = 1;
19803
19804   show (stream, "32", &column, &first);
19805   show (stream, "o64", &column, &first);
19806   show (stream, "n32", &column, &first);
19807   show (stream, "64", &column, &first);
19808   show (stream, "eabi", &column, &first);
19809
19810   fputc ('\n', stream);
19811
19812   fprintf (stream, _("\
19813 -32                     create o32 ABI object file (default)\n\
19814 -n32                    create n32 ABI object file\n\
19815 -64                     create 64 ABI object file\n"));
19816 #endif
19817 }
19818
19819 #ifdef TE_IRIX
19820 enum dwarf2_format
19821 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
19822 {
19823   if (HAVE_64BIT_SYMBOLS)
19824     return dwarf2_format_64bit_irix;
19825   else
19826     return dwarf2_format_32bit;
19827 }
19828 #endif
19829
19830 int
19831 mips_dwarf2_addr_size (void)
19832 {
19833   if (HAVE_64BIT_OBJECTS)
19834     return 8;
19835   else
19836     return 4;
19837 }
19838
19839 /* Standard calling conventions leave the CFA at SP on entry.  */
19840 void
19841 mips_cfi_frame_initial_instructions (void)
19842 {
19843   cfi_add_CFA_def_cfa_register (SP);
19844 }
19845
19846 int
19847 tc_mips_regname_to_dw2regnum (char *regname)
19848 {
19849   unsigned int regnum = -1;
19850   unsigned int reg;
19851
19852   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
19853     regnum = reg;
19854
19855   return regnum;
19856 }