3418787a72dbf40f45ececb2521157ad068e6537
[external/binutils.git] / gas / config / tc-mips.c
1 /* tc-mips.c -- assemble code for a MIPS chip.
2    Copyright 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
3    2003, 2004, 2005 Free Software Foundation, Inc.
4    Contributed by the OSF and Ralph Campbell.
5    Written by Keith Knowles and Ralph Campbell, working independently.
6    Modified for ECOFF and R4000 support by Ian Lance Taylor of Cygnus
7    Support.
8
9    This file is part of GAS.
10
11    GAS is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 2, or (at your option)
14    any later version.
15
16    GAS is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with GAS; see the file COPYING.  If not, write to the Free
23    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
24    02110-1301, USA.  */
25
26 #include "as.h"
27 #include "config.h"
28 #include "subsegs.h"
29 #include "safe-ctype.h"
30
31 #include <stdarg.h>
32
33 #include "opcode/mips.h"
34 #include "itbl-ops.h"
35 #include "dwarf2dbg.h"
36 #include "dw2gencfi.h"
37
38 #ifdef DEBUG
39 #define DBG(x) printf x
40 #else
41 #define DBG(x)
42 #endif
43
44 #ifdef OBJ_MAYBE_ELF
45 /* Clean up namespace so we can include obj-elf.h too.  */
46 static int mips_output_flavor (void);
47 static int mips_output_flavor (void) { return OUTPUT_FLAVOR; }
48 #undef OBJ_PROCESS_STAB
49 #undef OUTPUT_FLAVOR
50 #undef S_GET_ALIGN
51 #undef S_GET_SIZE
52 #undef S_SET_ALIGN
53 #undef S_SET_SIZE
54 #undef obj_frob_file
55 #undef obj_frob_file_after_relocs
56 #undef obj_frob_symbol
57 #undef obj_pop_insert
58 #undef obj_sec_sym_ok_for_reloc
59 #undef OBJ_COPY_SYMBOL_ATTRIBUTES
60
61 #include "obj-elf.h"
62 /* Fix any of them that we actually care about.  */
63 #undef OUTPUT_FLAVOR
64 #define OUTPUT_FLAVOR mips_output_flavor()
65 #endif
66
67 #if defined (OBJ_ELF)
68 #include "elf/mips.h"
69 #endif
70
71 #ifndef ECOFF_DEBUGGING
72 #define NO_ECOFF_DEBUGGING
73 #define ECOFF_DEBUGGING 0
74 #endif
75
76 int mips_flag_mdebug = -1;
77
78 /* Control generation of .pdr sections.  Off by default on IRIX: the native
79    linker doesn't know about and discards them, but relocations against them
80    remain, leading to rld crashes.  */
81 #ifdef TE_IRIX
82 int mips_flag_pdr = FALSE;
83 #else
84 int mips_flag_pdr = TRUE;
85 #endif
86
87 #include "ecoff.h"
88
89 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
90 static char *mips_regmask_frag;
91 #endif
92
93 #define ZERO 0
94 #define AT  1
95 #define TREG 24
96 #define PIC_CALL_REG 25
97 #define KT0 26
98 #define KT1 27
99 #define GP  28
100 #define SP  29
101 #define FP  30
102 #define RA  31
103
104 #define ILLEGAL_REG (32)
105
106 /* Allow override of standard little-endian ECOFF format.  */
107
108 #ifndef ECOFF_LITTLE_FORMAT
109 #define ECOFF_LITTLE_FORMAT "ecoff-littlemips"
110 #endif
111
112 extern int target_big_endian;
113
114 /* The name of the readonly data section.  */
115 #define RDATA_SECTION_NAME (OUTPUT_FLAVOR == bfd_target_ecoff_flavour \
116                             ? ".rdata" \
117                             : OUTPUT_FLAVOR == bfd_target_coff_flavour \
118                             ? ".rdata" \
119                             : OUTPUT_FLAVOR == bfd_target_elf_flavour \
120                             ? ".rodata" \
121                             : (abort (), ""))
122
123 /* Information about an instruction, including its format, operands
124    and fixups.  */
125 struct mips_cl_insn
126 {
127   /* The opcode's entry in mips_opcodes or mips16_opcodes.  */
128   const struct mips_opcode *insn_mo;
129
130   /* True if this is a mips16 instruction and if we want the extended
131      form of INSN_MO.  */
132   bfd_boolean use_extend;
133
134   /* The 16-bit extension instruction to use when USE_EXTEND is true.  */
135   unsigned short extend;
136
137   /* The 16-bit or 32-bit bitstring of the instruction itself.  This is
138      a copy of INSN_MO->match with the operands filled in.  */
139   unsigned long insn_opcode;
140
141   /* The frag that contains the instruction.  */
142   struct frag *frag;
143
144   /* The offset into FRAG of the first instruction byte.  */
145   long where;
146
147   /* The relocs associated with the instruction, if any.  */
148   fixS *fixp[3];
149
150   /* True if this entry cannot be moved from its current position.  */
151   unsigned int fixed_p : 1;
152
153   /* True if this instruction occurred in a .set noreorder block.  */
154   unsigned int noreorder_p : 1;
155
156   /* True for mips16 instructions that jump to an absolute address.  */
157   unsigned int mips16_absolute_jump_p : 1;
158 };
159
160 /* The ABI to use.  */
161 enum mips_abi_level
162 {
163   NO_ABI = 0,
164   O32_ABI,
165   O64_ABI,
166   N32_ABI,
167   N64_ABI,
168   EABI_ABI
169 };
170
171 /* MIPS ABI we are using for this output file.  */
172 static enum mips_abi_level mips_abi = NO_ABI;
173
174 /* Whether or not we have code that can call pic code.  */
175 int mips_abicalls = FALSE;
176
177 /* Whether or not we have code which can be put into a shared
178    library.  */
179 static bfd_boolean mips_in_shared = TRUE;
180
181 /* This is the set of options which may be modified by the .set
182    pseudo-op.  We use a struct so that .set push and .set pop are more
183    reliable.  */
184
185 struct mips_set_options
186 {
187   /* MIPS ISA (Instruction Set Architecture) level.  This is set to -1
188      if it has not been initialized.  Changed by `.set mipsN', and the
189      -mipsN command line option, and the default CPU.  */
190   int isa;
191   /* Enabled Application Specific Extensions (ASEs).  These are set to -1
192      if they have not been initialized.  Changed by `.set <asename>', by
193      command line options, and based on the default architecture.  */
194   int ase_mips3d;
195   int ase_mdmx;
196   int ase_dsp;
197   int ase_mt;
198   /* Whether we are assembling for the mips16 processor.  0 if we are
199      not, 1 if we are, and -1 if the value has not been initialized.
200      Changed by `.set mips16' and `.set nomips16', and the -mips16 and
201      -nomips16 command line options, and the default CPU.  */
202   int mips16;
203   /* Non-zero if we should not reorder instructions.  Changed by `.set
204      reorder' and `.set noreorder'.  */
205   int noreorder;
206   /* Non-zero if we should not permit the $at ($1) register to be used
207      in instructions.  Changed by `.set at' and `.set noat'.  */
208   int noat;
209   /* Non-zero if we should warn when a macro instruction expands into
210      more than one machine instruction.  Changed by `.set nomacro' and
211      `.set macro'.  */
212   int warn_about_macros;
213   /* Non-zero if we should not move instructions.  Changed by `.set
214      move', `.set volatile', `.set nomove', and `.set novolatile'.  */
215   int nomove;
216   /* Non-zero if we should not optimize branches by moving the target
217      of the branch into the delay slot.  Actually, we don't perform
218      this optimization anyhow.  Changed by `.set bopt' and `.set
219      nobopt'.  */
220   int nobopt;
221   /* Non-zero if we should not autoextend mips16 instructions.
222      Changed by `.set autoextend' and `.set noautoextend'.  */
223   int noautoextend;
224   /* Restrict general purpose registers and floating point registers
225      to 32 bit.  This is initially determined when -mgp32 or -mfp32
226      is passed but can changed if the assembler code uses .set mipsN.  */
227   int gp32;
228   int fp32;
229   /* MIPS architecture (CPU) type.  Changed by .set arch=FOO, the -march
230      command line option, and the default CPU.  */
231   int arch;
232   /* True if ".set sym32" is in effect.  */
233   bfd_boolean sym32;
234 };
235
236 /* True if -mgp32 was passed.  */
237 static int file_mips_gp32 = -1;
238
239 /* True if -mfp32 was passed.  */
240 static int file_mips_fp32 = -1;
241
242 /* This is the struct we use to hold the current set of options.  Note
243    that we must set the isa field to ISA_UNKNOWN and the ASE fields to
244    -1 to indicate that they have not been initialized.  */
245
246 static struct mips_set_options mips_opts =
247 {
248   ISA_UNKNOWN, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, CPU_UNKNOWN, FALSE
249 };
250
251 /* These variables are filled in with the masks of registers used.
252    The object format code reads them and puts them in the appropriate
253    place.  */
254 unsigned long mips_gprmask;
255 unsigned long mips_cprmask[4];
256
257 /* MIPS ISA we are using for this output file.  */
258 static int file_mips_isa = ISA_UNKNOWN;
259
260 /* True if -mips16 was passed or implied by arguments passed on the
261    command line (e.g., by -march).  */
262 static int file_ase_mips16;
263
264 /* True if -mips3d was passed or implied by arguments passed on the
265    command line (e.g., by -march).  */
266 static int file_ase_mips3d;
267
268 /* True if -mdmx was passed or implied by arguments passed on the
269    command line (e.g., by -march).  */
270 static int file_ase_mdmx;
271
272 /* True if -mdsp was passed or implied by arguments passed on the
273    command line (e.g., by -march).  */
274 static int file_ase_dsp;
275
276 /* True if -mmt was passed or implied by arguments passed on the
277    command line (e.g., by -march).  */
278 static int file_ase_mt;
279
280 /* The argument of the -march= flag.  The architecture we are assembling.  */
281 static int file_mips_arch = CPU_UNKNOWN;
282 static const char *mips_arch_string;
283
284 /* The argument of the -mtune= flag.  The architecture for which we
285    are optimizing.  */
286 static int mips_tune = CPU_UNKNOWN;
287 static const char *mips_tune_string;
288
289 /* True when generating 32-bit code for a 64-bit processor.  */
290 static int mips_32bitmode = 0;
291
292 /* True if the given ABI requires 32-bit registers.  */
293 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
294
295 /* Likewise 64-bit registers.  */
296 #define ABI_NEEDS_64BIT_REGS(ABI) \
297   ((ABI) == N32_ABI               \
298    || (ABI) == N64_ABI            \
299    || (ABI) == O64_ABI)
300
301 /*  Return true if ISA supports 64 bit gp register instructions.  */
302 #define ISA_HAS_64BIT_REGS(ISA) (    \
303    (ISA) == ISA_MIPS3                \
304    || (ISA) == ISA_MIPS4             \
305    || (ISA) == ISA_MIPS5             \
306    || (ISA) == ISA_MIPS64            \
307    || (ISA) == ISA_MIPS64R2          \
308    )
309
310 /* Return true if ISA supports 64-bit right rotate (dror et al.)
311    instructions.  */
312 #define ISA_HAS_DROR(ISA) (     \
313    (ISA) == ISA_MIPS64R2        \
314    )
315
316 /* Return true if ISA supports 32-bit right rotate (ror et al.)
317    instructions.  */
318 #define ISA_HAS_ROR(ISA) (      \
319    (ISA) == ISA_MIPS32R2        \
320    || (ISA) == ISA_MIPS64R2     \
321    )
322
323 #define HAVE_32BIT_GPRS                            \
324     (mips_opts.gp32 || ! ISA_HAS_64BIT_REGS (mips_opts.isa))
325
326 #define HAVE_32BIT_FPRS                            \
327     (mips_opts.fp32 || ! ISA_HAS_64BIT_REGS (mips_opts.isa))
328
329 #define HAVE_64BIT_GPRS (! HAVE_32BIT_GPRS)
330 #define HAVE_64BIT_FPRS (! HAVE_32BIT_FPRS)
331
332 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
333
334 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
335
336 /* True if relocations are stored in-place.  */
337 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
338
339 /* The ABI-derived address size.  */
340 #define HAVE_64BIT_ADDRESSES \
341   (HAVE_64BIT_GPRS && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
342 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
343
344 /* The size of symbolic constants (i.e., expressions of the form
345    "SYMBOL" or "SYMBOL + OFFSET").  */
346 #define HAVE_32BIT_SYMBOLS \
347   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
348 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
349
350 /* Addresses are loaded in different ways, depending on the address size
351    in use.  The n32 ABI Documentation also mandates the use of additions
352    with overflow checking, but existing implementations don't follow it.  */
353 #define ADDRESS_ADD_INSN                                                \
354    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
355
356 #define ADDRESS_ADDI_INSN                                               \
357    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
358
359 #define ADDRESS_LOAD_INSN                                               \
360    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
361
362 #define ADDRESS_STORE_INSN                                              \
363    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
364
365 /* Return true if the given CPU supports the MIPS16 ASE.  */
366 #define CPU_HAS_MIPS16(cpu)                                             \
367    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
368     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
369
370 /* Return true if the given CPU supports the MIPS3D ASE.  */
371 #define CPU_HAS_MIPS3D(cpu)     ((cpu) == CPU_SB1      \
372                                  )
373
374 /* Return true if the given CPU supports the MDMX ASE.  */
375 #define CPU_HAS_MDMX(cpu)       (FALSE                 \
376                                  )
377
378 /* Return true if the given CPU supports the DSP ASE.  */
379 #define CPU_HAS_DSP(cpu)        (FALSE                 \
380                                  )
381
382 /* Return true if the given CPU supports the MT ASE.  */
383 #define CPU_HAS_MT(cpu)         (FALSE                 \
384                                  )
385
386 /* True if CPU has a dror instruction.  */
387 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
388
389 /* True if CPU has a ror instruction.  */
390 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
391
392 /* True if mflo and mfhi can be immediately followed by instructions
393    which write to the HI and LO registers.
394
395    According to MIPS specifications, MIPS ISAs I, II, and III need
396    (at least) two instructions between the reads of HI/LO and
397    instructions which write them, and later ISAs do not.  Contradicting
398    the MIPS specifications, some MIPS IV processor user manuals (e.g.
399    the UM for the NEC Vr5000) document needing the instructions between
400    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
401    MIPS64 and later ISAs to have the interlocks, plus any specific
402    earlier-ISA CPUs for which CPU documentation declares that the
403    instructions are really interlocked.  */
404 #define hilo_interlocks \
405   (mips_opts.isa == ISA_MIPS32                        \
406    || mips_opts.isa == ISA_MIPS32R2                   \
407    || mips_opts.isa == ISA_MIPS64                     \
408    || mips_opts.isa == ISA_MIPS64R2                   \
409    || mips_opts.arch == CPU_R4010                     \
410    || mips_opts.arch == CPU_R10000                    \
411    || mips_opts.arch == CPU_R12000                    \
412    || mips_opts.arch == CPU_RM7000                    \
413    || mips_opts.arch == CPU_VR5500                    \
414    )
415
416 /* Whether the processor uses hardware interlocks to protect reads
417    from the GPRs after they are loaded from memory, and thus does not
418    require nops to be inserted.  This applies to instructions marked
419    INSN_LOAD_MEMORY_DELAY.  These nops are only required at MIPS ISA
420    level I.  */
421 #define gpr_interlocks \
422   (mips_opts.isa != ISA_MIPS1  \
423    || mips_opts.arch == CPU_R3900)
424
425 /* Whether the processor uses hardware interlocks to avoid delays
426    required by coprocessor instructions, and thus does not require
427    nops to be inserted.  This applies to instructions marked
428    INSN_LOAD_COPROC_DELAY, INSN_COPROC_MOVE_DELAY, and to delays
429    between instructions marked INSN_WRITE_COND_CODE and ones marked
430    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
431    levels I, II, and III.  */
432 /* Itbl support may require additional care here.  */
433 #define cop_interlocks                                \
434   ((mips_opts.isa != ISA_MIPS1                        \
435     && mips_opts.isa != ISA_MIPS2                     \
436     && mips_opts.isa != ISA_MIPS3)                    \
437    || mips_opts.arch == CPU_R4300                     \
438    )
439
440 /* Whether the processor uses hardware interlocks to protect reads
441    from coprocessor registers after they are loaded from memory, and
442    thus does not require nops to be inserted.  This applies to
443    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
444    requires at MIPS ISA level I.  */
445 #define cop_mem_interlocks (mips_opts.isa != ISA_MIPS1)
446
447 /* Is this a mfhi or mflo instruction?  */
448 #define MF_HILO_INSN(PINFO) \
449           ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
450
451 /* MIPS PIC level.  */
452
453 enum mips_pic_level mips_pic;
454
455 /* 1 if we should generate 32 bit offsets from the $gp register in
456    SVR4_PIC mode.  Currently has no meaning in other modes.  */
457 static int mips_big_got = 0;
458
459 /* 1 if trap instructions should used for overflow rather than break
460    instructions.  */
461 static int mips_trap = 0;
462
463 /* 1 if double width floating point constants should not be constructed
464    by assembling two single width halves into two single width floating
465    point registers which just happen to alias the double width destination
466    register.  On some architectures this aliasing can be disabled by a bit
467    in the status register, and the setting of this bit cannot be determined
468    automatically at assemble time.  */
469 static int mips_disable_float_construction;
470
471 /* Non-zero if any .set noreorder directives were used.  */
472
473 static int mips_any_noreorder;
474
475 /* Non-zero if nops should be inserted when the register referenced in
476    an mfhi/mflo instruction is read in the next two instructions.  */
477 static int mips_7000_hilo_fix;
478
479 /* The size of the small data section.  */
480 static unsigned int g_switch_value = 8;
481 /* Whether the -G option was used.  */
482 static int g_switch_seen = 0;
483
484 #define N_RMASK 0xc4
485 #define N_VFP   0xd4
486
487 /* If we can determine in advance that GP optimization won't be
488    possible, we can skip the relaxation stuff that tries to produce
489    GP-relative references.  This makes delay slot optimization work
490    better.
491
492    This function can only provide a guess, but it seems to work for
493    gcc output.  It needs to guess right for gcc, otherwise gcc
494    will put what it thinks is a GP-relative instruction in a branch
495    delay slot.
496
497    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
498    fixed it for the non-PIC mode.  KR 95/04/07  */
499 static int nopic_need_relax (symbolS *, int);
500
501 /* handle of the OPCODE hash table */
502 static struct hash_control *op_hash = NULL;
503
504 /* The opcode hash table we use for the mips16.  */
505 static struct hash_control *mips16_op_hash = NULL;
506
507 /* This array holds the chars that always start a comment.  If the
508     pre-processor is disabled, these aren't very useful */
509 const char comment_chars[] = "#";
510
511 /* This array holds the chars that only start a comment at the beginning of
512    a line.  If the line seems to have the form '# 123 filename'
513    .line and .file directives will appear in the pre-processed output */
514 /* Note that input_file.c hand checks for '#' at the beginning of the
515    first line of the input file.  This is because the compiler outputs
516    #NO_APP at the beginning of its output.  */
517 /* Also note that C style comments are always supported.  */
518 const char line_comment_chars[] = "#";
519
520 /* This array holds machine specific line separator characters.  */
521 const char line_separator_chars[] = ";";
522
523 /* Chars that can be used to separate mant from exp in floating point nums */
524 const char EXP_CHARS[] = "eE";
525
526 /* Chars that mean this number is a floating point constant */
527 /* As in 0f12.456 */
528 /* or    0d1.2345e12 */
529 const char FLT_CHARS[] = "rRsSfFdDxXpP";
530
531 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
532    changed in read.c .  Ideally it shouldn't have to know about it at all,
533    but nothing is ideal around here.
534  */
535
536 static char *insn_error;
537
538 static int auto_align = 1;
539
540 /* When outputting SVR4 PIC code, the assembler needs to know the
541    offset in the stack frame from which to restore the $gp register.
542    This is set by the .cprestore pseudo-op, and saved in this
543    variable.  */
544 static offsetT mips_cprestore_offset = -1;
545
546 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
547    more optimizations, it can use a register value instead of a memory-saved
548    offset and even an other register than $gp as global pointer.  */
549 static offsetT mips_cpreturn_offset = -1;
550 static int mips_cpreturn_register = -1;
551 static int mips_gp_register = GP;
552 static int mips_gprel_offset = 0;
553
554 /* Whether mips_cprestore_offset has been set in the current function
555    (or whether it has already been warned about, if not).  */
556 static int mips_cprestore_valid = 0;
557
558 /* This is the register which holds the stack frame, as set by the
559    .frame pseudo-op.  This is needed to implement .cprestore.  */
560 static int mips_frame_reg = SP;
561
562 /* Whether mips_frame_reg has been set in the current function
563    (or whether it has already been warned about, if not).  */
564 static int mips_frame_reg_valid = 0;
565
566 /* To output NOP instructions correctly, we need to keep information
567    about the previous two instructions.  */
568
569 /* Whether we are optimizing.  The default value of 2 means to remove
570    unneeded NOPs and swap branch instructions when possible.  A value
571    of 1 means to not swap branches.  A value of 0 means to always
572    insert NOPs.  */
573 static int mips_optimize = 2;
574
575 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
576    equivalent to seeing no -g option at all.  */
577 static int mips_debug = 0;
578
579 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
580 #define MAX_VR4130_NOPS 4
581
582 /* The maximum number of NOPs needed to fill delay slots.  */
583 #define MAX_DELAY_NOPS 2
584
585 /* The maximum number of NOPs needed for any purpose.  */
586 #define MAX_NOPS 4
587
588 /* A list of previous instructions, with index 0 being the most recent.
589    We need to look back MAX_NOPS instructions when filling delay slots
590    or working around processor errata.  We need to look back one
591    instruction further if we're thinking about using history[0] to
592    fill a branch delay slot.  */
593 static struct mips_cl_insn history[1 + MAX_NOPS];
594
595 /* Nop instructions used by emit_nop.  */
596 static struct mips_cl_insn nop_insn, mips16_nop_insn;
597
598 /* The appropriate nop for the current mode.  */
599 #define NOP_INSN (mips_opts.mips16 ? &mips16_nop_insn : &nop_insn)
600
601 /* If this is set, it points to a frag holding nop instructions which
602    were inserted before the start of a noreorder section.  If those
603    nops turn out to be unnecessary, the size of the frag can be
604    decreased.  */
605 static fragS *prev_nop_frag;
606
607 /* The number of nop instructions we created in prev_nop_frag.  */
608 static int prev_nop_frag_holds;
609
610 /* The number of nop instructions that we know we need in
611    prev_nop_frag.  */
612 static int prev_nop_frag_required;
613
614 /* The number of instructions we've seen since prev_nop_frag.  */
615 static int prev_nop_frag_since;
616
617 /* For ECOFF and ELF, relocations against symbols are done in two
618    parts, with a HI relocation and a LO relocation.  Each relocation
619    has only 16 bits of space to store an addend.  This means that in
620    order for the linker to handle carries correctly, it must be able
621    to locate both the HI and the LO relocation.  This means that the
622    relocations must appear in order in the relocation table.
623
624    In order to implement this, we keep track of each unmatched HI
625    relocation.  We then sort them so that they immediately precede the
626    corresponding LO relocation.  */
627
628 struct mips_hi_fixup
629 {
630   /* Next HI fixup.  */
631   struct mips_hi_fixup *next;
632   /* This fixup.  */
633   fixS *fixp;
634   /* The section this fixup is in.  */
635   segT seg;
636 };
637
638 /* The list of unmatched HI relocs.  */
639
640 static struct mips_hi_fixup *mips_hi_fixup_list;
641
642 /* The frag containing the last explicit relocation operator.
643    Null if explicit relocations have not been used.  */
644
645 static fragS *prev_reloc_op_frag;
646
647 /* Map normal MIPS register numbers to mips16 register numbers.  */
648
649 #define X ILLEGAL_REG
650 static const int mips32_to_16_reg_map[] =
651 {
652   X, X, 2, 3, 4, 5, 6, 7,
653   X, X, X, X, X, X, X, X,
654   0, 1, X, X, X, X, X, X,
655   X, X, X, X, X, X, X, X
656 };
657 #undef X
658
659 /* Map mips16 register numbers to normal MIPS register numbers.  */
660
661 static const unsigned int mips16_to_32_reg_map[] =
662 {
663   16, 17, 2, 3, 4, 5, 6, 7
664 };
665
666 /* Classifies the kind of instructions we're interested in when
667    implementing -mfix-vr4120.  */
668 enum fix_vr4120_class {
669   FIX_VR4120_MACC,
670   FIX_VR4120_DMACC,
671   FIX_VR4120_MULT,
672   FIX_VR4120_DMULT,
673   FIX_VR4120_DIV,
674   FIX_VR4120_MTHILO,
675   NUM_FIX_VR4120_CLASSES
676 };
677
678 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
679    there must be at least one other instruction between an instruction
680    of type X and an instruction of type Y.  */
681 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
682
683 /* True if -mfix-vr4120 is in force.  */
684 static int mips_fix_vr4120;
685
686 /* ...likewise -mfix-vr4130.  */
687 static int mips_fix_vr4130;
688
689 /* We don't relax branches by default, since this causes us to expand
690    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
691    fail to compute the offset before expanding the macro to the most
692    efficient expansion.  */
693
694 static int mips_relax_branch;
695 \f
696 /* The expansion of many macros depends on the type of symbol that
697    they refer to.  For example, when generating position-dependent code,
698    a macro that refers to a symbol may have two different expansions,
699    one which uses GP-relative addresses and one which uses absolute
700    addresses.  When generating SVR4-style PIC, a macro may have
701    different expansions for local and global symbols.
702
703    We handle these situations by generating both sequences and putting
704    them in variant frags.  In position-dependent code, the first sequence
705    will be the GP-relative one and the second sequence will be the
706    absolute one.  In SVR4 PIC, the first sequence will be for global
707    symbols and the second will be for local symbols.
708
709    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
710    SECOND are the lengths of the two sequences in bytes.  These fields
711    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
712    the subtype has the following flags:
713
714    RELAX_USE_SECOND
715         Set if it has been decided that we should use the second
716         sequence instead of the first.
717
718    RELAX_SECOND_LONGER
719         Set in the first variant frag if the macro's second implementation
720         is longer than its first.  This refers to the macro as a whole,
721         not an individual relaxation.
722
723    RELAX_NOMACRO
724         Set in the first variant frag if the macro appeared in a .set nomacro
725         block and if one alternative requires a warning but the other does not.
726
727    RELAX_DELAY_SLOT
728         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
729         delay slot.
730
731    The frag's "opcode" points to the first fixup for relaxable code.
732
733    Relaxable macros are generated using a sequence such as:
734
735       relax_start (SYMBOL);
736       ... generate first expansion ...
737       relax_switch ();
738       ... generate second expansion ...
739       relax_end ();
740
741    The code and fixups for the unwanted alternative are discarded
742    by md_convert_frag.  */
743 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
744
745 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
746 #define RELAX_SECOND(X) ((X) & 0xff)
747 #define RELAX_USE_SECOND 0x10000
748 #define RELAX_SECOND_LONGER 0x20000
749 #define RELAX_NOMACRO 0x40000
750 #define RELAX_DELAY_SLOT 0x80000
751
752 /* Branch without likely bit.  If label is out of range, we turn:
753
754         beq reg1, reg2, label
755         delay slot
756
757    into
758
759         bne reg1, reg2, 0f
760         nop
761         j label
762      0: delay slot
763
764    with the following opcode replacements:
765
766         beq <-> bne
767         blez <-> bgtz
768         bltz <-> bgez
769         bc1f <-> bc1t
770
771         bltzal <-> bgezal  (with jal label instead of j label)
772
773    Even though keeping the delay slot instruction in the delay slot of
774    the branch would be more efficient, it would be very tricky to do
775    correctly, because we'd have to introduce a variable frag *after*
776    the delay slot instruction, and expand that instead.  Let's do it
777    the easy way for now, even if the branch-not-taken case now costs
778    one additional instruction.  Out-of-range branches are not supposed
779    to be common, anyway.
780
781    Branch likely.  If label is out of range, we turn:
782
783         beql reg1, reg2, label
784         delay slot (annulled if branch not taken)
785
786    into
787
788         beql reg1, reg2, 1f
789         nop
790         beql $0, $0, 2f
791         nop
792      1: j[al] label
793         delay slot (executed only if branch taken)
794      2:
795
796    It would be possible to generate a shorter sequence by losing the
797    likely bit, generating something like:
798
799         bne reg1, reg2, 0f
800         nop
801         j[al] label
802         delay slot (executed only if branch taken)
803      0:
804
805         beql -> bne
806         bnel -> beq
807         blezl -> bgtz
808         bgtzl -> blez
809         bltzl -> bgez
810         bgezl -> bltz
811         bc1fl -> bc1t
812         bc1tl -> bc1f
813
814         bltzall -> bgezal  (with jal label instead of j label)
815         bgezall -> bltzal  (ditto)
816
817
818    but it's not clear that it would actually improve performance.  */
819 #define RELAX_BRANCH_ENCODE(uncond, likely, link, toofar) \
820   ((relax_substateT) \
821    (0xc0000000 \
822     | ((toofar) ? 1 : 0) \
823     | ((link) ? 2 : 0) \
824     | ((likely) ? 4 : 0) \
825     | ((uncond) ? 8 : 0)))
826 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
827 #define RELAX_BRANCH_UNCOND(i) (((i) & 8) != 0)
828 #define RELAX_BRANCH_LIKELY(i) (((i) & 4) != 0)
829 #define RELAX_BRANCH_LINK(i) (((i) & 2) != 0)
830 #define RELAX_BRANCH_TOOFAR(i) (((i) & 1) != 0)
831
832 /* For mips16 code, we use an entirely different form of relaxation.
833    mips16 supports two versions of most instructions which take
834    immediate values: a small one which takes some small value, and a
835    larger one which takes a 16 bit value.  Since branches also follow
836    this pattern, relaxing these values is required.
837
838    We can assemble both mips16 and normal MIPS code in a single
839    object.  Therefore, we need to support this type of relaxation at
840    the same time that we support the relaxation described above.  We
841    use the high bit of the subtype field to distinguish these cases.
842
843    The information we store for this type of relaxation is the
844    argument code found in the opcode file for this relocation, whether
845    the user explicitly requested a small or extended form, and whether
846    the relocation is in a jump or jal delay slot.  That tells us the
847    size of the value, and how it should be stored.  We also store
848    whether the fragment is considered to be extended or not.  We also
849    store whether this is known to be a branch to a different section,
850    whether we have tried to relax this frag yet, and whether we have
851    ever extended a PC relative fragment because of a shift count.  */
852 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
853   (0x80000000                                                   \
854    | ((type) & 0xff)                                            \
855    | ((small) ? 0x100 : 0)                                      \
856    | ((ext) ? 0x200 : 0)                                        \
857    | ((dslot) ? 0x400 : 0)                                      \
858    | ((jal_dslot) ? 0x800 : 0))
859 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
860 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
861 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
862 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
863 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
864 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
865 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
866 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
867 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
868 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
869 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
870 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
871
872 /* Is the given value a sign-extended 32-bit value?  */
873 #define IS_SEXT_32BIT_NUM(x)                                            \
874   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
875    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
876
877 /* Is the given value a sign-extended 16-bit value?  */
878 #define IS_SEXT_16BIT_NUM(x)                                            \
879   (((x) &~ (offsetT) 0x7fff) == 0                                       \
880    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
881
882 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
883 #define IS_ZEXT_32BIT_NUM(x)                                            \
884   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
885    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
886
887 /* Replace bits MASK << SHIFT of STRUCT with the equivalent bits in
888    VALUE << SHIFT.  VALUE is evaluated exactly once.  */
889 #define INSERT_BITS(STRUCT, VALUE, MASK, SHIFT) \
890   (STRUCT) = (((STRUCT) & ~((MASK) << (SHIFT))) \
891               | (((VALUE) & (MASK)) << (SHIFT)))
892
893 /* Extract bits MASK << SHIFT from STRUCT and shift them right
894    SHIFT places.  */
895 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
896   (((STRUCT) >> (SHIFT)) & (MASK))
897
898 /* Change INSN's opcode so that the operand given by FIELD has value VALUE.
899    INSN is a mips_cl_insn structure and VALUE is evaluated exactly once.
900
901    include/opcode/mips.h specifies operand fields using the macros
902    OP_MASK_<FIELD> and OP_SH_<FIELD>.  The MIPS16 equivalents start
903    with "MIPS16OP" instead of "OP".  */
904 #define INSERT_OPERAND(FIELD, INSN, VALUE) \
905   INSERT_BITS ((INSN).insn_opcode, VALUE, OP_MASK_##FIELD, OP_SH_##FIELD)
906 #define MIPS16_INSERT_OPERAND(FIELD, INSN, VALUE) \
907   INSERT_BITS ((INSN).insn_opcode, VALUE, \
908                 MIPS16OP_MASK_##FIELD, MIPS16OP_SH_##FIELD)
909
910 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
911 #define EXTRACT_OPERAND(FIELD, INSN) \
912   EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD)
913 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
914   EXTRACT_BITS ((INSN).insn_opcode, \
915                 MIPS16OP_MASK_##FIELD, \
916                 MIPS16OP_SH_##FIELD)
917 \f
918 /* Global variables used when generating relaxable macros.  See the
919    comment above RELAX_ENCODE for more details about how relaxation
920    is used.  */
921 static struct {
922   /* 0 if we're not emitting a relaxable macro.
923      1 if we're emitting the first of the two relaxation alternatives.
924      2 if we're emitting the second alternative.  */
925   int sequence;
926
927   /* The first relaxable fixup in the current frag.  (In other words,
928      the first fixup that refers to relaxable code.)  */
929   fixS *first_fixup;
930
931   /* sizes[0] says how many bytes of the first alternative are stored in
932      the current frag.  Likewise sizes[1] for the second alternative.  */
933   unsigned int sizes[2];
934
935   /* The symbol on which the choice of sequence depends.  */
936   symbolS *symbol;
937 } mips_relax;
938 \f
939 /* Global variables used to decide whether a macro needs a warning.  */
940 static struct {
941   /* True if the macro is in a branch delay slot.  */
942   bfd_boolean delay_slot_p;
943
944   /* For relaxable macros, sizes[0] is the length of the first alternative
945      in bytes and sizes[1] is the length of the second alternative.
946      For non-relaxable macros, both elements give the length of the
947      macro in bytes.  */
948   unsigned int sizes[2];
949
950   /* The first variant frag for this macro.  */
951   fragS *first_frag;
952 } mips_macro_warning;
953 \f
954 /* Prototypes for static functions.  */
955
956 #define internalError()                                                 \
957     as_fatal (_("internal Error, line %d, %s"), __LINE__, __FILE__)
958
959 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
960
961 static void append_insn
962   (struct mips_cl_insn *ip, expressionS *p, bfd_reloc_code_real_type *r);
963 static void mips_no_prev_insn (void);
964 static void mips16_macro_build
965   (expressionS *, const char *, const char *, va_list);
966 static void load_register (int, expressionS *, int);
967 static void macro_start (void);
968 static void macro_end (void);
969 static void macro (struct mips_cl_insn * ip);
970 static void mips16_macro (struct mips_cl_insn * ip);
971 #ifdef LOSING_COMPILER
972 static void macro2 (struct mips_cl_insn * ip);
973 #endif
974 static void mips_ip (char *str, struct mips_cl_insn * ip);
975 static void mips16_ip (char *str, struct mips_cl_insn * ip);
976 static void mips16_immed
977   (char *, unsigned int, int, offsetT, bfd_boolean, bfd_boolean, bfd_boolean,
978    unsigned long *, bfd_boolean *, unsigned short *);
979 static size_t my_getSmallExpression
980   (expressionS *, bfd_reloc_code_real_type *, char *);
981 static void my_getExpression (expressionS *, char *);
982 static void s_align (int);
983 static void s_change_sec (int);
984 static void s_change_section (int);
985 static void s_cons (int);
986 static void s_float_cons (int);
987 static void s_mips_globl (int);
988 static void s_option (int);
989 static void s_mipsset (int);
990 static void s_abicalls (int);
991 static void s_cpload (int);
992 static void s_cpsetup (int);
993 static void s_cplocal (int);
994 static void s_cprestore (int);
995 static void s_cpreturn (int);
996 static void s_gpvalue (int);
997 static void s_gpword (int);
998 static void s_gpdword (int);
999 static void s_cpadd (int);
1000 static void s_insn (int);
1001 static void md_obj_begin (void);
1002 static void md_obj_end (void);
1003 static void s_mips_ent (int);
1004 static void s_mips_end (int);
1005 static void s_mips_frame (int);
1006 static void s_mips_mask (int reg_type);
1007 static void s_mips_stab (int);
1008 static void s_mips_weakext (int);
1009 static void s_mips_file (int);
1010 static void s_mips_loc (int);
1011 static bfd_boolean pic_need_relax (symbolS *, asection *);
1012 static int relaxed_branch_length (fragS *, asection *, int);
1013 static int validate_mips_insn (const struct mips_opcode *);
1014
1015 /* Table and functions used to map between CPU/ISA names, and
1016    ISA levels, and CPU numbers.  */
1017
1018 struct mips_cpu_info
1019 {
1020   const char *name;           /* CPU or ISA name.  */
1021   int is_isa;                 /* Is this an ISA?  (If 0, a CPU.) */
1022   int isa;                    /* ISA level.  */
1023   int cpu;                    /* CPU number (default CPU if ISA).  */
1024 };
1025
1026 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1027 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1028 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1029 \f
1030 /* Pseudo-op table.
1031
1032    The following pseudo-ops from the Kane and Heinrich MIPS book
1033    should be defined here, but are currently unsupported: .alias,
1034    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1035
1036    The following pseudo-ops from the Kane and Heinrich MIPS book are
1037    specific to the type of debugging information being generated, and
1038    should be defined by the object format: .aent, .begin, .bend,
1039    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1040    .vreg.
1041
1042    The following pseudo-ops from the Kane and Heinrich MIPS book are
1043    not MIPS CPU specific, but are also not specific to the object file
1044    format.  This file is probably the best place to define them, but
1045    they are not currently supported: .asm0, .endr, .lab, .repeat,
1046    .struct.  */
1047
1048 static const pseudo_typeS mips_pseudo_table[] =
1049 {
1050   /* MIPS specific pseudo-ops.  */
1051   {"option", s_option, 0},
1052   {"set", s_mipsset, 0},
1053   {"rdata", s_change_sec, 'r'},
1054   {"sdata", s_change_sec, 's'},
1055   {"livereg", s_ignore, 0},
1056   {"abicalls", s_abicalls, 0},
1057   {"cpload", s_cpload, 0},
1058   {"cpsetup", s_cpsetup, 0},
1059   {"cplocal", s_cplocal, 0},
1060   {"cprestore", s_cprestore, 0},
1061   {"cpreturn", s_cpreturn, 0},
1062   {"gpvalue", s_gpvalue, 0},
1063   {"gpword", s_gpword, 0},
1064   {"gpdword", s_gpdword, 0},
1065   {"cpadd", s_cpadd, 0},
1066   {"insn", s_insn, 0},
1067
1068   /* Relatively generic pseudo-ops that happen to be used on MIPS
1069      chips.  */
1070   {"asciiz", stringer, 1},
1071   {"bss", s_change_sec, 'b'},
1072   {"err", s_err, 0},
1073   {"half", s_cons, 1},
1074   {"dword", s_cons, 3},
1075   {"weakext", s_mips_weakext, 0},
1076
1077   /* These pseudo-ops are defined in read.c, but must be overridden
1078      here for one reason or another.  */
1079   {"align", s_align, 0},
1080   {"byte", s_cons, 0},
1081   {"data", s_change_sec, 'd'},
1082   {"double", s_float_cons, 'd'},
1083   {"float", s_float_cons, 'f'},
1084   {"globl", s_mips_globl, 0},
1085   {"global", s_mips_globl, 0},
1086   {"hword", s_cons, 1},
1087   {"int", s_cons, 2},
1088   {"long", s_cons, 2},
1089   {"octa", s_cons, 4},
1090   {"quad", s_cons, 3},
1091   {"section", s_change_section, 0},
1092   {"short", s_cons, 1},
1093   {"single", s_float_cons, 'f'},
1094   {"stabn", s_mips_stab, 'n'},
1095   {"text", s_change_sec, 't'},
1096   {"word", s_cons, 2},
1097
1098   { "extern", ecoff_directive_extern, 0},
1099
1100   { NULL, NULL, 0 },
1101 };
1102
1103 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1104 {
1105   /* These pseudo-ops should be defined by the object file format.
1106      However, a.out doesn't support them, so we have versions here.  */
1107   {"aent", s_mips_ent, 1},
1108   {"bgnb", s_ignore, 0},
1109   {"end", s_mips_end, 0},
1110   {"endb", s_ignore, 0},
1111   {"ent", s_mips_ent, 0},
1112   {"file", s_mips_file, 0},
1113   {"fmask", s_mips_mask, 'F'},
1114   {"frame", s_mips_frame, 0},
1115   {"loc", s_mips_loc, 0},
1116   {"mask", s_mips_mask, 'R'},
1117   {"verstamp", s_ignore, 0},
1118   { NULL, NULL, 0 },
1119 };
1120
1121 extern void pop_insert (const pseudo_typeS *);
1122
1123 void
1124 mips_pop_insert (void)
1125 {
1126   pop_insert (mips_pseudo_table);
1127   if (! ECOFF_DEBUGGING)
1128     pop_insert (mips_nonecoff_pseudo_table);
1129 }
1130 \f
1131 /* Symbols labelling the current insn.  */
1132
1133 struct insn_label_list
1134 {
1135   struct insn_label_list *next;
1136   symbolS *label;
1137 };
1138
1139 static struct insn_label_list *insn_labels;
1140 static struct insn_label_list *free_insn_labels;
1141
1142 static void mips_clear_insn_labels (void);
1143
1144 static inline void
1145 mips_clear_insn_labels (void)
1146 {
1147   register struct insn_label_list **pl;
1148
1149   for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1150     ;
1151   *pl = insn_labels;
1152   insn_labels = NULL;
1153 }
1154 \f
1155 static char *expr_end;
1156
1157 /* Expressions which appear in instructions.  These are set by
1158    mips_ip.  */
1159
1160 static expressionS imm_expr;
1161 static expressionS imm2_expr;
1162 static expressionS offset_expr;
1163
1164 /* Relocs associated with imm_expr and offset_expr.  */
1165
1166 static bfd_reloc_code_real_type imm_reloc[3]
1167   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1168 static bfd_reloc_code_real_type offset_reloc[3]
1169   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1170
1171 /* These are set by mips16_ip if an explicit extension is used.  */
1172
1173 static bfd_boolean mips16_small, mips16_ext;
1174
1175 #ifdef OBJ_ELF
1176 /* The pdr segment for per procedure frame/regmask info.  Not used for
1177    ECOFF debugging.  */
1178
1179 static segT pdr_seg;
1180 #endif
1181
1182 /* The default target format to use.  */
1183
1184 const char *
1185 mips_target_format (void)
1186 {
1187   switch (OUTPUT_FLAVOR)
1188     {
1189     case bfd_target_ecoff_flavour:
1190       return target_big_endian ? "ecoff-bigmips" : ECOFF_LITTLE_FORMAT;
1191     case bfd_target_coff_flavour:
1192       return "pe-mips";
1193     case bfd_target_elf_flavour:
1194 #ifdef TE_VXWORKS
1195       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1196         return (target_big_endian
1197                 ? "elf32-bigmips-vxworks"
1198                 : "elf32-littlemips-vxworks");
1199 #endif
1200 #ifdef TE_TMIPS
1201       /* This is traditional mips.  */
1202       return (target_big_endian
1203               ? (HAVE_64BIT_OBJECTS
1204                  ? "elf64-tradbigmips"
1205                  : (HAVE_NEWABI
1206                     ? "elf32-ntradbigmips" : "elf32-tradbigmips"))
1207               : (HAVE_64BIT_OBJECTS
1208                  ? "elf64-tradlittlemips"
1209                  : (HAVE_NEWABI
1210                     ? "elf32-ntradlittlemips" : "elf32-tradlittlemips")));
1211 #else
1212       return (target_big_endian
1213               ? (HAVE_64BIT_OBJECTS
1214                  ? "elf64-bigmips"
1215                  : (HAVE_NEWABI
1216                     ? "elf32-nbigmips" : "elf32-bigmips"))
1217               : (HAVE_64BIT_OBJECTS
1218                  ? "elf64-littlemips"
1219                  : (HAVE_NEWABI
1220                     ? "elf32-nlittlemips" : "elf32-littlemips")));
1221 #endif
1222     default:
1223       abort ();
1224       return NULL;
1225     }
1226 }
1227
1228 /* Return the length of instruction INSN.  */
1229
1230 static inline unsigned int
1231 insn_length (const struct mips_cl_insn *insn)
1232 {
1233   if (!mips_opts.mips16)
1234     return 4;
1235   return insn->mips16_absolute_jump_p || insn->use_extend ? 4 : 2;
1236 }
1237
1238 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
1239
1240 static void
1241 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
1242 {
1243   size_t i;
1244
1245   insn->insn_mo = mo;
1246   insn->use_extend = FALSE;
1247   insn->extend = 0;
1248   insn->insn_opcode = mo->match;
1249   insn->frag = NULL;
1250   insn->where = 0;
1251   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
1252     insn->fixp[i] = NULL;
1253   insn->fixed_p = (mips_opts.noreorder > 0);
1254   insn->noreorder_p = (mips_opts.noreorder > 0);
1255   insn->mips16_absolute_jump_p = 0;
1256 }
1257
1258 /* Install INSN at the location specified by its "frag" and "where" fields.  */
1259
1260 static void
1261 install_insn (const struct mips_cl_insn *insn)
1262 {
1263   char *f = insn->frag->fr_literal + insn->where;
1264   if (!mips_opts.mips16)
1265     md_number_to_chars (f, insn->insn_opcode, 4);
1266   else if (insn->mips16_absolute_jump_p)
1267     {
1268       md_number_to_chars (f, insn->insn_opcode >> 16, 2);
1269       md_number_to_chars (f + 2, insn->insn_opcode & 0xffff, 2);
1270     }
1271   else
1272     {
1273       if (insn->use_extend)
1274         {
1275           md_number_to_chars (f, 0xf000 | insn->extend, 2);
1276           f += 2;
1277         }
1278       md_number_to_chars (f, insn->insn_opcode, 2);
1279     }
1280 }
1281
1282 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
1283    and install the opcode in the new location.  */
1284
1285 static void
1286 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
1287 {
1288   size_t i;
1289
1290   insn->frag = frag;
1291   insn->where = where;
1292   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
1293     if (insn->fixp[i] != NULL)
1294       {
1295         insn->fixp[i]->fx_frag = frag;
1296         insn->fixp[i]->fx_where = where;
1297       }
1298   install_insn (insn);
1299 }
1300
1301 /* Add INSN to the end of the output.  */
1302
1303 static void
1304 add_fixed_insn (struct mips_cl_insn *insn)
1305 {
1306   char *f = frag_more (insn_length (insn));
1307   move_insn (insn, frag_now, f - frag_now->fr_literal);
1308 }
1309
1310 /* Start a variant frag and move INSN to the start of the variant part,
1311    marking it as fixed.  The other arguments are as for frag_var.  */
1312
1313 static void
1314 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
1315                   relax_substateT subtype, symbolS *symbol, offsetT offset)
1316 {
1317   frag_grow (max_chars);
1318   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
1319   insn->fixed_p = 1;
1320   frag_var (rs_machine_dependent, max_chars, var,
1321             subtype, symbol, offset, NULL);
1322 }
1323
1324 /* Insert N copies of INSN into the history buffer, starting at
1325    position FIRST.  Neither FIRST nor N need to be clipped.  */
1326
1327 static void
1328 insert_into_history (unsigned int first, unsigned int n,
1329                      const struct mips_cl_insn *insn)
1330 {
1331   if (mips_relax.sequence != 2)
1332     {
1333       unsigned int i;
1334
1335       for (i = ARRAY_SIZE (history); i-- > first;)
1336         if (i >= first + n)
1337           history[i] = history[i - n];
1338         else
1339           history[i] = *insn;
1340     }
1341 }
1342
1343 /* Emit a nop instruction, recording it in the history buffer.  */
1344
1345 static void
1346 emit_nop (void)
1347 {
1348   add_fixed_insn (NOP_INSN);
1349   insert_into_history (0, 1, NOP_INSN);
1350 }
1351
1352 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
1353    the idea is to make it obvious at a glance that each errata is
1354    included.  */
1355
1356 static void
1357 init_vr4120_conflicts (void)
1358 {
1359 #define CONFLICT(FIRST, SECOND) \
1360     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
1361
1362   /* Errata 21 - [D]DIV[U] after [D]MACC */
1363   CONFLICT (MACC, DIV);
1364   CONFLICT (DMACC, DIV);
1365
1366   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
1367   CONFLICT (DMULT, DMULT);
1368   CONFLICT (DMULT, DMACC);
1369   CONFLICT (DMACC, DMULT);
1370   CONFLICT (DMACC, DMACC);
1371
1372   /* Errata 24 - MT{LO,HI} after [D]MACC */
1373   CONFLICT (MACC, MTHILO);
1374   CONFLICT (DMACC, MTHILO);
1375
1376   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
1377      instruction is executed immediately after a MACC or DMACC
1378      instruction, the result of [either instruction] is incorrect."  */
1379   CONFLICT (MACC, MULT);
1380   CONFLICT (MACC, DMULT);
1381   CONFLICT (DMACC, MULT);
1382   CONFLICT (DMACC, DMULT);
1383
1384   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
1385      executed immediately after a DMULT, DMULTU, DIV, DIVU,
1386      DDIV or DDIVU instruction, the result of the MACC or
1387      DMACC instruction is incorrect.".  */
1388   CONFLICT (DMULT, MACC);
1389   CONFLICT (DMULT, DMACC);
1390   CONFLICT (DIV, MACC);
1391   CONFLICT (DIV, DMACC);
1392
1393 #undef CONFLICT
1394 }
1395
1396 /* This function is called once, at assembler startup time.  It should
1397    set up all the tables, etc. that the MD part of the assembler will need.  */
1398
1399 void
1400 md_begin (void)
1401 {
1402   register const char *retval = NULL;
1403   int i = 0;
1404   int broken = 0;
1405
1406   if (mips_pic != NO_PIC)
1407     {
1408       if (g_switch_seen && g_switch_value != 0)
1409         as_bad (_("-G may not be used in position-independent code"));
1410       g_switch_value = 0;
1411     }
1412
1413   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_arch))
1414     as_warn (_("Could not set architecture and machine"));
1415
1416   op_hash = hash_new ();
1417
1418   for (i = 0; i < NUMOPCODES;)
1419     {
1420       const char *name = mips_opcodes[i].name;
1421
1422       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
1423       if (retval != NULL)
1424         {
1425           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
1426                    mips_opcodes[i].name, retval);
1427           /* Probably a memory allocation problem?  Give up now.  */
1428           as_fatal (_("Broken assembler.  No assembly attempted."));
1429         }
1430       do
1431         {
1432           if (mips_opcodes[i].pinfo != INSN_MACRO)
1433             {
1434               if (!validate_mips_insn (&mips_opcodes[i]))
1435                 broken = 1;
1436               if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
1437                 {
1438                   create_insn (&nop_insn, mips_opcodes + i);
1439                   nop_insn.fixed_p = 1;
1440                 }
1441             }
1442           ++i;
1443         }
1444       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
1445     }
1446
1447   mips16_op_hash = hash_new ();
1448
1449   i = 0;
1450   while (i < bfd_mips16_num_opcodes)
1451     {
1452       const char *name = mips16_opcodes[i].name;
1453
1454       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
1455       if (retval != NULL)
1456         as_fatal (_("internal: can't hash `%s': %s"),
1457                   mips16_opcodes[i].name, retval);
1458       do
1459         {
1460           if (mips16_opcodes[i].pinfo != INSN_MACRO
1461               && ((mips16_opcodes[i].match & mips16_opcodes[i].mask)
1462                   != mips16_opcodes[i].match))
1463             {
1464               fprintf (stderr, _("internal error: bad mips16 opcode: %s %s\n"),
1465                        mips16_opcodes[i].name, mips16_opcodes[i].args);
1466               broken = 1;
1467             }
1468           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
1469             {
1470               create_insn (&mips16_nop_insn, mips16_opcodes + i);
1471               mips16_nop_insn.fixed_p = 1;
1472             }
1473           ++i;
1474         }
1475       while (i < bfd_mips16_num_opcodes
1476              && strcmp (mips16_opcodes[i].name, name) == 0);
1477     }
1478
1479   if (broken)
1480     as_fatal (_("Broken assembler.  No assembly attempted."));
1481
1482   /* We add all the general register names to the symbol table.  This
1483      helps us detect invalid uses of them.  */
1484   for (i = 0; i < 32; i++)
1485     {
1486       char buf[5];
1487
1488       sprintf (buf, "$%d", i);
1489       symbol_table_insert (symbol_new (buf, reg_section, i,
1490                                        &zero_address_frag));
1491     }
1492   symbol_table_insert (symbol_new ("$ra", reg_section, RA,
1493                                    &zero_address_frag));
1494   symbol_table_insert (symbol_new ("$fp", reg_section, FP,
1495                                    &zero_address_frag));
1496   symbol_table_insert (symbol_new ("$sp", reg_section, SP,
1497                                    &zero_address_frag));
1498   symbol_table_insert (symbol_new ("$gp", reg_section, GP,
1499                                    &zero_address_frag));
1500   symbol_table_insert (symbol_new ("$at", reg_section, AT,
1501                                    &zero_address_frag));
1502   symbol_table_insert (symbol_new ("$kt0", reg_section, KT0,
1503                                    &zero_address_frag));
1504   symbol_table_insert (symbol_new ("$kt1", reg_section, KT1,
1505                                    &zero_address_frag));
1506   symbol_table_insert (symbol_new ("$zero", reg_section, ZERO,
1507                                    &zero_address_frag));
1508   symbol_table_insert (symbol_new ("$pc", reg_section, -1,
1509                                    &zero_address_frag));
1510
1511   /* If we don't add these register names to the symbol table, they
1512      may end up being added as regular symbols by operand(), and then
1513      make it to the object file as undefined in case they're not
1514      regarded as local symbols.  They're local in o32, since `$' is a
1515      local symbol prefix, but not in n32 or n64.  */
1516   for (i = 0; i < 8; i++)
1517     {
1518       char buf[6];
1519
1520       sprintf (buf, "$fcc%i", i);
1521       symbol_table_insert (symbol_new (buf, reg_section, -1,
1522                                        &zero_address_frag));
1523     }
1524
1525   mips_no_prev_insn ();
1526
1527   mips_gprmask = 0;
1528   mips_cprmask[0] = 0;
1529   mips_cprmask[1] = 0;
1530   mips_cprmask[2] = 0;
1531   mips_cprmask[3] = 0;
1532
1533   /* set the default alignment for the text section (2**2) */
1534   record_alignment (text_section, 2);
1535
1536   bfd_set_gp_size (stdoutput, g_switch_value);
1537
1538   if (OUTPUT_FLAVOR == bfd_target_elf_flavour)
1539     {
1540       /* On a native system other than VxWorks, sections must be aligned
1541          to 16 byte boundaries.  When configured for an embedded ELF
1542          target, we don't bother.  */
1543       if (strcmp (TARGET_OS, "elf") != 0
1544           && strcmp (TARGET_OS, "vxworks") != 0)
1545         {
1546           (void) bfd_set_section_alignment (stdoutput, text_section, 4);
1547           (void) bfd_set_section_alignment (stdoutput, data_section, 4);
1548           (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
1549         }
1550
1551       /* Create a .reginfo section for register masks and a .mdebug
1552          section for debugging information.  */
1553       {
1554         segT seg;
1555         subsegT subseg;
1556         flagword flags;
1557         segT sec;
1558
1559         seg = now_seg;
1560         subseg = now_subseg;
1561
1562         /* The ABI says this section should be loaded so that the
1563            running program can access it.  However, we don't load it
1564            if we are configured for an embedded target */
1565         flags = SEC_READONLY | SEC_DATA;
1566         if (strcmp (TARGET_OS, "elf") != 0)
1567           flags |= SEC_ALLOC | SEC_LOAD;
1568
1569         if (mips_abi != N64_ABI)
1570           {
1571             sec = subseg_new (".reginfo", (subsegT) 0);
1572
1573             bfd_set_section_flags (stdoutput, sec, flags);
1574             bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
1575
1576 #ifdef OBJ_ELF
1577             mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
1578 #endif
1579           }
1580         else
1581           {
1582             /* The 64-bit ABI uses a .MIPS.options section rather than
1583                .reginfo section.  */
1584             sec = subseg_new (".MIPS.options", (subsegT) 0);
1585             bfd_set_section_flags (stdoutput, sec, flags);
1586             bfd_set_section_alignment (stdoutput, sec, 3);
1587
1588 #ifdef OBJ_ELF
1589             /* Set up the option header.  */
1590             {
1591               Elf_Internal_Options opthdr;
1592               char *f;
1593
1594               opthdr.kind = ODK_REGINFO;
1595               opthdr.size = (sizeof (Elf_External_Options)
1596                              + sizeof (Elf64_External_RegInfo));
1597               opthdr.section = 0;
1598               opthdr.info = 0;
1599               f = frag_more (sizeof (Elf_External_Options));
1600               bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
1601                                              (Elf_External_Options *) f);
1602
1603               mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
1604             }
1605 #endif
1606           }
1607
1608         if (ECOFF_DEBUGGING)
1609           {
1610             sec = subseg_new (".mdebug", (subsegT) 0);
1611             (void) bfd_set_section_flags (stdoutput, sec,
1612                                           SEC_HAS_CONTENTS | SEC_READONLY);
1613             (void) bfd_set_section_alignment (stdoutput, sec, 2);
1614           }
1615 #ifdef OBJ_ELF
1616         else if (OUTPUT_FLAVOR == bfd_target_elf_flavour && mips_flag_pdr)
1617           {
1618             pdr_seg = subseg_new (".pdr", (subsegT) 0);
1619             (void) bfd_set_section_flags (stdoutput, pdr_seg,
1620                                           SEC_READONLY | SEC_RELOC
1621                                           | SEC_DEBUGGING);
1622             (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
1623           }
1624 #endif
1625
1626         subseg_set (seg, subseg);
1627       }
1628     }
1629
1630   if (! ECOFF_DEBUGGING)
1631     md_obj_begin ();
1632
1633   if (mips_fix_vr4120)
1634     init_vr4120_conflicts ();
1635 }
1636
1637 void
1638 md_mips_end (void)
1639 {
1640   if (! ECOFF_DEBUGGING)
1641     md_obj_end ();
1642 }
1643
1644 void
1645 md_assemble (char *str)
1646 {
1647   struct mips_cl_insn insn;
1648   bfd_reloc_code_real_type unused_reloc[3]
1649     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1650
1651   imm_expr.X_op = O_absent;
1652   imm2_expr.X_op = O_absent;
1653   offset_expr.X_op = O_absent;
1654   imm_reloc[0] = BFD_RELOC_UNUSED;
1655   imm_reloc[1] = BFD_RELOC_UNUSED;
1656   imm_reloc[2] = BFD_RELOC_UNUSED;
1657   offset_reloc[0] = BFD_RELOC_UNUSED;
1658   offset_reloc[1] = BFD_RELOC_UNUSED;
1659   offset_reloc[2] = BFD_RELOC_UNUSED;
1660
1661   if (mips_opts.mips16)
1662     mips16_ip (str, &insn);
1663   else
1664     {
1665       mips_ip (str, &insn);
1666       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
1667             str, insn.insn_opcode));
1668     }
1669
1670   if (insn_error)
1671     {
1672       as_bad ("%s `%s'", insn_error, str);
1673       return;
1674     }
1675
1676   if (insn.insn_mo->pinfo == INSN_MACRO)
1677     {
1678       macro_start ();
1679       if (mips_opts.mips16)
1680         mips16_macro (&insn);
1681       else
1682         macro (&insn);
1683       macro_end ();
1684     }
1685   else
1686     {
1687       if (imm_expr.X_op != O_absent)
1688         append_insn (&insn, &imm_expr, imm_reloc);
1689       else if (offset_expr.X_op != O_absent)
1690         append_insn (&insn, &offset_expr, offset_reloc);
1691       else
1692         append_insn (&insn, NULL, unused_reloc);
1693     }
1694 }
1695
1696 /* Return true if the given relocation might need a matching %lo().
1697    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
1698    need a matching %lo() when applied to local symbols.  */
1699
1700 static inline bfd_boolean
1701 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
1702 {
1703   return (HAVE_IN_PLACE_ADDENDS
1704           && (reloc == BFD_RELOC_HI16_S
1705               || reloc == BFD_RELOC_MIPS16_HI16_S
1706               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
1707                  all GOT16 relocations evaluate to "G".  */
1708               || (reloc == BFD_RELOC_MIPS_GOT16 && mips_pic != VXWORKS_PIC)));
1709 }
1710
1711 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
1712    relocation.  */
1713
1714 static inline bfd_boolean
1715 fixup_has_matching_lo_p (fixS *fixp)
1716 {
1717   return (fixp->fx_next != NULL
1718           && (fixp->fx_next->fx_r_type == BFD_RELOC_LO16
1719              || fixp->fx_next->fx_r_type == BFD_RELOC_MIPS16_LO16)
1720           && fixp->fx_addsy == fixp->fx_next->fx_addsy
1721           && fixp->fx_offset == fixp->fx_next->fx_offset);
1722 }
1723
1724 /* See whether instruction IP reads register REG.  CLASS is the type
1725    of register.  */
1726
1727 static int
1728 insn_uses_reg (const struct mips_cl_insn *ip, unsigned int reg,
1729                enum mips_regclass class)
1730 {
1731   if (class == MIPS16_REG)
1732     {
1733       assert (mips_opts.mips16);
1734       reg = mips16_to_32_reg_map[reg];
1735       class = MIPS_GR_REG;
1736     }
1737
1738   /* Don't report on general register ZERO, since it never changes.  */
1739   if (class == MIPS_GR_REG && reg == ZERO)
1740     return 0;
1741
1742   if (class == MIPS_FP_REG)
1743     {
1744       assert (! mips_opts.mips16);
1745       /* If we are called with either $f0 or $f1, we must check $f0.
1746          This is not optimal, because it will introduce an unnecessary
1747          NOP between "lwc1 $f0" and "swc1 $f1".  To fix this we would
1748          need to distinguish reading both $f0 and $f1 or just one of
1749          them.  Note that we don't have to check the other way,
1750          because there is no instruction that sets both $f0 and $f1
1751          and requires a delay.  */
1752       if ((ip->insn_mo->pinfo & INSN_READ_FPR_S)
1753           && ((EXTRACT_OPERAND (FS, *ip) & ~(unsigned) 1)
1754               == (reg &~ (unsigned) 1)))
1755         return 1;
1756       if ((ip->insn_mo->pinfo & INSN_READ_FPR_T)
1757           && ((EXTRACT_OPERAND (FT, *ip) & ~(unsigned) 1)
1758               == (reg &~ (unsigned) 1)))
1759         return 1;
1760     }
1761   else if (! mips_opts.mips16)
1762     {
1763       if ((ip->insn_mo->pinfo & INSN_READ_GPR_S)
1764           && EXTRACT_OPERAND (RS, *ip) == reg)
1765         return 1;
1766       if ((ip->insn_mo->pinfo & INSN_READ_GPR_T)
1767           && EXTRACT_OPERAND (RT, *ip) == reg)
1768         return 1;
1769     }
1770   else
1771     {
1772       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_X)
1773           && mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)] == reg)
1774         return 1;
1775       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_Y)
1776           && mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)] == reg)
1777         return 1;
1778       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_Z)
1779           && (mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (MOVE32Z, *ip)]
1780               == reg))
1781         return 1;
1782       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_T) && reg == TREG)
1783         return 1;
1784       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_SP) && reg == SP)
1785         return 1;
1786       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_31) && reg == RA)
1787         return 1;
1788       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_GPR_X)
1789           && MIPS16_EXTRACT_OPERAND (REGR32, *ip) == reg)
1790         return 1;
1791     }
1792
1793   return 0;
1794 }
1795
1796 /* This function returns true if modifying a register requires a
1797    delay.  */
1798
1799 static int
1800 reg_needs_delay (unsigned int reg)
1801 {
1802   unsigned long prev_pinfo;
1803
1804   prev_pinfo = history[0].insn_mo->pinfo;
1805   if (! mips_opts.noreorder
1806       && (((prev_pinfo & INSN_LOAD_MEMORY_DELAY)
1807            && ! gpr_interlocks)
1808           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY)
1809               && ! cop_interlocks)))
1810     {
1811       /* A load from a coprocessor or from memory.  All load delays
1812          delay the use of general register rt for one instruction.  */
1813       /* Itbl support may require additional care here.  */
1814       know (prev_pinfo & INSN_WRITE_GPR_T);
1815       if (reg == EXTRACT_OPERAND (RT, history[0]))
1816         return 1;
1817     }
1818
1819   return 0;
1820 }
1821
1822 /* Move all labels in insn_labels to the current insertion point.  */
1823
1824 static void
1825 mips_move_labels (void)
1826 {
1827   struct insn_label_list *l;
1828   valueT val;
1829
1830   for (l = insn_labels; l != NULL; l = l->next)
1831     {
1832       assert (S_GET_SEGMENT (l->label) == now_seg);
1833       symbol_set_frag (l->label, frag_now);
1834       val = (valueT) frag_now_fix ();
1835       /* mips16 text labels are stored as odd.  */
1836       if (mips_opts.mips16)
1837         ++val;
1838       S_SET_VALUE (l->label, val);
1839     }
1840 }
1841
1842 /* Mark instruction labels in mips16 mode.  This permits the linker to
1843    handle them specially, such as generating jalx instructions when
1844    needed.  We also make them odd for the duration of the assembly, in
1845    order to generate the right sort of code.  We will make them even
1846    in the adjust_symtab routine, while leaving them marked.  This is
1847    convenient for the debugger and the disassembler.  The linker knows
1848    to make them odd again.  */
1849
1850 static void
1851 mips16_mark_labels (void)
1852 {
1853   if (mips_opts.mips16)
1854     {
1855       struct insn_label_list *l;
1856       valueT val;
1857
1858       for (l = insn_labels; l != NULL; l = l->next)
1859         {
1860 #ifdef OBJ_ELF
1861           if (OUTPUT_FLAVOR == bfd_target_elf_flavour)
1862             S_SET_OTHER (l->label, STO_MIPS16);
1863 #endif
1864           val = S_GET_VALUE (l->label);
1865           if ((val & 1) == 0)
1866             S_SET_VALUE (l->label, val + 1);
1867         }
1868     }
1869 }
1870
1871 /* End the current frag.  Make it a variant frag and record the
1872    relaxation info.  */
1873
1874 static void
1875 relax_close_frag (void)
1876 {
1877   mips_macro_warning.first_frag = frag_now;
1878   frag_var (rs_machine_dependent, 0, 0,
1879             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
1880             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
1881
1882   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
1883   mips_relax.first_fixup = 0;
1884 }
1885
1886 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
1887    See the comment above RELAX_ENCODE for more details.  */
1888
1889 static void
1890 relax_start (symbolS *symbol)
1891 {
1892   assert (mips_relax.sequence == 0);
1893   mips_relax.sequence = 1;
1894   mips_relax.symbol = symbol;
1895 }
1896
1897 /* Start generating the second version of a relaxable sequence.
1898    See the comment above RELAX_ENCODE for more details.  */
1899
1900 static void
1901 relax_switch (void)
1902 {
1903   assert (mips_relax.sequence == 1);
1904   mips_relax.sequence = 2;
1905 }
1906
1907 /* End the current relaxable sequence.  */
1908
1909 static void
1910 relax_end (void)
1911 {
1912   assert (mips_relax.sequence == 2);
1913   relax_close_frag ();
1914   mips_relax.sequence = 0;
1915 }
1916
1917 /* Classify an instruction according to the FIX_VR4120_* enumeration.
1918    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
1919    by VR4120 errata.  */
1920
1921 static unsigned int
1922 classify_vr4120_insn (const char *name)
1923 {
1924   if (strncmp (name, "macc", 4) == 0)
1925     return FIX_VR4120_MACC;
1926   if (strncmp (name, "dmacc", 5) == 0)
1927     return FIX_VR4120_DMACC;
1928   if (strncmp (name, "mult", 4) == 0)
1929     return FIX_VR4120_MULT;
1930   if (strncmp (name, "dmult", 5) == 0)
1931     return FIX_VR4120_DMULT;
1932   if (strstr (name, "div"))
1933     return FIX_VR4120_DIV;
1934   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
1935     return FIX_VR4120_MTHILO;
1936   return NUM_FIX_VR4120_CLASSES;
1937 }
1938
1939 /* Return the number of instructions that must separate INSN1 and INSN2,
1940    where INSN1 is the earlier instruction.  Return the worst-case value
1941    for any INSN2 if INSN2 is null.  */
1942
1943 static unsigned int
1944 insns_between (const struct mips_cl_insn *insn1,
1945                const struct mips_cl_insn *insn2)
1946 {
1947   unsigned long pinfo1, pinfo2;
1948
1949   /* This function needs to know which pinfo flags are set for INSN2
1950      and which registers INSN2 uses.  The former is stored in PINFO2 and
1951      the latter is tested via INSN2_USES_REG.  If INSN2 is null, PINFO2
1952      will have every flag set and INSN2_USES_REG will always return true.  */
1953   pinfo1 = insn1->insn_mo->pinfo;
1954   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
1955
1956 #define INSN2_USES_REG(REG, CLASS) \
1957    (insn2 == NULL || insn_uses_reg (insn2, REG, CLASS))
1958
1959   /* For most targets, write-after-read dependencies on the HI and LO
1960      registers must be separated by at least two instructions.  */
1961   if (!hilo_interlocks)
1962     {
1963       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
1964         return 2;
1965       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
1966         return 2;
1967     }
1968
1969   /* If we're working around r7000 errata, there must be two instructions
1970      between an mfhi or mflo and any instruction that uses the result.  */
1971   if (mips_7000_hilo_fix
1972       && MF_HILO_INSN (pinfo1)
1973       && INSN2_USES_REG (EXTRACT_OPERAND (RD, *insn1), MIPS_GR_REG))
1974     return 2;
1975
1976   /* If working around VR4120 errata, check for combinations that need
1977      a single intervening instruction.  */
1978   if (mips_fix_vr4120)
1979     {
1980       unsigned int class1, class2;
1981
1982       class1 = classify_vr4120_insn (insn1->insn_mo->name);
1983       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
1984         {
1985           if (insn2 == NULL)
1986             return 1;
1987           class2 = classify_vr4120_insn (insn2->insn_mo->name);
1988           if (vr4120_conflicts[class1] & (1 << class2))
1989             return 1;
1990         }
1991     }
1992
1993   if (!mips_opts.mips16)
1994     {
1995       /* Check for GPR or coprocessor load delays.  All such delays
1996          are on the RT register.  */
1997       /* Itbl support may require additional care here.  */
1998       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY_DELAY))
1999           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
2000         {
2001           know (pinfo1 & INSN_WRITE_GPR_T);
2002           if (INSN2_USES_REG (EXTRACT_OPERAND (RT, *insn1), MIPS_GR_REG))
2003             return 1;
2004         }
2005
2006       /* Check for generic coprocessor hazards.
2007
2008          This case is not handled very well.  There is no special
2009          knowledge of CP0 handling, and the coprocessors other than
2010          the floating point unit are not distinguished at all.  */
2011       /* Itbl support may require additional care here. FIXME!
2012          Need to modify this to include knowledge about
2013          user specified delays!  */
2014       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
2015                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
2016         {
2017           /* Handle cases where INSN1 writes to a known general coprocessor
2018              register.  There must be a one instruction delay before INSN2
2019              if INSN2 reads that register, otherwise no delay is needed.  */
2020           if (pinfo1 & INSN_WRITE_FPR_T)
2021             {
2022               if (INSN2_USES_REG (EXTRACT_OPERAND (FT, *insn1), MIPS_FP_REG))
2023                 return 1;
2024             }
2025           else if (pinfo1 & INSN_WRITE_FPR_S)
2026             {
2027               if (INSN2_USES_REG (EXTRACT_OPERAND (FS, *insn1), MIPS_FP_REG))
2028                 return 1;
2029             }
2030           else
2031             {
2032               /* Read-after-write dependencies on the control registers
2033                  require a two-instruction gap.  */
2034               if ((pinfo1 & INSN_WRITE_COND_CODE)
2035                   && (pinfo2 & INSN_READ_COND_CODE))
2036                 return 2;
2037
2038               /* We don't know exactly what INSN1 does.  If INSN2 is
2039                  also a coprocessor instruction, assume there must be
2040                  a one instruction gap.  */
2041               if (pinfo2 & INSN_COP)
2042                 return 1;
2043             }
2044         }
2045
2046       /* Check for read-after-write dependencies on the coprocessor
2047          control registers in cases where INSN1 does not need a general
2048          coprocessor delay.  This means that INSN1 is a floating point
2049          comparison instruction.  */
2050       /* Itbl support may require additional care here.  */
2051       else if (!cop_interlocks
2052                && (pinfo1 & INSN_WRITE_COND_CODE)
2053                && (pinfo2 & INSN_READ_COND_CODE))
2054         return 1;
2055     }
2056
2057 #undef INSN2_USES_REG
2058
2059   return 0;
2060 }
2061
2062 /* Return the number of nops that would be needed to work around the
2063    VR4130 mflo/mfhi errata if instruction INSN immediately followed
2064    the MAX_VR4130_NOPS instructions described by HISTORY.  */
2065
2066 static int
2067 nops_for_vr4130 (const struct mips_cl_insn *history,
2068                  const struct mips_cl_insn *insn)
2069 {
2070   int i, j, reg;
2071
2072   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
2073      are not affected by the errata.  */
2074   if (insn != 0
2075       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
2076           || strcmp (insn->insn_mo->name, "mtlo") == 0
2077           || strcmp (insn->insn_mo->name, "mthi") == 0))
2078     return 0;
2079
2080   /* Search for the first MFLO or MFHI.  */
2081   for (i = 0; i < MAX_VR4130_NOPS; i++)
2082     if (!history[i].noreorder_p && MF_HILO_INSN (history[i].insn_mo->pinfo))
2083       {
2084         /* Extract the destination register.  */
2085         if (mips_opts.mips16)
2086           reg = mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, history[i])];
2087         else
2088           reg = EXTRACT_OPERAND (RD, history[i]);
2089
2090         /* No nops are needed if INSN reads that register.  */
2091         if (insn != NULL && insn_uses_reg (insn, reg, MIPS_GR_REG))
2092           return 0;
2093
2094         /* ...or if any of the intervening instructions do.  */
2095         for (j = 0; j < i; j++)
2096           if (insn_uses_reg (&history[j], reg, MIPS_GR_REG))
2097             return 0;
2098
2099         return MAX_VR4130_NOPS - i;
2100       }
2101   return 0;
2102 }
2103
2104 /* Return the number of nops that would be needed if instruction INSN
2105    immediately followed the MAX_NOPS instructions given by HISTORY,
2106    where HISTORY[0] is the most recent instruction.  If INSN is null,
2107    return the worse-case number of nops for any instruction.  */
2108
2109 static int
2110 nops_for_insn (const struct mips_cl_insn *history,
2111                const struct mips_cl_insn *insn)
2112 {
2113   int i, nops, tmp_nops;
2114
2115   nops = 0;
2116   for (i = 0; i < MAX_DELAY_NOPS; i++)
2117     if (!history[i].noreorder_p)
2118       {
2119         tmp_nops = insns_between (history + i, insn) - i;
2120         if (tmp_nops > nops)
2121           nops = tmp_nops;
2122       }
2123
2124   if (mips_fix_vr4130)
2125     {
2126       tmp_nops = nops_for_vr4130 (history, insn);
2127       if (tmp_nops > nops)
2128         nops = tmp_nops;
2129     }
2130
2131   return nops;
2132 }
2133
2134 /* The variable arguments provide NUM_INSNS extra instructions that
2135    might be added to HISTORY.  Return the largest number of nops that
2136    would be needed after the extended sequence.  */
2137
2138 static int
2139 nops_for_sequence (int num_insns, const struct mips_cl_insn *history, ...)
2140 {
2141   va_list args;
2142   struct mips_cl_insn buffer[MAX_NOPS];
2143   struct mips_cl_insn *cursor;
2144   int nops;
2145
2146   va_start (args, history);
2147   cursor = buffer + num_insns;
2148   memcpy (cursor, history, (MAX_NOPS - num_insns) * sizeof (*cursor));
2149   while (cursor > buffer)
2150     *--cursor = *va_arg (args, const struct mips_cl_insn *);
2151
2152   nops = nops_for_insn (buffer, NULL);
2153   va_end (args);
2154   return nops;
2155 }
2156
2157 /* Like nops_for_insn, but if INSN is a branch, take into account the
2158    worst-case delay for the branch target.  */
2159
2160 static int
2161 nops_for_insn_or_target (const struct mips_cl_insn *history,
2162                          const struct mips_cl_insn *insn)
2163 {
2164   int nops, tmp_nops;
2165
2166   nops = nops_for_insn (history, insn);
2167   if (insn->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
2168                               | INSN_COND_BRANCH_DELAY
2169                               | INSN_COND_BRANCH_LIKELY))
2170     {
2171       tmp_nops = nops_for_sequence (2, history, insn, NOP_INSN);
2172       if (tmp_nops > nops)
2173         nops = tmp_nops;
2174     }
2175   else if (mips_opts.mips16 && (insn->insn_mo->pinfo & MIPS16_INSN_BRANCH))
2176     {
2177       tmp_nops = nops_for_sequence (1, history, insn);
2178       if (tmp_nops > nops)
2179         nops = tmp_nops;
2180     }
2181   return nops;
2182 }
2183
2184 /* Output an instruction.  IP is the instruction information.
2185    ADDRESS_EXPR is an operand of the instruction to be used with
2186    RELOC_TYPE.  */
2187
2188 static void
2189 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
2190              bfd_reloc_code_real_type *reloc_type)
2191 {
2192   register unsigned long prev_pinfo, pinfo;
2193   relax_stateT prev_insn_frag_type = 0;
2194   bfd_boolean relaxed_branch = FALSE;
2195
2196   /* Mark instruction labels in mips16 mode.  */
2197   mips16_mark_labels ();
2198
2199   prev_pinfo = history[0].insn_mo->pinfo;
2200   pinfo = ip->insn_mo->pinfo;
2201
2202   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
2203     {
2204       /* There are a lot of optimizations we could do that we don't.
2205          In particular, we do not, in general, reorder instructions.
2206          If you use gcc with optimization, it will reorder
2207          instructions and generally do much more optimization then we
2208          do here; repeating all that work in the assembler would only
2209          benefit hand written assembly code, and does not seem worth
2210          it.  */
2211       int nops = (mips_optimize == 0
2212                   ? nops_for_insn (history, NULL)
2213                   : nops_for_insn_or_target (history, ip));
2214       if (nops > 0)
2215         {
2216           fragS *old_frag;
2217           unsigned long old_frag_offset;
2218           int i;
2219
2220           old_frag = frag_now;
2221           old_frag_offset = frag_now_fix ();
2222
2223           for (i = 0; i < nops; i++)
2224             emit_nop ();
2225
2226           if (listing)
2227             {
2228               listing_prev_line ();
2229               /* We may be at the start of a variant frag.  In case we
2230                  are, make sure there is enough space for the frag
2231                  after the frags created by listing_prev_line.  The
2232                  argument to frag_grow here must be at least as large
2233                  as the argument to all other calls to frag_grow in
2234                  this file.  We don't have to worry about being in the
2235                  middle of a variant frag, because the variants insert
2236                  all needed nop instructions themselves.  */
2237               frag_grow (40);
2238             }
2239
2240           mips_move_labels ();
2241
2242 #ifndef NO_ECOFF_DEBUGGING
2243           if (ECOFF_DEBUGGING)
2244             ecoff_fix_loc (old_frag, old_frag_offset);
2245 #endif
2246         }
2247     }
2248   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
2249     {
2250       /* Work out how many nops in prev_nop_frag are needed by IP.  */
2251       int nops = nops_for_insn_or_target (history, ip);
2252       assert (nops <= prev_nop_frag_holds);
2253
2254       /* Enforce NOPS as a minimum.  */
2255       if (nops > prev_nop_frag_required)
2256         prev_nop_frag_required = nops;
2257
2258       if (prev_nop_frag_holds == prev_nop_frag_required)
2259         {
2260           /* Settle for the current number of nops.  Update the history
2261              accordingly (for the benefit of any future .set reorder code).  */
2262           prev_nop_frag = NULL;
2263           insert_into_history (prev_nop_frag_since,
2264                                prev_nop_frag_holds, NOP_INSN);
2265         }
2266       else
2267         {
2268           /* Allow this instruction to replace one of the nops that was
2269              tentatively added to prev_nop_frag.  */
2270           prev_nop_frag->fr_fix -= mips_opts.mips16 ? 2 : 4;
2271           prev_nop_frag_holds--;
2272           prev_nop_frag_since++;
2273         }
2274     }
2275
2276 #ifdef OBJ_ELF
2277   /* The value passed to dwarf2_emit_insn is the distance between
2278      the beginning of the current instruction and the address that
2279      should be recorded in the debug tables.  For MIPS16 debug info
2280      we want to use ISA-encoded addresses, so we pass -1 for an
2281      address higher by one than the current.  */
2282   dwarf2_emit_insn (mips_opts.mips16 ? -1 : 0);
2283 #endif
2284
2285   /* Record the frag type before frag_var.  */
2286   if (history[0].frag)
2287     prev_insn_frag_type = history[0].frag->fr_type;
2288
2289   if (address_expr
2290       && *reloc_type == BFD_RELOC_16_PCREL_S2
2291       && (pinfo & INSN_UNCOND_BRANCH_DELAY || pinfo & INSN_COND_BRANCH_DELAY
2292           || pinfo & INSN_COND_BRANCH_LIKELY)
2293       && mips_relax_branch
2294       /* Don't try branch relaxation within .set nomacro, or within
2295          .set noat if we use $at for PIC computations.  If it turns
2296          out that the branch was out-of-range, we'll get an error.  */
2297       && !mips_opts.warn_about_macros
2298       && !(mips_opts.noat && mips_pic != NO_PIC)
2299       && !mips_opts.mips16)
2300     {
2301       relaxed_branch = TRUE;
2302       add_relaxed_insn (ip, (relaxed_branch_length
2303                              (NULL, NULL,
2304                               (pinfo & INSN_UNCOND_BRANCH_DELAY) ? -1
2305                               : (pinfo & INSN_COND_BRANCH_LIKELY) ? 1
2306                               : 0)), 4,
2307                         RELAX_BRANCH_ENCODE
2308                         (pinfo & INSN_UNCOND_BRANCH_DELAY,
2309                          pinfo & INSN_COND_BRANCH_LIKELY,
2310                          pinfo & INSN_WRITE_GPR_31,
2311                          0),
2312                         address_expr->X_add_symbol,
2313                         address_expr->X_add_number);
2314       *reloc_type = BFD_RELOC_UNUSED;
2315     }
2316   else if (*reloc_type > BFD_RELOC_UNUSED)
2317     {
2318       /* We need to set up a variant frag.  */
2319       assert (mips_opts.mips16 && address_expr != NULL);
2320       add_relaxed_insn (ip, 4, 0,
2321                         RELAX_MIPS16_ENCODE
2322                         (*reloc_type - BFD_RELOC_UNUSED,
2323                          mips16_small, mips16_ext,
2324                          prev_pinfo & INSN_UNCOND_BRANCH_DELAY,
2325                          history[0].mips16_absolute_jump_p),
2326                         make_expr_symbol (address_expr), 0);
2327     }
2328   else if (mips_opts.mips16
2329            && ! ip->use_extend
2330            && *reloc_type != BFD_RELOC_MIPS16_JMP)
2331     {
2332       if ((pinfo & INSN_UNCOND_BRANCH_DELAY) == 0)
2333         /* Make sure there is enough room to swap this instruction with
2334            a following jump instruction.  */
2335         frag_grow (6);
2336       add_fixed_insn (ip);
2337     }
2338   else
2339     {
2340       if (mips_opts.mips16
2341           && mips_opts.noreorder
2342           && (prev_pinfo & INSN_UNCOND_BRANCH_DELAY) != 0)
2343         as_warn (_("extended instruction in delay slot"));
2344
2345       if (mips_relax.sequence)
2346         {
2347           /* If we've reached the end of this frag, turn it into a variant
2348              frag and record the information for the instructions we've
2349              written so far.  */
2350           if (frag_room () < 4)
2351             relax_close_frag ();
2352           mips_relax.sizes[mips_relax.sequence - 1] += 4;
2353         }
2354
2355       if (mips_relax.sequence != 2)
2356         mips_macro_warning.sizes[0] += 4;
2357       if (mips_relax.sequence != 1)
2358         mips_macro_warning.sizes[1] += 4;
2359
2360       if (mips_opts.mips16)
2361         {
2362           ip->fixed_p = 1;
2363           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
2364         }
2365       add_fixed_insn (ip);
2366     }
2367
2368   if (address_expr != NULL && *reloc_type <= BFD_RELOC_UNUSED)
2369     {
2370       if (address_expr->X_op == O_constant)
2371         {
2372           unsigned int tmp;
2373
2374           switch (*reloc_type)
2375             {
2376             case BFD_RELOC_32:
2377               ip->insn_opcode |= address_expr->X_add_number;
2378               break;
2379
2380             case BFD_RELOC_MIPS_HIGHEST:
2381               tmp = (address_expr->X_add_number + 0x800080008000ull) >> 48;
2382               ip->insn_opcode |= tmp & 0xffff;
2383               break;
2384
2385             case BFD_RELOC_MIPS_HIGHER:
2386               tmp = (address_expr->X_add_number + 0x80008000ull) >> 32;
2387               ip->insn_opcode |= tmp & 0xffff;
2388               break;
2389
2390             case BFD_RELOC_HI16_S:
2391               tmp = (address_expr->X_add_number + 0x8000) >> 16;
2392               ip->insn_opcode |= tmp & 0xffff;
2393               break;
2394
2395             case BFD_RELOC_HI16:
2396               ip->insn_opcode |= (address_expr->X_add_number >> 16) & 0xffff;
2397               break;
2398
2399             case BFD_RELOC_UNUSED:
2400             case BFD_RELOC_LO16:
2401             case BFD_RELOC_MIPS_GOT_DISP:
2402               ip->insn_opcode |= address_expr->X_add_number & 0xffff;
2403               break;
2404
2405             case BFD_RELOC_MIPS_JMP:
2406               if ((address_expr->X_add_number & 3) != 0)
2407                 as_bad (_("jump to misaligned address (0x%lx)"),
2408                         (unsigned long) address_expr->X_add_number);
2409               if (address_expr->X_add_number & ~0xfffffff)
2410                 as_bad (_("jump address range overflow (0x%lx)"),
2411                         (unsigned long) address_expr->X_add_number);
2412               ip->insn_opcode |= (address_expr->X_add_number >> 2) & 0x3ffffff;
2413               break;
2414
2415             case BFD_RELOC_MIPS16_JMP:
2416               if ((address_expr->X_add_number & 3) != 0)
2417                 as_bad (_("jump to misaligned address (0x%lx)"),
2418                         (unsigned long) address_expr->X_add_number);
2419               if (address_expr->X_add_number & ~0xfffffff)
2420                 as_bad (_("jump address range overflow (0x%lx)"),
2421                         (unsigned long) address_expr->X_add_number);
2422               ip->insn_opcode |=
2423                 (((address_expr->X_add_number & 0x7c0000) << 3)
2424                  | ((address_expr->X_add_number & 0xf800000) >> 7)
2425                  | ((address_expr->X_add_number & 0x3fffc) >> 2));
2426               break;
2427
2428             case BFD_RELOC_16_PCREL_S2:
2429               if ((address_expr->X_add_number & 3) != 0)
2430                 as_bad (_("branch to misaligned address (0x%lx)"),
2431                         (unsigned long) address_expr->X_add_number);
2432               if (mips_relax_branch)
2433                 goto need_reloc;
2434               if ((address_expr->X_add_number + 0x20000) & ~0x3ffff)
2435                 as_bad (_("branch address range overflow (0x%lx)"),
2436                         (unsigned long) address_expr->X_add_number);
2437               ip->insn_opcode |= (address_expr->X_add_number >> 2) & 0xffff;
2438               break;
2439
2440             default:
2441               internalError ();
2442             }
2443         }
2444       else if (*reloc_type < BFD_RELOC_UNUSED)
2445         need_reloc:
2446         {
2447           reloc_howto_type *howto;
2448           int i;
2449
2450           /* In a compound relocation, it is the final (outermost)
2451              operator that determines the relocated field.  */
2452           for (i = 1; i < 3; i++)
2453             if (reloc_type[i] == BFD_RELOC_UNUSED)
2454               break;
2455
2456           howto = bfd_reloc_type_lookup (stdoutput, reloc_type[i - 1]);
2457           ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
2458                                      bfd_get_reloc_size (howto),
2459                                      address_expr,
2460                                      reloc_type[0] == BFD_RELOC_16_PCREL_S2,
2461                                      reloc_type[0]);
2462
2463           /* These relocations can have an addend that won't fit in
2464              4 octets for 64bit assembly.  */
2465           if (HAVE_64BIT_GPRS
2466               && ! howto->partial_inplace
2467               && (reloc_type[0] == BFD_RELOC_16
2468                   || reloc_type[0] == BFD_RELOC_32
2469                   || reloc_type[0] == BFD_RELOC_MIPS_JMP
2470                   || reloc_type[0] == BFD_RELOC_HI16_S
2471                   || reloc_type[0] == BFD_RELOC_LO16
2472                   || reloc_type[0] == BFD_RELOC_GPREL16
2473                   || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
2474                   || reloc_type[0] == BFD_RELOC_GPREL32
2475                   || reloc_type[0] == BFD_RELOC_64
2476                   || reloc_type[0] == BFD_RELOC_CTOR
2477                   || reloc_type[0] == BFD_RELOC_MIPS_SUB
2478                   || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
2479                   || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
2480                   || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
2481                   || reloc_type[0] == BFD_RELOC_MIPS_REL16
2482                   || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
2483                   || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
2484                   || reloc_type[0] == BFD_RELOC_MIPS16_HI16_S
2485                   || reloc_type[0] == BFD_RELOC_MIPS16_LO16))
2486             ip->fixp[0]->fx_no_overflow = 1;
2487
2488           if (mips_relax.sequence)
2489             {
2490               if (mips_relax.first_fixup == 0)
2491                 mips_relax.first_fixup = ip->fixp[0];
2492             }
2493           else if (reloc_needs_lo_p (*reloc_type))
2494             {
2495               struct mips_hi_fixup *hi_fixup;
2496
2497               /* Reuse the last entry if it already has a matching %lo.  */
2498               hi_fixup = mips_hi_fixup_list;
2499               if (hi_fixup == 0
2500                   || !fixup_has_matching_lo_p (hi_fixup->fixp))
2501                 {
2502                   hi_fixup = ((struct mips_hi_fixup *)
2503                               xmalloc (sizeof (struct mips_hi_fixup)));
2504                   hi_fixup->next = mips_hi_fixup_list;
2505                   mips_hi_fixup_list = hi_fixup;
2506                 }
2507               hi_fixup->fixp = ip->fixp[0];
2508               hi_fixup->seg = now_seg;
2509             }
2510
2511           /* Add fixups for the second and third relocations, if given.
2512              Note that the ABI allows the second relocation to be
2513              against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
2514              moment we only use RSS_UNDEF, but we could add support
2515              for the others if it ever becomes necessary.  */
2516           for (i = 1; i < 3; i++)
2517             if (reloc_type[i] != BFD_RELOC_UNUSED)
2518               {
2519                 ip->fixp[i] = fix_new (ip->frag, ip->where,
2520                                        ip->fixp[0]->fx_size, NULL, 0,
2521                                        FALSE, reloc_type[i]);
2522
2523                 /* Use fx_tcbit to mark compound relocs.  */
2524                 ip->fixp[0]->fx_tcbit = 1;
2525                 ip->fixp[i]->fx_tcbit = 1;
2526               }
2527         }
2528     }
2529   install_insn (ip);
2530
2531   /* Update the register mask information.  */
2532   if (! mips_opts.mips16)
2533     {
2534       if (pinfo & INSN_WRITE_GPR_D)
2535         mips_gprmask |= 1 << EXTRACT_OPERAND (RD, *ip);
2536       if ((pinfo & (INSN_WRITE_GPR_T | INSN_READ_GPR_T)) != 0)
2537         mips_gprmask |= 1 << EXTRACT_OPERAND (RT, *ip);
2538       if (pinfo & INSN_READ_GPR_S)
2539         mips_gprmask |= 1 << EXTRACT_OPERAND (RS, *ip);
2540       if (pinfo & INSN_WRITE_GPR_31)
2541         mips_gprmask |= 1 << RA;
2542       if (pinfo & INSN_WRITE_FPR_D)
2543         mips_cprmask[1] |= 1 << EXTRACT_OPERAND (FD, *ip);
2544       if ((pinfo & (INSN_WRITE_FPR_S | INSN_READ_FPR_S)) != 0)
2545         mips_cprmask[1] |= 1 << EXTRACT_OPERAND (FS, *ip);
2546       if ((pinfo & (INSN_WRITE_FPR_T | INSN_READ_FPR_T)) != 0)
2547         mips_cprmask[1] |= 1 << EXTRACT_OPERAND (FT, *ip);
2548       if ((pinfo & INSN_READ_FPR_R) != 0)
2549         mips_cprmask[1] |= 1 << EXTRACT_OPERAND (FR, *ip);
2550       if (pinfo & INSN_COP)
2551         {
2552           /* We don't keep enough information to sort these cases out.
2553              The itbl support does keep this information however, although
2554              we currently don't support itbl fprmats as part of the cop
2555              instruction.  May want to add this support in the future.  */
2556         }
2557       /* Never set the bit for $0, which is always zero.  */
2558       mips_gprmask &= ~1 << 0;
2559     }
2560   else
2561     {
2562       if (pinfo & (MIPS16_INSN_WRITE_X | MIPS16_INSN_READ_X))
2563         mips_gprmask |= 1 << MIPS16_EXTRACT_OPERAND (RX, *ip);
2564       if (pinfo & (MIPS16_INSN_WRITE_Y | MIPS16_INSN_READ_Y))
2565         mips_gprmask |= 1 << MIPS16_EXTRACT_OPERAND (RY, *ip);
2566       if (pinfo & MIPS16_INSN_WRITE_Z)
2567         mips_gprmask |= 1 << MIPS16_EXTRACT_OPERAND (RZ, *ip);
2568       if (pinfo & (MIPS16_INSN_WRITE_T | MIPS16_INSN_READ_T))
2569         mips_gprmask |= 1 << TREG;
2570       if (pinfo & (MIPS16_INSN_WRITE_SP | MIPS16_INSN_READ_SP))
2571         mips_gprmask |= 1 << SP;
2572       if (pinfo & (MIPS16_INSN_WRITE_31 | MIPS16_INSN_READ_31))
2573         mips_gprmask |= 1 << RA;
2574       if (pinfo & MIPS16_INSN_WRITE_GPR_Y)
2575         mips_gprmask |= 1 << MIPS16OP_EXTRACT_REG32R (ip->insn_opcode);
2576       if (pinfo & MIPS16_INSN_READ_Z)
2577         mips_gprmask |= 1 << MIPS16_EXTRACT_OPERAND (MOVE32Z, *ip);
2578       if (pinfo & MIPS16_INSN_READ_GPR_X)
2579         mips_gprmask |= 1 << MIPS16_EXTRACT_OPERAND (REGR32, *ip);
2580     }
2581
2582   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
2583     {
2584       /* Filling the branch delay slot is more complex.  We try to
2585          switch the branch with the previous instruction, which we can
2586          do if the previous instruction does not set up a condition
2587          that the branch tests and if the branch is not itself the
2588          target of any branch.  */
2589       if ((pinfo & INSN_UNCOND_BRANCH_DELAY)
2590           || (pinfo & INSN_COND_BRANCH_DELAY))
2591         {
2592           if (mips_optimize < 2
2593               /* If we have seen .set volatile or .set nomove, don't
2594                  optimize.  */
2595               || mips_opts.nomove != 0
2596               /* We can't swap if the previous instruction's position
2597                  is fixed.  */
2598               || history[0].fixed_p
2599               /* If the previous previous insn was in a .set
2600                  noreorder, we can't swap.  Actually, the MIPS
2601                  assembler will swap in this situation.  However, gcc
2602                  configured -with-gnu-as will generate code like
2603                    .set noreorder
2604                    lw   $4,XXX
2605                    .set reorder
2606                    INSN
2607                    bne  $4,$0,foo
2608                  in which we can not swap the bne and INSN.  If gcc is
2609                  not configured -with-gnu-as, it does not output the
2610                  .set pseudo-ops.  */
2611               || history[1].noreorder_p
2612               /* If the branch is itself the target of a branch, we
2613                  can not swap.  We cheat on this; all we check for is
2614                  whether there is a label on this instruction.  If
2615                  there are any branches to anything other than a
2616                  label, users must use .set noreorder.  */
2617               || insn_labels != NULL
2618               /* If the previous instruction is in a variant frag
2619                  other than this branch's one, we cannot do the swap.
2620                  This does not apply to the mips16, which uses variant
2621                  frags for different purposes.  */
2622               || (! mips_opts.mips16
2623                   && prev_insn_frag_type == rs_machine_dependent)
2624               /* Check for conflicts between the branch and the instructions
2625                  before the candidate delay slot.  */
2626               || nops_for_insn (history + 1, ip) > 0
2627               /* Check for conflicts between the swapped sequence and the
2628                  target of the branch.  */
2629               || nops_for_sequence (2, history + 1, ip, history) > 0
2630               /* We do not swap with a trap instruction, since it
2631                  complicates trap handlers to have the trap
2632                  instruction be in a delay slot.  */
2633               || (prev_pinfo & INSN_TRAP)
2634               /* If the branch reads a register that the previous
2635                  instruction sets, we can not swap.  */
2636               || (! mips_opts.mips16
2637                   && (prev_pinfo & INSN_WRITE_GPR_T)
2638                   && insn_uses_reg (ip, EXTRACT_OPERAND (RT, history[0]),
2639                                     MIPS_GR_REG))
2640               || (! mips_opts.mips16
2641                   && (prev_pinfo & INSN_WRITE_GPR_D)
2642                   && insn_uses_reg (ip, EXTRACT_OPERAND (RD, history[0]),
2643                                     MIPS_GR_REG))
2644               || (mips_opts.mips16
2645                   && (((prev_pinfo & MIPS16_INSN_WRITE_X)
2646                        && (insn_uses_reg
2647                            (ip, MIPS16_EXTRACT_OPERAND (RX, history[0]),
2648                             MIPS16_REG)))
2649                       || ((prev_pinfo & MIPS16_INSN_WRITE_Y)
2650                           && (insn_uses_reg
2651                               (ip, MIPS16_EXTRACT_OPERAND (RY, history[0]),
2652                                MIPS16_REG)))
2653                       || ((prev_pinfo & MIPS16_INSN_WRITE_Z)
2654                           && (insn_uses_reg
2655                               (ip, MIPS16_EXTRACT_OPERAND (RZ, history[0]),
2656                                MIPS16_REG)))
2657                       || ((prev_pinfo & MIPS16_INSN_WRITE_T)
2658                           && insn_uses_reg (ip, TREG, MIPS_GR_REG))
2659                       || ((prev_pinfo & MIPS16_INSN_WRITE_31)
2660                           && insn_uses_reg (ip, RA, MIPS_GR_REG))
2661                       || ((prev_pinfo & MIPS16_INSN_WRITE_GPR_Y)
2662                           && insn_uses_reg (ip,
2663                                             MIPS16OP_EXTRACT_REG32R
2664                                               (history[0].insn_opcode),
2665                                             MIPS_GR_REG))))
2666               /* If the branch writes a register that the previous
2667                  instruction sets, we can not swap (we know that
2668                  branches write only to RD or to $31).  */
2669               || (! mips_opts.mips16
2670                   && (prev_pinfo & INSN_WRITE_GPR_T)
2671                   && (((pinfo & INSN_WRITE_GPR_D)
2672                        && (EXTRACT_OPERAND (RT, history[0])
2673                            == EXTRACT_OPERAND (RD, *ip)))
2674                       || ((pinfo & INSN_WRITE_GPR_31)
2675                           && EXTRACT_OPERAND (RT, history[0]) == RA)))
2676               || (! mips_opts.mips16
2677                   && (prev_pinfo & INSN_WRITE_GPR_D)
2678                   && (((pinfo & INSN_WRITE_GPR_D)
2679                        && (EXTRACT_OPERAND (RD, history[0])
2680                            == EXTRACT_OPERAND (RD, *ip)))
2681                       || ((pinfo & INSN_WRITE_GPR_31)
2682                           && EXTRACT_OPERAND (RD, history[0]) == RA)))
2683               || (mips_opts.mips16
2684                   && (pinfo & MIPS16_INSN_WRITE_31)
2685                   && ((prev_pinfo & MIPS16_INSN_WRITE_31)
2686                       || ((prev_pinfo & MIPS16_INSN_WRITE_GPR_Y)
2687                           && (MIPS16OP_EXTRACT_REG32R (history[0].insn_opcode)
2688                               == RA))))
2689               /* If the branch writes a register that the previous
2690                  instruction reads, we can not swap (we know that
2691                  branches only write to RD or to $31).  */
2692               || (! mips_opts.mips16
2693                   && (pinfo & INSN_WRITE_GPR_D)
2694                   && insn_uses_reg (&history[0],
2695                                     EXTRACT_OPERAND (RD, *ip),
2696                                     MIPS_GR_REG))
2697               || (! mips_opts.mips16
2698                   && (pinfo & INSN_WRITE_GPR_31)
2699                   && insn_uses_reg (&history[0], RA, MIPS_GR_REG))
2700               || (mips_opts.mips16
2701                   && (pinfo & MIPS16_INSN_WRITE_31)
2702                   && insn_uses_reg (&history[0], RA, MIPS_GR_REG))
2703               /* If one instruction sets a condition code and the
2704                  other one uses a condition code, we can not swap.  */
2705               || ((pinfo & INSN_READ_COND_CODE)
2706                   && (prev_pinfo & INSN_WRITE_COND_CODE))
2707               || ((pinfo & INSN_WRITE_COND_CODE)
2708                   && (prev_pinfo & INSN_READ_COND_CODE))
2709               /* If the previous instruction uses the PC, we can not
2710                  swap.  */
2711               || (mips_opts.mips16
2712                   && (prev_pinfo & MIPS16_INSN_READ_PC))
2713               /* If the previous instruction had a fixup in mips16
2714                  mode, we can not swap.  This normally means that the
2715                  previous instruction was a 4 byte branch anyhow.  */
2716               || (mips_opts.mips16 && history[0].fixp[0])
2717               /* If the previous instruction is a sync, sync.l, or
2718                  sync.p, we can not swap.  */
2719               || (prev_pinfo & INSN_SYNC))
2720             {
2721               if (mips_opts.mips16
2722                   && (pinfo & INSN_UNCOND_BRANCH_DELAY)
2723                   && (pinfo & (MIPS16_INSN_READ_X | MIPS16_INSN_READ_31))
2724                   && (mips_opts.isa == ISA_MIPS32
2725                       || mips_opts.isa == ISA_MIPS32R2
2726                       || mips_opts.isa == ISA_MIPS64
2727                       || mips_opts.isa == ISA_MIPS64R2))
2728                 {
2729                   /* Convert MIPS16 jr/jalr into a "compact" jump.  */
2730                   ip->insn_opcode |= 0x0080;
2731                   install_insn (ip);
2732                   insert_into_history (0, 1, ip);
2733                 } 
2734               else
2735                 {
2736                   /* We could do even better for unconditional branches to
2737                      portions of this object file; we could pick up the
2738                      instruction at the destination, put it in the delay
2739                      slot, and bump the destination address.  */
2740                   insert_into_history (0, 1, ip);
2741                   emit_nop ();
2742                 }
2743                 
2744               if (mips_relax.sequence)
2745                 mips_relax.sizes[mips_relax.sequence - 1] += 4;
2746             }
2747           else
2748             {
2749               /* It looks like we can actually do the swap.  */
2750               struct mips_cl_insn delay = history[0];
2751               if (mips_opts.mips16)
2752                 {
2753                   know (delay.frag == ip->frag);
2754                   move_insn (ip, delay.frag, delay.where);
2755                   move_insn (&delay, ip->frag, ip->where + insn_length (ip));
2756                 }
2757               else if (relaxed_branch)
2758                 {
2759                   /* Add the delay slot instruction to the end of the
2760                      current frag and shrink the fixed part of the
2761                      original frag.  If the branch occupies the tail of
2762                      the latter, move it backwards to cover the gap.  */
2763                   delay.frag->fr_fix -= 4;
2764                   if (delay.frag == ip->frag)
2765                     move_insn (ip, ip->frag, ip->where - 4);
2766                   add_fixed_insn (&delay);
2767                 }
2768               else
2769                 {
2770                   move_insn (&delay, ip->frag, ip->where);
2771                   move_insn (ip, history[0].frag, history[0].where);
2772                 }
2773               history[0] = *ip;
2774               delay.fixed_p = 1;
2775               insert_into_history (0, 1, &delay);
2776             }
2777
2778           /* If that was an unconditional branch, forget the previous
2779              insn information.  */
2780           if (pinfo & INSN_UNCOND_BRANCH_DELAY)
2781             mips_no_prev_insn ();
2782         }
2783       else if (pinfo & INSN_COND_BRANCH_LIKELY)
2784         {
2785           /* We don't yet optimize a branch likely.  What we should do
2786              is look at the target, copy the instruction found there
2787              into the delay slot, and increment the branch to jump to
2788              the next instruction.  */
2789           insert_into_history (0, 1, ip);
2790           emit_nop ();
2791         }
2792       else
2793         insert_into_history (0, 1, ip);
2794     }
2795   else
2796     insert_into_history (0, 1, ip);
2797
2798   /* We just output an insn, so the next one doesn't have a label.  */
2799   mips_clear_insn_labels ();
2800 }
2801
2802 /* Forget that there was any previous instruction or label.  */
2803
2804 static void
2805 mips_no_prev_insn (void)
2806 {
2807   prev_nop_frag = NULL;
2808   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
2809   mips_clear_insn_labels ();
2810 }
2811
2812 /* This function must be called before we emit something other than
2813    instructions.  It is like mips_no_prev_insn except that it inserts
2814    any NOPS that might be needed by previous instructions.  */
2815
2816 void
2817 mips_emit_delays (void)
2818 {
2819   if (! mips_opts.noreorder)
2820     {
2821       int nops = nops_for_insn (history, NULL);
2822       if (nops > 0)
2823         {
2824           while (nops-- > 0)
2825             add_fixed_insn (NOP_INSN);
2826           mips_move_labels ();
2827         }
2828     }
2829   mips_no_prev_insn ();
2830 }
2831
2832 /* Start a (possibly nested) noreorder block.  */
2833
2834 static void
2835 start_noreorder (void)
2836 {
2837   if (mips_opts.noreorder == 0)
2838     {
2839       unsigned int i;
2840       int nops;
2841
2842       /* None of the instructions before the .set noreorder can be moved.  */
2843       for (i = 0; i < ARRAY_SIZE (history); i++)
2844         history[i].fixed_p = 1;
2845
2846       /* Insert any nops that might be needed between the .set noreorder
2847          block and the previous instructions.  We will later remove any
2848          nops that turn out not to be needed.  */
2849       nops = nops_for_insn (history, NULL);
2850       if (nops > 0)
2851         {
2852           if (mips_optimize != 0)
2853             {
2854               /* Record the frag which holds the nop instructions, so
2855                  that we can remove them if we don't need them.  */
2856               frag_grow (mips_opts.mips16 ? nops * 2 : nops * 4);
2857               prev_nop_frag = frag_now;
2858               prev_nop_frag_holds = nops;
2859               prev_nop_frag_required = 0;
2860               prev_nop_frag_since = 0;
2861             }
2862
2863           for (; nops > 0; --nops)
2864             add_fixed_insn (NOP_INSN);
2865
2866           /* Move on to a new frag, so that it is safe to simply
2867              decrease the size of prev_nop_frag.  */
2868           frag_wane (frag_now);
2869           frag_new (0);
2870           mips_move_labels ();
2871         }
2872       mips16_mark_labels ();
2873       mips_clear_insn_labels ();
2874     }
2875   mips_opts.noreorder++;
2876   mips_any_noreorder = 1;
2877 }
2878
2879 /* End a nested noreorder block.  */
2880
2881 static void
2882 end_noreorder (void)
2883 {
2884   mips_opts.noreorder--;
2885   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
2886     {
2887       /* Commit to inserting prev_nop_frag_required nops and go back to
2888          handling nop insertion the .set reorder way.  */
2889       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
2890                                 * (mips_opts.mips16 ? 2 : 4));
2891       insert_into_history (prev_nop_frag_since,
2892                            prev_nop_frag_required, NOP_INSN);
2893       prev_nop_frag = NULL;
2894     }
2895 }
2896
2897 /* Set up global variables for the start of a new macro.  */
2898
2899 static void
2900 macro_start (void)
2901 {
2902   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
2903   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
2904                                      && (history[0].insn_mo->pinfo
2905                                          & (INSN_UNCOND_BRANCH_DELAY
2906                                             | INSN_COND_BRANCH_DELAY
2907                                             | INSN_COND_BRANCH_LIKELY)) != 0);
2908 }
2909
2910 /* Given that a macro is longer than 4 bytes, return the appropriate warning
2911    for it.  Return null if no warning is needed.  SUBTYPE is a bitmask of
2912    RELAX_DELAY_SLOT and RELAX_NOMACRO.  */
2913
2914 static const char *
2915 macro_warning (relax_substateT subtype)
2916 {
2917   if (subtype & RELAX_DELAY_SLOT)
2918     return _("Macro instruction expanded into multiple instructions"
2919              " in a branch delay slot");
2920   else if (subtype & RELAX_NOMACRO)
2921     return _("Macro instruction expanded into multiple instructions");
2922   else
2923     return 0;
2924 }
2925
2926 /* Finish up a macro.  Emit warnings as appropriate.  */
2927
2928 static void
2929 macro_end (void)
2930 {
2931   if (mips_macro_warning.sizes[0] > 4 || mips_macro_warning.sizes[1] > 4)
2932     {
2933       relax_substateT subtype;
2934
2935       /* Set up the relaxation warning flags.  */
2936       subtype = 0;
2937       if (mips_macro_warning.sizes[1] > mips_macro_warning.sizes[0])
2938         subtype |= RELAX_SECOND_LONGER;
2939       if (mips_opts.warn_about_macros)
2940         subtype |= RELAX_NOMACRO;
2941       if (mips_macro_warning.delay_slot_p)
2942         subtype |= RELAX_DELAY_SLOT;
2943
2944       if (mips_macro_warning.sizes[0] > 4 && mips_macro_warning.sizes[1] > 4)
2945         {
2946           /* Either the macro has a single implementation or both
2947              implementations are longer than 4 bytes.  Emit the
2948              warning now.  */
2949           const char *msg = macro_warning (subtype);
2950           if (msg != 0)
2951             as_warn (msg);
2952         }
2953       else
2954         {
2955           /* One implementation might need a warning but the other
2956              definitely doesn't.  */
2957           mips_macro_warning.first_frag->fr_subtype |= subtype;
2958         }
2959     }
2960 }
2961
2962 /* Read a macro's relocation codes from *ARGS and store them in *R.
2963    The first argument in *ARGS will be either the code for a single
2964    relocation or -1 followed by the three codes that make up a
2965    composite relocation.  */
2966
2967 static void
2968 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
2969 {
2970   int i, next;
2971
2972   next = va_arg (*args, int);
2973   if (next >= 0)
2974     r[0] = (bfd_reloc_code_real_type) next;
2975   else
2976     for (i = 0; i < 3; i++)
2977       r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
2978 }
2979
2980 /* Build an instruction created by a macro expansion.  This is passed
2981    a pointer to the count of instructions created so far, an
2982    expression, the name of the instruction to build, an operand format
2983    string, and corresponding arguments.  */
2984
2985 static void
2986 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
2987 {
2988   const struct mips_opcode *mo;
2989   struct mips_cl_insn insn;
2990   bfd_reloc_code_real_type r[3];
2991   va_list args;
2992
2993   va_start (args, fmt);
2994
2995   if (mips_opts.mips16)
2996     {
2997       mips16_macro_build (ep, name, fmt, args);
2998       va_end (args);
2999       return;
3000     }
3001
3002   r[0] = BFD_RELOC_UNUSED;
3003   r[1] = BFD_RELOC_UNUSED;
3004   r[2] = BFD_RELOC_UNUSED;
3005   mo = (struct mips_opcode *) hash_find (op_hash, name);
3006   assert (mo);
3007   assert (strcmp (name, mo->name) == 0);
3008
3009   /* Search until we get a match for NAME.  It is assumed here that
3010      macros will never generate MDMX or MIPS-3D instructions.  */
3011   while (strcmp (fmt, mo->args) != 0
3012          || mo->pinfo == INSN_MACRO
3013          || !OPCODE_IS_MEMBER (mo,
3014                                (mips_opts.isa
3015                                 | (file_ase_mips16 ? INSN_MIPS16 : 0)),
3016                                mips_opts.arch)
3017          || (mips_opts.arch == CPU_R4650 && (mo->pinfo & FP_D) != 0))
3018     {
3019       ++mo;
3020       assert (mo->name);
3021       assert (strcmp (name, mo->name) == 0);
3022     }
3023
3024   create_insn (&insn, mo);
3025   for (;;)
3026     {
3027       switch (*fmt++)
3028         {
3029         case '\0':
3030           break;
3031
3032         case ',':
3033         case '(':
3034         case ')':
3035           continue;
3036
3037         case '+':
3038           switch (*fmt++)
3039             {
3040             case 'A':
3041             case 'E':
3042               INSERT_OPERAND (SHAMT, insn, va_arg (args, int));
3043               continue;
3044
3045             case 'B':
3046             case 'F':
3047               /* Note that in the macro case, these arguments are already
3048                  in MSB form.  (When handling the instruction in the
3049                  non-macro case, these arguments are sizes from which
3050                  MSB values must be calculated.)  */
3051               INSERT_OPERAND (INSMSB, insn, va_arg (args, int));
3052               continue;
3053
3054             case 'C':
3055             case 'G':
3056             case 'H':
3057               /* Note that in the macro case, these arguments are already
3058                  in MSBD form.  (When handling the instruction in the
3059                  non-macro case, these arguments are sizes from which
3060                  MSBD values must be calculated.)  */
3061               INSERT_OPERAND (EXTMSBD, insn, va_arg (args, int));
3062               continue;
3063
3064             default:
3065               internalError ();
3066             }
3067           continue;
3068
3069         case 't':
3070         case 'w':
3071         case 'E':
3072           INSERT_OPERAND (RT, insn, va_arg (args, int));
3073           continue;
3074
3075         case 'c':
3076           INSERT_OPERAND (CODE, insn, va_arg (args, int));
3077           continue;
3078
3079         case 'T':
3080         case 'W':
3081           INSERT_OPERAND (FT, insn, va_arg (args, int));
3082           continue;
3083
3084         case 'd':
3085         case 'G':
3086         case 'K':
3087           INSERT_OPERAND (RD, insn, va_arg (args, int));
3088           continue;
3089
3090         case 'U':
3091           {
3092             int tmp = va_arg (args, int);
3093
3094             INSERT_OPERAND (RT, insn, tmp);
3095             INSERT_OPERAND (RD, insn, tmp);
3096             continue;
3097           }
3098
3099         case 'V':
3100         case 'S':
3101           INSERT_OPERAND (FS, insn, va_arg (args, int));
3102           continue;
3103
3104         case 'z':
3105           continue;
3106
3107         case '<':
3108           INSERT_OPERAND (SHAMT, insn, va_arg (args, int));
3109           continue;
3110
3111         case 'D':
3112           INSERT_OPERAND (FD, insn, va_arg (args, int));
3113           continue;
3114
3115         case 'B':
3116           INSERT_OPERAND (CODE20, insn, va_arg (args, int));
3117           continue;
3118
3119         case 'J':
3120           INSERT_OPERAND (CODE19, insn, va_arg (args, int));
3121           continue;
3122
3123         case 'q':
3124           INSERT_OPERAND (CODE2, insn, va_arg (args, int));
3125           continue;
3126
3127         case 'b':
3128         case 's':
3129         case 'r':
3130         case 'v':
3131           INSERT_OPERAND (RS, insn, va_arg (args, int));
3132           continue;
3133
3134         case 'i':
3135         case 'j':
3136         case 'o':
3137           macro_read_relocs (&args, r);
3138           assert (*r == BFD_RELOC_GPREL16
3139                   || *r == BFD_RELOC_MIPS_LITERAL
3140                   || *r == BFD_RELOC_MIPS_HIGHER
3141                   || *r == BFD_RELOC_HI16_S
3142                   || *r == BFD_RELOC_LO16
3143                   || *r == BFD_RELOC_MIPS_GOT16
3144                   || *r == BFD_RELOC_MIPS_CALL16
3145                   || *r == BFD_RELOC_MIPS_GOT_DISP
3146                   || *r == BFD_RELOC_MIPS_GOT_PAGE
3147                   || *r == BFD_RELOC_MIPS_GOT_OFST
3148                   || *r == BFD_RELOC_MIPS_GOT_LO16
3149                   || *r == BFD_RELOC_MIPS_CALL_LO16);
3150           continue;
3151
3152         case 'u':
3153           macro_read_relocs (&args, r);
3154           assert (ep != NULL
3155                   && (ep->X_op == O_constant
3156                       || (ep->X_op == O_symbol
3157                           && (*r == BFD_RELOC_MIPS_HIGHEST
3158                               || *r == BFD_RELOC_HI16_S
3159                               || *r == BFD_RELOC_HI16
3160                               || *r == BFD_RELOC_GPREL16
3161                               || *r == BFD_RELOC_MIPS_GOT_HI16
3162                               || *r == BFD_RELOC_MIPS_CALL_HI16))));
3163           continue;
3164
3165         case 'p':
3166           assert (ep != NULL);
3167
3168           /*
3169            * This allows macro() to pass an immediate expression for
3170            * creating short branches without creating a symbol.
3171            *
3172            * We don't allow branch relaxation for these branches, as
3173            * they should only appear in ".set nomacro" anyway.
3174            */
3175           if (ep->X_op == O_constant)
3176             {
3177               if ((ep->X_add_number & 3) != 0)
3178                 as_bad (_("branch to misaligned address (0x%lx)"),
3179                         (unsigned long) ep->X_add_number);
3180               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
3181                 as_bad (_("branch address range overflow (0x%lx)"),
3182                         (unsigned long) ep->X_add_number);
3183               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
3184               ep = NULL;
3185             }
3186           else
3187             *r = BFD_RELOC_16_PCREL_S2;
3188           continue;
3189
3190         case 'a':
3191           assert (ep != NULL);
3192           *r = BFD_RELOC_MIPS_JMP;
3193           continue;
3194
3195         case 'C':
3196           insn.insn_opcode |= va_arg (args, unsigned long);
3197           continue;
3198
3199         case 'k':
3200           insn.insn_opcode |= va_arg (args, unsigned long) << OP_SH_CACHE;
3201           continue;
3202
3203         default:
3204           internalError ();
3205         }
3206       break;
3207     }
3208   va_end (args);
3209   assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
3210
3211   append_insn (&insn, ep, r);
3212 }
3213
3214 static void
3215 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
3216                     va_list args)
3217 {
3218   struct mips_opcode *mo;
3219   struct mips_cl_insn insn;
3220   bfd_reloc_code_real_type r[3]
3221     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
3222
3223   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
3224   assert (mo);
3225   assert (strcmp (name, mo->name) == 0);
3226
3227   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
3228     {
3229       ++mo;
3230       assert (mo->name);
3231       assert (strcmp (name, mo->name) == 0);
3232     }
3233
3234   create_insn (&insn, mo);
3235   for (;;)
3236     {
3237       int c;
3238
3239       c = *fmt++;
3240       switch (c)
3241         {
3242         case '\0':
3243           break;
3244
3245         case ',':
3246         case '(':
3247         case ')':
3248           continue;
3249
3250         case 'y':
3251         case 'w':
3252           MIPS16_INSERT_OPERAND (RY, insn, va_arg (args, int));
3253           continue;
3254
3255         case 'x':
3256         case 'v':
3257           MIPS16_INSERT_OPERAND (RX, insn, va_arg (args, int));
3258           continue;
3259
3260         case 'z':
3261           MIPS16_INSERT_OPERAND (RZ, insn, va_arg (args, int));
3262           continue;
3263
3264         case 'Z':
3265           MIPS16_INSERT_OPERAND (MOVE32Z, insn, va_arg (args, int));
3266           continue;
3267
3268         case '0':
3269         case 'S':
3270         case 'P':
3271         case 'R':
3272           continue;
3273
3274         case 'X':
3275           MIPS16_INSERT_OPERAND (REGR32, insn, va_arg (args, int));
3276           continue;
3277
3278         case 'Y':
3279           {
3280             int regno;
3281
3282             regno = va_arg (args, int);
3283             regno = ((regno & 7) << 2) | ((regno & 0x18) >> 3);
3284             insn.insn_opcode |= regno << MIPS16OP_SH_REG32R;
3285           }
3286           continue;
3287
3288         case '<':
3289         case '>':
3290         case '4':
3291         case '5':
3292         case 'H':
3293         case 'W':
3294         case 'D':
3295         case 'j':
3296         case '8':
3297         case 'V':
3298         case 'C':
3299         case 'U':
3300         case 'k':
3301         case 'K':
3302         case 'p':
3303         case 'q':
3304           {
3305             assert (ep != NULL);
3306
3307             if (ep->X_op != O_constant)
3308               *r = (int) BFD_RELOC_UNUSED + c;
3309             else
3310               {
3311                 mips16_immed (NULL, 0, c, ep->X_add_number, FALSE, FALSE,
3312                               FALSE, &insn.insn_opcode, &insn.use_extend,
3313                               &insn.extend);
3314                 ep = NULL;
3315                 *r = BFD_RELOC_UNUSED;
3316               }
3317           }
3318           continue;
3319
3320         case '6':
3321           MIPS16_INSERT_OPERAND (IMM6, insn, va_arg (args, int));
3322           continue;
3323         }
3324
3325       break;
3326     }
3327
3328   assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
3329
3330   append_insn (&insn, ep, r);
3331 }
3332
3333 /*
3334  * Sign-extend 32-bit mode constants that have bit 31 set and all
3335  * higher bits unset.
3336  */
3337 static void
3338 normalize_constant_expr (expressionS *ex)
3339 {
3340   if (ex->X_op == O_constant
3341       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
3342     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
3343                         - 0x80000000);
3344 }
3345
3346 /*
3347  * Sign-extend 32-bit mode address offsets that have bit 31 set and
3348  * all higher bits unset.
3349  */
3350 static void
3351 normalize_address_expr (expressionS *ex)
3352 {
3353   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
3354         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
3355       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
3356     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
3357                         - 0x80000000);
3358 }
3359
3360 /*
3361  * Generate a "jalr" instruction with a relocation hint to the called
3362  * function.  This occurs in NewABI PIC code.
3363  */
3364 static void
3365 macro_build_jalr (expressionS *ep)
3366 {
3367   char *f = NULL;
3368
3369   if (HAVE_NEWABI)
3370     {
3371       frag_grow (8);
3372       f = frag_more (0);
3373     }
3374   macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
3375   if (HAVE_NEWABI)
3376     fix_new_exp (frag_now, f - frag_now->fr_literal,
3377                  4, ep, FALSE, BFD_RELOC_MIPS_JALR);
3378 }
3379
3380 /*
3381  * Generate a "lui" instruction.
3382  */
3383 static void
3384 macro_build_lui (expressionS *ep, int regnum)
3385 {
3386   expressionS high_expr;
3387   const struct mips_opcode *mo;
3388   struct mips_cl_insn insn;
3389   bfd_reloc_code_real_type r[3]
3390     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
3391   const char *name = "lui";
3392   const char *fmt = "t,u";
3393
3394   assert (! mips_opts.mips16);
3395
3396   high_expr = *ep;
3397
3398   if (high_expr.X_op == O_constant)
3399     {
3400       /* we can compute the instruction now without a relocation entry */
3401       high_expr.X_add_number = ((high_expr.X_add_number + 0x8000)
3402                                 >> 16) & 0xffff;
3403       *r = BFD_RELOC_UNUSED;
3404     }
3405   else
3406     {
3407       assert (ep->X_op == O_symbol);
3408       /* _gp_disp is a special case, used from s_cpload.
3409          __gnu_local_gp is used if mips_no_shared.  */
3410       assert (mips_pic == NO_PIC
3411               || (! HAVE_NEWABI
3412                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
3413               || (! mips_in_shared
3414                   && strcmp (S_GET_NAME (ep->X_add_symbol),
3415                              "__gnu_local_gp") == 0));
3416       *r = BFD_RELOC_HI16_S;
3417     }
3418
3419   mo = hash_find (op_hash, name);
3420   assert (strcmp (name, mo->name) == 0);
3421   assert (strcmp (fmt, mo->args) == 0);
3422   create_insn (&insn, mo);
3423
3424   insn.insn_opcode = insn.insn_mo->match;
3425   INSERT_OPERAND (RT, insn, regnum);
3426   if (*r == BFD_RELOC_UNUSED)
3427     {
3428       insn.insn_opcode |= high_expr.X_add_number;
3429       append_insn (&insn, NULL, r);
3430     }
3431   else
3432     append_insn (&insn, &high_expr, r);
3433 }
3434
3435 /* Generate a sequence of instructions to do a load or store from a constant
3436    offset off of a base register (breg) into/from a target register (treg),
3437    using AT if necessary.  */
3438 static void
3439 macro_build_ldst_constoffset (expressionS *ep, const char *op,
3440                               int treg, int breg, int dbl)
3441 {
3442   assert (ep->X_op == O_constant);
3443
3444   /* Sign-extending 32-bit constants makes their handling easier.  */
3445   if (!dbl)
3446     normalize_constant_expr (ep);
3447
3448   /* Right now, this routine can only handle signed 32-bit constants.  */
3449   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
3450     as_warn (_("operand overflow"));
3451
3452   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
3453     {
3454       /* Signed 16-bit offset will fit in the op.  Easy!  */
3455       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
3456     }
3457   else
3458     {
3459       /* 32-bit offset, need multiple instructions and AT, like:
3460            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
3461            addu     $tempreg,$tempreg,$breg
3462            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
3463          to handle the complete offset.  */
3464       macro_build_lui (ep, AT);
3465       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
3466       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
3467
3468       if (mips_opts.noat)
3469         as_bad (_("Macro used $at after \".set noat\""));
3470     }
3471 }
3472
3473 /*                      set_at()
3474  * Generates code to set the $at register to true (one)
3475  * if reg is less than the immediate expression.
3476  */
3477 static void
3478 set_at (int reg, int unsignedp)
3479 {
3480   if (imm_expr.X_op == O_constant
3481       && imm_expr.X_add_number >= -0x8000
3482       && imm_expr.X_add_number < 0x8000)
3483     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
3484                  AT, reg, BFD_RELOC_LO16);
3485   else
3486     {
3487       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
3488       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
3489     }
3490 }
3491
3492 /* Warn if an expression is not a constant.  */
3493
3494 static void
3495 check_absolute_expr (struct mips_cl_insn *ip, expressionS *ex)
3496 {
3497   if (ex->X_op == O_big)
3498     as_bad (_("unsupported large constant"));
3499   else if (ex->X_op != O_constant)
3500     as_bad (_("Instruction %s requires absolute expression"),
3501             ip->insn_mo->name);
3502
3503   if (HAVE_32BIT_GPRS)
3504     normalize_constant_expr (ex);
3505 }
3506
3507 /* Count the leading zeroes by performing a binary chop. This is a
3508    bulky bit of source, but performance is a LOT better for the
3509    majority of values than a simple loop to count the bits:
3510        for (lcnt = 0; (lcnt < 32); lcnt++)
3511          if ((v) & (1 << (31 - lcnt)))
3512            break;
3513   However it is not code size friendly, and the gain will drop a bit
3514   on certain cached systems.
3515 */
3516 #define COUNT_TOP_ZEROES(v)             \
3517   (((v) & ~0xffff) == 0                 \
3518    ? ((v) & ~0xff) == 0                 \
3519      ? ((v) & ~0xf) == 0                \
3520        ? ((v) & ~0x3) == 0              \
3521          ? ((v) & ~0x1) == 0            \
3522            ? !(v)                       \
3523              ? 32                       \
3524              : 31                       \
3525            : 30                         \
3526          : ((v) & ~0x7) == 0            \
3527            ? 29                         \
3528            : 28                         \
3529        : ((v) & ~0x3f) == 0             \
3530          ? ((v) & ~0x1f) == 0           \
3531            ? 27                         \
3532            : 26                         \
3533          : ((v) & ~0x7f) == 0           \
3534            ? 25                         \
3535            : 24                         \
3536      : ((v) & ~0xfff) == 0              \
3537        ? ((v) & ~0x3ff) == 0            \
3538          ? ((v) & ~0x1ff) == 0          \
3539            ? 23                         \
3540            : 22                         \
3541          : ((v) & ~0x7ff) == 0          \
3542            ? 21                         \
3543            : 20                         \
3544        : ((v) & ~0x3fff) == 0           \
3545          ? ((v) & ~0x1fff) == 0         \
3546            ? 19                         \
3547            : 18                         \
3548          : ((v) & ~0x7fff) == 0         \
3549            ? 17                         \
3550            : 16                         \
3551    : ((v) & ~0xffffff) == 0             \
3552      ? ((v) & ~0xfffff) == 0            \
3553        ? ((v) & ~0x3ffff) == 0          \
3554          ? ((v) & ~0x1ffff) == 0        \
3555            ? 15                         \
3556            : 14                         \
3557          : ((v) & ~0x7ffff) == 0        \
3558            ? 13                         \
3559            : 12                         \
3560        : ((v) & ~0x3fffff) == 0         \
3561          ? ((v) & ~0x1fffff) == 0       \
3562            ? 11                         \
3563            : 10                         \
3564          : ((v) & ~0x7fffff) == 0       \
3565            ? 9                          \
3566            : 8                          \
3567      : ((v) & ~0xfffffff) == 0          \
3568        ? ((v) & ~0x3ffffff) == 0        \
3569          ? ((v) & ~0x1ffffff) == 0      \
3570            ? 7                          \
3571            : 6                          \
3572          : ((v) & ~0x7ffffff) == 0      \
3573            ? 5                          \
3574            : 4                          \
3575        : ((v) & ~0x3fffffff) == 0       \
3576          ? ((v) & ~0x1fffffff) == 0     \
3577            ? 3                          \
3578            : 2                          \
3579          : ((v) & ~0x7fffffff) == 0     \
3580            ? 1                          \
3581            : 0)
3582
3583 /*                      load_register()
3584  *  This routine generates the least number of instructions necessary to load
3585  *  an absolute expression value into a register.
3586  */
3587 static void
3588 load_register (int reg, expressionS *ep, int dbl)
3589 {
3590   int freg;
3591   expressionS hi32, lo32;
3592
3593   if (ep->X_op != O_big)
3594     {
3595       assert (ep->X_op == O_constant);
3596
3597       /* Sign-extending 32-bit constants makes their handling easier.  */
3598       if (!dbl)
3599         normalize_constant_expr (ep);
3600
3601       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
3602         {
3603           /* We can handle 16 bit signed values with an addiu to
3604              $zero.  No need to ever use daddiu here, since $zero and
3605              the result are always correct in 32 bit mode.  */
3606           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
3607           return;
3608         }
3609       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
3610         {
3611           /* We can handle 16 bit unsigned values with an ori to
3612              $zero.  */
3613           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
3614           return;
3615         }
3616       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
3617         {
3618           /* 32 bit values require an lui.  */
3619           macro_build (ep, "lui", "t,u", reg, BFD_RELOC_HI16);
3620           if ((ep->X_add_number & 0xffff) != 0)
3621             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
3622           return;
3623         }
3624     }
3625
3626   /* The value is larger than 32 bits.  */
3627
3628   if (!dbl || HAVE_32BIT_GPRS)
3629     {
3630       char value[32];
3631
3632       sprintf_vma (value, ep->X_add_number);
3633       as_bad (_("Number (0x%s) larger than 32 bits"), value);
3634       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
3635       return;
3636     }
3637
3638   if (ep->X_op != O_big)
3639     {
3640       hi32 = *ep;
3641       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
3642       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
3643       hi32.X_add_number &= 0xffffffff;
3644       lo32 = *ep;
3645       lo32.X_add_number &= 0xffffffff;
3646     }
3647   else
3648     {
3649       assert (ep->X_add_number > 2);
3650       if (ep->X_add_number == 3)
3651         generic_bignum[3] = 0;
3652       else if (ep->X_add_number > 4)
3653         as_bad (_("Number larger than 64 bits"));
3654       lo32.X_op = O_constant;
3655       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
3656       hi32.X_op = O_constant;
3657       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
3658     }
3659
3660   if (hi32.X_add_number == 0)
3661     freg = 0;
3662   else
3663     {
3664       int shift, bit;
3665       unsigned long hi, lo;
3666
3667       if (hi32.X_add_number == (offsetT) 0xffffffff)
3668         {
3669           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
3670             {
3671               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
3672               return;
3673             }
3674           if (lo32.X_add_number & 0x80000000)
3675             {
3676               macro_build (&lo32, "lui", "t,u", reg, BFD_RELOC_HI16);
3677               if (lo32.X_add_number & 0xffff)
3678                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
3679               return;
3680             }
3681         }
3682
3683       /* Check for 16bit shifted constant.  We know that hi32 is
3684          non-zero, so start the mask on the first bit of the hi32
3685          value.  */
3686       shift = 17;
3687       do
3688         {
3689           unsigned long himask, lomask;
3690
3691           if (shift < 32)
3692             {
3693               himask = 0xffff >> (32 - shift);
3694               lomask = (0xffff << shift) & 0xffffffff;
3695             }
3696           else
3697             {
3698               himask = 0xffff << (shift - 32);
3699               lomask = 0;
3700             }
3701           if ((hi32.X_add_number & ~(offsetT) himask) == 0
3702               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
3703             {
3704               expressionS tmp;
3705
3706               tmp.X_op = O_constant;
3707               if (shift < 32)
3708                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
3709                                     | (lo32.X_add_number >> shift));
3710               else
3711                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
3712               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
3713               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", "d,w,<",
3714                            reg, reg, (shift >= 32) ? shift - 32 : shift);
3715               return;
3716             }
3717           ++shift;
3718         }
3719       while (shift <= (64 - 16));
3720
3721       /* Find the bit number of the lowest one bit, and store the
3722          shifted value in hi/lo.  */
3723       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
3724       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
3725       if (lo != 0)
3726         {
3727           bit = 0;
3728           while ((lo & 1) == 0)
3729             {
3730               lo >>= 1;
3731               ++bit;
3732             }
3733           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
3734           hi >>= bit;
3735         }
3736       else
3737         {
3738           bit = 32;
3739           while ((hi & 1) == 0)
3740             {
3741               hi >>= 1;
3742               ++bit;
3743             }
3744           lo = hi;
3745           hi = 0;
3746         }
3747
3748       /* Optimize if the shifted value is a (power of 2) - 1.  */
3749       if ((hi == 0 && ((lo + 1) & lo) == 0)
3750           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
3751         {
3752           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
3753           if (shift != 0)
3754             {
3755               expressionS tmp;
3756
3757               /* This instruction will set the register to be all
3758                  ones.  */
3759               tmp.X_op = O_constant;
3760               tmp.X_add_number = (offsetT) -1;
3761               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
3762               if (bit != 0)
3763                 {
3764                   bit += shift;
3765                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", "d,w,<",
3766                                reg, reg, (bit >= 32) ? bit - 32 : bit);
3767                 }
3768               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", "d,w,<",
3769                            reg, reg, (shift >= 32) ? shift - 32 : shift);
3770               return;
3771             }
3772         }
3773
3774       /* Sign extend hi32 before calling load_register, because we can
3775          generally get better code when we load a sign extended value.  */
3776       if ((hi32.X_add_number & 0x80000000) != 0)
3777         hi32.X_add_number |= ~(offsetT) 0xffffffff;
3778       load_register (reg, &hi32, 0);
3779       freg = reg;
3780     }
3781   if ((lo32.X_add_number & 0xffff0000) == 0)
3782     {
3783       if (freg != 0)
3784         {
3785           macro_build (NULL, "dsll32", "d,w,<", reg, freg, 0);
3786           freg = reg;
3787         }
3788     }
3789   else
3790     {
3791       expressionS mid16;
3792
3793       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
3794         {
3795           macro_build (&lo32, "lui", "t,u", reg, BFD_RELOC_HI16);
3796           macro_build (NULL, "dsrl32", "d,w,<", reg, reg, 0);
3797           return;
3798         }
3799
3800       if (freg != 0)
3801         {
3802           macro_build (NULL, "dsll", "d,w,<", reg, freg, 16);
3803           freg = reg;
3804         }
3805       mid16 = lo32;
3806       mid16.X_add_number >>= 16;
3807       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
3808       macro_build (NULL, "dsll", "d,w,<", reg, reg, 16);
3809       freg = reg;
3810     }
3811   if ((lo32.X_add_number & 0xffff) != 0)
3812     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
3813 }
3814
3815 static inline void
3816 load_delay_nop (void)
3817 {
3818   if (!gpr_interlocks)
3819     macro_build (NULL, "nop", "");
3820 }
3821
3822 /* Load an address into a register.  */
3823
3824 static void
3825 load_address (int reg, expressionS *ep, int *used_at)
3826 {
3827   if (ep->X_op != O_constant
3828       && ep->X_op != O_symbol)
3829     {
3830       as_bad (_("expression too complex"));
3831       ep->X_op = O_constant;
3832     }
3833
3834   if (ep->X_op == O_constant)
3835     {
3836       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
3837       return;
3838     }
3839
3840   if (mips_pic == NO_PIC)
3841     {
3842       /* If this is a reference to a GP relative symbol, we want
3843            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
3844          Otherwise we want
3845            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
3846            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
3847          If we have an addend, we always use the latter form.
3848
3849          With 64bit address space and a usable $at we want
3850            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
3851            lui          $at,<sym>               (BFD_RELOC_HI16_S)
3852            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
3853            daddiu       $at,<sym>               (BFD_RELOC_LO16)
3854            dsll32       $reg,0
3855            daddu        $reg,$reg,$at
3856
3857          If $at is already in use, we use a path which is suboptimal
3858          on superscalar processors.
3859            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
3860            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
3861            dsll         $reg,16
3862            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
3863            dsll         $reg,16
3864            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
3865
3866          For GP relative symbols in 64bit address space we can use
3867          the same sequence as in 32bit address space.  */
3868       if (HAVE_64BIT_SYMBOLS)
3869         {
3870           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
3871               && !nopic_need_relax (ep->X_add_symbol, 1))
3872             {
3873               relax_start (ep->X_add_symbol);
3874               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
3875                            mips_gp_register, BFD_RELOC_GPREL16);
3876               relax_switch ();
3877             }
3878
3879           if (*used_at == 0 && !mips_opts.noat)
3880             {
3881               macro_build (ep, "lui", "t,u", reg, BFD_RELOC_MIPS_HIGHEST);
3882               macro_build (ep, "lui", "t,u", AT, BFD_RELOC_HI16_S);
3883               macro_build (ep, "daddiu", "t,r,j", reg, reg,
3884                            BFD_RELOC_MIPS_HIGHER);
3885               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
3886               macro_build (NULL, "dsll32", "d,w,<", reg, reg, 0);
3887               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
3888               *used_at = 1;
3889             }
3890           else
3891             {
3892               macro_build (ep, "lui", "t,u", reg, BFD_RELOC_MIPS_HIGHEST);
3893               macro_build (ep, "daddiu", "t,r,j", reg, reg,
3894                            BFD_RELOC_MIPS_HIGHER);
3895               macro_build (NULL, "dsll", "d,w,<", reg, reg, 16);
3896               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
3897               macro_build (NULL, "dsll", "d,w,<", reg, reg, 16);
3898               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
3899             }
3900
3901           if (mips_relax.sequence)
3902             relax_end ();
3903         }
3904       else
3905         {
3906           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
3907               && !nopic_need_relax (ep->X_add_symbol, 1))
3908             {
3909               relax_start (ep->X_add_symbol);
3910               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
3911                            mips_gp_register, BFD_RELOC_GPREL16);
3912               relax_switch ();
3913             }
3914           macro_build_lui (ep, reg);
3915           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
3916                        reg, reg, BFD_RELOC_LO16);
3917           if (mips_relax.sequence)
3918             relax_end ();
3919         }
3920     }
3921   else if (!mips_big_got)
3922     {
3923       expressionS ex;
3924
3925       /* If this is a reference to an external symbol, we want
3926            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
3927          Otherwise we want
3928            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
3929            nop
3930            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
3931          If there is a constant, it must be added in after.
3932
3933          If we have NewABI, we want
3934            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
3935          unless we're referencing a global symbol with a non-zero
3936          offset, in which case cst must be added separately.  */
3937       if (HAVE_NEWABI)
3938         {
3939           if (ep->X_add_number)
3940             {
3941               ex.X_add_number = ep->X_add_number;
3942               ep->X_add_number = 0;
3943               relax_start (ep->X_add_symbol);
3944               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
3945                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
3946               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
3947                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
3948               ex.X_op = O_constant;
3949               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
3950                            reg, reg, BFD_RELOC_LO16);
3951               ep->X_add_number = ex.X_add_number;
3952               relax_switch ();
3953             }
3954           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
3955                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
3956           if (mips_relax.sequence)
3957             relax_end ();
3958         }
3959       else
3960         {
3961           ex.X_add_number = ep->X_add_number;
3962           ep->X_add_number = 0;
3963           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
3964                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
3965           load_delay_nop ();
3966           relax_start (ep->X_add_symbol);
3967           relax_switch ();
3968           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
3969                        BFD_RELOC_LO16);
3970           relax_end ();
3971
3972           if (ex.X_add_number != 0)
3973             {
3974               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
3975                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
3976               ex.X_op = O_constant;
3977               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
3978                            reg, reg, BFD_RELOC_LO16);
3979             }
3980         }
3981     }
3982   else if (mips_big_got)
3983     {
3984       expressionS ex;
3985
3986       /* This is the large GOT case.  If this is a reference to an
3987          external symbol, we want
3988            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
3989            addu         $reg,$reg,$gp
3990            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
3991
3992          Otherwise, for a reference to a local symbol in old ABI, we want
3993            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
3994            nop
3995            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
3996          If there is a constant, it must be added in after.
3997
3998          In the NewABI, for local symbols, with or without offsets, we want:
3999            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
4000            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
4001       */
4002       if (HAVE_NEWABI)
4003         {
4004           ex.X_add_number = ep->X_add_number;
4005           ep->X_add_number = 0;
4006           relax_start (ep->X_add_symbol);
4007           macro_build (ep, "lui", "t,u", reg, BFD_RELOC_MIPS_GOT_HI16);
4008           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
4009                        reg, reg, mips_gp_register);
4010           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
4011                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
4012           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
4013             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
4014           else if (ex.X_add_number)
4015             {
4016               ex.X_op = O_constant;
4017               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
4018                            BFD_RELOC_LO16);
4019             }
4020
4021           ep->X_add_number = ex.X_add_number;
4022           relax_switch ();
4023           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
4024                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
4025           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
4026                        BFD_RELOC_MIPS_GOT_OFST);
4027           relax_end ();
4028         }
4029       else
4030         {
4031           ex.X_add_number = ep->X_add_number;
4032           ep->X_add_number = 0;
4033           relax_start (ep->X_add_symbol);
4034           macro_build (ep, "lui", "t,u", reg, BFD_RELOC_MIPS_GOT_HI16);
4035           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
4036                        reg, reg, mips_gp_register);
4037           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
4038                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
4039           relax_switch ();
4040           if (reg_needs_delay (mips_gp_register))
4041             {
4042               /* We need a nop before loading from $gp.  This special
4043                  check is required because the lui which starts the main
4044                  instruction stream does not refer to $gp, and so will not
4045                  insert the nop which may be required.  */
4046               macro_build (NULL, "nop", "");
4047             }
4048           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
4049                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
4050           load_delay_nop ();
4051           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
4052                        BFD_RELOC_LO16);
4053           relax_end ();
4054
4055           if (ex.X_add_number != 0)
4056             {
4057               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
4058                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
4059               ex.X_op = O_constant;
4060               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
4061                            BFD_RELOC_LO16);
4062             }
4063         }
4064     }
4065   else
4066     abort ();
4067
4068   if (mips_opts.noat && *used_at == 1)
4069     as_bad (_("Macro used $at after \".set noat\""));
4070 }
4071
4072 /* Move the contents of register SOURCE into register DEST.  */
4073
4074 static void
4075 move_register (int dest, int source)
4076 {
4077   macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
4078                dest, source, 0);
4079 }
4080
4081 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
4082    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
4083    The two alternatives are:
4084
4085    Global symbol                Local sybmol
4086    -------------                ------------
4087    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
4088    ...                          ...
4089    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
4090
4091    load_got_offset emits the first instruction and add_got_offset
4092    emits the second for a 16-bit offset or add_got_offset_hilo emits
4093    a sequence to add a 32-bit offset using a scratch register.  */
4094
4095 static void
4096 load_got_offset (int dest, expressionS *local)
4097 {
4098   expressionS global;
4099
4100   global = *local;
4101   global.X_add_number = 0;
4102
4103   relax_start (local->X_add_symbol);
4104   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
4105                BFD_RELOC_MIPS_GOT16, mips_gp_register);
4106   relax_switch ();
4107   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
4108                BFD_RELOC_MIPS_GOT16, mips_gp_register);
4109   relax_end ();
4110 }
4111
4112 static void
4113 add_got_offset (int dest, expressionS *local)
4114 {
4115   expressionS global;
4116
4117   global.X_op = O_constant;
4118   global.X_op_symbol = NULL;
4119   global.X_add_symbol = NULL;
4120   global.X_add_number = local->X_add_number;
4121
4122   relax_start (local->X_add_symbol);
4123   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
4124                dest, dest, BFD_RELOC_LO16);
4125   relax_switch ();
4126   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
4127   relax_end ();
4128 }
4129
4130 static void
4131 add_got_offset_hilo (int dest, expressionS *local, int tmp)
4132 {
4133   expressionS global;
4134   int hold_mips_optimize;
4135
4136   global.X_op = O_constant;
4137   global.X_op_symbol = NULL;
4138   global.X_add_symbol = NULL;
4139   global.X_add_number = local->X_add_number;
4140
4141   relax_start (local->X_add_symbol);
4142   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
4143   relax_switch ();
4144   /* Set mips_optimize around the lui instruction to avoid
4145      inserting an unnecessary nop after the lw.  */
4146   hold_mips_optimize = mips_optimize;
4147   mips_optimize = 2;
4148   macro_build_lui (&global, tmp);
4149   mips_optimize = hold_mips_optimize;
4150   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
4151   relax_end ();
4152
4153   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
4154 }
4155
4156 /*
4157  *                      Build macros
4158  *   This routine implements the seemingly endless macro or synthesized
4159  * instructions and addressing modes in the mips assembly language. Many
4160  * of these macros are simple and are similar to each other. These could
4161  * probably be handled by some kind of table or grammar approach instead of
4162  * this verbose method. Others are not simple macros but are more like
4163  * optimizing code generation.
4164  *   One interesting optimization is when several store macros appear
4165  * consecutively that would load AT with the upper half of the same address.
4166  * The ensuing load upper instructions are ommited. This implies some kind
4167  * of global optimization. We currently only optimize within a single macro.
4168  *   For many of the load and store macros if the address is specified as a
4169  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
4170  * first load register 'at' with zero and use it as the base register. The
4171  * mips assembler simply uses register $zero. Just one tiny optimization
4172  * we're missing.
4173  */
4174 static void
4175 macro (struct mips_cl_insn *ip)
4176 {
4177   register int treg, sreg, dreg, breg;
4178   int tempreg;
4179   int mask;
4180   int used_at = 0;
4181   expressionS expr1;
4182   const char *s;
4183   const char *s2;
4184   const char *fmt;
4185   int likely = 0;
4186   int dbl = 0;
4187   int coproc = 0;
4188   int lr = 0;
4189   int imm = 0;
4190   int call = 0;
4191   int off;
4192   offsetT maxnum;
4193   bfd_reloc_code_real_type r;
4194   int hold_mips_optimize;
4195
4196   assert (! mips_opts.mips16);
4197
4198   treg = (ip->insn_opcode >> 16) & 0x1f;
4199   dreg = (ip->insn_opcode >> 11) & 0x1f;
4200   sreg = breg = (ip->insn_opcode >> 21) & 0x1f;
4201   mask = ip->insn_mo->mask;
4202
4203   expr1.X_op = O_constant;
4204   expr1.X_op_symbol = NULL;
4205   expr1.X_add_symbol = NULL;
4206   expr1.X_add_number = 1;
4207
4208   switch (mask)
4209     {
4210     case M_DABS:
4211       dbl = 1;
4212     case M_ABS:
4213       /* bgez $a0,.+12
4214          move v0,$a0
4215          sub v0,$zero,$a0
4216          */
4217
4218       start_noreorder ();
4219
4220       expr1.X_add_number = 8;
4221       macro_build (&expr1, "bgez", "s,p", sreg);
4222       if (dreg == sreg)
4223         macro_build (NULL, "nop", "", 0);
4224       else
4225         move_register (dreg, sreg);
4226       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", dreg, 0, sreg);
4227
4228       end_noreorder ();
4229       break;
4230
4231     case M_ADD_I:
4232       s = "addi";
4233       s2 = "add";
4234       goto do_addi;
4235     case M_ADDU_I:
4236       s = "addiu";
4237       s2 = "addu";
4238       goto do_addi;
4239     case M_DADD_I:
4240       dbl = 1;
4241       s = "daddi";
4242       s2 = "dadd";
4243       goto do_addi;
4244     case M_DADDU_I:
4245       dbl = 1;
4246       s = "daddiu";
4247       s2 = "daddu";
4248     do_addi:
4249       if (imm_expr.X_op == O_constant
4250           && imm_expr.X_add_number >= -0x8000
4251           && imm_expr.X_add_number < 0x8000)
4252         {
4253           macro_build (&imm_expr, s, "t,r,j", treg, sreg, BFD_RELOC_LO16);
4254           break;
4255         }
4256       used_at = 1;
4257       load_register (AT, &imm_expr, dbl);
4258       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
4259       break;
4260
4261     case M_AND_I:
4262       s = "andi";
4263       s2 = "and";
4264       goto do_bit;
4265     case M_OR_I:
4266       s = "ori";
4267       s2 = "or";
4268       goto do_bit;
4269     case M_NOR_I:
4270       s = "";
4271       s2 = "nor";
4272       goto do_bit;
4273     case M_XOR_I:
4274       s = "xori";
4275       s2 = "xor";
4276     do_bit:
4277       if (imm_expr.X_op == O_constant
4278           && imm_expr.X_add_number >= 0
4279           && imm_expr.X_add_number < 0x10000)
4280         {
4281           if (mask != M_NOR_I)
4282             macro_build (&imm_expr, s, "t,r,i", treg, sreg, BFD_RELOC_LO16);
4283           else
4284             {
4285               macro_build (&imm_expr, "ori", "t,r,i",
4286                            treg, sreg, BFD_RELOC_LO16);
4287               macro_build (NULL, "nor", "d,v,t", treg, treg, 0);
4288             }
4289           break;
4290         }
4291
4292       used_at = 1;
4293       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
4294       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
4295       break;
4296
4297     case M_BEQ_I:
4298       s = "beq";
4299       goto beq_i;
4300     case M_BEQL_I:
4301       s = "beql";
4302       likely = 1;
4303       goto beq_i;
4304     case M_BNE_I:
4305       s = "bne";
4306       goto beq_i;
4307     case M_BNEL_I:
4308       s = "bnel";
4309       likely = 1;
4310     beq_i:
4311       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
4312         {
4313           macro_build (&offset_expr, s, "s,t,p", sreg, 0);
4314           break;
4315         }
4316       used_at = 1;
4317       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
4318       macro_build (&offset_expr, s, "s,t,p", sreg, AT);
4319       break;
4320
4321     case M_BGEL:
4322       likely = 1;
4323     case M_BGE:
4324       if (treg == 0)
4325         {
4326           macro_build (&offset_expr, likely ? "bgezl" : "bgez", "s,p", sreg);
4327           break;
4328         }
4329       if (sreg == 0)
4330         {
4331           macro_build (&offset_expr, likely ? "blezl" : "blez", "s,p", treg);
4332           break;
4333         }
4334       used_at = 1;
4335       macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
4336       macro_build (&offset_expr, likely ? "beql" : "beq", "s,t,p", AT, 0);
4337       break;
4338
4339     case M_BGTL_I:
4340       likely = 1;
4341     case M_BGT_I:
4342       /* check for > max integer */
4343       maxnum = 0x7fffffff;
4344       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
4345         {
4346           maxnum <<= 16;
4347           maxnum |= 0xffff;
4348           maxnum <<= 16;
4349           maxnum |= 0xffff;
4350         }
4351       if (imm_expr.X_op == O_constant
4352           && imm_expr.X_add_number >= maxnum
4353           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
4354         {
4355         do_false:
4356           /* result is always false */
4357           if (! likely)
4358             macro_build (NULL, "nop", "", 0);
4359           else
4360             macro_build (&offset_expr, "bnel", "s,t,p", 0, 0);
4361           break;
4362         }
4363       if (imm_expr.X_op != O_constant)
4364         as_bad (_("Unsupported large constant"));
4365       ++imm_expr.X_add_number;
4366       /* FALLTHROUGH */
4367     case M_BGE_I:
4368     case M_BGEL_I:
4369       if (mask == M_BGEL_I)
4370         likely = 1;
4371       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
4372         {
4373           macro_build (&offset_expr, likely ? "bgezl" : "bgez", "s,p", sreg);
4374           break;
4375         }
4376       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
4377         {
4378           macro_build (&offset_expr, likely ? "bgtzl" : "bgtz", "s,p", sreg);
4379           break;
4380         }
4381       maxnum = 0x7fffffff;
4382       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
4383         {
4384           maxnum <<= 16;
4385           maxnum |= 0xffff;
4386           maxnum <<= 16;
4387           maxnum |= 0xffff;
4388         }
4389       maxnum = - maxnum - 1;
4390       if (imm_expr.X_op == O_constant
4391           && imm_expr.X_add_number <= maxnum
4392           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
4393         {
4394         do_true:
4395           /* result is always true */
4396           as_warn (_("Branch %s is always true"), ip->insn_mo->name);
4397           macro_build (&offset_expr, "b", "p");
4398           break;
4399         }
4400       used_at = 1;
4401       set_at (sreg, 0);
4402       macro_build (&offset_expr, likely ? "beql" : "beq", "s,t,p", AT, 0);
4403       break;
4404
4405     case M_BGEUL:
4406       likely = 1;
4407     case M_BGEU:
4408       if (treg == 0)
4409         goto do_true;
4410       if (sreg == 0)
4411         {
4412           macro_build (&offset_expr, likely ? "beql" : "beq",
4413                        "s,t,p", 0, treg);
4414           break;
4415         }
4416       used_at = 1;
4417       macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
4418       macro_build (&offset_expr, likely ? "beql" : "beq", "s,t,p", AT, 0);
4419       break;
4420
4421     case M_BGTUL_I:
4422       likely = 1;
4423     case M_BGTU_I:
4424       if (sreg == 0
4425           || (HAVE_32BIT_GPRS
4426               && imm_expr.X_op == O_constant
4427               && imm_expr.X_add_number == (offsetT) 0xffffffff))
4428         goto do_false;
4429       if (imm_expr.X_op != O_constant)
4430         as_bad (_("Unsupported large constant"));
4431       ++imm_expr.X_add_number;
4432       /* FALLTHROUGH */
4433     case M_BGEU_I:
4434     case M_BGEUL_I:
4435       if (mask == M_BGEUL_I)
4436         likely = 1;
4437       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
4438         goto do_true;
4439       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
4440         {
4441           macro_build (&offset_expr, likely ? "bnel" : "bne",
4442                        "s,t,p", sreg, 0);
4443           break;
4444         }
4445       used_at = 1;
4446       set_at (sreg, 1);
4447       macro_build (&offset_expr, likely ? "beql" : "beq", "s,t,p", AT, 0);
4448       break;
4449
4450     case M_BGTL:
4451       likely = 1;
4452     case M_BGT:
4453       if (treg == 0)
4454         {
4455           macro_build (&offset_expr, likely ? "bgtzl" : "bgtz", "s,p", sreg);
4456           break;
4457         }
4458       if (sreg == 0)
4459         {
4460           macro_build (&offset_expr, likely ? "bltzl" : "bltz", "s,p", treg);
4461           break;
4462         }
4463       used_at = 1;
4464       macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
4465       macro_build (&offset_expr, likely ? "bnel" : "bne", "s,t,p", AT, 0);
4466       break;
4467
4468     case M_BGTUL:
4469       likely = 1;
4470     case M_BGTU:
4471       if (treg == 0)
4472         {
4473           macro_build (&offset_expr, likely ? "bnel" : "bne",
4474                        "s,t,p", sreg, 0);
4475           break;
4476         }
4477       if (sreg == 0)
4478         goto do_false;
4479       used_at = 1;
4480       macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
4481       macro_build (&offset_expr, likely ? "bnel" : "bne", "s,t,p", AT, 0);
4482       break;
4483
4484     case M_BLEL:
4485       likely = 1;
4486     case M_BLE:
4487       if (treg == 0)
4488         {
4489           macro_build (&offset_expr, likely ? "blezl" : "blez", "s,p", sreg);
4490           break;
4491         }
4492       if (sreg == 0)
4493         {
4494           macro_build (&offset_expr, likely ? "bgezl" : "bgez", "s,p", treg);
4495           break;
4496         }
4497       used_at = 1;
4498       macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
4499       macro_build (&offset_expr, likely ? "beql" : "beq", "s,t,p", AT, 0);
4500       break;
4501
4502     case M_BLEL_I:
4503       likely = 1;
4504     case M_BLE_I:
4505       maxnum = 0x7fffffff;
4506       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
4507         {
4508           maxnum <<= 16;
4509           maxnum |= 0xffff;
4510           maxnum <<= 16;
4511           maxnum |= 0xffff;
4512         }
4513       if (imm_expr.X_op == O_constant
4514           && imm_expr.X_add_number >= maxnum
4515           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
4516         goto do_true;
4517       if (imm_expr.X_op != O_constant)
4518         as_bad (_("Unsupported large constant"));
4519       ++imm_expr.X_add_number;
4520       /* FALLTHROUGH */
4521     case M_BLT_I:
4522     case M_BLTL_I:
4523       if (mask == M_BLTL_I)
4524         likely = 1;
4525       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
4526         {
4527           macro_build (&offset_expr, likely ? "bltzl" : "bltz", "s,p", sreg);
4528           break;
4529         }
4530       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
4531         {
4532           macro_build (&offset_expr, likely ? "blezl" : "blez", "s,p", sreg);
4533           break;
4534         }
4535       used_at = 1;
4536       set_at (sreg, 0);
4537       macro_build (&offset_expr, likely ? "bnel" : "bne", "s,t,p", AT, 0);
4538       break;
4539
4540     case M_BLEUL:
4541       likely = 1;
4542     case M_BLEU:
4543       if (treg == 0)
4544         {
4545           macro_build (&offset_expr, likely ? "beql" : "beq",
4546                        "s,t,p", sreg, 0);
4547           break;
4548         }
4549       if (sreg == 0)
4550         goto do_true;
4551       used_at = 1;
4552       macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
4553       macro_build (&offset_expr, likely ? "beql" : "beq", "s,t,p", AT, 0);
4554       break;
4555
4556     case M_BLEUL_I:
4557       likely = 1;
4558     case M_BLEU_I:
4559       if (sreg == 0
4560           || (HAVE_32BIT_GPRS
4561               && imm_expr.X_op == O_constant
4562               && imm_expr.X_add_number == (offsetT) 0xffffffff))
4563         goto do_true;
4564       if (imm_expr.X_op != O_constant)
4565         as_bad (_("Unsupported large constant"));
4566       ++imm_expr.X_add_number;
4567       /* FALLTHROUGH */
4568     case M_BLTU_I:
4569     case M_BLTUL_I:
4570       if (mask == M_BLTUL_I)
4571         likely = 1;
4572       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
4573         goto do_false;
4574       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
4575         {
4576           macro_build (&offset_expr, likely ? "beql" : "beq",
4577                        "s,t,p", sreg, 0);
4578           break;
4579         }
4580       used_at = 1;
4581       set_at (sreg, 1);
4582       macro_build (&offset_expr, likely ? "bnel" : "bne", "s,t,p", AT, 0);
4583       break;
4584
4585     case M_BLTL:
4586       likely = 1;
4587     case M_BLT:
4588       if (treg == 0)
4589         {
4590           macro_build (&offset_expr, likely ? "bltzl" : "bltz", "s,p", sreg);
4591           break;
4592         }
4593       if (sreg == 0)
4594         {
4595           macro_build (&offset_expr, likely ? "bgtzl" : "bgtz", "s,p", treg);
4596           break;
4597         }
4598       used_at = 1;
4599       macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
4600       macro_build (&offset_expr, likely ? "bnel" : "bne", "s,t,p", AT, 0);
4601       break;
4602
4603     case M_BLTUL:
4604       likely = 1;
4605     case M_BLTU:
4606       if (treg == 0)
4607         goto do_false;
4608       if (sreg == 0)
4609         {
4610           macro_build (&offset_expr, likely ? "bnel" : "bne",
4611                        "s,t,p", 0, treg);
4612           break;
4613         }
4614       used_at = 1;
4615       macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
4616       macro_build (&offset_expr, likely ? "bnel" : "bne", "s,t,p", AT, 0);
4617       break;
4618
4619     case M_DEXT:
4620       {
4621         unsigned long pos;
4622         unsigned long size;
4623
4624         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
4625           {
4626             as_bad (_("Unsupported large constant"));
4627             pos = size = 1;
4628           }
4629         else
4630           {
4631             pos = (unsigned long) imm_expr.X_add_number;
4632             size = (unsigned long) imm2_expr.X_add_number;
4633           }
4634
4635         if (pos > 63)
4636           {
4637             as_bad (_("Improper position (%lu)"), pos);
4638             pos = 1;
4639           }
4640         if (size == 0 || size > 64
4641             || (pos + size - 1) > 63)
4642           {
4643             as_bad (_("Improper extract size (%lu, position %lu)"),
4644                     size, pos);
4645             size = 1;
4646           }
4647
4648         if (size <= 32 && pos < 32)
4649           {
4650             s = "dext";
4651             fmt = "t,r,+A,+C";
4652           }
4653         else if (size <= 32)
4654           {
4655             s = "dextu";
4656             fmt = "t,r,+E,+H";
4657           }
4658         else
4659           {
4660             s = "dextm";
4661             fmt = "t,r,+A,+G";
4662           }
4663         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, pos, size - 1);
4664       }
4665       break;
4666
4667     case M_DINS:
4668       {
4669         unsigned long pos;
4670         unsigned long size;
4671
4672         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
4673           {
4674             as_bad (_("Unsupported large constant"));
4675             pos = size = 1;
4676           }
4677         else
4678           {
4679             pos = (unsigned long) imm_expr.X_add_number;
4680             size = (unsigned long) imm2_expr.X_add_number;
4681           }
4682
4683         if (pos > 63)
4684           {
4685             as_bad (_("Improper position (%lu)"), pos);
4686             pos = 1;
4687           }
4688         if (size == 0 || size > 64
4689             || (pos + size - 1) > 63)
4690           {
4691             as_bad (_("Improper insert size (%lu, position %lu)"),
4692                     size, pos);
4693             size = 1;
4694           }
4695
4696         if (pos < 32 && (pos + size - 1) < 32)
4697           {
4698             s = "dins";
4699             fmt = "t,r,+A,+B";
4700           }
4701         else if (pos >= 32)
4702           {
4703             s = "dinsu";
4704             fmt = "t,r,+E,+F";
4705           }
4706         else
4707           {
4708             s = "dinsm";
4709             fmt = "t,r,+A,+F";
4710           }
4711         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, pos,
4712                      pos + size - 1);
4713       }
4714       break;
4715
4716     case M_DDIV_3:
4717       dbl = 1;
4718     case M_DIV_3:
4719       s = "mflo";
4720       goto do_div3;
4721     case M_DREM_3:
4722       dbl = 1;
4723     case M_REM_3:
4724       s = "mfhi";
4725     do_div3:
4726       if (treg == 0)
4727         {
4728           as_warn (_("Divide by zero."));
4729           if (mips_trap)
4730             macro_build (NULL, "teq", "s,t,q", 0, 0, 7);
4731           else
4732             macro_build (NULL, "break", "c", 7);
4733           break;
4734         }
4735
4736       start_noreorder ();
4737       if (mips_trap)
4738         {
4739           macro_build (NULL, "teq", "s,t,q", treg, 0, 7);
4740           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
4741         }
4742       else
4743         {
4744           expr1.X_add_number = 8;
4745           macro_build (&expr1, "bne", "s,t,p", treg, 0);
4746           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
4747           macro_build (NULL, "break", "c", 7);
4748         }
4749       expr1.X_add_number = -1;
4750       used_at = 1;
4751       load_register (AT, &expr1, dbl);
4752       expr1.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
4753       macro_build (&expr1, "bne", "s,t,p", treg, AT);
4754       if (dbl)
4755         {
4756           expr1.X_add_number = 1;
4757           load_register (AT, &expr1, dbl);
4758           macro_build (NULL, "dsll32", "d,w,<", AT, AT, 31);
4759         }
4760       else
4761         {
4762           expr1.X_add_number = 0x80000000;
4763           macro_build (&expr1, "lui", "t,u", AT, BFD_RELOC_HI16);
4764         }
4765       if (mips_trap)
4766         {
4767           macro_build (NULL, "teq", "s,t,q", sreg, AT, 6);
4768           /* We want to close the noreorder block as soon as possible, so
4769              that later insns are available for delay slot filling.  */
4770           end_noreorder ();
4771         }
4772       else
4773         {
4774           expr1.X_add_number = 8;
4775           macro_build (&expr1, "bne", "s,t,p", sreg, AT);
4776           macro_build (NULL, "nop", "", 0);
4777
4778           /* We want to close the noreorder block as soon as possible, so
4779              that later insns are available for delay slot filling.  */
4780           end_noreorder ();
4781
4782           macro_build (NULL, "break", "c", 6);
4783         }
4784       macro_build (NULL, s, "d", dreg);
4785       break;
4786
4787     case M_DIV_3I:
4788       s = "div";
4789       s2 = "mflo";
4790       goto do_divi;
4791     case M_DIVU_3I:
4792       s = "divu";
4793       s2 = "mflo";
4794       goto do_divi;
4795     case M_REM_3I:
4796       s = "div";
4797       s2 = "mfhi";
4798       goto do_divi;
4799     case M_REMU_3I:
4800       s = "divu";
4801       s2 = "mfhi";
4802       goto do_divi;
4803     case M_DDIV_3I:
4804       dbl = 1;
4805       s = "ddiv";
4806       s2 = "mflo";
4807       goto do_divi;
4808     case M_DDIVU_3I:
4809       dbl = 1;
4810       s = "ddivu";
4811       s2 = "mflo";
4812       goto do_divi;
4813     case M_DREM_3I:
4814       dbl = 1;
4815       s = "ddiv";
4816       s2 = "mfhi";
4817       goto do_divi;
4818     case M_DREMU_3I:
4819       dbl = 1;
4820       s = "ddivu";
4821       s2 = "mfhi";
4822     do_divi:
4823       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
4824         {
4825           as_warn (_("Divide by zero."));
4826           if (mips_trap)
4827             macro_build (NULL, "teq", "s,t,q", 0, 0, 7);
4828           else
4829             macro_build (NULL, "break", "c", 7);
4830           break;
4831         }
4832       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
4833         {
4834           if (strcmp (s2, "mflo") == 0)
4835             move_register (dreg, sreg);
4836           else
4837             move_register (dreg, 0);
4838           break;
4839         }
4840       if (imm_expr.X_op == O_constant
4841           && imm_expr.X_add_number == -1
4842           && s[strlen (s) - 1] != 'u')
4843         {
4844           if (strcmp (s2, "mflo") == 0)
4845             {
4846               macro_build (NULL, dbl ? "dneg" : "neg", "d,w", dreg, sreg);
4847             }
4848           else
4849             move_register (dreg, 0);
4850           break;
4851         }
4852
4853       used_at = 1;
4854       load_register (AT, &imm_expr, dbl);
4855       macro_build (NULL, s, "z,s,t", sreg, AT);
4856       macro_build (NULL, s2, "d", dreg);
4857       break;
4858
4859     case M_DIVU_3:
4860       s = "divu";
4861       s2 = "mflo";
4862       goto do_divu3;
4863     case M_REMU_3:
4864       s = "divu";
4865       s2 = "mfhi";
4866       goto do_divu3;
4867     case M_DDIVU_3:
4868       s = "ddivu";
4869       s2 = "mflo";
4870       goto do_divu3;
4871     case M_DREMU_3:
4872       s = "ddivu";
4873       s2 = "mfhi";
4874     do_divu3:
4875       start_noreorder ();
4876       if (mips_trap)
4877         {
4878           macro_build (NULL, "teq", "s,t,q", treg, 0, 7);
4879           macro_build (NULL, s, "z,s,t", sreg, treg);
4880           /* We want to close the noreorder block as soon as possible, so
4881              that later insns are available for delay slot filling.  */
4882           end_noreorder ();
4883         }
4884       else
4885         {
4886           expr1.X_add_number = 8;
4887           macro_build (&expr1, "bne", "s,t,p", treg, 0);
4888           macro_build (NULL, s, "z,s,t", sreg, treg);
4889
4890           /* We want to close the noreorder block as soon as possible, so
4891              that later insns are available for delay slot filling.  */
4892           end_noreorder ();
4893           macro_build (NULL, "break", "c", 7);
4894         }
4895       macro_build (NULL, s2, "d", dreg);
4896       break;
4897
4898     case M_DLCA_AB:
4899       dbl = 1;
4900     case M_LCA_AB:
4901       call = 1;
4902       goto do_la;
4903     case M_DLA_AB:
4904       dbl = 1;
4905     case M_LA_AB:
4906     do_la:
4907       /* Load the address of a symbol into a register.  If breg is not
4908          zero, we then add a base register to it.  */
4909
4910       if (dbl && HAVE_32BIT_GPRS)
4911         as_warn (_("dla used to load 32-bit register"));
4912
4913       if (! dbl && HAVE_64BIT_OBJECTS)
4914         as_warn (_("la used to load 64-bit address"));
4915
4916       if (offset_expr.X_op == O_constant
4917           && offset_expr.X_add_number >= -0x8000
4918           && offset_expr.X_add_number < 0x8000)
4919         {
4920           macro_build (&offset_expr, ADDRESS_ADDI_INSN,
4921                        "t,r,j", treg, sreg, BFD_RELOC_LO16);
4922           break;
4923         }
4924
4925       if (!mips_opts.noat && (treg == breg))
4926         {
4927           tempreg = AT;
4928           used_at = 1;
4929         }
4930       else
4931         {
4932           tempreg = treg;
4933         }
4934
4935       if (offset_expr.X_op != O_symbol
4936           && offset_expr.X_op != O_constant)
4937         {
4938           as_bad (_("expression too complex"));
4939           offset_expr.X_op = O_constant;
4940         }
4941
4942       if (offset_expr.X_op == O_constant)
4943         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
4944       else if (mips_pic == NO_PIC)
4945         {
4946           /* If this is a reference to a GP relative symbol, we want
4947                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
4948              Otherwise we want
4949                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
4950                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
4951              If we have a constant, we need two instructions anyhow,
4952              so we may as well always use the latter form.
4953
4954              With 64bit address space and a usable $at we want
4955                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
4956                lui      $at,<sym>               (BFD_RELOC_HI16_S)
4957                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
4958                daddiu   $at,<sym>               (BFD_RELOC_LO16)
4959                dsll32   $tempreg,0
4960                daddu    $tempreg,$tempreg,$at
4961
4962              If $at is already in use, we use a path which is suboptimal
4963              on superscalar processors.
4964                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
4965                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
4966                dsll     $tempreg,16
4967                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
4968                dsll     $tempreg,16
4969                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
4970
4971              For GP relative symbols in 64bit address space we can use
4972              the same sequence as in 32bit address space.  */
4973           if (HAVE_64BIT_SYMBOLS)
4974             {
4975               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
4976                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
4977                 {
4978                   relax_start (offset_expr.X_add_symbol);
4979                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
4980                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
4981                   relax_switch ();
4982                 }
4983
4984               if (used_at == 0 && !mips_opts.noat)
4985                 {
4986                   macro_build (&offset_expr, "lui", "t,u",
4987                                tempreg, BFD_RELOC_MIPS_HIGHEST);
4988                   macro_build (&offset_expr, "lui", "t,u",
4989                                AT, BFD_RELOC_HI16_S);
4990                   macro_build (&offset_expr, "daddiu", "t,r,j",
4991                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
4992                   macro_build (&offset_expr, "daddiu", "t,r,j",
4993                                AT, AT, BFD_RELOC_LO16);
4994                   macro_build (NULL, "dsll32", "d,w,<", tempreg, tempreg, 0);
4995                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
4996                   used_at = 1;
4997                 }
4998               else
4999                 {
5000                   macro_build (&offset_expr, "lui", "t,u",
5001                                tempreg, BFD_RELOC_MIPS_HIGHEST);
5002                   macro_build (&offset_expr, "daddiu", "t,r,j",
5003                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
5004                   macro_build (NULL, "dsll", "d,w,<", tempreg, tempreg, 16);
5005                   macro_build (&offset_expr, "daddiu", "t,r,j",
5006                                tempreg, tempreg, BFD_RELOC_HI16_S);
5007                   macro_build (NULL, "dsll", "d,w,<", tempreg, tempreg, 16);
5008                   macro_build (&offset_expr, "daddiu", "t,r,j",
5009                                tempreg, tempreg, BFD_RELOC_LO16);
5010                 }
5011
5012               if (mips_relax.sequence)
5013                 relax_end ();
5014             }
5015           else
5016             {
5017               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
5018                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
5019                 {
5020                   relax_start (offset_expr.X_add_symbol);
5021                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
5022                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
5023                   relax_switch ();
5024                 }
5025               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
5026                 as_bad (_("offset too large"));
5027               macro_build_lui (&offset_expr, tempreg);
5028               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
5029                            tempreg, tempreg, BFD_RELOC_LO16);
5030               if (mips_relax.sequence)
5031                 relax_end ();
5032             }
5033         }
5034       else if (!mips_big_got && !HAVE_NEWABI)
5035         {
5036           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
5037
5038           /* If this is a reference to an external symbol, and there
5039              is no constant, we want
5040                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5041              or for lca or if tempreg is PIC_CALL_REG
5042                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
5043              For a local symbol, we want
5044                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5045                nop
5046                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
5047
5048              If we have a small constant, and this is a reference to
5049              an external symbol, we want
5050                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5051                nop
5052                addiu    $tempreg,$tempreg,<constant>
5053              For a local symbol, we want the same instruction
5054              sequence, but we output a BFD_RELOC_LO16 reloc on the
5055              addiu instruction.
5056
5057              If we have a large constant, and this is a reference to
5058              an external symbol, we want
5059                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5060                lui      $at,<hiconstant>
5061                addiu    $at,$at,<loconstant>
5062                addu     $tempreg,$tempreg,$at
5063              For a local symbol, we want the same instruction
5064              sequence, but we output a BFD_RELOC_LO16 reloc on the
5065              addiu instruction.
5066            */
5067
5068           if (offset_expr.X_add_number == 0)
5069             {
5070               if (mips_pic == SVR4_PIC
5071                   && breg == 0
5072                   && (call || tempreg == PIC_CALL_REG))
5073                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
5074
5075               relax_start (offset_expr.X_add_symbol);
5076               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5077                            lw_reloc_type, mips_gp_register);
5078               if (breg != 0)
5079                 {
5080                   /* We're going to put in an addu instruction using
5081                      tempreg, so we may as well insert the nop right
5082                      now.  */
5083                   load_delay_nop ();
5084                 }
5085               relax_switch ();
5086               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5087                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
5088               load_delay_nop ();
5089               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
5090                            tempreg, tempreg, BFD_RELOC_LO16);
5091               relax_end ();
5092               /* FIXME: If breg == 0, and the next instruction uses
5093                  $tempreg, then if this variant case is used an extra
5094                  nop will be generated.  */
5095             }
5096           else if (offset_expr.X_add_number >= -0x8000
5097                    && offset_expr.X_add_number < 0x8000)
5098             {
5099               load_got_offset (tempreg, &offset_expr);
5100               load_delay_nop ();
5101               add_got_offset (tempreg, &offset_expr);
5102             }
5103           else
5104             {
5105               expr1.X_add_number = offset_expr.X_add_number;
5106               offset_expr.X_add_number =
5107                 ((offset_expr.X_add_number + 0x8000) & 0xffff) - 0x8000;
5108               load_got_offset (tempreg, &offset_expr);
5109               offset_expr.X_add_number = expr1.X_add_number;
5110               /* If we are going to add in a base register, and the
5111                  target register and the base register are the same,
5112                  then we are using AT as a temporary register.  Since
5113                  we want to load the constant into AT, we add our
5114                  current AT (from the global offset table) and the
5115                  register into the register now, and pretend we were
5116                  not using a base register.  */
5117               if (breg == treg)
5118                 {
5119                   load_delay_nop ();
5120                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5121                                treg, AT, breg);
5122                   breg = 0;
5123                   tempreg = treg;
5124                 }
5125               add_got_offset_hilo (tempreg, &offset_expr, AT);
5126               used_at = 1;
5127             }
5128         }
5129       else if (!mips_big_got && HAVE_NEWABI)
5130         {
5131           int add_breg_early = 0;
5132
5133           /* If this is a reference to an external, and there is no
5134              constant, or local symbol (*), with or without a
5135              constant, we want
5136                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
5137              or for lca or if tempreg is PIC_CALL_REG
5138                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
5139
5140              If we have a small constant, and this is a reference to
5141              an external symbol, we want
5142                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
5143                addiu    $tempreg,$tempreg,<constant>
5144
5145              If we have a large constant, and this is a reference to
5146              an external symbol, we want
5147                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
5148                lui      $at,<hiconstant>
5149                addiu    $at,$at,<loconstant>
5150                addu     $tempreg,$tempreg,$at
5151
5152              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
5153              local symbols, even though it introduces an additional
5154              instruction.  */
5155
5156           if (offset_expr.X_add_number)
5157             {
5158               expr1.X_add_number = offset_expr.X_add_number;
5159               offset_expr.X_add_number = 0;
5160
5161               relax_start (offset_expr.X_add_symbol);
5162               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5163                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
5164
5165               if (expr1.X_add_number >= -0x8000
5166                   && expr1.X_add_number < 0x8000)
5167                 {
5168                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
5169                                tempreg, tempreg, BFD_RELOC_LO16);
5170                 }
5171               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
5172                 {
5173                   int dreg;
5174
5175                   /* If we are going to add in a base register, and the
5176                      target register and the base register are the same,
5177                      then we are using AT as a temporary register.  Since
5178                      we want to load the constant into AT, we add our
5179                      current AT (from the global offset table) and the
5180                      register into the register now, and pretend we were
5181                      not using a base register.  */
5182                   if (breg != treg)
5183                     dreg = tempreg;
5184                   else
5185                     {
5186                       assert (tempreg == AT);
5187                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5188                                    treg, AT, breg);
5189                       dreg = treg;
5190                       add_breg_early = 1;
5191                     }
5192
5193                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
5194                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5195                                dreg, dreg, AT);
5196
5197                   used_at = 1;
5198                 }
5199               else
5200                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
5201
5202               relax_switch ();
5203               offset_expr.X_add_number = expr1.X_add_number;
5204
5205               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5206                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
5207               if (add_breg_early)
5208                 {
5209                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5210                                treg, tempreg, breg);
5211                   breg = 0;
5212                   tempreg = treg;
5213                 }
5214               relax_end ();
5215             }
5216           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
5217             {
5218               relax_start (offset_expr.X_add_symbol);
5219               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5220                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
5221               relax_switch ();
5222               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5223                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
5224               relax_end ();
5225             }
5226           else
5227             {
5228               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5229                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
5230             }
5231         }
5232       else if (mips_big_got && !HAVE_NEWABI)
5233         {
5234           int gpdelay;
5235           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
5236           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
5237           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
5238
5239           /* This is the large GOT case.  If this is a reference to an
5240              external symbol, and there is no constant, we want
5241                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
5242                addu     $tempreg,$tempreg,$gp
5243                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
5244              or for lca or if tempreg is PIC_CALL_REG
5245                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
5246                addu     $tempreg,$tempreg,$gp
5247                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
5248              For a local symbol, we want
5249                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5250                nop
5251                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
5252
5253              If we have a small constant, and this is a reference to
5254              an external symbol, we want
5255                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
5256                addu     $tempreg,$tempreg,$gp
5257                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
5258                nop
5259                addiu    $tempreg,$tempreg,<constant>
5260              For a local symbol, we want
5261                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5262                nop
5263                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
5264
5265              If we have a large constant, and this is a reference to
5266              an external symbol, we want
5267                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
5268                addu     $tempreg,$tempreg,$gp
5269                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
5270                lui      $at,<hiconstant>
5271                addiu    $at,$at,<loconstant>
5272                addu     $tempreg,$tempreg,$at
5273              For a local symbol, we want
5274                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5275                lui      $at,<hiconstant>
5276                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
5277                addu     $tempreg,$tempreg,$at
5278           */
5279
5280           expr1.X_add_number = offset_expr.X_add_number;
5281           offset_expr.X_add_number = 0;
5282           relax_start (offset_expr.X_add_symbol);
5283           gpdelay = reg_needs_delay (mips_gp_register);
5284           if (expr1.X_add_number == 0 && breg == 0
5285               && (call || tempreg == PIC_CALL_REG))
5286             {
5287               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
5288               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
5289             }
5290           macro_build (&offset_expr, "lui", "t,u", tempreg, lui_reloc_type);
5291           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5292                        tempreg, tempreg, mips_gp_register);
5293           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5294                        tempreg, lw_reloc_type, tempreg);
5295           if (expr1.X_add_number == 0)
5296             {
5297               if (breg != 0)
5298                 {
5299                   /* We're going to put in an addu instruction using
5300                      tempreg, so we may as well insert the nop right
5301                      now.  */
5302                   load_delay_nop ();
5303                 }
5304             }
5305           else if (expr1.X_add_number >= -0x8000
5306                    && expr1.X_add_number < 0x8000)
5307             {
5308               load_delay_nop ();
5309               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
5310                            tempreg, tempreg, BFD_RELOC_LO16);
5311             }
5312           else
5313             {
5314               int dreg;
5315
5316               /* If we are going to add in a base register, and the
5317                  target register and the base register are the same,
5318                  then we are using AT as a temporary register.  Since
5319                  we want to load the constant into AT, we add our
5320                  current AT (from the global offset table) and the
5321                  register into the register now, and pretend we were
5322                  not using a base register.  */
5323               if (breg != treg)
5324                 dreg = tempreg;
5325               else
5326                 {
5327                   assert (tempreg == AT);
5328                   load_delay_nop ();
5329                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5330                                treg, AT, breg);
5331                   dreg = treg;
5332                 }
5333
5334               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
5335               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
5336
5337               used_at = 1;
5338             }
5339           offset_expr.X_add_number =
5340             ((expr1.X_add_number + 0x8000) & 0xffff) - 0x8000;
5341           relax_switch ();
5342
5343           if (gpdelay)
5344             {
5345               /* This is needed because this instruction uses $gp, but
5346                  the first instruction on the main stream does not.  */
5347               macro_build (NULL, "nop", "");
5348             }
5349
5350           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5351                        local_reloc_type, mips_gp_register);
5352           if (expr1.X_add_number >= -0x8000
5353               && expr1.X_add_number < 0x8000)
5354             {
5355               load_delay_nop ();
5356               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
5357                            tempreg, tempreg, BFD_RELOC_LO16);
5358               /* FIXME: If add_number is 0, and there was no base
5359                  register, the external symbol case ended with a load,
5360                  so if the symbol turns out to not be external, and
5361                  the next instruction uses tempreg, an unnecessary nop
5362                  will be inserted.  */
5363             }
5364           else
5365             {
5366               if (breg == treg)
5367                 {
5368                   /* We must add in the base register now, as in the
5369                      external symbol case.  */
5370                   assert (tempreg == AT);
5371                   load_delay_nop ();
5372                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5373                                treg, AT, breg);
5374                   tempreg = treg;
5375                   /* We set breg to 0 because we have arranged to add
5376                      it in in both cases.  */
5377                   breg = 0;
5378                 }
5379
5380               macro_build_lui (&expr1, AT);
5381               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
5382                            AT, AT, BFD_RELOC_LO16);
5383               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5384                            tempreg, tempreg, AT);
5385               used_at = 1;
5386             }
5387           relax_end ();
5388         }
5389       else if (mips_big_got && HAVE_NEWABI)
5390         {
5391           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
5392           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
5393           int add_breg_early = 0;
5394
5395           /* This is the large GOT case.  If this is a reference to an
5396              external symbol, and there is no constant, we want
5397                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
5398                add      $tempreg,$tempreg,$gp
5399                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
5400              or for lca or if tempreg is PIC_CALL_REG
5401                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
5402                add      $tempreg,$tempreg,$gp
5403                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
5404
5405              If we have a small constant, and this is a reference to
5406              an external symbol, we want
5407                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
5408                add      $tempreg,$tempreg,$gp
5409                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
5410                addi     $tempreg,$tempreg,<constant>
5411
5412              If we have a large constant, and this is a reference to
5413              an external symbol, we want
5414                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
5415                addu     $tempreg,$tempreg,$gp
5416                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
5417                lui      $at,<hiconstant>
5418                addi     $at,$at,<loconstant>
5419                add      $tempreg,$tempreg,$at
5420
5421              If we have NewABI, and we know it's a local symbol, we want
5422                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
5423                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
5424              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
5425
5426           relax_start (offset_expr.X_add_symbol);
5427
5428           expr1.X_add_number = offset_expr.X_add_number;
5429           offset_expr.X_add_number = 0;
5430
5431           if (expr1.X_add_number == 0 && breg == 0
5432               && (call || tempreg == PIC_CALL_REG))
5433             {
5434               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
5435               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
5436             }
5437           macro_build (&offset_expr, "lui", "t,u", tempreg, lui_reloc_type);
5438           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5439                        tempreg, tempreg, mips_gp_register);
5440           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5441                        tempreg, lw_reloc_type, tempreg);
5442
5443           if (expr1.X_add_number == 0)
5444             ;
5445           else if (expr1.X_add_number >= -0x8000
5446                    && expr1.X_add_number < 0x8000)
5447             {
5448               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
5449                            tempreg, tempreg, BFD_RELOC_LO16);
5450             }
5451           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
5452             {
5453               int dreg;
5454
5455               /* If we are going to add in a base register, and the
5456                  target register and the base register are the same,
5457                  then we are using AT as a temporary register.  Since
5458                  we want to load the constant into AT, we add our
5459                  current AT (from the global offset table) and the
5460                  register into the register now, and pretend we were
5461                  not using a base register.  */
5462               if (breg != treg)
5463                 dreg = tempreg;
5464               else
5465                 {
5466                   assert (tempreg == AT);
5467                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5468                                treg, AT, breg);
5469                   dreg = treg;
5470                   add_breg_early = 1;
5471                 }
5472
5473               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
5474               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
5475
5476               used_at = 1;
5477             }
5478           else
5479             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
5480
5481           relax_switch ();
5482           offset_expr.X_add_number = expr1.X_add_number;
5483           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5484                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
5485           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
5486                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
5487           if (add_breg_early)
5488             {
5489               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5490                            treg, tempreg, breg);
5491               breg = 0;
5492               tempreg = treg;
5493             }
5494           relax_end ();
5495         }
5496       else
5497         abort ();
5498
5499       if (breg != 0)
5500         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", treg, tempreg, breg);
5501       break;
5502
5503     case M_J_A:
5504       /* The j instruction may not be used in PIC code, since it
5505          requires an absolute address.  We convert it to a b
5506          instruction.  */
5507       if (mips_pic == NO_PIC)
5508         macro_build (&offset_expr, "j", "a");
5509       else
5510         macro_build (&offset_expr, "b", "p");
5511       break;
5512
5513       /* The jal instructions must be handled as macros because when
5514          generating PIC code they expand to multi-instruction
5515          sequences.  Normally they are simple instructions.  */
5516     case M_JAL_1:
5517       dreg = RA;
5518       /* Fall through.  */
5519     case M_JAL_2:
5520       if (mips_pic == NO_PIC)
5521         macro_build (NULL, "jalr", "d,s", dreg, sreg);
5522       else
5523         {
5524           if (sreg != PIC_CALL_REG)
5525             as_warn (_("MIPS PIC call to register other than $25"));
5526
5527           macro_build (NULL, "jalr", "d,s", dreg, sreg);
5528           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
5529             {
5530               if (mips_cprestore_offset < 0)
5531                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
5532               else
5533                 {
5534                   if (! mips_frame_reg_valid)
5535                     {
5536                       as_warn (_("No .frame pseudo-op used in PIC code"));
5537                       /* Quiet this warning.  */
5538                       mips_frame_reg_valid = 1;
5539                     }
5540                   if (! mips_cprestore_valid)
5541                     {
5542                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
5543                       /* Quiet this warning.  */
5544                       mips_cprestore_valid = 1;
5545                     }
5546                   expr1.X_add_number = mips_cprestore_offset;
5547                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
5548                                                 mips_gp_register,
5549                                                 mips_frame_reg,
5550                                                 HAVE_64BIT_ADDRESSES);
5551                 }
5552             }
5553         }
5554
5555       break;
5556
5557     case M_JAL_A:
5558       if (mips_pic == NO_PIC)
5559         macro_build (&offset_expr, "jal", "a");
5560       else if (mips_pic == SVR4_PIC)
5561         {
5562           /* If this is a reference to an external symbol, and we are
5563              using a small GOT, we want
5564                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
5565                nop
5566                jalr     $ra,$25
5567                nop
5568                lw       $gp,cprestore($sp)
5569              The cprestore value is set using the .cprestore
5570              pseudo-op.  If we are using a big GOT, we want
5571                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
5572                addu     $25,$25,$gp
5573                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
5574                nop
5575                jalr     $ra,$25
5576                nop
5577                lw       $gp,cprestore($sp)
5578              If the symbol is not external, we want
5579                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
5580                nop
5581                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
5582                jalr     $ra,$25
5583                nop
5584                lw $gp,cprestore($sp)
5585
5586              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
5587              sequences above, minus nops, unless the symbol is local,
5588              which enables us to use GOT_PAGE/GOT_OFST (big got) or
5589              GOT_DISP.  */
5590           if (HAVE_NEWABI)
5591             {
5592               if (! mips_big_got)
5593                 {
5594                   relax_start (offset_expr.X_add_symbol);
5595                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5596                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
5597                                mips_gp_register);
5598                   relax_switch ();
5599                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5600                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
5601                                mips_gp_register);
5602                   relax_end ();
5603                 }
5604               else
5605                 {
5606                   relax_start (offset_expr.X_add_symbol);
5607                   macro_build (&offset_expr, "lui", "t,u", PIC_CALL_REG,
5608                                BFD_RELOC_MIPS_CALL_HI16);
5609                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
5610                                PIC_CALL_REG, mips_gp_register);
5611                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5612                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
5613                                PIC_CALL_REG);
5614                   relax_switch ();
5615                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5616                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
5617                                mips_gp_register);
5618                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
5619                                PIC_CALL_REG, PIC_CALL_REG,
5620                                BFD_RELOC_MIPS_GOT_OFST);
5621                   relax_end ();
5622                 }
5623
5624               macro_build_jalr (&offset_expr);
5625             }
5626           else
5627             {
5628               relax_start (offset_expr.X_add_symbol);
5629               if (! mips_big_got)
5630                 {
5631                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5632                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
5633                                mips_gp_register);
5634                   load_delay_nop ();
5635                   relax_switch ();
5636                 }
5637               else
5638                 {
5639                   int gpdelay;
5640
5641                   gpdelay = reg_needs_delay (mips_gp_register);
5642                   macro_build (&offset_expr, "lui", "t,u", PIC_CALL_REG,
5643                                BFD_RELOC_MIPS_CALL_HI16);
5644                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
5645                                PIC_CALL_REG, mips_gp_register);
5646                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5647                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
5648                                PIC_CALL_REG);
5649                   load_delay_nop ();
5650                   relax_switch ();
5651                   if (gpdelay)
5652                     macro_build (NULL, "nop", "");
5653                 }
5654               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5655                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
5656                            mips_gp_register);
5657               load_delay_nop ();
5658               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
5659                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
5660               relax_end ();
5661               macro_build_jalr (&offset_expr);
5662
5663               if (mips_cprestore_offset < 0)
5664                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
5665               else
5666                 {
5667                   if (! mips_frame_reg_valid)
5668                     {
5669                       as_warn (_("No .frame pseudo-op used in PIC code"));
5670                       /* Quiet this warning.  */
5671                       mips_frame_reg_valid = 1;
5672                     }
5673                   if (! mips_cprestore_valid)
5674                     {
5675                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
5676                       /* Quiet this warning.  */
5677                       mips_cprestore_valid = 1;
5678                     }
5679                   if (mips_opts.noreorder)
5680                     macro_build (NULL, "nop", "");
5681                   expr1.X_add_number = mips_cprestore_offset;
5682                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
5683                                                 mips_gp_register,
5684                                                 mips_frame_reg,
5685                                                 HAVE_64BIT_ADDRESSES);
5686                 }
5687             }
5688         }
5689       else if (mips_pic == VXWORKS_PIC)
5690         as_bad (_("Non-PIC jump used in PIC library"));
5691       else
5692         abort ();
5693
5694       break;
5695
5696     case M_LB_AB:
5697       s = "lb";
5698       goto ld;
5699     case M_LBU_AB:
5700       s = "lbu";
5701       goto ld;
5702     case M_LH_AB:
5703       s = "lh";
5704       goto ld;
5705     case M_LHU_AB:
5706       s = "lhu";
5707       goto ld;
5708     case M_LW_AB:
5709       s = "lw";
5710       goto ld;
5711     case M_LWC0_AB:
5712       s = "lwc0";
5713       /* Itbl support may require additional care here.  */
5714       coproc = 1;
5715       goto ld;
5716     case M_LWC1_AB:
5717       s = "lwc1";
5718       /* Itbl support may require additional care here.  */
5719       coproc = 1;
5720       goto ld;
5721     case M_LWC2_AB:
5722       s = "lwc2";
5723       /* Itbl support may require additional care here.  */
5724       coproc = 1;
5725       goto ld;
5726     case M_LWC3_AB:
5727       s = "lwc3";
5728       /* Itbl support may require additional care here.  */
5729       coproc = 1;
5730       goto ld;
5731     case M_LWL_AB:
5732       s = "lwl";
5733       lr = 1;
5734       goto ld;
5735     case M_LWR_AB:
5736       s = "lwr";
5737       lr = 1;
5738       goto ld;
5739     case M_LDC1_AB:
5740       if (mips_opts.arch == CPU_R4650)
5741         {
5742           as_bad (_("opcode not supported on this processor"));
5743           break;
5744         }
5745       s = "ldc1";
5746       /* Itbl support may require additional care here.  */
5747       coproc = 1;
5748       goto ld;
5749     case M_LDC2_AB:
5750       s = "ldc2";
5751       /* Itbl support may require additional care here.  */
5752       coproc = 1;
5753       goto ld;
5754     case M_LDC3_AB:
5755       s = "ldc3";
5756       /* Itbl support may require additional care here.  */
5757       coproc = 1;
5758       goto ld;
5759     case M_LDL_AB:
5760       s = "ldl";
5761       lr = 1;
5762       goto ld;
5763     case M_LDR_AB:
5764       s = "ldr";
5765       lr = 1;
5766       goto ld;
5767     case M_LL_AB:
5768       s = "ll";
5769       goto ld;
5770     case M_LLD_AB:
5771       s = "lld";
5772       goto ld;
5773     case M_LWU_AB:
5774       s = "lwu";
5775     ld:
5776       if (breg == treg || coproc || lr)
5777         {
5778           tempreg = AT;
5779           used_at = 1;
5780         }
5781       else
5782         {
5783           tempreg = treg;
5784         }
5785       goto ld_st;
5786     case M_SB_AB:
5787       s = "sb";
5788       goto st;
5789     case M_SH_AB:
5790       s = "sh";
5791       goto st;
5792     case M_SW_AB:
5793       s = "sw";
5794       goto st;
5795     case M_SWC0_AB:
5796       s = "swc0";
5797       /* Itbl support may require additional care here.  */
5798       coproc = 1;
5799       goto st;
5800     case M_SWC1_AB:
5801       s = "swc1";
5802       /* Itbl support may require additional care here.  */
5803       coproc = 1;
5804       goto st;
5805     case M_SWC2_AB:
5806       s = "swc2";
5807       /* Itbl support may require additional care here.  */
5808       coproc = 1;
5809       goto st;
5810     case M_SWC3_AB:
5811       s = "swc3";
5812       /* Itbl support may require additional care here.  */
5813       coproc = 1;
5814       goto st;
5815     case M_SWL_AB:
5816       s = "swl";
5817       goto st;
5818     case M_SWR_AB:
5819       s = "swr";
5820       goto st;
5821     case M_SC_AB:
5822       s = "sc";
5823       goto st;
5824     case M_SCD_AB:
5825       s = "scd";
5826       goto st;
5827     case M_CACHE_AB:
5828       s = "cache";
5829       goto st;
5830     case M_SDC1_AB:
5831       if (mips_opts.arch == CPU_R4650)
5832         {
5833           as_bad (_("opcode not supported on this processor"));
5834           break;
5835         }
5836       s = "sdc1";
5837       coproc = 1;
5838       /* Itbl support may require additional care here.  */
5839       goto st;
5840     case M_SDC2_AB:
5841       s = "sdc2";
5842       /* Itbl support may require additional care here.  */
5843       coproc = 1;
5844       goto st;
5845     case M_SDC3_AB:
5846       s = "sdc3";
5847       /* Itbl support may require additional care here.  */
5848       coproc = 1;
5849       goto st;
5850     case M_SDL_AB:
5851       s = "sdl";
5852       goto st;
5853     case M_SDR_AB:
5854       s = "sdr";
5855     st:
5856       tempreg = AT;
5857       used_at = 1;
5858     ld_st:
5859       /* Itbl support may require additional care here.  */
5860       if (mask == M_LWC1_AB
5861           || mask == M_SWC1_AB
5862           || mask == M_LDC1_AB
5863           || mask == M_SDC1_AB
5864           || mask == M_L_DAB
5865           || mask == M_S_DAB)
5866         fmt = "T,o(b)";
5867       else if (mask == M_CACHE_AB)
5868         fmt = "k,o(b)";
5869       else if (coproc)
5870         fmt = "E,o(b)";
5871       else
5872         fmt = "t,o(b)";
5873
5874       if (offset_expr.X_op != O_constant
5875           && offset_expr.X_op != O_symbol)
5876         {
5877           as_bad (_("expression too complex"));
5878           offset_expr.X_op = O_constant;
5879         }
5880
5881       if (HAVE_32BIT_ADDRESSES
5882           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
5883         {
5884           char value [32];
5885
5886           sprintf_vma (value, offset_expr.X_add_number);
5887           as_bad (_("Number (0x%s) larger than 32 bits"), value);
5888         }
5889
5890       /* A constant expression in PIC code can be handled just as it
5891          is in non PIC code.  */
5892       if (offset_expr.X_op == O_constant)
5893         {
5894           expr1.X_add_number = ((offset_expr.X_add_number + 0x8000)
5895                                 & ~(bfd_vma) 0xffff);
5896           normalize_address_expr (&expr1);
5897           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
5898           if (breg != 0)
5899             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5900                          tempreg, tempreg, breg);
5901           macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16, tempreg);
5902         }
5903       else if (mips_pic == NO_PIC)
5904         {
5905           /* If this is a reference to a GP relative symbol, and there
5906              is no base register, we want
5907                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
5908              Otherwise, if there is no base register, we want
5909                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
5910                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
5911              If we have a constant, we need two instructions anyhow,
5912              so we always use the latter form.
5913
5914              If we have a base register, and this is a reference to a
5915              GP relative symbol, we want
5916                addu     $tempreg,$breg,$gp
5917                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_GPREL16)
5918              Otherwise we want
5919                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
5920                addu     $tempreg,$tempreg,$breg
5921                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
5922              With a constant we always use the latter case.
5923
5924              With 64bit address space and no base register and $at usable,
5925              we want
5926                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
5927                lui      $at,<sym>               (BFD_RELOC_HI16_S)
5928                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
5929                dsll32   $tempreg,0
5930                daddu    $tempreg,$at
5931                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
5932              If we have a base register, we want
5933                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
5934                lui      $at,<sym>               (BFD_RELOC_HI16_S)
5935                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
5936                daddu    $at,$breg
5937                dsll32   $tempreg,0
5938                daddu    $tempreg,$at
5939                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
5940
5941              Without $at we can't generate the optimal path for superscalar
5942              processors here since this would require two temporary registers.
5943                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
5944                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
5945                dsll     $tempreg,16
5946                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
5947                dsll     $tempreg,16
5948                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
5949              If we have a base register, we want
5950                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
5951                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
5952                dsll     $tempreg,16
5953                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
5954                dsll     $tempreg,16
5955                daddu    $tempreg,$tempreg,$breg
5956                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
5957
5958              For GP relative symbols in 64bit address space we can use
5959              the same sequence as in 32bit address space.  */
5960           if (HAVE_64BIT_SYMBOLS)
5961             {
5962               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
5963                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
5964                 {
5965                   relax_start (offset_expr.X_add_symbol);
5966                   if (breg == 0)
5967                     {
5968                       macro_build (&offset_expr, s, fmt, treg,
5969                                    BFD_RELOC_GPREL16, mips_gp_register);
5970                     }
5971                   else
5972                     {
5973                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5974                                    tempreg, breg, mips_gp_register);
5975                       macro_build (&offset_expr, s, fmt, treg,
5976                                    BFD_RELOC_GPREL16, tempreg);
5977                     }
5978                   relax_switch ();
5979                 }
5980
5981               if (used_at == 0 && !mips_opts.noat)
5982                 {
5983                   macro_build (&offset_expr, "lui", "t,u", tempreg,
5984                                BFD_RELOC_MIPS_HIGHEST);
5985                   macro_build (&offset_expr, "lui", "t,u", AT,
5986                                BFD_RELOC_HI16_S);
5987                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
5988                                tempreg, BFD_RELOC_MIPS_HIGHER);
5989                   if (breg != 0)
5990                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
5991                   macro_build (NULL, "dsll32", "d,w,<", tempreg, tempreg, 0);
5992                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
5993                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16,
5994                                tempreg);
5995                   used_at = 1;
5996                 }
5997               else
5998                 {
5999                   macro_build (&offset_expr, "lui", "t,u", tempreg,
6000                                BFD_RELOC_MIPS_HIGHEST);
6001                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
6002                                tempreg, BFD_RELOC_MIPS_HIGHER);
6003                   macro_build (NULL, "dsll", "d,w,<", tempreg, tempreg, 16);
6004                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
6005                                tempreg, BFD_RELOC_HI16_S);
6006                   macro_build (NULL, "dsll", "d,w,<", tempreg, tempreg, 16);
6007                   if (breg != 0)
6008                     macro_build (NULL, "daddu", "d,v,t",
6009                                  tempreg, tempreg, breg);
6010                   macro_build (&offset_expr, s, fmt, treg,
6011                                BFD_RELOC_LO16, tempreg);
6012                 }
6013
6014               if (mips_relax.sequence)
6015                 relax_end ();
6016               break;
6017             }
6018
6019           if (breg == 0)
6020             {
6021               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
6022                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
6023                 {
6024                   relax_start (offset_expr.X_add_symbol);
6025                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_GPREL16,
6026                                mips_gp_register);
6027                   relax_switch ();
6028                 }
6029               macro_build_lui (&offset_expr, tempreg);
6030               macro_build (&offset_expr, s, fmt, treg,
6031                            BFD_RELOC_LO16, tempreg);
6032               if (mips_relax.sequence)
6033                 relax_end ();
6034             }
6035           else
6036             {
6037               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
6038                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
6039                 {
6040                   relax_start (offset_expr.X_add_symbol);
6041                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6042                                tempreg, breg, mips_gp_register);
6043                   macro_build (&offset_expr, s, fmt, treg,
6044                                BFD_RELOC_GPREL16, tempreg);
6045                   relax_switch ();
6046                 }
6047               macro_build_lui (&offset_expr, tempreg);
6048               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6049                            tempreg, tempreg, breg);
6050               macro_build (&offset_expr, s, fmt, treg,
6051                            BFD_RELOC_LO16, tempreg);
6052               if (mips_relax.sequence)
6053                 relax_end ();
6054             }
6055         }
6056       else if (!mips_big_got)
6057         {
6058           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
6059
6060           /* If this is a reference to an external symbol, we want
6061                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
6062                nop
6063                <op>     $treg,0($tempreg)
6064              Otherwise we want
6065                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
6066                nop
6067                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
6068                <op>     $treg,0($tempreg)
6069
6070              For NewABI, we want
6071                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
6072                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
6073
6074              If there is a base register, we add it to $tempreg before
6075              the <op>.  If there is a constant, we stick it in the
6076              <op> instruction.  We don't handle constants larger than
6077              16 bits, because we have no way to load the upper 16 bits
6078              (actually, we could handle them for the subset of cases
6079              in which we are not using $at).  */
6080           assert (offset_expr.X_op == O_symbol);
6081           if (HAVE_NEWABI)
6082             {
6083               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
6084                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
6085               if (breg != 0)
6086                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6087                              tempreg, tempreg, breg);
6088               macro_build (&offset_expr, s, fmt, treg,
6089                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
6090               break;
6091             }
6092           expr1.X_add_number = offset_expr.X_add_number;
6093           offset_expr.X_add_number = 0;
6094           if (expr1.X_add_number < -0x8000
6095               || expr1.X_add_number >= 0x8000)
6096             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6097           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
6098                        lw_reloc_type, mips_gp_register);
6099           load_delay_nop ();
6100           relax_start (offset_expr.X_add_symbol);
6101           relax_switch ();
6102           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
6103                        tempreg, BFD_RELOC_LO16);
6104           relax_end ();
6105           if (breg != 0)
6106             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6107                          tempreg, tempreg, breg);
6108           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
6109         }
6110       else if (mips_big_got && !HAVE_NEWABI)
6111         {
6112           int gpdelay;
6113
6114           /* If this is a reference to an external symbol, we want
6115                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
6116                addu     $tempreg,$tempreg,$gp
6117                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
6118                <op>     $treg,0($tempreg)
6119              Otherwise we want
6120                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
6121                nop
6122                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
6123                <op>     $treg,0($tempreg)
6124              If there is a base register, we add it to $tempreg before
6125              the <op>.  If there is a constant, we stick it in the
6126              <op> instruction.  We don't handle constants larger than
6127              16 bits, because we have no way to load the upper 16 bits
6128              (actually, we could handle them for the subset of cases
6129              in which we are not using $at).  */
6130           assert (offset_expr.X_op == O_symbol);
6131           expr1.X_add_number = offset_expr.X_add_number;
6132           offset_expr.X_add_number = 0;
6133           if (expr1.X_add_number < -0x8000
6134               || expr1.X_add_number >= 0x8000)
6135             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6136           gpdelay = reg_needs_delay (mips_gp_register);
6137           relax_start (offset_expr.X_add_symbol);
6138           macro_build (&offset_expr, "lui", "t,u", tempreg,
6139                        BFD_RELOC_MIPS_GOT_HI16);
6140           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
6141                        mips_gp_register);
6142           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
6143                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
6144           relax_switch ();
6145           if (gpdelay)
6146             macro_build (NULL, "nop", "");
6147           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
6148                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
6149           load_delay_nop ();
6150           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
6151                        tempreg, BFD_RELOC_LO16);
6152           relax_end ();
6153
6154           if (breg != 0)
6155             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6156                          tempreg, tempreg, breg);
6157           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
6158         }
6159       else if (mips_big_got && HAVE_NEWABI)
6160         {
6161           /* If this is a reference to an external symbol, we want
6162                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
6163                add      $tempreg,$tempreg,$gp
6164                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
6165                <op>     $treg,<ofst>($tempreg)
6166              Otherwise, for local symbols, we want:
6167                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
6168                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
6169           assert (offset_expr.X_op == O_symbol);
6170           expr1.X_add_number = offset_expr.X_add_number;
6171           offset_expr.X_add_number = 0;
6172           if (expr1.X_add_number < -0x8000
6173               || expr1.X_add_number >= 0x8000)
6174             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6175           relax_start (offset_expr.X_add_symbol);
6176           macro_build (&offset_expr, "lui", "t,u", tempreg,
6177                        BFD_RELOC_MIPS_GOT_HI16);
6178           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
6179                        mips_gp_register);
6180           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
6181                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
6182           if (breg != 0)
6183             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6184                          tempreg, tempreg, breg);
6185           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
6186
6187           relax_switch ();
6188           offset_expr.X_add_number = expr1.X_add_number;
6189           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
6190                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
6191           if (breg != 0)
6192             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6193                          tempreg, tempreg, breg);
6194           macro_build (&offset_expr, s, fmt, treg,
6195                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
6196           relax_end ();
6197         }
6198       else
6199         abort ();
6200
6201       break;
6202
6203     case M_LI:
6204     case M_LI_S:
6205       load_register (treg, &imm_expr, 0);
6206       break;
6207
6208     case M_DLI:
6209       load_register (treg, &imm_expr, 1);
6210       break;
6211
6212     case M_LI_SS:
6213       if (imm_expr.X_op == O_constant)
6214         {
6215           used_at = 1;
6216           load_register (AT, &imm_expr, 0);
6217           macro_build (NULL, "mtc1", "t,G", AT, treg);
6218           break;
6219         }
6220       else
6221         {
6222           assert (offset_expr.X_op == O_symbol
6223                   && strcmp (segment_name (S_GET_SEGMENT
6224                                            (offset_expr.X_add_symbol)),
6225                              ".lit4") == 0
6226                   && offset_expr.X_add_number == 0);
6227           macro_build (&offset_expr, "lwc1", "T,o(b)", treg,
6228                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
6229           break;
6230         }
6231
6232     case M_LI_D:
6233       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
6234          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
6235          order 32 bits of the value and the low order 32 bits are either
6236          zero or in OFFSET_EXPR.  */
6237       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
6238         {
6239           if (HAVE_64BIT_GPRS)
6240             load_register (treg, &imm_expr, 1);
6241           else
6242             {
6243               int hreg, lreg;
6244
6245               if (target_big_endian)
6246                 {
6247                   hreg = treg;
6248                   lreg = treg + 1;
6249                 }
6250               else
6251                 {
6252                   hreg = treg + 1;
6253                   lreg = treg;
6254                 }
6255
6256               if (hreg <= 31)
6257                 load_register (hreg, &imm_expr, 0);
6258               if (lreg <= 31)
6259                 {
6260                   if (offset_expr.X_op == O_absent)
6261                     move_register (lreg, 0);
6262                   else
6263                     {
6264                       assert (offset_expr.X_op == O_constant);
6265                       load_register (lreg, &offset_expr, 0);
6266                     }
6267                 }
6268             }
6269           break;
6270         }
6271
6272       /* We know that sym is in the .rdata section.  First we get the
6273          upper 16 bits of the address.  */
6274       if (mips_pic == NO_PIC)
6275         {
6276           macro_build_lui (&offset_expr, AT);
6277           used_at = 1;
6278         }
6279       else
6280         {
6281           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
6282                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
6283           used_at = 1;
6284         }
6285
6286       /* Now we load the register(s).  */
6287       if (HAVE_64BIT_GPRS)
6288         {
6289           used_at = 1;
6290           macro_build (&offset_expr, "ld", "t,o(b)", treg, BFD_RELOC_LO16, AT);
6291         }
6292       else
6293         {
6294           used_at = 1;
6295           macro_build (&offset_expr, "lw", "t,o(b)", treg, BFD_RELOC_LO16, AT);
6296           if (treg != RA)
6297             {
6298               /* FIXME: How in the world do we deal with the possible
6299                  overflow here?  */
6300               offset_expr.X_add_number += 4;
6301               macro_build (&offset_expr, "lw", "t,o(b)",
6302                            treg + 1, BFD_RELOC_LO16, AT);
6303             }
6304         }
6305       break;
6306
6307     case M_LI_DD:
6308       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
6309          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
6310          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
6311          the value and the low order 32 bits are either zero or in
6312          OFFSET_EXPR.  */
6313       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
6314         {
6315           used_at = 1;
6316           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
6317           if (HAVE_64BIT_FPRS)
6318             {
6319               assert (HAVE_64BIT_GPRS);
6320               macro_build (NULL, "dmtc1", "t,S", AT, treg);
6321             }
6322           else
6323             {
6324               macro_build (NULL, "mtc1", "t,G", AT, treg + 1);
6325               if (offset_expr.X_op == O_absent)
6326                 macro_build (NULL, "mtc1", "t,G", 0, treg);
6327               else
6328                 {
6329                   assert (offset_expr.X_op == O_constant);
6330                   load_register (AT, &offset_expr, 0);
6331                   macro_build (NULL, "mtc1", "t,G", AT, treg);
6332                 }
6333             }
6334           break;
6335         }
6336
6337       assert (offset_expr.X_op == O_symbol
6338               && offset_expr.X_add_number == 0);
6339       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
6340       if (strcmp (s, ".lit8") == 0)
6341         {
6342           if (mips_opts.isa != ISA_MIPS1)
6343             {
6344               macro_build (&offset_expr, "ldc1", "T,o(b)", treg,
6345                            BFD_RELOC_MIPS_LITERAL, mips_gp_register);
6346               break;
6347             }
6348           breg = mips_gp_register;
6349           r = BFD_RELOC_MIPS_LITERAL;
6350           goto dob;
6351         }
6352       else
6353         {
6354           assert (strcmp (s, RDATA_SECTION_NAME) == 0);
6355           used_at = 1;
6356           if (mips_pic != NO_PIC)
6357             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
6358                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
6359           else
6360             {
6361               /* FIXME: This won't work for a 64 bit address.  */
6362               macro_build_lui (&offset_expr, AT);
6363             }
6364
6365           if (mips_opts.isa != ISA_MIPS1)
6366             {
6367               macro_build (&offset_expr, "ldc1", "T,o(b)",
6368                            treg, BFD_RELOC_LO16, AT);
6369               break;
6370             }
6371           breg = AT;
6372           r = BFD_RELOC_LO16;
6373           goto dob;
6374         }
6375
6376     case M_L_DOB:
6377       if (mips_opts.arch == CPU_R4650)
6378         {
6379           as_bad (_("opcode not supported on this processor"));
6380           break;
6381         }
6382       /* Even on a big endian machine $fn comes before $fn+1.  We have
6383          to adjust when loading from memory.  */
6384       r = BFD_RELOC_LO16;
6385     dob:
6386       assert (mips_opts.isa == ISA_MIPS1);
6387       macro_build (&offset_expr, "lwc1", "T,o(b)",
6388                    target_big_endian ? treg + 1 : treg, r, breg);
6389       /* FIXME: A possible overflow which I don't know how to deal
6390          with.  */
6391       offset_expr.X_add_number += 4;
6392       macro_build (&offset_expr, "lwc1", "T,o(b)",
6393                    target_big_endian ? treg : treg + 1, r, breg);
6394       break;
6395
6396     case M_L_DAB:
6397       /*
6398        * The MIPS assembler seems to check for X_add_number not
6399        * being double aligned and generating:
6400        *        lui     at,%hi(foo+1)
6401        *        addu    at,at,v1
6402        *        addiu   at,at,%lo(foo+1)
6403        *        lwc1    f2,0(at)
6404        *        lwc1    f3,4(at)
6405        * But, the resulting address is the same after relocation so why
6406        * generate the extra instruction?
6407        */
6408       if (mips_opts.arch == CPU_R4650)
6409         {
6410           as_bad (_("opcode not supported on this processor"));
6411           break;
6412         }
6413       /* Itbl support may require additional care here.  */
6414       coproc = 1;
6415       if (mips_opts.isa != ISA_MIPS1)
6416         {
6417           s = "ldc1";
6418           goto ld;
6419         }
6420
6421       s = "lwc1";
6422       fmt = "T,o(b)";
6423       goto ldd_std;
6424
6425     case M_S_DAB:
6426       if (mips_opts.arch == CPU_R4650)
6427         {
6428           as_bad (_("opcode not supported on this processor"));
6429           break;
6430         }
6431
6432       if (mips_opts.isa != ISA_MIPS1)
6433         {
6434           s = "sdc1";
6435           goto st;
6436         }
6437
6438       s = "swc1";
6439       fmt = "T,o(b)";
6440       /* Itbl support may require additional care here.  */
6441       coproc = 1;
6442       goto ldd_std;
6443
6444     case M_LD_AB:
6445       if (HAVE_64BIT_GPRS)
6446         {
6447           s = "ld";
6448           goto ld;
6449         }
6450
6451       s = "lw";
6452       fmt = "t,o(b)";
6453       goto ldd_std;
6454
6455     case M_SD_AB:
6456       if (HAVE_64BIT_GPRS)
6457         {
6458           s = "sd";
6459           goto st;
6460         }
6461
6462       s = "sw";
6463       fmt = "t,o(b)";
6464
6465     ldd_std:
6466       if (offset_expr.X_op != O_symbol
6467           && offset_expr.X_op != O_constant)
6468         {
6469           as_bad (_("expression too complex"));
6470           offset_expr.X_op = O_constant;
6471         }
6472
6473       if (HAVE_32BIT_ADDRESSES
6474           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
6475         {
6476           char value [32];
6477
6478           sprintf_vma (value, offset_expr.X_add_number);
6479           as_bad (_("Number (0x%s) larger than 32 bits"), value);
6480         }
6481
6482       /* Even on a big endian machine $fn comes before $fn+1.  We have
6483          to adjust when loading from memory.  We set coproc if we must
6484          load $fn+1 first.  */
6485       /* Itbl support may require additional care here.  */
6486       if (! target_big_endian)
6487         coproc = 0;
6488
6489       if (mips_pic == NO_PIC
6490           || offset_expr.X_op == O_constant)
6491         {
6492           /* If this is a reference to a GP relative symbol, we want
6493                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
6494                <op>     $treg+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
6495              If we have a base register, we use this
6496                addu     $at,$breg,$gp
6497                <op>     $treg,<sym>($at)        (BFD_RELOC_GPREL16)
6498                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
6499              If this is not a GP relative symbol, we want
6500                lui      $at,<sym>               (BFD_RELOC_HI16_S)
6501                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
6502                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
6503              If there is a base register, we add it to $at after the
6504              lui instruction.  If there is a constant, we always use
6505              the last case.  */
6506           if (offset_expr.X_op == O_symbol
6507               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
6508               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
6509             {
6510               relax_start (offset_expr.X_add_symbol);
6511               if (breg == 0)
6512                 {
6513                   tempreg = mips_gp_register;
6514                 }
6515               else
6516                 {
6517                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6518                                AT, breg, mips_gp_register);
6519                   tempreg = AT;
6520                   used_at = 1;
6521                 }
6522
6523               /* Itbl support may require additional care here.  */
6524               macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
6525                            BFD_RELOC_GPREL16, tempreg);
6526               offset_expr.X_add_number += 4;
6527
6528               /* Set mips_optimize to 2 to avoid inserting an
6529                  undesired nop.  */
6530               hold_mips_optimize = mips_optimize;
6531               mips_optimize = 2;
6532               /* Itbl support may require additional care here.  */
6533               macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
6534                            BFD_RELOC_GPREL16, tempreg);
6535               mips_optimize = hold_mips_optimize;
6536
6537               relax_switch ();
6538
6539               /* We just generated two relocs.  When tc_gen_reloc
6540                  handles this case, it will skip the first reloc and
6541                  handle the second.  The second reloc already has an
6542                  extra addend of 4, which we added above.  We must
6543                  subtract it out, and then subtract another 4 to make
6544                  the first reloc come out right.  The second reloc
6545                  will come out right because we are going to add 4 to
6546                  offset_expr when we build its instruction below.
6547
6548                  If we have a symbol, then we don't want to include
6549                  the offset, because it will wind up being included
6550                  when we generate the reloc.  */
6551
6552               if (offset_expr.X_op == O_constant)
6553                 offset_expr.X_add_number -= 8;
6554               else
6555                 {
6556                   offset_expr.X_add_number = -4;
6557                   offset_expr.X_op = O_constant;
6558                 }
6559             }
6560           used_at = 1;
6561           macro_build_lui (&offset_expr, AT);
6562           if (breg != 0)
6563             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
6564           /* Itbl support may require additional care here.  */
6565           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
6566                        BFD_RELOC_LO16, AT);
6567           /* FIXME: How do we handle overflow here?  */
6568           offset_expr.X_add_number += 4;
6569           /* Itbl support may require additional care here.  */
6570           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
6571                        BFD_RELOC_LO16, AT);
6572           if (mips_relax.sequence)
6573             relax_end ();
6574         }
6575       else if (!mips_big_got)
6576         {
6577           /* If this is a reference to an external symbol, we want
6578                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
6579                nop
6580                <op>     $treg,0($at)
6581                <op>     $treg+1,4($at)
6582              Otherwise we want
6583                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
6584                nop
6585                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
6586                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
6587              If there is a base register we add it to $at before the
6588              lwc1 instructions.  If there is a constant we include it
6589              in the lwc1 instructions.  */
6590           used_at = 1;
6591           expr1.X_add_number = offset_expr.X_add_number;
6592           if (expr1.X_add_number < -0x8000
6593               || expr1.X_add_number >= 0x8000 - 4)
6594             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6595           load_got_offset (AT, &offset_expr);
6596           load_delay_nop ();
6597           if (breg != 0)
6598             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
6599
6600           /* Set mips_optimize to 2 to avoid inserting an undesired
6601              nop.  */
6602           hold_mips_optimize = mips_optimize;
6603           mips_optimize = 2;
6604
6605           /* Itbl support may require additional care here.  */
6606           relax_start (offset_expr.X_add_symbol);
6607           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
6608                        BFD_RELOC_LO16, AT);
6609           expr1.X_add_number += 4;
6610           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
6611                        BFD_RELOC_LO16, AT);
6612           relax_switch ();
6613           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
6614                        BFD_RELOC_LO16, AT);
6615           offset_expr.X_add_number += 4;
6616           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
6617                        BFD_RELOC_LO16, AT);
6618           relax_end ();
6619
6620           mips_optimize = hold_mips_optimize;
6621         }
6622       else if (mips_big_got)
6623         {
6624           int gpdelay;
6625
6626           /* If this is a reference to an external symbol, we want
6627                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
6628                addu     $at,$at,$gp
6629                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
6630                nop
6631                <op>     $treg,0($at)
6632                <op>     $treg+1,4($at)
6633              Otherwise we want
6634                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
6635                nop
6636                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
6637                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
6638              If there is a base register we add it to $at before the
6639              lwc1 instructions.  If there is a constant we include it
6640              in the lwc1 instructions.  */
6641           used_at = 1;
6642           expr1.X_add_number = offset_expr.X_add_number;
6643           offset_expr.X_add_number = 0;
6644           if (expr1.X_add_number < -0x8000
6645               || expr1.X_add_number >= 0x8000 - 4)
6646             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6647           gpdelay = reg_needs_delay (mips_gp_register);
6648           relax_start (offset_expr.X_add_symbol);
6649           macro_build (&offset_expr, "lui", "t,u",
6650                        AT, BFD_RELOC_MIPS_GOT_HI16);
6651           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6652                        AT, AT, mips_gp_register);
6653           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
6654                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
6655           load_delay_nop ();
6656           if (breg != 0)
6657             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
6658           /* Itbl support may require additional care here.  */
6659           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
6660                        BFD_RELOC_LO16, AT);
6661           expr1.X_add_number += 4;
6662
6663           /* Set mips_optimize to 2 to avoid inserting an undesired
6664              nop.  */
6665           hold_mips_optimize = mips_optimize;
6666           mips_optimize = 2;
6667           /* Itbl support may require additional care here.  */
6668           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
6669                        BFD_RELOC_LO16, AT);
6670           mips_optimize = hold_mips_optimize;
6671           expr1.X_add_number -= 4;
6672
6673           relax_switch ();
6674           offset_expr.X_add_number = expr1.X_add_number;
6675           if (gpdelay)
6676             macro_build (NULL, "nop", "");
6677           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
6678                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
6679           load_delay_nop ();
6680           if (breg != 0)
6681             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
6682           /* Itbl support may require additional care here.  */
6683           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
6684                        BFD_RELOC_LO16, AT);
6685           offset_expr.X_add_number += 4;
6686
6687           /* Set mips_optimize to 2 to avoid inserting an undesired
6688              nop.  */
6689           hold_mips_optimize = mips_optimize;
6690           mips_optimize = 2;
6691           /* Itbl support may require additional care here.  */
6692           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
6693                        BFD_RELOC_LO16, AT);
6694           mips_optimize = hold_mips_optimize;
6695           relax_end ();
6696         }
6697       else
6698         abort ();
6699
6700       break;
6701
6702     case M_LD_OB:
6703       s = "lw";
6704       goto sd_ob;
6705     case M_SD_OB:
6706       s = "sw";
6707     sd_ob:
6708       assert (HAVE_32BIT_ADDRESSES);
6709       macro_build (&offset_expr, s, "t,o(b)", treg, BFD_RELOC_LO16, breg);
6710       offset_expr.X_add_number += 4;
6711       macro_build (&offset_expr, s, "t,o(b)", treg + 1, BFD_RELOC_LO16, breg);
6712       break;
6713
6714    /* New code added to support COPZ instructions.
6715       This code builds table entries out of the macros in mip_opcodes.
6716       R4000 uses interlocks to handle coproc delays.
6717       Other chips (like the R3000) require nops to be inserted for delays.
6718
6719       FIXME: Currently, we require that the user handle delays.
6720       In order to fill delay slots for non-interlocked chips,
6721       we must have a way to specify delays based on the coprocessor.
6722       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
6723       What are the side-effects of the cop instruction?
6724       What cache support might we have and what are its effects?
6725       Both coprocessor & memory require delays. how long???
6726       What registers are read/set/modified?
6727
6728       If an itbl is provided to interpret cop instructions,
6729       this knowledge can be encoded in the itbl spec.  */
6730
6731     case M_COP0:
6732       s = "c0";
6733       goto copz;
6734     case M_COP1:
6735       s = "c1";
6736       goto copz;
6737     case M_COP2:
6738       s = "c2";
6739       goto copz;
6740     case M_COP3:
6741       s = "c3";
6742     copz:
6743       /* For now we just do C (same as Cz).  The parameter will be
6744          stored in insn_opcode by mips_ip.  */
6745       macro_build (NULL, s, "C", ip->insn_opcode);
6746       break;
6747
6748     case M_MOVE:
6749       move_register (dreg, sreg);
6750       break;
6751
6752 #ifdef LOSING_COMPILER
6753     default:
6754       /* Try and see if this is a new itbl instruction.
6755          This code builds table entries out of the macros in mip_opcodes.
6756          FIXME: For now we just assemble the expression and pass it's
6757          value along as a 32-bit immediate.
6758          We may want to have the assembler assemble this value,
6759          so that we gain the assembler's knowledge of delay slots,
6760          symbols, etc.
6761          Would it be more efficient to use mask (id) here? */
6762       if (itbl_have_entries
6763           && (immed_expr = itbl_assemble (ip->insn_mo->name, "")))
6764         {
6765           s = ip->insn_mo->name;
6766           s2 = "cop3";
6767           coproc = ITBL_DECODE_PNUM (immed_expr);;
6768           macro_build (&immed_expr, s, "C");
6769           break;
6770         }
6771       macro2 (ip);
6772       break;
6773     }
6774   if (mips_opts.noat && used_at)
6775     as_bad (_("Macro used $at after \".set noat\""));
6776 }
6777
6778 static void
6779 macro2 (struct mips_cl_insn *ip)
6780 {
6781   register int treg, sreg, dreg, breg;
6782   int tempreg;
6783   int mask;
6784   int used_at;
6785   expressionS expr1;
6786   const char *s;
6787   const char *s2;
6788   const char *fmt;
6789   int likely = 0;
6790   int dbl = 0;
6791   int coproc = 0;
6792   int lr = 0;
6793   int imm = 0;
6794   int off;
6795   offsetT maxnum;
6796   bfd_reloc_code_real_type r;
6797
6798   treg = (ip->insn_opcode >> 16) & 0x1f;
6799   dreg = (ip->insn_opcode >> 11) & 0x1f;
6800   sreg = breg = (ip->insn_opcode >> 21) & 0x1f;
6801   mask = ip->insn_mo->mask;
6802
6803   expr1.X_op = O_constant;
6804   expr1.X_op_symbol = NULL;
6805   expr1.X_add_symbol = NULL;
6806   expr1.X_add_number = 1;
6807
6808   switch (mask)
6809     {
6810 #endif /* LOSING_COMPILER */
6811
6812     case M_DMUL:
6813       dbl = 1;
6814     case M_MUL:
6815       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", sreg, treg);
6816       macro_build (NULL, "mflo", "d", dreg);
6817       break;
6818
6819     case M_DMUL_I:
6820       dbl = 1;
6821     case M_MUL_I:
6822       /* The MIPS assembler some times generates shifts and adds.  I'm
6823          not trying to be that fancy. GCC should do this for us
6824          anyway.  */
6825       used_at = 1;
6826       load_register (AT, &imm_expr, dbl);
6827       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, AT);
6828       macro_build (NULL, "mflo", "d", dreg);
6829       break;
6830
6831     case M_DMULO_I:
6832       dbl = 1;
6833     case M_MULO_I:
6834       imm = 1;
6835       goto do_mulo;
6836
6837     case M_DMULO:
6838       dbl = 1;
6839     case M_MULO:
6840     do_mulo:
6841       start_noreorder ();
6842       used_at = 1;
6843       if (imm)
6844         load_register (AT, &imm_expr, dbl);
6845       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, imm ? AT : treg);
6846       macro_build (NULL, "mflo", "d", dreg);
6847       macro_build (NULL, dbl ? "dsra32" : "sra", "d,w,<", dreg, dreg, RA);
6848       macro_build (NULL, "mfhi", "d", AT);
6849       if (mips_trap)
6850         macro_build (NULL, "tne", "s,t,q", dreg, AT, 6);
6851       else
6852         {
6853           expr1.X_add_number = 8;
6854           macro_build (&expr1, "beq", "s,t,p", dreg, AT);
6855           macro_build (NULL, "nop", "", 0);
6856           macro_build (NULL, "break", "c", 6);
6857         }
6858       end_noreorder ();
6859       macro_build (NULL, "mflo", "d", dreg);
6860       break;
6861
6862     case M_DMULOU_I:
6863       dbl = 1;
6864     case M_MULOU_I:
6865       imm = 1;
6866       goto do_mulou;
6867
6868     case M_DMULOU:
6869       dbl = 1;
6870     case M_MULOU:
6871     do_mulou:
6872       start_noreorder ();
6873       used_at = 1;
6874       if (imm)
6875         load_register (AT, &imm_expr, dbl);
6876       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
6877                    sreg, imm ? AT : treg);
6878       macro_build (NULL, "mfhi", "d", AT);
6879       macro_build (NULL, "mflo", "d", dreg);
6880       if (mips_trap)
6881         macro_build (NULL, "tne", "s,t,q", AT, 0, 6);
6882       else
6883         {
6884           expr1.X_add_number = 8;
6885           macro_build (&expr1, "beq", "s,t,p", AT, 0);
6886           macro_build (NULL, "nop", "", 0);
6887           macro_build (NULL, "break", "c", 6);
6888         }
6889       end_noreorder ();
6890       break;
6891
6892     case M_DROL:
6893       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
6894         {
6895           if (dreg == sreg)
6896             {
6897               tempreg = AT;
6898               used_at = 1;
6899             }
6900           else
6901             {
6902               tempreg = dreg;
6903             }
6904           macro_build (NULL, "dnegu", "d,w", tempreg, treg);
6905           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, tempreg);
6906           break;
6907         }
6908       used_at = 1;
6909       macro_build (NULL, "dsubu", "d,v,t", AT, 0, treg);
6910       macro_build (NULL, "dsrlv", "d,t,s", AT, sreg, AT);
6911       macro_build (NULL, "dsllv", "d,t,s", dreg, sreg, treg);
6912       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
6913       break;
6914
6915     case M_ROL:
6916       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
6917         {
6918           if (dreg == sreg)
6919             {
6920               tempreg = AT;
6921               used_at = 1;
6922             }
6923           else
6924             {
6925               tempreg = dreg;
6926             }
6927           macro_build (NULL, "negu", "d,w", tempreg, treg);
6928           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, tempreg);
6929           break;
6930         }
6931       used_at = 1;
6932       macro_build (NULL, "subu", "d,v,t", AT, 0, treg);
6933       macro_build (NULL, "srlv", "d,t,s", AT, sreg, AT);
6934       macro_build (NULL, "sllv", "d,t,s", dreg, sreg, treg);
6935       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
6936       break;
6937
6938     case M_DROL_I:
6939       {
6940         unsigned int rot;
6941         char *l, *r;
6942
6943         if (imm_expr.X_op != O_constant)
6944           as_bad (_("Improper rotate count"));
6945         rot = imm_expr.X_add_number & 0x3f;
6946         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
6947           {
6948             rot = (64 - rot) & 0x3f;
6949             if (rot >= 32)
6950               macro_build (NULL, "dror32", "d,w,<", dreg, sreg, rot - 32);
6951             else
6952               macro_build (NULL, "dror", "d,w,<", dreg, sreg, rot);
6953             break;
6954           }
6955         if (rot == 0)
6956           {
6957             macro_build (NULL, "dsrl", "d,w,<", dreg, sreg, 0);
6958             break;
6959           }
6960         l = (rot < 0x20) ? "dsll" : "dsll32";
6961         r = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
6962         rot &= 0x1f;
6963         used_at = 1;
6964         macro_build (NULL, l, "d,w,<", AT, sreg, rot);
6965         macro_build (NULL, r, "d,w,<", dreg, sreg, (0x20 - rot) & 0x1f);
6966         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
6967       }
6968       break;
6969
6970     case M_ROL_I:
6971       {
6972         unsigned int rot;
6973
6974         if (imm_expr.X_op != O_constant)
6975           as_bad (_("Improper rotate count"));
6976         rot = imm_expr.X_add_number & 0x1f;
6977         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
6978           {
6979             macro_build (NULL, "ror", "d,w,<", dreg, sreg, (32 - rot) & 0x1f);
6980             break;
6981           }
6982         if (rot == 0)
6983           {
6984             macro_build (NULL, "srl", "d,w,<", dreg, sreg, 0);
6985             break;
6986           }
6987         used_at = 1;
6988         macro_build (NULL, "sll", "d,w,<", AT, sreg, rot);
6989         macro_build (NULL, "srl", "d,w,<", dreg, sreg, (0x20 - rot) & 0x1f);
6990         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
6991       }
6992       break;
6993
6994     case M_DROR:
6995       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
6996         {
6997           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, treg);
6998           break;
6999         }
7000       used_at = 1;
7001       macro_build (NULL, "dsubu", "d,v,t", AT, 0, treg);
7002       macro_build (NULL, "dsllv", "d,t,s", AT, sreg, AT);
7003       macro_build (NULL, "dsrlv", "d,t,s", dreg, sreg, treg);
7004       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
7005       break;
7006
7007     case M_ROR:
7008       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
7009         {
7010           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, treg);
7011           break;
7012         }
7013       used_at = 1;
7014       macro_build (NULL, "subu", "d,v,t", AT, 0, treg);
7015       macro_build (NULL, "sllv", "d,t,s", AT, sreg, AT);
7016       macro_build (NULL, "srlv", "d,t,s", dreg, sreg, treg);
7017       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
7018       break;
7019
7020     case M_DROR_I:
7021       {
7022         unsigned int rot;
7023         char *l, *r;
7024
7025         if (imm_expr.X_op != O_constant)
7026           as_bad (_("Improper rotate count"));
7027         rot = imm_expr.X_add_number & 0x3f;
7028         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
7029           {
7030             if (rot >= 32)
7031               macro_build (NULL, "dror32", "d,w,<", dreg, sreg, rot - 32);
7032             else
7033               macro_build (NULL, "dror", "d,w,<", dreg, sreg, rot);
7034             break;
7035           }
7036         if (rot == 0)
7037           {
7038             macro_build (NULL, "dsrl", "d,w,<", dreg, sreg, 0);
7039             break;
7040           }
7041         r = (rot < 0x20) ? "dsrl" : "dsrl32";
7042         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
7043         rot &= 0x1f;
7044         used_at = 1;
7045         macro_build (NULL, r, "d,w,<", AT, sreg, rot);
7046         macro_build (NULL, l, "d,w,<", dreg, sreg, (0x20 - rot) & 0x1f);
7047         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
7048       }
7049       break;
7050
7051     case M_ROR_I:
7052       {
7053         unsigned int rot;
7054
7055         if (imm_expr.X_op != O_constant)
7056           as_bad (_("Improper rotate count"));
7057         rot = imm_expr.X_add_number & 0x1f;
7058         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
7059           {
7060             macro_build (NULL, "ror", "d,w,<", dreg, sreg, rot);
7061             break;
7062           }
7063         if (rot == 0)
7064           {
7065             macro_build (NULL, "srl", "d,w,<", dreg, sreg, 0);
7066             break;
7067           }
7068         used_at = 1;
7069         macro_build (NULL, "srl", "d,w,<", AT, sreg, rot);
7070         macro_build (NULL, "sll", "d,w,<", dreg, sreg, (0x20 - rot) & 0x1f);
7071         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
7072       }
7073       break;
7074
7075     case M_S_DOB:
7076       if (mips_opts.arch == CPU_R4650)
7077         {
7078           as_bad (_("opcode not supported on this processor"));
7079           break;
7080         }
7081       assert (mips_opts.isa == ISA_MIPS1);
7082       /* Even on a big endian machine $fn comes before $fn+1.  We have
7083          to adjust when storing to memory.  */
7084       macro_build (&offset_expr, "swc1", "T,o(b)",
7085                    target_big_endian ? treg + 1 : treg, BFD_RELOC_LO16, breg);
7086       offset_expr.X_add_number += 4;
7087       macro_build (&offset_expr, "swc1", "T,o(b)",
7088                    target_big_endian ? treg : treg + 1, BFD_RELOC_LO16, breg);
7089       break;
7090
7091     case M_SEQ:
7092       if (sreg == 0)
7093         macro_build (&expr1, "sltiu", "t,r,j", dreg, treg, BFD_RELOC_LO16);
7094       else if (treg == 0)
7095         macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
7096       else
7097         {
7098           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
7099           macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
7100         }
7101       break;
7102
7103     case M_SEQ_I:
7104       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7105         {
7106           macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
7107           break;
7108         }
7109       if (sreg == 0)
7110         {
7111           as_warn (_("Instruction %s: result is always false"),
7112                    ip->insn_mo->name);
7113           move_register (dreg, 0);
7114           break;
7115         }
7116       if (imm_expr.X_op == O_constant
7117           && imm_expr.X_add_number >= 0
7118           && imm_expr.X_add_number < 0x10000)
7119         {
7120           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
7121         }
7122       else if (imm_expr.X_op == O_constant
7123                && imm_expr.X_add_number > -0x8000
7124                && imm_expr.X_add_number < 0)
7125         {
7126           imm_expr.X_add_number = -imm_expr.X_add_number;
7127           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
7128                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
7129         }
7130       else
7131         {
7132           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7133           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
7134           used_at = 1;
7135         }
7136       macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
7137       break;
7138
7139     case M_SGE:         /* sreg >= treg <==> not (sreg < treg) */
7140       s = "slt";
7141       goto sge;
7142     case M_SGEU:
7143       s = "sltu";
7144     sge:
7145       macro_build (NULL, s, "d,v,t", dreg, sreg, treg);
7146       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
7147       break;
7148
7149     case M_SGE_I:               /* sreg >= I <==> not (sreg < I) */
7150     case M_SGEU_I:
7151       if (imm_expr.X_op == O_constant
7152           && imm_expr.X_add_number >= -0x8000
7153           && imm_expr.X_add_number < 0x8000)
7154         {
7155           macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
7156                        dreg, sreg, BFD_RELOC_LO16);
7157         }
7158       else
7159         {
7160           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7161           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
7162                        dreg, sreg, AT);
7163           used_at = 1;
7164         }
7165       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
7166       break;
7167
7168     case M_SGT:         /* sreg > treg  <==>  treg < sreg */
7169       s = "slt";
7170       goto sgt;
7171     case M_SGTU:
7172       s = "sltu";
7173     sgt:
7174       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
7175       break;
7176
7177     case M_SGT_I:               /* sreg > I  <==>  I < sreg */
7178       s = "slt";
7179       goto sgti;
7180     case M_SGTU_I:
7181       s = "sltu";
7182     sgti:
7183       used_at = 1;
7184       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7185       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
7186       break;
7187
7188     case M_SLE: /* sreg <= treg  <==>  treg >= sreg  <==>  not (treg < sreg) */
7189       s = "slt";
7190       goto sle;
7191     case M_SLEU:
7192       s = "sltu";
7193     sle:
7194       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
7195       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
7196       break;
7197
7198     case M_SLE_I:       /* sreg <= I <==> I >= sreg <==> not (I < sreg) */
7199       s = "slt";
7200       goto slei;
7201     case M_SLEU_I:
7202       s = "sltu";
7203     slei:
7204       used_at = 1;
7205       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7206       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
7207       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
7208       break;
7209
7210     case M_SLT_I:
7211       if (imm_expr.X_op == O_constant
7212           && imm_expr.X_add_number >= -0x8000
7213           && imm_expr.X_add_number < 0x8000)
7214         {
7215           macro_build (&imm_expr, "slti", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
7216           break;
7217         }
7218       used_at = 1;
7219       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7220       macro_build (NULL, "slt", "d,v,t", dreg, sreg, AT);
7221       break;
7222
7223     case M_SLTU_I:
7224       if (imm_expr.X_op == O_constant
7225           && imm_expr.X_add_number >= -0x8000
7226           && imm_expr.X_add_number < 0x8000)
7227         {
7228           macro_build (&imm_expr, "sltiu", "t,r,j", dreg, sreg,
7229                        BFD_RELOC_LO16);
7230           break;
7231         }
7232       used_at = 1;
7233       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7234       macro_build (NULL, "sltu", "d,v,t", dreg, sreg, AT);
7235       break;
7236
7237     case M_SNE:
7238       if (sreg == 0)
7239         macro_build (NULL, "sltu", "d,v,t", dreg, 0, treg);
7240       else if (treg == 0)
7241         macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
7242       else
7243         {
7244           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
7245           macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
7246         }
7247       break;
7248
7249     case M_SNE_I:
7250       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7251         {
7252           macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
7253           break;
7254         }
7255       if (sreg == 0)
7256         {
7257           as_warn (_("Instruction %s: result is always true"),
7258                    ip->insn_mo->name);
7259           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
7260                        dreg, 0, BFD_RELOC_LO16);
7261           break;
7262         }
7263       if (imm_expr.X_op == O_constant
7264           && imm_expr.X_add_number >= 0
7265           && imm_expr.X_add_number < 0x10000)
7266         {
7267           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
7268         }
7269       else if (imm_expr.X_op == O_constant
7270                && imm_expr.X_add_number > -0x8000
7271                && imm_expr.X_add_number < 0)
7272         {
7273           imm_expr.X_add_number = -imm_expr.X_add_number;
7274           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
7275                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
7276         }
7277       else
7278         {
7279           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7280           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
7281           used_at = 1;
7282         }
7283       macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
7284       break;
7285
7286     case M_DSUB_I:
7287       dbl = 1;
7288     case M_SUB_I:
7289       if (imm_expr.X_op == O_constant
7290           && imm_expr.X_add_number > -0x8000
7291           && imm_expr.X_add_number <= 0x8000)
7292         {
7293           imm_expr.X_add_number = -imm_expr.X_add_number;
7294           macro_build (&imm_expr, dbl ? "daddi" : "addi", "t,r,j",
7295                        dreg, sreg, BFD_RELOC_LO16);
7296           break;
7297         }
7298       used_at = 1;
7299       load_register (AT, &imm_expr, dbl);
7300       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", dreg, sreg, AT);
7301       break;
7302
7303     case M_DSUBU_I:
7304       dbl = 1;
7305     case M_SUBU_I:
7306       if (imm_expr.X_op == O_constant
7307           && imm_expr.X_add_number > -0x8000
7308           && imm_expr.X_add_number <= 0x8000)
7309         {
7310           imm_expr.X_add_number = -imm_expr.X_add_number;
7311           macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "t,r,j",
7312                        dreg, sreg, BFD_RELOC_LO16);
7313           break;
7314         }
7315       used_at = 1;
7316       load_register (AT, &imm_expr, dbl);
7317       macro_build (NULL, dbl ? "dsubu" : "subu", "d,v,t", dreg, sreg, AT);
7318       break;
7319
7320     case M_TEQ_I:
7321       s = "teq";
7322       goto trap;
7323     case M_TGE_I:
7324       s = "tge";
7325       goto trap;
7326     case M_TGEU_I:
7327       s = "tgeu";
7328       goto trap;
7329     case M_TLT_I:
7330       s = "tlt";
7331       goto trap;
7332     case M_TLTU_I:
7333       s = "tltu";
7334       goto trap;
7335     case M_TNE_I:
7336       s = "tne";
7337     trap:
7338       used_at = 1;
7339       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7340       macro_build (NULL, s, "s,t", sreg, AT);
7341       break;
7342
7343     case M_TRUNCWS:
7344     case M_TRUNCWD:
7345       assert (mips_opts.isa == ISA_MIPS1);
7346       used_at = 1;
7347       sreg = (ip->insn_opcode >> 11) & 0x1f;    /* floating reg */
7348       dreg = (ip->insn_opcode >> 06) & 0x1f;    /* floating reg */
7349
7350       /*
7351        * Is the double cfc1 instruction a bug in the mips assembler;
7352        * or is there a reason for it?
7353        */
7354       start_noreorder ();
7355       macro_build (NULL, "cfc1", "t,G", treg, RA);
7356       macro_build (NULL, "cfc1", "t,G", treg, RA);
7357       macro_build (NULL, "nop", "");
7358       expr1.X_add_number = 3;
7359       macro_build (&expr1, "ori", "t,r,i", AT, treg, BFD_RELOC_LO16);
7360       expr1.X_add_number = 2;
7361       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
7362       macro_build (NULL, "ctc1", "t,G", AT, RA);
7363       macro_build (NULL, "nop", "");
7364       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
7365                    dreg, sreg);
7366       macro_build (NULL, "ctc1", "t,G", treg, RA);
7367       macro_build (NULL, "nop", "");
7368       end_noreorder ();
7369       break;
7370
7371     case M_ULH:
7372       s = "lb";
7373       goto ulh;
7374     case M_ULHU:
7375       s = "lbu";
7376     ulh:
7377       used_at = 1;
7378       if (offset_expr.X_add_number >= 0x7fff)
7379         as_bad (_("operand overflow"));
7380       if (! target_big_endian)
7381         ++offset_expr.X_add_number;
7382       macro_build (&offset_expr, s, "t,o(b)", AT, BFD_RELOC_LO16, breg);
7383       if (! target_big_endian)
7384         --offset_expr.X_add_number;
7385       else
7386         ++offset_expr.X_add_number;
7387       macro_build (&offset_expr, "lbu", "t,o(b)", treg, BFD_RELOC_LO16, breg);
7388       macro_build (NULL, "sll", "d,w,<", AT, AT, 8);
7389       macro_build (NULL, "or", "d,v,t", treg, treg, AT);
7390       break;
7391
7392     case M_ULD:
7393       s = "ldl";
7394       s2 = "ldr";
7395       off = 7;
7396       goto ulw;
7397     case M_ULW:
7398       s = "lwl";
7399       s2 = "lwr";
7400       off = 3;
7401     ulw:
7402       if (offset_expr.X_add_number >= 0x8000 - off)
7403         as_bad (_("operand overflow"));
7404       if (treg != breg)
7405         tempreg = treg;
7406       else
7407         {
7408           used_at = 1;
7409           tempreg = AT;
7410         }
7411       if (! target_big_endian)
7412         offset_expr.X_add_number += off;
7413       macro_build (&offset_expr, s, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
7414       if (! target_big_endian)
7415         offset_expr.X_add_number -= off;
7416       else
7417         offset_expr.X_add_number += off;
7418       macro_build (&offset_expr, s2, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
7419
7420       /* If necessary, move the result in tempreg the final destination.  */
7421       if (treg == tempreg)
7422         break;
7423       /* Protect second load's delay slot.  */
7424       load_delay_nop ();
7425       move_register (treg, tempreg);
7426       break;
7427
7428     case M_ULD_A:
7429       s = "ldl";
7430       s2 = "ldr";
7431       off = 7;
7432       goto ulwa;
7433     case M_ULW_A:
7434       s = "lwl";
7435       s2 = "lwr";
7436       off = 3;
7437     ulwa:
7438       used_at = 1;
7439       load_address (AT, &offset_expr, &used_at);
7440       if (breg != 0)
7441         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
7442       if (! target_big_endian)
7443         expr1.X_add_number = off;
7444       else
7445         expr1.X_add_number = 0;
7446       macro_build (&expr1, s, "t,o(b)", treg, BFD_RELOC_LO16, AT);
7447       if (! target_big_endian)
7448         expr1.X_add_number = 0;
7449       else
7450         expr1.X_add_number = off;
7451       macro_build (&expr1, s2, "t,o(b)", treg, BFD_RELOC_LO16, AT);
7452       break;
7453
7454     case M_ULH_A:
7455     case M_ULHU_A:
7456       used_at = 1;
7457       load_address (AT, &offset_expr, &used_at);
7458       if (breg != 0)
7459         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
7460       if (target_big_endian)
7461         expr1.X_add_number = 0;
7462       macro_build (&expr1, mask == M_ULH_A ? "lb" : "lbu", "t,o(b)",
7463                    treg, BFD_RELOC_LO16, AT);
7464       if (target_big_endian)
7465         expr1.X_add_number = 1;
7466       else
7467         expr1.X_add_number = 0;
7468       macro_build (&expr1, "lbu", "t,o(b)", AT, BFD_RELOC_LO16, AT);
7469       macro_build (NULL, "sll", "d,w,<", treg, treg, 8);
7470       macro_build (NULL, "or", "d,v,t", treg, treg, AT);
7471       break;
7472
7473     case M_USH:
7474       used_at = 1;
7475       if (offset_expr.X_add_number >= 0x7fff)
7476         as_bad (_("operand overflow"));
7477       if (target_big_endian)
7478         ++offset_expr.X_add_number;
7479       macro_build (&offset_expr, "sb", "t,o(b)", treg, BFD_RELOC_LO16, breg);
7480       macro_build (NULL, "srl", "d,w,<", AT, treg, 8);
7481       if (target_big_endian)
7482         --offset_expr.X_add_number;
7483       else
7484         ++offset_expr.X_add_number;
7485       macro_build (&offset_expr, "sb", "t,o(b)", AT, BFD_RELOC_LO16, breg);
7486       break;
7487
7488     case M_USD:
7489       s = "sdl";
7490       s2 = "sdr";
7491       off = 7;
7492       goto usw;
7493     case M_USW:
7494       s = "swl";
7495       s2 = "swr";
7496       off = 3;
7497     usw:
7498       if (offset_expr.X_add_number >= 0x8000 - off)
7499         as_bad (_("operand overflow"));
7500       if (! target_big_endian)
7501         offset_expr.X_add_number += off;
7502       macro_build (&offset_expr, s, "t,o(b)", treg, BFD_RELOC_LO16, breg);
7503       if (! target_big_endian)
7504         offset_expr.X_add_number -= off;
7505       else
7506         offset_expr.X_add_number += off;
7507       macro_build (&offset_expr, s2, "t,o(b)", treg, BFD_RELOC_LO16, breg);
7508       break;
7509
7510     case M_USD_A:
7511       s = "sdl";
7512       s2 = "sdr";
7513       off = 7;
7514       goto uswa;
7515     case M_USW_A:
7516       s = "swl";
7517       s2 = "swr";
7518       off = 3;
7519     uswa:
7520       used_at = 1;
7521       load_address (AT, &offset_expr, &used_at);
7522       if (breg != 0)
7523         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
7524       if (! target_big_endian)
7525         expr1.X_add_number = off;
7526       else
7527         expr1.X_add_number = 0;
7528       macro_build (&expr1, s, "t,o(b)", treg, BFD_RELOC_LO16, AT);
7529       if (! target_big_endian)
7530         expr1.X_add_number = 0;
7531       else
7532         expr1.X_add_number = off;
7533       macro_build (&expr1, s2, "t,o(b)", treg, BFD_RELOC_LO16, AT);
7534       break;
7535
7536     case M_USH_A:
7537       used_at = 1;
7538       load_address (AT, &offset_expr, &used_at);
7539       if (breg != 0)
7540         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
7541       if (! target_big_endian)
7542         expr1.X_add_number = 0;
7543       macro_build (&expr1, "sb", "t,o(b)", treg, BFD_RELOC_LO16, AT);
7544       macro_build (NULL, "srl", "d,w,<", treg, treg, 8);
7545       if (! target_big_endian)
7546         expr1.X_add_number = 1;
7547       else
7548         expr1.X_add_number = 0;
7549       macro_build (&expr1, "sb", "t,o(b)", treg, BFD_RELOC_LO16, AT);
7550       if (! target_big_endian)
7551         expr1.X_add_number = 0;
7552       else
7553         expr1.X_add_number = 1;
7554       macro_build (&expr1, "lbu", "t,o(b)", AT, BFD_RELOC_LO16, AT);
7555       macro_build (NULL, "sll", "d,w,<", treg, treg, 8);
7556       macro_build (NULL, "or", "d,v,t", treg, treg, AT);
7557       break;
7558
7559     default:
7560       /* FIXME: Check if this is one of the itbl macros, since they
7561          are added dynamically.  */
7562       as_bad (_("Macro %s not implemented yet"), ip->insn_mo->name);
7563       break;
7564     }
7565   if (mips_opts.noat && used_at)
7566     as_bad (_("Macro used $at after \".set noat\""));
7567 }
7568
7569 /* Implement macros in mips16 mode.  */
7570
7571 static void
7572 mips16_macro (struct mips_cl_insn *ip)
7573 {
7574   int mask;
7575   int xreg, yreg, zreg, tmp;
7576   expressionS expr1;
7577   int dbl;
7578   const char *s, *s2, *s3;
7579
7580   mask = ip->insn_mo->mask;
7581
7582   xreg = MIPS16_EXTRACT_OPERAND (RX, *ip);
7583   yreg = MIPS16_EXTRACT_OPERAND (RY, *ip);
7584   zreg = MIPS16_EXTRACT_OPERAND (RZ, *ip);
7585
7586   expr1.X_op = O_constant;
7587   expr1.X_op_symbol = NULL;
7588   expr1.X_add_symbol = NULL;
7589   expr1.X_add_number = 1;
7590
7591   dbl = 0;
7592
7593   switch (mask)
7594     {
7595     default:
7596       internalError ();
7597
7598     case M_DDIV_3:
7599       dbl = 1;
7600     case M_DIV_3:
7601       s = "mflo";
7602       goto do_div3;
7603     case M_DREM_3:
7604       dbl = 1;
7605     case M_REM_3:
7606       s = "mfhi";
7607     do_div3:
7608       start_noreorder ();
7609       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", xreg, yreg);
7610       expr1.X_add_number = 2;
7611       macro_build (&expr1, "bnez", "x,p", yreg);
7612       macro_build (NULL, "break", "6", 7);
7613
7614       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
7615          since that causes an overflow.  We should do that as well,
7616          but I don't see how to do the comparisons without a temporary
7617          register.  */
7618       end_noreorder ();
7619       macro_build (NULL, s, "x", zreg);
7620       break;
7621
7622     case M_DIVU_3:
7623       s = "divu";
7624       s2 = "mflo";
7625       goto do_divu3;
7626     case M_REMU_3:
7627       s = "divu";
7628       s2 = "mfhi";
7629       goto do_divu3;
7630     case M_DDIVU_3:
7631       s = "ddivu";
7632       s2 = "mflo";
7633       goto do_divu3;
7634     case M_DREMU_3:
7635       s = "ddivu";
7636       s2 = "mfhi";
7637     do_divu3:
7638       start_noreorder ();
7639       macro_build (NULL, s, "0,x,y", xreg, yreg);
7640       expr1.X_add_number = 2;
7641       macro_build (&expr1, "bnez", "x,p", yreg);
7642       macro_build (NULL, "break", "6", 7);
7643       end_noreorder ();
7644       macro_build (NULL, s2, "x", zreg);
7645       break;
7646
7647     case M_DMUL:
7648       dbl = 1;
7649     case M_MUL:
7650       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", xreg, yreg);
7651       macro_build (NULL, "mflo", "x", zreg);
7652       break;
7653
7654     case M_DSUBU_I:
7655       dbl = 1;
7656       goto do_subu;
7657     case M_SUBU_I:
7658     do_subu:
7659       if (imm_expr.X_op != O_constant)
7660         as_bad (_("Unsupported large constant"));
7661       imm_expr.X_add_number = -imm_expr.X_add_number;
7662       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", yreg, xreg);
7663       break;
7664
7665     case M_SUBU_I_2:
7666       if (imm_expr.X_op != O_constant)
7667         as_bad (_("Unsupported large constant"));
7668       imm_expr.X_add_number = -imm_expr.X_add_number;
7669       macro_build (&imm_expr, "addiu", "x,k", xreg);
7670       break;
7671
7672     case M_DSUBU_I_2:
7673       if (imm_expr.X_op != O_constant)
7674         as_bad (_("Unsupported large constant"));
7675       imm_expr.X_add_number = -imm_expr.X_add_number;
7676       macro_build (&imm_expr, "daddiu", "y,j", yreg);
7677       break;
7678
7679     case M_BEQ:
7680       s = "cmp";
7681       s2 = "bteqz";
7682       goto do_branch;
7683     case M_BNE:
7684       s = "cmp";
7685       s2 = "btnez";
7686       goto do_branch;
7687     case M_BLT:
7688       s = "slt";
7689       s2 = "btnez";
7690       goto do_branch;
7691     case M_BLTU:
7692       s = "sltu";
7693       s2 = "btnez";
7694       goto do_branch;
7695     case M_BLE:
7696       s = "slt";
7697       s2 = "bteqz";
7698       goto do_reverse_branch;
7699     case M_BLEU:
7700       s = "sltu";
7701       s2 = "bteqz";
7702       goto do_reverse_branch;
7703     case M_BGE:
7704       s = "slt";
7705       s2 = "bteqz";
7706       goto do_branch;
7707     case M_BGEU:
7708       s = "sltu";
7709       s2 = "bteqz";
7710       goto do_branch;
7711     case M_BGT:
7712       s = "slt";
7713       s2 = "btnez";
7714       goto do_reverse_branch;
7715     case M_BGTU:
7716       s = "sltu";
7717       s2 = "btnez";
7718
7719     do_reverse_branch:
7720       tmp = xreg;
7721       xreg = yreg;
7722       yreg = tmp;
7723
7724     do_branch:
7725       macro_build (NULL, s, "x,y", xreg, yreg);
7726       macro_build (&offset_expr, s2, "p");
7727       break;
7728
7729     case M_BEQ_I:
7730       s = "cmpi";
7731       s2 = "bteqz";
7732       s3 = "x,U";
7733       goto do_branch_i;
7734     case M_BNE_I:
7735       s = "cmpi";
7736       s2 = "btnez";
7737       s3 = "x,U";
7738       goto do_branch_i;
7739     case M_BLT_I:
7740       s = "slti";
7741       s2 = "btnez";
7742       s3 = "x,8";
7743       goto do_branch_i;
7744     case M_BLTU_I:
7745       s = "sltiu";
7746       s2 = "btnez";
7747       s3 = "x,8";
7748       goto do_branch_i;
7749     case M_BLE_I:
7750       s = "slti";
7751       s2 = "btnez";
7752       s3 = "x,8";
7753       goto do_addone_branch_i;
7754     case M_BLEU_I:
7755       s = "sltiu";
7756       s2 = "btnez";
7757       s3 = "x,8";
7758       goto do_addone_branch_i;
7759     case M_BGE_I:
7760       s = "slti";
7761       s2 = "bteqz";
7762       s3 = "x,8";
7763       goto do_branch_i;
7764     case M_BGEU_I:
7765       s = "sltiu";
7766       s2 = "bteqz";
7767       s3 = "x,8";
7768       goto do_branch_i;
7769     case M_BGT_I:
7770       s = "slti";
7771       s2 = "bteqz";
7772       s3 = "x,8";
7773       goto do_addone_branch_i;
7774     case M_BGTU_I:
7775       s = "sltiu";
7776       s2 = "bteqz";
7777       s3 = "x,8";
7778
7779     do_addone_branch_i:
7780       if (imm_expr.X_op != O_constant)
7781         as_bad (_("Unsupported large constant"));
7782       ++imm_expr.X_add_number;
7783
7784     do_branch_i:
7785       macro_build (&imm_expr, s, s3, xreg);
7786       macro_build (&offset_expr, s2, "p");
7787       break;
7788
7789     case M_ABS:
7790       expr1.X_add_number = 0;
7791       macro_build (&expr1, "slti", "x,8", yreg);
7792       if (xreg != yreg)
7793         move_register (xreg, yreg);
7794       expr1.X_add_number = 2;
7795       macro_build (&expr1, "bteqz", "p");
7796       macro_build (NULL, "neg", "x,w", xreg, xreg);
7797     }
7798 }
7799
7800 /* For consistency checking, verify that all bits are specified either
7801    by the match/mask part of the instruction definition, or by the
7802    operand list.  */
7803 static int
7804 validate_mips_insn (const struct mips_opcode *opc)
7805 {
7806   const char *p = opc->args;
7807   char c;
7808   unsigned long used_bits = opc->mask;
7809
7810   if ((used_bits & opc->match) != opc->match)
7811     {
7812       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
7813               opc->name, opc->args);
7814       return 0;
7815     }
7816 #define USE_BITS(mask,shift)    (used_bits |= ((mask) << (shift)))
7817   while (*p)
7818     switch (c = *p++)
7819       {
7820       case ',': break;
7821       case '(': break;
7822       case ')': break;
7823       case '+':
7824         switch (c = *p++)
7825           {
7826           case '1': USE_BITS (OP_MASK_UDI1,     OP_SH_UDI1);    break;
7827           case '2': USE_BITS (OP_MASK_UDI2,     OP_SH_UDI2);    break;
7828           case '3': USE_BITS (OP_MASK_UDI3,     OP_SH_UDI3);    break;
7829           case '4': USE_BITS (OP_MASK_UDI4,     OP_SH_UDI4);    break;
7830           case 'A': USE_BITS (OP_MASK_SHAMT,    OP_SH_SHAMT);   break;
7831           case 'B': USE_BITS (OP_MASK_INSMSB,   OP_SH_INSMSB);  break;
7832           case 'C': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
7833           case 'D': USE_BITS (OP_MASK_RD,       OP_SH_RD);
7834                     USE_BITS (OP_MASK_SEL,      OP_SH_SEL);     break;
7835           case 'E': USE_BITS (OP_MASK_SHAMT,    OP_SH_SHAMT);   break;
7836           case 'F': USE_BITS (OP_MASK_INSMSB,   OP_SH_INSMSB);  break;
7837           case 'G': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
7838           case 'H': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
7839           case 'I': break;
7840           case 't': USE_BITS (OP_MASK_RT,       OP_SH_RT);      break;
7841           case 'T': USE_BITS (OP_MASK_RT,       OP_SH_RT);
7842                     USE_BITS (OP_MASK_SEL,      OP_SH_SEL);     break;
7843           default:
7844             as_bad (_("internal: bad mips opcode (unknown extension operand type `+%c'): %s %s"),
7845                     c, opc->name, opc->args);
7846             return 0;
7847           }
7848         break;
7849       case '<': USE_BITS (OP_MASK_SHAMT,        OP_SH_SHAMT);   break;
7850       case '>': USE_BITS (OP_MASK_SHAMT,        OP_SH_SHAMT);   break;
7851       case 'A': break;
7852       case 'B': USE_BITS (OP_MASK_CODE20,       OP_SH_CODE20);  break;
7853       case 'C': USE_BITS (OP_MASK_COPZ,         OP_SH_COPZ);    break;
7854       case 'D': USE_BITS (OP_MASK_FD,           OP_SH_FD);      break;
7855       case 'E': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
7856       case 'F': break;
7857       case 'G': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
7858       case 'H': USE_BITS (OP_MASK_SEL,          OP_SH_SEL);     break;
7859       case 'I': break;
7860       case 'J': USE_BITS (OP_MASK_CODE19,       OP_SH_CODE19);  break;
7861       case 'K': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
7862       case 'L': break;
7863       case 'M': USE_BITS (OP_MASK_CCC,          OP_SH_CCC);     break;
7864       case 'N': USE_BITS (OP_MASK_BCC,          OP_SH_BCC);     break;
7865       case 'O': USE_BITS (OP_MASK_ALN,          OP_SH_ALN);     break;
7866       case 'Q': USE_BITS (OP_MASK_VSEL,         OP_SH_VSEL);
7867                 USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
7868       case 'R': USE_BITS (OP_MASK_FR,           OP_SH_FR);      break;
7869       case 'S': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
7870       case 'T': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
7871       case 'V': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
7872       case 'W': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
7873       case 'X': USE_BITS (OP_MASK_FD,           OP_SH_FD);      break;
7874       case 'Y': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
7875       case 'Z': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
7876       case 'a': USE_BITS (OP_MASK_TARGET,       OP_SH_TARGET);  break;
7877       case 'b': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
7878       case 'c': USE_BITS (OP_MASK_CODE,         OP_SH_CODE);    break;
7879       case 'd': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
7880       case 'f': break;
7881       case 'h': USE_BITS (OP_MASK_PREFX,        OP_SH_PREFX);   break;
7882       case 'i': USE_BITS (OP_MASK_IMMEDIATE,    OP_SH_IMMEDIATE); break;
7883       case 'j': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
7884       case 'k': USE_BITS (OP_MASK_CACHE,        OP_SH_CACHE);   break;
7885       case 'l': break;
7886       case 'o': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
7887       case 'p': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
7888       case 'q': USE_BITS (OP_MASK_CODE2,        OP_SH_CODE2);   break;
7889       case 'r': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
7890       case 's': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
7891       case 't': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
7892       case 'u': USE_BITS (OP_MASK_IMMEDIATE,    OP_SH_IMMEDIATE); break;
7893       case 'v': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
7894       case 'w': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
7895       case 'x': break;
7896       case 'z': break;
7897       case 'P': USE_BITS (OP_MASK_PERFREG,      OP_SH_PERFREG); break;
7898       case 'U': USE_BITS (OP_MASK_RD,           OP_SH_RD);
7899                 USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
7900       case 'e': USE_BITS (OP_MASK_VECBYTE,      OP_SH_VECBYTE); break;
7901       case '%': USE_BITS (OP_MASK_VECALIGN,     OP_SH_VECALIGN); break;
7902       case '[': break;
7903       case ']': break;
7904       case '3': USE_BITS (OP_MASK_SA3,          OP_SH_SA3);     break;
7905       case '4': USE_BITS (OP_MASK_SA4,          OP_SH_SA4);     break;
7906       case '5': USE_BITS (OP_MASK_IMM8,         OP_SH_IMM8);    break;
7907       case '6': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
7908       case '7': USE_BITS (OP_MASK_DSPACC,       OP_SH_DSPACC);  break;
7909       case '8': USE_BITS (OP_MASK_WRDSP,        OP_SH_WRDSP);   break;
7910       case '9': USE_BITS (OP_MASK_DSPACC_S,     OP_SH_DSPACC_S);break;
7911       case '0': USE_BITS (OP_MASK_DSPSFT,       OP_SH_DSPSFT);  break;
7912       case '\'': USE_BITS (OP_MASK_RDDSP,       OP_SH_RDDSP);   break;
7913       case ':': USE_BITS (OP_MASK_DSPSFT_7,     OP_SH_DSPSFT_7);break;
7914       case '@': USE_BITS (OP_MASK_IMM10,        OP_SH_IMM10);   break;
7915       case '!': USE_BITS (OP_MASK_MT_U,         OP_SH_MT_U);    break;
7916       case '$': USE_BITS (OP_MASK_MT_H,         OP_SH_MT_H);    break;
7917       case '*': USE_BITS (OP_MASK_MTACC_T,      OP_SH_MTACC_T); break;
7918       case '&': USE_BITS (OP_MASK_MTACC_D,      OP_SH_MTACC_D); break;
7919       case 'g': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
7920       default:
7921         as_bad (_("internal: bad mips opcode (unknown operand type `%c'): %s %s"),
7922                 c, opc->name, opc->args);
7923         return 0;
7924       }
7925 #undef USE_BITS
7926   if (used_bits != 0xffffffff)
7927     {
7928       as_bad (_("internal: bad mips opcode (bits 0x%lx undefined): %s %s"),
7929               ~used_bits & 0xffffffff, opc->name, opc->args);
7930       return 0;
7931     }
7932   return 1;
7933 }
7934
7935 /* UDI immediates.  */
7936 struct mips_immed {
7937   char          type;
7938   unsigned int  shift;
7939   unsigned long mask;
7940   const char *  desc;
7941 };
7942
7943 static const struct mips_immed mips_immed[] = {
7944   { '1',        OP_SH_UDI1,     OP_MASK_UDI1,           0},
7945   { '2',        OP_SH_UDI2,     OP_MASK_UDI2,           0},
7946   { '3',        OP_SH_UDI3,     OP_MASK_UDI3,           0},
7947   { '4',        OP_SH_UDI4,     OP_MASK_UDI4,           0},
7948   { 0,0,0,0 }
7949 };
7950
7951 /* This routine assembles an instruction into its binary format.  As a
7952    side effect, it sets one of the global variables imm_reloc or
7953    offset_reloc to the type of relocation to do if one of the operands
7954    is an address expression.  */
7955
7956 static void
7957 mips_ip (char *str, struct mips_cl_insn *ip)
7958 {
7959   char *s;
7960   const char *args;
7961   char c = 0;
7962   struct mips_opcode *insn;
7963   char *argsStart;
7964   unsigned int regno;
7965   unsigned int lastregno = 0;
7966   unsigned int lastpos = 0;
7967   unsigned int limlo, limhi;
7968   char *s_reset;
7969   char save_c = 0;
7970   offsetT min_range, max_range;
7971
7972   insn_error = NULL;
7973
7974   /* If the instruction contains a '.', we first try to match an instruction
7975      including the '.'.  Then we try again without the '.'.  */
7976   insn = NULL;
7977   for (s = str; *s != '\0' && !ISSPACE (*s); ++s)
7978     continue;
7979
7980   /* If we stopped on whitespace, then replace the whitespace with null for
7981      the call to hash_find.  Save the character we replaced just in case we
7982      have to re-parse the instruction.  */
7983   if (ISSPACE (*s))
7984     {
7985       save_c = *s;
7986       *s++ = '\0';
7987     }
7988
7989   insn = (struct mips_opcode *) hash_find (op_hash, str);
7990
7991   /* If we didn't find the instruction in the opcode table, try again, but
7992      this time with just the instruction up to, but not including the
7993      first '.'.  */
7994   if (insn == NULL)
7995     {
7996       /* Restore the character we overwrite above (if any).  */
7997       if (save_c)
7998         *(--s) = save_c;
7999
8000       /* Scan up to the first '.' or whitespace.  */
8001       for (s = str;
8002            *s != '\0' && *s != '.' && !ISSPACE (*s);
8003            ++s)
8004         continue;
8005
8006       /* If we did not find a '.', then we can quit now.  */
8007       if (*s != '.')
8008         {
8009           insn_error = "unrecognized opcode";
8010           return;
8011         }
8012
8013       /* Lookup the instruction in the hash table.  */
8014       *s++ = '\0';
8015       if ((insn = (struct mips_opcode *) hash_find (op_hash, str)) == NULL)
8016         {
8017           insn_error = "unrecognized opcode";
8018           return;
8019         }
8020     }
8021
8022   argsStart = s;
8023   for (;;)
8024     {
8025       bfd_boolean ok;
8026
8027       assert (strcmp (insn->name, str) == 0);
8028
8029       if (OPCODE_IS_MEMBER (insn,
8030                             (mips_opts.isa
8031                              | (file_ase_mips16 ? INSN_MIPS16 : 0)
8032                              | (mips_opts.ase_mdmx ? INSN_MDMX : 0)
8033                              | (mips_opts.ase_dsp ? INSN_DSP : 0)
8034                              | (mips_opts.ase_mt ? INSN_MT : 0)
8035                              | (mips_opts.ase_mips3d ? INSN_MIPS3D : 0)),
8036                             mips_opts.arch))
8037         ok = TRUE;
8038       else
8039         ok = FALSE;
8040
8041       if (insn->pinfo != INSN_MACRO)
8042         {
8043           if (mips_opts.arch == CPU_R4650 && (insn->pinfo & FP_D) != 0)
8044             ok = FALSE;
8045         }
8046
8047       if (! ok)
8048         {
8049           if (insn + 1 < &mips_opcodes[NUMOPCODES]
8050               && strcmp (insn->name, insn[1].name) == 0)
8051             {
8052               ++insn;
8053               continue;
8054             }
8055           else
8056             {
8057               if (!insn_error)
8058                 {
8059                   static char buf[100];
8060                   sprintf (buf,
8061                            _("opcode not supported on this processor: %s (%s)"),
8062                            mips_cpu_info_from_arch (mips_opts.arch)->name,
8063                            mips_cpu_info_from_isa (mips_opts.isa)->name);
8064                   insn_error = buf;
8065                 }
8066               if (save_c)
8067                 *(--s) = save_c;
8068               return;
8069             }
8070         }
8071
8072       create_insn (ip, insn);
8073       insn_error = NULL;
8074       for (args = insn->args;; ++args)
8075         {
8076           int is_mdmx;
8077
8078           s += strspn (s, " \t");
8079           is_mdmx = 0;
8080           switch (*args)
8081             {
8082             case '\0':          /* end of args */
8083               if (*s == '\0')
8084                 return;
8085               break;
8086
8087             case '3': /* dsp 3-bit unsigned immediate in bit 21 */
8088               my_getExpression (&imm_expr, s);
8089               check_absolute_expr (ip, &imm_expr);
8090               if (imm_expr.X_add_number & ~OP_MASK_SA3)
8091                 {
8092                   as_warn (_("DSP immediate not in range 0..%d (%lu)"),
8093                            OP_MASK_SA3, (unsigned long) imm_expr.X_add_number);
8094                   imm_expr.X_add_number &= OP_MASK_SA3;
8095                 }
8096               ip->insn_opcode |= imm_expr.X_add_number << OP_SH_SA3;
8097               imm_expr.X_op = O_absent;
8098               s = expr_end;
8099               continue;
8100
8101             case '4': /* dsp 4-bit unsigned immediate in bit 21 */
8102               my_getExpression (&imm_expr, s);
8103               check_absolute_expr (ip, &imm_expr);
8104               if (imm_expr.X_add_number & ~OP_MASK_SA4)
8105                 {
8106                   as_warn (_("DSP immediate not in range 0..%d (%lu)"),
8107                            OP_MASK_SA4, (unsigned long) imm_expr.X_add_number);
8108                   imm_expr.X_add_number &= OP_MASK_SA4;
8109                 }
8110               ip->insn_opcode |= imm_expr.X_add_number << OP_SH_SA4;
8111               imm_expr.X_op = O_absent;
8112               s = expr_end;
8113               continue;
8114
8115             case '5': /* dsp 8-bit unsigned immediate in bit 16 */
8116               my_getExpression (&imm_expr, s);
8117               check_absolute_expr (ip, &imm_expr);
8118               if (imm_expr.X_add_number & ~OP_MASK_IMM8)
8119                 {
8120                   as_warn (_("DSP immediate not in range 0..%d (%lu)"),
8121                            OP_MASK_IMM8, (unsigned long) imm_expr.X_add_number);
8122                   imm_expr.X_add_number &= OP_MASK_IMM8;
8123                 }
8124               ip->insn_opcode |= imm_expr.X_add_number << OP_SH_IMM8;
8125               imm_expr.X_op = O_absent;
8126               s = expr_end;
8127               continue;
8128
8129             case '6': /* dsp 5-bit unsigned immediate in bit 21 */
8130               my_getExpression (&imm_expr, s);
8131               check_absolute_expr (ip, &imm_expr);
8132               if (imm_expr.X_add_number & ~OP_MASK_RS)
8133                 {
8134                   as_warn (_("DSP immediate not in range 0..%d (%lu)"),
8135                            OP_MASK_RS, (unsigned long) imm_expr.X_add_number);
8136                   imm_expr.X_add_number &= OP_MASK_RS;
8137                 }
8138               ip->insn_opcode |= imm_expr.X_add_number << OP_SH_RS;
8139               imm_expr.X_op = O_absent;
8140               s = expr_end;
8141               continue;
8142
8143             case '7': /* four dsp accumulators in bits 11,12 */ 
8144               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
8145                   s[3] >= '0' && s[3] <= '3')
8146                 {
8147                   regno = s[3] - '0';
8148                   s += 4;
8149                   ip->insn_opcode |= regno << OP_SH_DSPACC;
8150                   continue;
8151                 }
8152               else
8153                 as_bad (_("Invalid dsp acc register"));
8154               break;
8155
8156             case '8': /* dsp 6-bit unsigned immediate in bit 11 */
8157               my_getExpression (&imm_expr, s);
8158               check_absolute_expr (ip, &imm_expr);
8159               if (imm_expr.X_add_number & ~OP_MASK_WRDSP)
8160                 {
8161                   as_warn (_("DSP immediate not in range 0..%d (%lu)"),
8162                            OP_MASK_WRDSP,
8163                            (unsigned long) imm_expr.X_add_number);
8164                   imm_expr.X_add_number &= OP_MASK_WRDSP;
8165                 }
8166               ip->insn_opcode |= imm_expr.X_add_number << OP_SH_WRDSP;
8167               imm_expr.X_op = O_absent;
8168               s = expr_end;
8169               continue;
8170
8171             case '9': /* four dsp accumulators in bits 21,22 */
8172               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
8173                   s[3] >= '0' && s[3] <= '3')
8174                 {
8175                   regno = s[3] - '0';
8176                   s += 4;
8177                   ip->insn_opcode |= regno << OP_SH_DSPACC_S;
8178                   continue;
8179                 }
8180               else
8181                 as_bad (_("Invalid dsp acc register"));
8182               break;
8183
8184             case '0': /* dsp 6-bit signed immediate in bit 20 */
8185               my_getExpression (&imm_expr, s);
8186               check_absolute_expr (ip, &imm_expr);
8187               min_range = -((OP_MASK_DSPSFT + 1) >> 1);
8188               max_range = ((OP_MASK_DSPSFT + 1) >> 1) - 1;
8189               if (imm_expr.X_add_number < min_range ||
8190                   imm_expr.X_add_number > max_range)
8191                 {
8192                   as_warn (_("DSP immediate not in range %ld..%ld (%ld)"),
8193                            (long) min_range, (long) max_range,
8194                            (long) imm_expr.X_add_number);
8195                 }
8196               imm_expr.X_add_number &= OP_MASK_DSPSFT;
8197               ip->insn_opcode |= ((unsigned long) imm_expr.X_add_number
8198                                   << OP_SH_DSPSFT);
8199               imm_expr.X_op = O_absent;
8200               s = expr_end;
8201               continue;
8202
8203             case '\'': /* dsp 6-bit unsigned immediate in bit 16 */
8204               my_getExpression (&imm_expr, s);
8205               check_absolute_expr (ip, &imm_expr);
8206               if (imm_expr.X_add_number & ~OP_MASK_RDDSP)
8207                 {
8208                   as_warn (_("DSP immediate not in range 0..%d (%lu)"),
8209                            OP_MASK_RDDSP,
8210                            (unsigned long) imm_expr.X_add_number);
8211                   imm_expr.X_add_number &= OP_MASK_RDDSP;
8212                 }
8213               ip->insn_opcode |= imm_expr.X_add_number << OP_SH_RDDSP;
8214               imm_expr.X_op = O_absent;
8215               s = expr_end;
8216               continue;
8217
8218             case ':': /* dsp 7-bit signed immediate in bit 19 */
8219               my_getExpression (&imm_expr, s);
8220               check_absolute_expr (ip, &imm_expr);
8221               min_range = -((OP_MASK_DSPSFT_7 + 1) >> 1);
8222               max_range = ((OP_MASK_DSPSFT_7 + 1) >> 1) - 1;
8223               if (imm_expr.X_add_number < min_range ||
8224                   imm_expr.X_add_number > max_range)
8225                 {
8226                   as_warn (_("DSP immediate not in range %ld..%ld (%ld)"),
8227                            (long) min_range, (long) max_range,
8228                            (long) imm_expr.X_add_number);
8229                 }
8230               imm_expr.X_add_number &= OP_MASK_DSPSFT_7;
8231               ip->insn_opcode |= ((unsigned long) imm_expr.X_add_number
8232                                   << OP_SH_DSPSFT_7);
8233               imm_expr.X_op = O_absent;
8234               s = expr_end;
8235               continue;
8236
8237             case '@': /* dsp 10-bit signed immediate in bit 16 */
8238               my_getExpression (&imm_expr, s);
8239               check_absolute_expr (ip, &imm_expr);
8240               min_range = -((OP_MASK_IMM10 + 1) >> 1);
8241               max_range = ((OP_MASK_IMM10 + 1) >> 1) - 1;
8242               if (imm_expr.X_add_number < min_range ||
8243                   imm_expr.X_add_number > max_range)
8244                 {
8245                   as_warn (_("DSP immediate not in range %ld..%ld (%ld)"),
8246                            (long) min_range, (long) max_range,
8247                            (long) imm_expr.X_add_number);
8248                 }
8249               imm_expr.X_add_number &= OP_MASK_IMM10;
8250               ip->insn_opcode |= ((unsigned long) imm_expr.X_add_number
8251                                   << OP_SH_IMM10);
8252               imm_expr.X_op = O_absent;
8253               s = expr_end;
8254               continue;
8255
8256             case '!': /* mt 1-bit unsigned immediate in bit 5 */
8257               my_getExpression (&imm_expr, s);
8258               check_absolute_expr (ip, &imm_expr);
8259               if (imm_expr.X_add_number & ~OP_MASK_MT_U)
8260                 {
8261                   as_warn (_("MT immediate not in range 0..%d (%lu)"),
8262                            OP_MASK_MT_U, (unsigned long) imm_expr.X_add_number);
8263                   imm_expr.X_add_number &= OP_MASK_MT_U;
8264                 }
8265               ip->insn_opcode |= imm_expr.X_add_number << OP_SH_MT_U;
8266               imm_expr.X_op = O_absent;
8267               s = expr_end;
8268               continue;
8269
8270             case '$': /* mt 1-bit unsigned immediate in bit 4 */
8271               my_getExpression (&imm_expr, s);
8272               check_absolute_expr (ip, &imm_expr);
8273               if (imm_expr.X_add_number & ~OP_MASK_MT_H)
8274                 {
8275                   as_warn (_("MT immediate not in range 0..%d (%lu)"),
8276                            OP_MASK_MT_H, (unsigned long) imm_expr.X_add_number);
8277                   imm_expr.X_add_number &= OP_MASK_MT_H;
8278                 }
8279               ip->insn_opcode |= imm_expr.X_add_number << OP_SH_MT_H;
8280               imm_expr.X_op = O_absent;
8281               s = expr_end;
8282               continue;
8283
8284             case '*': /* four dsp accumulators in bits 18,19 */ 
8285               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
8286                   s[3] >= '0' && s[3] <= '3')
8287                 {
8288                   regno = s[3] - '0';
8289                   s += 4;
8290                   ip->insn_opcode |= regno << OP_SH_MTACC_T;
8291                   continue;
8292                 }
8293               else
8294                 as_bad (_("Invalid dsp/smartmips acc register"));
8295               break;
8296
8297             case '&': /* four dsp accumulators in bits 13,14 */ 
8298               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
8299                   s[3] >= '0' && s[3] <= '3')
8300                 {
8301                   regno = s[3] - '0';
8302                   s += 4;
8303                   ip->insn_opcode |= regno << OP_SH_MTACC_D;
8304                   continue;
8305                 }
8306               else
8307                 as_bad (_("Invalid dsp/smartmips acc register"));
8308               break;
8309
8310             case ',':
8311               if (*s++ == *args)
8312                 continue;
8313               s--;
8314               switch (*++args)
8315                 {
8316                 case 'r':
8317                 case 'v':
8318                   INSERT_OPERAND (RS, *ip, lastregno);
8319                   continue;
8320
8321                 case 'w':
8322                   INSERT_OPERAND (RT, *ip, lastregno);
8323                   continue;
8324
8325                 case 'W':
8326                   INSERT_OPERAND (FT, *ip, lastregno);
8327                   continue;
8328
8329                 case 'V':
8330                   INSERT_OPERAND (FS, *ip, lastregno);
8331                   continue;
8332                 }
8333               break;
8334
8335             case '(':
8336               /* Handle optional base register.
8337                  Either the base register is omitted or
8338                  we must have a left paren.  */
8339               /* This is dependent on the next operand specifier
8340                  is a base register specification.  */
8341               assert (args[1] == 'b' || args[1] == '5'
8342                       || args[1] == '-' || args[1] == '4');
8343               if (*s == '\0')
8344                 return;
8345
8346             case ')':           /* these must match exactly */
8347             case '[':
8348             case ']':
8349               if (*s++ == *args)
8350                 continue;
8351               break;
8352
8353             case '+':           /* Opcode extension character.  */
8354               switch (*++args)
8355                 {
8356                 case '1':       /* UDI immediates.  */
8357                 case '2':
8358                 case '3':
8359                 case '4':
8360                   {
8361                     const struct mips_immed *imm = mips_immed;
8362
8363                     while (imm->type && imm->type != *args)
8364                       ++imm;
8365                     if (! imm->type)
8366                       internalError ();
8367                     my_getExpression (&imm_expr, s);
8368                     check_absolute_expr (ip, &imm_expr);
8369                     if ((unsigned long) imm_expr.X_add_number & ~imm->mask)
8370                       {
8371                         as_warn (_("Illegal %s number (%lu, 0x%lx)"),
8372                                  imm->desc ? imm->desc : ip->insn_mo->name,
8373                                  (unsigned long) imm_expr.X_add_number,
8374                                  (unsigned long) imm_expr.X_add_number);
8375                               imm_expr.X_add_number &= imm->mask;
8376                       }
8377                     ip->insn_opcode |= ((unsigned long) imm_expr.X_add_number
8378                                         << imm->shift);
8379                     imm_expr.X_op = O_absent;
8380                     s = expr_end;
8381                   }
8382                   continue;
8383                   
8384                 case 'A':               /* ins/ext position, becomes LSB.  */
8385                   limlo = 0;
8386                   limhi = 31;
8387                   goto do_lsb;
8388                 case 'E':
8389                   limlo = 32;
8390                   limhi = 63;
8391                   goto do_lsb;
8392 do_lsb:
8393                   my_getExpression (&imm_expr, s);
8394                   check_absolute_expr (ip, &imm_expr);
8395                   if ((unsigned long) imm_expr.X_add_number < limlo
8396                       || (unsigned long) imm_expr.X_add_number > limhi)
8397                     {
8398                       as_bad (_("Improper position (%lu)"),
8399                               (unsigned long) imm_expr.X_add_number);
8400                       imm_expr.X_add_number = limlo;
8401                     }
8402                   lastpos = imm_expr.X_add_number;
8403                   INSERT_OPERAND (SHAMT, *ip, imm_expr.X_add_number);
8404                   imm_expr.X_op = O_absent;
8405                   s = expr_end;
8406                   continue;
8407
8408                 case 'B':               /* ins size, becomes MSB.  */
8409                   limlo = 1;
8410                   limhi = 32;
8411                   goto do_msb;
8412                 case 'F':
8413                   limlo = 33;
8414                   limhi = 64;
8415                   goto do_msb;
8416 do_msb:
8417                   my_getExpression (&imm_expr, s);
8418                   check_absolute_expr (ip, &imm_expr);
8419                   /* Check for negative input so that small negative numbers
8420                      will not succeed incorrectly.  The checks against
8421                      (pos+size) transitively check "size" itself,
8422                      assuming that "pos" is reasonable.  */
8423                   if ((long) imm_expr.X_add_number < 0
8424                       || ((unsigned long) imm_expr.X_add_number
8425                           + lastpos) < limlo
8426                       || ((unsigned long) imm_expr.X_add_number
8427                           + lastpos) > limhi)
8428                     {
8429                       as_bad (_("Improper insert size (%lu, position %lu)"),
8430                               (unsigned long) imm_expr.X_add_number,
8431                               (unsigned long) lastpos);
8432                       imm_expr.X_add_number = limlo - lastpos;
8433                     }
8434                   INSERT_OPERAND (INSMSB, *ip,
8435                                  lastpos + imm_expr.X_add_number - 1);
8436                   imm_expr.X_op = O_absent;
8437                   s = expr_end;
8438                   continue;
8439
8440                 case 'C':               /* ext size, becomes MSBD.  */
8441                   limlo = 1;
8442                   limhi = 32;
8443                   goto do_msbd;
8444                 case 'G':
8445                   limlo = 33;
8446                   limhi = 64;
8447                   goto do_msbd;
8448                 case 'H':
8449                   limlo = 33;
8450                   limhi = 64;
8451                   goto do_msbd;
8452 do_msbd:
8453                   my_getExpression (&imm_expr, s);
8454                   check_absolute_expr (ip, &imm_expr);
8455                   /* Check for negative input so that small negative numbers
8456                      will not succeed incorrectly.  The checks against
8457                      (pos+size) transitively check "size" itself,
8458                      assuming that "pos" is reasonable.  */
8459                   if ((long) imm_expr.X_add_number < 0
8460                       || ((unsigned long) imm_expr.X_add_number
8461                           + lastpos) < limlo
8462                       || ((unsigned long) imm_expr.X_add_number
8463                           + lastpos) > limhi)
8464                     {
8465                       as_bad (_("Improper extract size (%lu, position %lu)"),
8466                               (unsigned long) imm_expr.X_add_number,
8467                               (unsigned long) lastpos);
8468                       imm_expr.X_add_number = limlo - lastpos;
8469                     }
8470                   INSERT_OPERAND (EXTMSBD, *ip, imm_expr.X_add_number - 1);
8471                   imm_expr.X_op = O_absent;
8472                   s = expr_end;
8473                   continue;
8474
8475                 case 'D':
8476                   /* +D is for disassembly only; never match.  */
8477                   break;
8478
8479                 case 'I':
8480                   /* "+I" is like "I", except that imm2_expr is used.  */
8481                   my_getExpression (&imm2_expr, s);
8482                   if (imm2_expr.X_op != O_big
8483                       && imm2_expr.X_op != O_constant)
8484                   insn_error = _("absolute expression required");
8485                   if (HAVE_32BIT_GPRS)
8486                     normalize_constant_expr (&imm2_expr);
8487                   s = expr_end;
8488                   continue;
8489
8490                 case 'T': /* Coprocessor register */
8491                   /* +T is for disassembly only; never match.  */
8492                   break;
8493
8494                 case 't': /* Coprocessor register number */
8495                   if (s[0] == '$' && ISDIGIT (s[1]))
8496                     {
8497                       ++s;
8498                       regno = 0;
8499                       do
8500                         {
8501                           regno *= 10;
8502                           regno += *s - '0';
8503                           ++s;
8504                         }
8505                       while (ISDIGIT (*s));
8506                       if (regno > 31)
8507                         as_bad (_("Invalid register number (%d)"), regno);
8508                       else
8509                         {
8510                           ip->insn_opcode |= regno << OP_SH_RT;
8511                           continue;
8512                         }
8513                     }
8514                   else
8515                     as_bad (_("Invalid coprocessor 0 register number"));
8516                   break;
8517
8518                 default:
8519                   as_bad (_("internal: bad mips opcode (unknown extension operand type `+%c'): %s %s"),
8520                     *args, insn->name, insn->args);
8521                   /* Further processing is fruitless.  */
8522                   return;
8523                 }
8524               break;
8525
8526             case '<':           /* must be at least one digit */
8527               /*
8528                * According to the manual, if the shift amount is greater
8529                * than 31 or less than 0, then the shift amount should be
8530                * mod 32.  In reality the mips assembler issues an error.
8531                * We issue a warning and mask out all but the low 5 bits.
8532                */
8533               my_getExpression (&imm_expr, s);
8534               check_absolute_expr (ip, &imm_expr);
8535               if ((unsigned long) imm_expr.X_add_number > 31)
8536                 as_warn (_("Improper shift amount (%lu)"),
8537                          (unsigned long) imm_expr.X_add_number);
8538               INSERT_OPERAND (SHAMT, *ip, imm_expr.X_add_number);
8539               imm_expr.X_op = O_absent;
8540               s = expr_end;
8541               continue;
8542
8543             case '>':           /* shift amount minus 32 */
8544               my_getExpression (&imm_expr, s);
8545               check_absolute_expr (ip, &imm_expr);
8546               if ((unsigned long) imm_expr.X_add_number < 32
8547                   || (unsigned long) imm_expr.X_add_number > 63)
8548                 break;
8549               INSERT_OPERAND (SHAMT, *ip, imm_expr.X_add_number - 32);
8550               imm_expr.X_op = O_absent;
8551               s = expr_end;
8552               continue;
8553
8554             case 'k':           /* cache code */
8555             case 'h':           /* prefx code */
8556               my_getExpression (&imm_expr, s);
8557               check_absolute_expr (ip, &imm_expr);
8558               if ((unsigned long) imm_expr.X_add_number > 31)
8559                 as_warn (_("Invalid value for `%s' (%lu)"),
8560                          ip->insn_mo->name,
8561                          (unsigned long) imm_expr.X_add_number);
8562               if (*args == 'k')
8563                 INSERT_OPERAND (CACHE, *ip, imm_expr.X_add_number);
8564               else
8565                 INSERT_OPERAND (PREFX, *ip, imm_expr.X_add_number);
8566               imm_expr.X_op = O_absent;
8567               s = expr_end;
8568               continue;
8569
8570             case 'c':           /* break code */
8571               my_getExpression (&imm_expr, s);
8572               check_absolute_expr (ip, &imm_expr);
8573               if ((unsigned long) imm_expr.X_add_number > 1023)
8574                 as_warn (_("Illegal break code (%lu)"),
8575                          (unsigned long) imm_expr.X_add_number);
8576               INSERT_OPERAND (CODE, *ip, imm_expr.X_add_number);
8577               imm_expr.X_op = O_absent;
8578               s = expr_end;
8579               continue;
8580
8581             case 'q':           /* lower break code */
8582               my_getExpression (&imm_expr, s);
8583               check_absolute_expr (ip, &imm_expr);
8584               if ((unsigned long) imm_expr.X_add_number > 1023)
8585                 as_warn (_("Illegal lower break code (%lu)"),
8586                          (unsigned long) imm_expr.X_add_number);
8587               INSERT_OPERAND (CODE2, *ip, imm_expr.X_add_number);
8588               imm_expr.X_op = O_absent;
8589               s = expr_end;
8590               continue;
8591
8592             case 'B':           /* 20-bit syscall/break code.  */
8593               my_getExpression (&imm_expr, s);
8594               check_absolute_expr (ip, &imm_expr);
8595               if ((unsigned long) imm_expr.X_add_number > OP_MASK_CODE20)
8596                 as_warn (_("Illegal 20-bit code (%lu)"),
8597                          (unsigned long) imm_expr.X_add_number);
8598               INSERT_OPERAND (CODE20, *ip, imm_expr.X_add_number);
8599               imm_expr.X_op = O_absent;
8600               s = expr_end;
8601               continue;
8602
8603             case 'C':           /* Coprocessor code */
8604               my_getExpression (&imm_expr, s);
8605               check_absolute_expr (ip, &imm_expr);
8606               if ((unsigned long) imm_expr.X_add_number >= (1 << 25))
8607                 {
8608                   as_warn (_("Coproccesor code > 25 bits (%lu)"),
8609                            (unsigned long) imm_expr.X_add_number);
8610                   imm_expr.X_add_number &= ((1 << 25) - 1);
8611                 }
8612               ip->insn_opcode |= imm_expr.X_add_number;
8613               imm_expr.X_op = O_absent;
8614               s = expr_end;
8615               continue;
8616
8617             case 'J':           /* 19-bit wait code.  */
8618               my_getExpression (&imm_expr, s);
8619               check_absolute_expr (ip, &imm_expr);
8620               if ((unsigned long) imm_expr.X_add_number > OP_MASK_CODE19)
8621                 as_warn (_("Illegal 19-bit code (%lu)"),
8622                          (unsigned long) imm_expr.X_add_number);
8623               INSERT_OPERAND (CODE19, *ip, imm_expr.X_add_number);
8624               imm_expr.X_op = O_absent;
8625               s = expr_end;
8626               continue;
8627
8628             case 'P':           /* Performance register */
8629               my_getExpression (&imm_expr, s);
8630               check_absolute_expr (ip, &imm_expr);
8631               if (imm_expr.X_add_number != 0 && imm_expr.X_add_number != 1)
8632                 as_warn (_("Invalid performance register (%lu)"),
8633                          (unsigned long) imm_expr.X_add_number);
8634               INSERT_OPERAND (PERFREG, *ip, imm_expr.X_add_number);
8635               imm_expr.X_op = O_absent;
8636               s = expr_end;
8637               continue;
8638
8639             case 'b':           /* base register */
8640             case 'd':           /* destination register */
8641             case 's':           /* source register */
8642             case 't':           /* target register */
8643             case 'r':           /* both target and source */
8644             case 'v':           /* both dest and source */
8645             case 'w':           /* both dest and target */
8646             case 'E':           /* coprocessor target register */
8647             case 'G':           /* coprocessor destination register */
8648             case 'K':           /* 'rdhwr' destination register */
8649             case 'x':           /* ignore register name */
8650             case 'z':           /* must be zero register */
8651             case 'U':           /* destination register (clo/clz).  */
8652             case 'g':           /* coprocessor destination register */
8653               s_reset = s;
8654               if (s[0] == '$')
8655                 {
8656                   if (ISDIGIT (s[1]))
8657                     {
8658                       ++s;
8659                       regno = 0;
8660                       do
8661                         {
8662                           regno *= 10;
8663                           regno += *s - '0';
8664                           ++s;
8665                         }
8666                       while (ISDIGIT (*s));
8667                       if (regno > 31)
8668                         as_bad (_("Invalid register number (%d)"), regno);
8669                     }
8670                   else if (*args == 'E' || *args == 'G' || *args == 'K')
8671                     goto notreg;
8672                   else
8673                     {
8674                       if (s[1] == 'r' && s[2] == 'a')
8675                         {
8676                           s += 3;
8677                           regno = RA;
8678                         }
8679                       else if (s[1] == 'f' && s[2] == 'p')
8680                         {
8681                           s += 3;
8682                           regno = FP;
8683                         }
8684                       else if (s[1] == 's' && s[2] == 'p')
8685                         {
8686                           s += 3;
8687                           regno = SP;
8688                         }
8689                       else if (s[1] == 'g' && s[2] == 'p')
8690                         {
8691                           s += 3;
8692                           regno = GP;
8693                         }
8694                       else if (s[1] == 'a' && s[2] == 't')
8695                         {
8696                           s += 3;
8697                           regno = AT;
8698                         }
8699                       else if (s[1] == 'k' && s[2] == 't' && s[3] == '0')
8700                         {
8701                           s += 4;
8702                           regno = KT0;
8703                         }
8704                       else if (s[1] == 'k' && s[2] == 't' && s[3] == '1')
8705                         {
8706                           s += 4;
8707                           regno = KT1;
8708                         }
8709                       else if (s[1] == 'z' && s[2] == 'e' && s[3] == 'r' && s[4] == 'o')
8710                         {
8711                           s += 5;
8712                           regno = ZERO;
8713                         }
8714                       else if (itbl_have_entries)
8715                         {
8716                           char *p, *n;
8717                           unsigned long r;
8718
8719                           p = s + 1;    /* advance past '$' */
8720                           n = itbl_get_field (&p);  /* n is name */
8721
8722                           /* See if this is a register defined in an
8723                              itbl entry.  */
8724                           if (itbl_get_reg_val (n, &r))
8725                             {
8726                               /* Get_field advances to the start of
8727                                  the next field, so we need to back
8728                                  rack to the end of the last field.  */
8729                               if (p)
8730                                 s = p - 1;
8731                               else
8732                                 s = strchr (s, '\0');
8733                               regno = r;
8734                             }
8735                           else
8736                             goto notreg;
8737                         }
8738                       else
8739                         goto notreg;
8740                     }
8741                   if (regno == AT
8742                       && ! mips_opts.noat
8743                       && *args != 'E'
8744                       && *args != 'G'
8745                       && *args != 'K')
8746                     as_warn (_("Used $at without \".set noat\""));
8747                   c = *args;
8748                   if (*s == ' ')
8749                     ++s;
8750                   if (args[1] != *s)
8751                     {
8752                       if (c == 'r' || c == 'v' || c == 'w')
8753                         {
8754                           regno = lastregno;
8755                           s = s_reset;
8756                           ++args;
8757                         }
8758                     }
8759                   /* 'z' only matches $0.  */
8760                   if (c == 'z' && regno != 0)
8761                     break;
8762
8763         /* Now that we have assembled one operand, we use the args string
8764          * to figure out where it goes in the instruction.  */
8765                   switch (c)
8766                     {
8767                     case 'r':
8768                     case 's':
8769                     case 'v':
8770                     case 'b':
8771                       INSERT_OPERAND (RS, *ip, regno);
8772                       break;
8773                     case 'd':
8774                     case 'G':
8775                     case 'K':
8776                     case 'g':
8777                       INSERT_OPERAND (RD, *ip, regno);
8778                       break;
8779                     case 'U':
8780                       INSERT_OPERAND (RD, *ip, regno);
8781                       INSERT_OPERAND (RT, *ip, regno);
8782                       break;
8783                     case 'w':
8784                     case 't':
8785                     case 'E':
8786                       INSERT_OPERAND (RT, *ip, regno);
8787                       break;
8788                     case 'x':
8789                       /* This case exists because on the r3000 trunc
8790                          expands into a macro which requires a gp
8791                          register.  On the r6000 or r4000 it is
8792                          assembled into a single instruction which
8793                          ignores the register.  Thus the insn version
8794                          is MIPS_ISA2 and uses 'x', and the macro
8795                          version is MIPS_ISA1 and uses 't'.  */
8796                       break;
8797                     case 'z':
8798                       /* This case is for the div instruction, which
8799                          acts differently if the destination argument
8800                          is $0.  This only matches $0, and is checked
8801                          outside the switch.  */
8802                       break;
8803                     case 'D':
8804                       /* Itbl operand; not yet implemented. FIXME ?? */
8805                       break;
8806                       /* What about all other operands like 'i', which
8807                          can be specified in the opcode table? */
8808                     }
8809                   lastregno = regno;
8810                   continue;
8811                 }
8812             notreg:
8813               switch (*args++)
8814                 {
8815                 case 'r':
8816                 case 'v':
8817                   INSERT_OPERAND (RS, *ip, lastregno);
8818                   continue;
8819                 case 'w':
8820                   INSERT_OPERAND (RT, *ip, lastregno);
8821                   continue;
8822                 }
8823               break;
8824
8825             case 'O':           /* MDMX alignment immediate constant.  */
8826               my_getExpression (&imm_expr, s);
8827               check_absolute_expr (ip, &imm_expr);
8828               if ((unsigned long) imm_expr.X_add_number > OP_MASK_ALN)
8829                 as_warn ("Improper align amount (%ld), using low bits",
8830                          (long) imm_expr.X_add_number);
8831               INSERT_OPERAND (ALN, *ip, imm_expr.X_add_number);
8832               imm_expr.X_op = O_absent;
8833               s = expr_end;
8834               continue;
8835
8836             case 'Q':           /* MDMX vector, element sel, or const.  */
8837               if (s[0] != '$')
8838                 {
8839                   /* MDMX Immediate.  */
8840                   my_getExpression (&imm_expr, s);
8841                   check_absolute_expr (ip, &imm_expr);
8842                   if ((unsigned long) imm_expr.X_add_number > OP_MASK_FT)
8843                     as_warn (_("Invalid MDMX Immediate (%ld)"),
8844                              (long) imm_expr.X_add_number);
8845                   INSERT_OPERAND (FT, *ip, imm_expr.X_add_number);
8846                   if (ip->insn_opcode & (OP_MASK_VSEL << OP_SH_VSEL))
8847                     ip->insn_opcode |= MDMX_FMTSEL_IMM_QH << OP_SH_VSEL;
8848                   else
8849                     ip->insn_opcode |= MDMX_FMTSEL_IMM_OB << OP_SH_VSEL;
8850                   imm_expr.X_op = O_absent;
8851                   s = expr_end;
8852                   continue;
8853                 }
8854               /* Not MDMX Immediate.  Fall through.  */
8855             case 'X':           /* MDMX destination register.  */
8856             case 'Y':           /* MDMX source register.  */
8857             case 'Z':           /* MDMX target register.  */
8858               is_mdmx = 1;
8859             case 'D':           /* floating point destination register */
8860             case 'S':           /* floating point source register */
8861             case 'T':           /* floating point target register */
8862             case 'R':           /* floating point source register */
8863             case 'V':
8864             case 'W':
8865               s_reset = s;
8866               /* Accept $fN for FP and MDMX register numbers, and in
8867                  addition accept $vN for MDMX register numbers.  */
8868               if ((s[0] == '$' && s[1] == 'f' && ISDIGIT (s[2]))
8869                   || (is_mdmx != 0 && s[0] == '$' && s[1] == 'v'
8870                       && ISDIGIT (s[2])))
8871                 {
8872                   s += 2;
8873                   regno = 0;
8874                   do
8875                     {
8876                       regno *= 10;
8877                       regno += *s - '0';
8878                       ++s;
8879                     }
8880                   while (ISDIGIT (*s));
8881
8882                   if (regno > 31)
8883                     as_bad (_("Invalid float register number (%d)"), regno);
8884
8885                   if ((regno & 1) != 0
8886                       && HAVE_32BIT_FPRS
8887                       && ! (strcmp (str, "mtc1") == 0
8888                             || strcmp (str, "mfc1") == 0
8889                             || strcmp (str, "lwc1") == 0
8890                             || strcmp (str, "swc1") == 0
8891                             || strcmp (str, "l.s") == 0
8892                             || strcmp (str, "s.s") == 0
8893                             || strcmp (str, "mftc1") == 0
8894                             || strcmp (str, "mfthc1") == 0
8895                             || strcmp (str, "cftc1") == 0
8896                             || strcmp (str, "mttc1") == 0
8897                             || strcmp (str, "mtthc1") == 0
8898                             || strcmp (str, "cttc1") == 0))
8899                     as_warn (_("Float register should be even, was %d"),
8900                              regno);
8901
8902                   c = *args;
8903                   if (*s == ' ')
8904                     ++s;
8905                   if (args[1] != *s)
8906                     {
8907                       if (c == 'V' || c == 'W')
8908                         {
8909                           regno = lastregno;
8910                           s = s_reset;
8911                           ++args;
8912                         }
8913                     }
8914                   switch (c)
8915                     {
8916                     case 'D':
8917                     case 'X':
8918                       INSERT_OPERAND (FD, *ip, regno);
8919                       break;
8920                     case 'V':
8921                     case 'S':
8922                     case 'Y':
8923                       INSERT_OPERAND (FS, *ip, regno);
8924                       break;
8925                     case 'Q':
8926                       /* This is like 'Z', but also needs to fix the MDMX
8927                          vector/scalar select bits.  Note that the
8928                          scalar immediate case is handled above.  */
8929                       if (*s == '[')
8930                         {
8931                           int is_qh = (ip->insn_opcode & (1 << OP_SH_VSEL));
8932                           int max_el = (is_qh ? 3 : 7);
8933                           s++;
8934                           my_getExpression(&imm_expr, s);
8935                           check_absolute_expr (ip, &imm_expr);
8936                           s = expr_end;
8937                           if (imm_expr.X_add_number > max_el)
8938                             as_bad(_("Bad element selector %ld"),
8939                                    (long) imm_expr.X_add_number);
8940                           imm_expr.X_add_number &= max_el;
8941                           ip->insn_opcode |= (imm_expr.X_add_number
8942                                               << (OP_SH_VSEL +
8943                                                   (is_qh ? 2 : 1)));
8944                           imm_expr.X_op = O_absent;
8945                           if (*s != ']')
8946                             as_warn(_("Expecting ']' found '%s'"), s);
8947                           else
8948                             s++;
8949                         }
8950                       else
8951                         {
8952                           if (ip->insn_opcode & (OP_MASK_VSEL << OP_SH_VSEL))
8953                             ip->insn_opcode |= (MDMX_FMTSEL_VEC_QH
8954                                                 << OP_SH_VSEL);
8955                           else
8956                             ip->insn_opcode |= (MDMX_FMTSEL_VEC_OB <<
8957                                                 OP_SH_VSEL);
8958                         }
8959                       /* Fall through */
8960                     case 'W':
8961                     case 'T':
8962                     case 'Z':
8963                       INSERT_OPERAND (FT, *ip, regno);
8964                       break;
8965                     case 'R':
8966                       INSERT_OPERAND (FR, *ip, regno);
8967                       break;
8968                     }
8969                   lastregno = regno;
8970                   continue;
8971                 }
8972
8973               switch (*args++)
8974                 {
8975                 case 'V':
8976                   INSERT_OPERAND (FS, *ip, lastregno);
8977                   continue;
8978                 case 'W':
8979                   INSERT_OPERAND (FT, *ip, lastregno);
8980                   continue;
8981                 }
8982               break;
8983
8984             case 'I':
8985               my_getExpression (&imm_expr, s);
8986               if (imm_expr.X_op != O_big
8987                   && imm_expr.X_op != O_constant)
8988                 insn_error = _("absolute expression required");
8989               if (HAVE_32BIT_GPRS)
8990                 normalize_constant_expr (&imm_expr);
8991               s = expr_end;
8992               continue;
8993
8994             case 'A':
8995               my_getExpression (&offset_expr, s);
8996               normalize_address_expr (&offset_expr);
8997               *imm_reloc = BFD_RELOC_32;
8998               s = expr_end;
8999               continue;
9000
9001             case 'F':
9002             case 'L':
9003             case 'f':
9004             case 'l':
9005               {
9006                 int f64;
9007                 int using_gprs;
9008                 char *save_in;
9009                 char *err;
9010                 unsigned char temp[8];
9011                 int len;
9012                 unsigned int length;
9013                 segT seg;
9014                 subsegT subseg;
9015                 char *p;
9016
9017                 /* These only appear as the last operand in an
9018                    instruction, and every instruction that accepts
9019                    them in any variant accepts them in all variants.
9020                    This means we don't have to worry about backing out
9021                    any changes if the instruction does not match.
9022
9023                    The difference between them is the size of the
9024                    floating point constant and where it goes.  For 'F'
9025                    and 'L' the constant is 64 bits; for 'f' and 'l' it
9026                    is 32 bits.  Where the constant is placed is based
9027                    on how the MIPS assembler does things:
9028                     F -- .rdata
9029                     L -- .lit8
9030                     f -- immediate value
9031                     l -- .lit4
9032
9033                     The .lit4 and .lit8 sections are only used if
9034                     permitted by the -G argument.
9035
9036                     The code below needs to know whether the target register
9037                     is 32 or 64 bits wide.  It relies on the fact 'f' and
9038                     'F' are used with GPR-based instructions and 'l' and
9039                     'L' are used with FPR-based instructions.  */
9040
9041                 f64 = *args == 'F' || *args == 'L';
9042                 using_gprs = *args == 'F' || *args == 'f';
9043
9044                 save_in = input_line_pointer;
9045                 input_line_pointer = s;
9046                 err = md_atof (f64 ? 'd' : 'f', (char *) temp, &len);
9047                 length = len;
9048                 s = input_line_pointer;
9049                 input_line_pointer = save_in;
9050                 if (err != NULL && *err != '\0')
9051                   {
9052                     as_bad (_("Bad floating point constant: %s"), err);
9053                     memset (temp, '\0', sizeof temp);
9054                     length = f64 ? 8 : 4;
9055                   }
9056
9057                 assert (length == (unsigned) (f64 ? 8 : 4));
9058
9059                 if (*args == 'f'
9060                     || (*args == 'l'
9061                         && (g_switch_value < 4
9062                             || (temp[0] == 0 && temp[1] == 0)
9063                             || (temp[2] == 0 && temp[3] == 0))))
9064                   {
9065                     imm_expr.X_op = O_constant;
9066                     if (! target_big_endian)
9067                       imm_expr.X_add_number = bfd_getl32 (temp);
9068                     else
9069                       imm_expr.X_add_number = bfd_getb32 (temp);
9070                   }
9071                 else if (length > 4
9072                          && ! mips_disable_float_construction
9073                          /* Constants can only be constructed in GPRs and
9074                             copied to FPRs if the GPRs are at least as wide
9075                             as the FPRs.  Force the constant into memory if
9076                             we are using 64-bit FPRs but the GPRs are only
9077                             32 bits wide.  */
9078                          && (using_gprs
9079                              || ! (HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
9080                          && ((temp[0] == 0 && temp[1] == 0)
9081                              || (temp[2] == 0 && temp[3] == 0))
9082                          && ((temp[4] == 0 && temp[5] == 0)
9083                              || (temp[6] == 0 && temp[7] == 0)))
9084                   {
9085                     /* The value is simple enough to load with a couple of
9086                        instructions.  If using 32-bit registers, set
9087                        imm_expr to the high order 32 bits and offset_expr to
9088                        the low order 32 bits.  Otherwise, set imm_expr to
9089                        the entire 64 bit constant.  */
9090                     if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
9091                       {
9092                         imm_expr.X_op = O_constant;
9093                         offset_expr.X_op = O_constant;
9094                         if (! target_big_endian)
9095                           {
9096                             imm_expr.X_add_number = bfd_getl32 (temp + 4);
9097                             offset_expr.X_add_number = bfd_getl32 (temp);
9098                           }
9099                         else
9100                           {
9101                             imm_expr.X_add_number = bfd_getb32 (temp);
9102                             offset_expr.X_add_number = bfd_getb32 (temp + 4);
9103                           }
9104                         if (offset_expr.X_add_number == 0)
9105                           offset_expr.X_op = O_absent;
9106                       }
9107                     else if (sizeof (imm_expr.X_add_number) > 4)
9108                       {
9109                         imm_expr.X_op = O_constant;
9110                         if (! target_big_endian)
9111                           imm_expr.X_add_number = bfd_getl64 (temp);
9112                         else
9113                           imm_expr.X_add_number = bfd_getb64 (temp);
9114                       }
9115                     else
9116                       {
9117                         imm_expr.X_op = O_big;
9118                         imm_expr.X_add_number = 4;
9119                         if (! target_big_endian)
9120                           {
9121                             generic_bignum[0] = bfd_getl16 (temp);
9122                             generic_bignum[1] = bfd_getl16 (temp + 2);
9123                             generic_bignum[2] = bfd_getl16 (temp + 4);
9124                             generic_bignum[3] = bfd_getl16 (temp + 6);
9125                           }
9126                         else
9127                           {
9128                             generic_bignum[0] = bfd_getb16 (temp + 6);
9129                             generic_bignum[1] = bfd_getb16 (temp + 4);
9130                             generic_bignum[2] = bfd_getb16 (temp + 2);
9131                             generic_bignum[3] = bfd_getb16 (temp);
9132                           }
9133                       }
9134                   }
9135                 else
9136                   {
9137                     const char *newname;
9138                     segT new_seg;
9139
9140                     /* Switch to the right section.  */
9141                     seg = now_seg;
9142                     subseg = now_subseg;
9143                     switch (*args)
9144                       {
9145                       default: /* unused default case avoids warnings.  */
9146                       case 'L':
9147                         newname = RDATA_SECTION_NAME;
9148                         if (g_switch_value >= 8)
9149                           newname = ".lit8";
9150                         break;
9151                       case 'F':
9152                         newname = RDATA_SECTION_NAME;
9153                         break;
9154                       case 'l':
9155                         assert (g_switch_value >= 4);
9156                         newname = ".lit4";
9157                         break;
9158                       }
9159                     new_seg = subseg_new (newname, (subsegT) 0);
9160                     if (OUTPUT_FLAVOR == bfd_target_elf_flavour)
9161                       bfd_set_section_flags (stdoutput, new_seg,
9162                                              (SEC_ALLOC
9163                                               | SEC_LOAD
9164                                               | SEC_READONLY
9165                                               | SEC_DATA));
9166                     frag_align (*args == 'l' ? 2 : 3, 0, 0);
9167                     if (OUTPUT_FLAVOR == bfd_target_elf_flavour
9168                         && strcmp (TARGET_OS, "elf") != 0)
9169                       record_alignment (new_seg, 4);
9170                     else
9171                       record_alignment (new_seg, *args == 'l' ? 2 : 3);
9172                     if (seg == now_seg)
9173                       as_bad (_("Can't use floating point insn in this section"));
9174
9175                     /* Set the argument to the current address in the
9176                        section.  */
9177                     offset_expr.X_op = O_symbol;
9178                     offset_expr.X_add_symbol =
9179                       symbol_new ("L0\001", now_seg,
9180                                   (valueT) frag_now_fix (), frag_now);
9181                     offset_expr.X_add_number = 0;
9182
9183                     /* Put the floating point number into the section.  */
9184                     p = frag_more ((int) length);
9185                     memcpy (p, temp, length);
9186
9187                     /* Switch back to the original section.  */
9188                     subseg_set (seg, subseg);
9189                   }
9190               }
9191               continue;
9192
9193             case 'i':           /* 16 bit unsigned immediate */
9194             case 'j':           /* 16 bit signed immediate */
9195               *imm_reloc = BFD_RELOC_LO16;
9196               if (my_getSmallExpression (&imm_expr, imm_reloc, s) == 0)
9197                 {
9198                   int more;
9199                   offsetT minval, maxval;
9200
9201                   more = (insn + 1 < &mips_opcodes[NUMOPCODES]
9202                           && strcmp (insn->name, insn[1].name) == 0);
9203
9204                   /* If the expression was written as an unsigned number,
9205                      only treat it as signed if there are no more
9206                      alternatives.  */
9207                   if (more
9208                       && *args == 'j'
9209                       && sizeof (imm_expr.X_add_number) <= 4
9210                       && imm_expr.X_op == O_constant
9211                       && imm_expr.X_add_number < 0
9212                       && imm_expr.X_unsigned
9213                       && HAVE_64BIT_GPRS)
9214                     break;
9215
9216                   /* For compatibility with older assemblers, we accept
9217                      0x8000-0xffff as signed 16-bit numbers when only
9218                      signed numbers are allowed.  */
9219                   if (*args == 'i')
9220                     minval = 0, maxval = 0xffff;
9221                   else if (more)
9222                     minval = -0x8000, maxval = 0x7fff;
9223                   else
9224                     minval = -0x8000, maxval = 0xffff;
9225
9226                   if (imm_expr.X_op != O_constant
9227                       || imm_expr.X_add_number < minval
9228                       || imm_expr.X_add_number > maxval)
9229                     {
9230                       if (more)
9231                         break;
9232                       if (imm_expr.X_op == O_constant
9233                           || imm_expr.X_op == O_big)
9234                         as_bad (_("expression out of range"));
9235                     }
9236                 }
9237               s = expr_end;
9238               continue;
9239
9240             case 'o':           /* 16 bit offset */
9241               /* Check whether there is only a single bracketed expression
9242                  left.  If so, it must be the base register and the
9243                  constant must be zero.  */
9244               if (*s == '(' && strchr (s + 1, '(') == 0)
9245                 {
9246                   offset_expr.X_op = O_constant;
9247                   offset_expr.X_add_number = 0;
9248                   continue;
9249                 }
9250
9251               /* If this value won't fit into a 16 bit offset, then go
9252                  find a macro that will generate the 32 bit offset
9253                  code pattern.  */
9254               if (my_getSmallExpression (&offset_expr, offset_reloc, s) == 0
9255                   && (offset_expr.X_op != O_constant
9256                       || offset_expr.X_add_number >= 0x8000
9257                       || offset_expr.X_add_number < -0x8000))
9258                 break;
9259
9260               s = expr_end;
9261               continue;
9262
9263             case 'p':           /* pc relative offset */
9264               *offset_reloc = BFD_RELOC_16_PCREL_S2;
9265               my_getExpression (&offset_expr, s);
9266               s = expr_end;
9267               continue;
9268
9269             case 'u':           /* upper 16 bits */
9270               if (my_getSmallExpression (&imm_expr, imm_reloc, s) == 0
9271                   && imm_expr.X_op == O_constant
9272                   && (imm_expr.X_add_number < 0
9273                       || imm_expr.X_add_number >= 0x10000))
9274                 as_bad (_("lui expression not in range 0..65535"));
9275               s = expr_end;
9276               continue;
9277
9278             case 'a':           /* 26 bit address */
9279               my_getExpression (&offset_expr, s);
9280               s = expr_end;
9281               *offset_reloc = BFD_RELOC_MIPS_JMP;
9282               continue;
9283
9284             case 'N':           /* 3 bit branch condition code */
9285             case 'M':           /* 3 bit compare condition code */
9286               if (strncmp (s, "$fcc", 4) != 0)
9287                 break;
9288               s += 4;
9289               regno = 0;
9290               do
9291                 {
9292                   regno *= 10;
9293                   regno += *s - '0';
9294                   ++s;
9295                 }
9296               while (ISDIGIT (*s));
9297               if (regno > 7)
9298                 as_bad (_("Invalid condition code register $fcc%d"), regno);
9299               if ((strcmp(str + strlen(str) - 3, ".ps") == 0
9300                    || strcmp(str + strlen(str) - 5, "any2f") == 0
9301                    || strcmp(str + strlen(str) - 5, "any2t") == 0)
9302                   && (regno & 1) != 0)
9303                 as_warn(_("Condition code register should be even for %s, was %d"),
9304                         str, regno);
9305               if ((strcmp(str + strlen(str) - 5, "any4f") == 0
9306                    || strcmp(str + strlen(str) - 5, "any4t") == 0)
9307                   && (regno & 3) != 0)
9308                 as_warn(_("Condition code register should be 0 or 4 for %s, was %d"),
9309                         str, regno);
9310               if (*args == 'N')
9311                 INSERT_OPERAND (BCC, *ip, regno);
9312               else
9313                 INSERT_OPERAND (CCC, *ip, regno);
9314               continue;
9315
9316             case 'H':
9317               if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
9318                 s += 2;
9319               if (ISDIGIT (*s))
9320                 {
9321                   c = 0;
9322                   do
9323                     {
9324                       c *= 10;
9325                       c += *s - '0';
9326                       ++s;
9327                     }
9328                   while (ISDIGIT (*s));
9329                 }
9330               else
9331                 c = 8; /* Invalid sel value.  */
9332
9333               if (c > 7)
9334                 as_bad (_("invalid coprocessor sub-selection value (0-7)"));
9335               ip->insn_opcode |= c;
9336               continue;
9337
9338             case 'e':
9339               /* Must be at least one digit.  */
9340               my_getExpression (&imm_expr, s);
9341               check_absolute_expr (ip, &imm_expr);
9342
9343               if ((unsigned long) imm_expr.X_add_number
9344                   > (unsigned long) OP_MASK_VECBYTE)
9345                 {
9346                   as_bad (_("bad byte vector index (%ld)"),
9347                            (long) imm_expr.X_add_number);
9348                   imm_expr.X_add_number = 0;
9349                 }
9350
9351               INSERT_OPERAND (VECBYTE, *ip, imm_expr.X_add_number);
9352               imm_expr.X_op = O_absent;
9353               s = expr_end;
9354               continue;
9355
9356             case '%':
9357               my_getExpression (&imm_expr, s);
9358               check_absolute_expr (ip, &imm_expr);
9359
9360               if ((unsigned long) imm_expr.X_add_number
9361                   > (unsigned long) OP_MASK_VECALIGN)
9362                 {
9363                   as_bad (_("bad byte vector index (%ld)"),
9364                            (long) imm_expr.X_add_number);
9365                   imm_expr.X_add_number = 0;
9366                 }
9367
9368               INSERT_OPERAND (VECALIGN, *ip, imm_expr.X_add_number);
9369               imm_expr.X_op = O_absent;
9370               s = expr_end;
9371               continue;
9372
9373             default:
9374               as_bad (_("bad char = '%c'\n"), *args);
9375               internalError ();
9376             }
9377           break;
9378         }
9379       /* Args don't match.  */
9380       if (insn + 1 < &mips_opcodes[NUMOPCODES] &&
9381           !strcmp (insn->name, insn[1].name))
9382         {
9383           ++insn;
9384           s = argsStart;
9385           insn_error = _("illegal operands");
9386           continue;
9387         }
9388       if (save_c)
9389         *(--s) = save_c;
9390       insn_error = _("illegal operands");
9391       return;
9392     }
9393 }
9394
9395 #define SKIP_SPACE_TABS(S) { while (*(S) == ' ' || *(S) == '\t') ++(S); }
9396
9397 /* This routine assembles an instruction into its binary format when
9398    assembling for the mips16.  As a side effect, it sets one of the
9399    global variables imm_reloc or offset_reloc to the type of
9400    relocation to do if one of the operands is an address expression.
9401    It also sets mips16_small and mips16_ext if the user explicitly
9402    requested a small or extended instruction.  */
9403
9404 static void
9405 mips16_ip (char *str, struct mips_cl_insn *ip)
9406 {
9407   char *s;
9408   const char *args;
9409   struct mips_opcode *insn;
9410   char *argsstart;
9411   unsigned int regno;
9412   unsigned int lastregno = 0;
9413   char *s_reset;
9414   size_t i;
9415
9416   insn_error = NULL;
9417
9418   mips16_small = FALSE;
9419   mips16_ext = FALSE;
9420
9421   for (s = str; ISLOWER (*s); ++s)
9422     ;
9423   switch (*s)
9424     {
9425     case '\0':
9426       break;
9427
9428     case ' ':
9429       *s++ = '\0';
9430       break;
9431
9432     case '.':
9433       if (s[1] == 't' && s[2] == ' ')
9434         {
9435           *s = '\0';
9436           mips16_small = TRUE;
9437           s += 3;
9438           break;
9439         }
9440       else if (s[1] == 'e' && s[2] == ' ')
9441         {
9442           *s = '\0';
9443           mips16_ext = TRUE;
9444           s += 3;
9445           break;
9446         }
9447       /* Fall through.  */
9448     default:
9449       insn_error = _("unknown opcode");
9450       return;
9451     }
9452
9453   if (mips_opts.noautoextend && ! mips16_ext)
9454     mips16_small = TRUE;
9455
9456   if ((insn = (struct mips_opcode *) hash_find (mips16_op_hash, str)) == NULL)
9457     {
9458       insn_error = _("unrecognized opcode");
9459       return;
9460     }
9461
9462   argsstart = s;
9463   for (;;)
9464     {
9465       assert (strcmp (insn->name, str) == 0);
9466
9467       create_insn (ip, insn);
9468       imm_expr.X_op = O_absent;
9469       imm_reloc[0] = BFD_RELOC_UNUSED;
9470       imm_reloc[1] = BFD_RELOC_UNUSED;
9471       imm_reloc[2] = BFD_RELOC_UNUSED;
9472       imm2_expr.X_op = O_absent;
9473       offset_expr.X_op = O_absent;
9474       offset_reloc[0] = BFD_RELOC_UNUSED;
9475       offset_reloc[1] = BFD_RELOC_UNUSED;
9476       offset_reloc[2] = BFD_RELOC_UNUSED;
9477       for (args = insn->args; 1; ++args)
9478         {
9479           int c;
9480
9481           if (*s == ' ')
9482             ++s;
9483
9484           /* In this switch statement we call break if we did not find
9485              a match, continue if we did find a match, or return if we
9486              are done.  */
9487
9488           c = *args;
9489           switch (c)
9490             {
9491             case '\0':
9492               if (*s == '\0')
9493                 {
9494                   /* Stuff the immediate value in now, if we can.  */
9495                   if (imm_expr.X_op == O_constant
9496                       && *imm_reloc > BFD_RELOC_UNUSED
9497                       && insn->pinfo != INSN_MACRO)
9498                     {
9499                       valueT tmp;
9500
9501                       switch (*offset_reloc)
9502                         {
9503                           case BFD_RELOC_MIPS16_HI16_S:
9504                             tmp = (imm_expr.X_add_number + 0x8000) >> 16;
9505                             break;
9506
9507                           case BFD_RELOC_MIPS16_HI16:
9508                             tmp = imm_expr.X_add_number >> 16;
9509                             break;
9510
9511                           case BFD_RELOC_MIPS16_LO16:
9512                             tmp = ((imm_expr.X_add_number + 0x8000) & 0xffff)
9513                                   - 0x8000;
9514                             break;
9515
9516                           case BFD_RELOC_UNUSED:
9517                             tmp = imm_expr.X_add_number;
9518                             break;
9519
9520                           default:
9521                             internalError ();
9522                         }
9523                       *offset_reloc = BFD_RELOC_UNUSED;
9524
9525                       mips16_immed (NULL, 0, *imm_reloc - BFD_RELOC_UNUSED,
9526                                     tmp, TRUE, mips16_small,
9527                                     mips16_ext, &ip->insn_opcode,
9528                                     &ip->use_extend, &ip->extend);
9529                       imm_expr.X_op = O_absent;
9530                       *imm_reloc = BFD_RELOC_UNUSED;
9531                     }
9532
9533                   return;
9534                 }
9535               break;
9536
9537             case ',':
9538               if (*s++ == c)
9539                 continue;
9540               s--;
9541               switch (*++args)
9542                 {
9543                 case 'v':
9544                   MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
9545                   continue;
9546                 case 'w':
9547                   MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
9548                   continue;
9549                 }
9550               break;
9551
9552             case '(':
9553             case ')':
9554               if (*s++ == c)
9555                 continue;
9556               break;
9557
9558             case 'v':
9559             case 'w':
9560               if (s[0] != '$')
9561                 {
9562                   if (c == 'v')
9563                     MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
9564                   else
9565                     MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
9566                   ++args;
9567                   continue;
9568                 }
9569               /* Fall through.  */
9570             case 'x':
9571             case 'y':
9572             case 'z':
9573             case 'Z':
9574             case '0':
9575             case 'S':
9576             case 'R':
9577             case 'X':
9578             case 'Y':
9579               if (s[0] != '$')
9580                 break;
9581               s_reset = s;
9582               if (ISDIGIT (s[1]))
9583                 {
9584                   ++s;
9585                   regno = 0;
9586                   do
9587                     {
9588                       regno *= 10;
9589                       regno += *s - '0';
9590                       ++s;
9591                     }
9592                   while (ISDIGIT (*s));
9593                   if (regno > 31)
9594                     {
9595                       as_bad (_("invalid register number (%d)"), regno);
9596                       regno = 2;
9597                     }
9598                 }
9599               else
9600                 {
9601                   if (s[1] == 'r' && s[2] == 'a')
9602                     {
9603                       s += 3;
9604                       regno = RA;
9605                     }
9606                   else if (s[1] == 'f' && s[2] == 'p')
9607                     {
9608                       s += 3;
9609                       regno = FP;
9610                     }
9611                   else if (s[1] == 's' && s[2] == 'p')
9612                     {
9613                       s += 3;
9614                       regno = SP;
9615                     }
9616                   else if (s[1] == 'g' && s[2] == 'p')
9617                     {
9618                       s += 3;
9619                       regno = GP;
9620                     }
9621                   else if (s[1] == 'a' && s[2] == 't')
9622                     {
9623                       s += 3;
9624                       regno = AT;
9625                     }
9626                   else if (s[1] == 'k' && s[2] == 't' && s[3] == '0')
9627                     {
9628                       s += 4;
9629                       regno = KT0;
9630                     }
9631                   else if (s[1] == 'k' && s[2] == 't' && s[3] == '1')
9632                     {
9633                       s += 4;
9634                       regno = KT1;
9635                     }
9636                   else if (s[1] == 'z' && s[2] == 'e' && s[3] == 'r' && s[4] == 'o')
9637                     {
9638                       s += 5;
9639                       regno = ZERO;
9640                     }
9641                   else
9642                     break;
9643                 }
9644
9645               if (*s == ' ')
9646                 ++s;
9647               if (args[1] != *s)
9648                 {
9649                   if (c == 'v' || c == 'w')
9650                     {
9651                       regno = mips16_to_32_reg_map[lastregno];
9652                       s = s_reset;
9653                       ++args;
9654                     }
9655                 }
9656
9657               switch (c)
9658                 {
9659                 case 'x':
9660                 case 'y':
9661                 case 'z':
9662                 case 'v':
9663                 case 'w':
9664                 case 'Z':
9665                   regno = mips32_to_16_reg_map[regno];
9666                   break;
9667
9668                 case '0':
9669                   if (regno != 0)
9670                     regno = ILLEGAL_REG;
9671                   break;
9672
9673                 case 'S':
9674                   if (regno != SP)
9675                     regno = ILLEGAL_REG;
9676                   break;
9677
9678                 case 'R':
9679                   if (regno != RA)
9680                     regno = ILLEGAL_REG;
9681                   break;
9682
9683                 case 'X':
9684                 case 'Y':
9685                   if (regno == AT && ! mips_opts.noat)
9686                     as_warn (_("used $at without \".set noat\""));
9687                   break;
9688
9689                 default:
9690                   internalError ();
9691                 }
9692
9693               if (regno == ILLEGAL_REG)
9694                 break;
9695
9696               switch (c)
9697                 {
9698                 case 'x':
9699                 case 'v':
9700                   MIPS16_INSERT_OPERAND (RX, *ip, regno);
9701                   break;
9702                 case 'y':
9703                 case 'w':
9704                   MIPS16_INSERT_OPERAND (RY, *ip, regno);
9705                   break;
9706                 case 'z':
9707                   MIPS16_INSERT_OPERAND (RZ, *ip, regno);
9708                   break;
9709                 case 'Z':
9710                   MIPS16_INSERT_OPERAND (MOVE32Z, *ip, regno);
9711                 case '0':
9712                 case 'S':
9713                 case 'R':
9714                   break;
9715                 case 'X':
9716                   MIPS16_INSERT_OPERAND (REGR32, *ip, regno);
9717                   break;
9718                 case 'Y':
9719                   regno = ((regno & 7) << 2) | ((regno & 0x18) >> 3);
9720                   MIPS16_INSERT_OPERAND (REG32R, *ip, regno);
9721                   break;
9722                 default:
9723                   internalError ();
9724                 }
9725
9726               lastregno = regno;
9727               continue;
9728
9729             case 'P':
9730               if (strncmp (s, "$pc", 3) == 0)
9731                 {
9732                   s += 3;
9733                   continue;
9734                 }
9735               break;
9736
9737             case '5':
9738             case 'H':
9739             case 'W':
9740             case 'D':
9741             case 'j':
9742             case 'V':
9743             case 'C':
9744             case 'U':
9745             case 'k':
9746             case 'K':
9747               i = my_getSmallExpression (&imm_expr, imm_reloc, s);
9748               if (i > 0)
9749                 {
9750                   if (imm_expr.X_op != O_constant)
9751                     {
9752                       mips16_ext = TRUE;
9753                       ip->use_extend = TRUE;
9754                       ip->extend = 0;
9755                     }
9756                   else
9757                     {
9758                       /* We need to relax this instruction.  */
9759                       *offset_reloc = *imm_reloc;
9760                       *imm_reloc = (int) BFD_RELOC_UNUSED + c;
9761                     }
9762                   s = expr_end;
9763                   continue;
9764                 }
9765               *imm_reloc = BFD_RELOC_UNUSED;
9766               /* Fall through.  */
9767             case '<':
9768             case '>':
9769             case '[':
9770             case ']':
9771             case '4':
9772             case '8':
9773               my_getExpression (&imm_expr, s);
9774               if (imm_expr.X_op == O_register)
9775                 {
9776                   /* What we thought was an expression turned out to
9777                      be a register.  */
9778
9779                   if (s[0] == '(' && args[1] == '(')
9780                     {
9781                       /* It looks like the expression was omitted
9782                          before a register indirection, which means
9783                          that the expression is implicitly zero.  We
9784                          still set up imm_expr, so that we handle
9785                          explicit extensions correctly.  */
9786                       imm_expr.X_op = O_constant;
9787                       imm_expr.X_add_number = 0;
9788                       *imm_reloc = (int) BFD_RELOC_UNUSED + c;
9789                       continue;
9790                     }
9791
9792                   break;
9793                 }
9794
9795               /* We need to relax this instruction.  */
9796               *imm_reloc = (int) BFD_RELOC_UNUSED + c;
9797               s = expr_end;
9798               continue;
9799
9800             case 'p':
9801             case 'q':
9802             case 'A':
9803             case 'B':
9804             case 'E':
9805               /* We use offset_reloc rather than imm_reloc for the PC
9806                  relative operands.  This lets macros with both
9807                  immediate and address operands work correctly.  */
9808               my_getExpression (&offset_expr, s);
9809
9810               if (offset_expr.X_op == O_register)
9811                 break;
9812
9813               /* We need to relax this instruction.  */
9814               *offset_reloc = (int) BFD_RELOC_UNUSED + c;
9815               s = expr_end;
9816               continue;
9817
9818             case '6':           /* break code */
9819               my_getExpression (&imm_expr, s);
9820               check_absolute_expr (ip, &imm_expr);
9821               if ((unsigned long) imm_expr.X_add_number > 63)
9822                 as_warn (_("Invalid value for `%s' (%lu)"),
9823                          ip->insn_mo->name,
9824                          (unsigned long) imm_expr.X_add_number);
9825               MIPS16_INSERT_OPERAND (IMM6, *ip, imm_expr.X_add_number);
9826               imm_expr.X_op = O_absent;
9827               s = expr_end;
9828               continue;
9829
9830             case 'a':           /* 26 bit address */
9831               my_getExpression (&offset_expr, s);
9832               s = expr_end;
9833               *offset_reloc = BFD_RELOC_MIPS16_JMP;
9834               ip->insn_opcode <<= 16;
9835               continue;
9836
9837             case 'l':           /* register list for entry macro */
9838             case 'L':           /* register list for exit macro */
9839               {
9840                 int mask;
9841
9842                 if (c == 'l')
9843                   mask = 0;
9844                 else
9845                   mask = 7 << 3;
9846                 while (*s != '\0')
9847                   {
9848                     int freg, reg1, reg2;
9849
9850                     while (*s == ' ' || *s == ',')
9851                       ++s;
9852                     if (*s != '$')
9853                       {
9854                         as_bad (_("can't parse register list"));
9855                         break;
9856                       }
9857                     ++s;
9858                     if (*s != 'f')
9859                       freg = 0;
9860                     else
9861                       {
9862                         freg = 1;
9863                         ++s;
9864                       }
9865                     reg1 = 0;
9866                     while (ISDIGIT (*s))
9867                       {
9868                         reg1 *= 10;
9869                         reg1 += *s - '0';
9870                         ++s;
9871                       }
9872                     if (*s == ' ')
9873                       ++s;
9874                     if (*s != '-')
9875                       reg2 = reg1;
9876                     else
9877                       {
9878                         ++s;
9879                         if (*s != '$')
9880                           break;
9881                         ++s;
9882                         if (freg)
9883                           {
9884                             if (*s == 'f')
9885                               ++s;
9886                             else
9887                               {
9888                                 as_bad (_("invalid register list"));
9889                                 break;
9890                               }
9891                           }
9892                         reg2 = 0;
9893                         while (ISDIGIT (*s))
9894                           {
9895                             reg2 *= 10;
9896                             reg2 += *s - '0';
9897                             ++s;
9898                           }
9899                       }
9900                     if (freg && reg1 == 0 && reg2 == 0 && c == 'L')
9901                       {
9902                         mask &= ~ (7 << 3);
9903                         mask |= 5 << 3;
9904                       }
9905                     else if (freg && reg1 == 0 && reg2 == 1 && c == 'L')
9906                       {
9907                         mask &= ~ (7 << 3);
9908                         mask |= 6 << 3;
9909                       }
9910                     else if (reg1 == 4 && reg2 >= 4 && reg2 <= 7 && c != 'L')
9911                       mask |= (reg2 - 3) << 3;
9912                     else if (reg1 == 16 && reg2 >= 16 && reg2 <= 17)
9913                       mask |= (reg2 - 15) << 1;
9914                     else if (reg1 == RA && reg2 == RA)
9915                       mask |= 1;
9916                     else
9917                       {
9918                         as_bad (_("invalid register list"));
9919                         break;
9920                       }
9921                   }
9922                 /* The mask is filled in in the opcode table for the
9923                    benefit of the disassembler.  We remove it before
9924                    applying the actual mask.  */
9925                 ip->insn_opcode &= ~ ((7 << 3) << MIPS16OP_SH_IMM6);
9926                 ip->insn_opcode |= mask << MIPS16OP_SH_IMM6;
9927               }
9928             continue;
9929
9930             case 'm':           /* Register list for save insn.  */
9931             case 'M':           /* Register list for restore insn.  */
9932               {
9933                 int opcode = 0;
9934                 int framesz = 0, seen_framesz = 0;
9935                 int args = 0, statics = 0, sregs = 0;
9936
9937                 while (*s != '\0')
9938                   {
9939                     unsigned int reg1, reg2;
9940
9941                     SKIP_SPACE_TABS (s);
9942                     while (*s == ',')
9943                       ++s;
9944                     SKIP_SPACE_TABS (s);
9945
9946                     my_getExpression (&imm_expr, s);
9947                     if (imm_expr.X_op == O_constant)
9948                       {
9949                         /* Handle the frame size.  */
9950                         if (seen_framesz)
9951                           {
9952                             as_bad (_("more than one frame size in list"));
9953                             break;
9954                           }
9955                         seen_framesz = 1;
9956                         framesz = imm_expr.X_add_number;
9957                         imm_expr.X_op = O_absent;
9958                         s = expr_end;
9959                         continue;
9960                       }
9961
9962                     if (*s != '$')
9963                       {
9964                         as_bad (_("can't parse register list"));
9965                         break;
9966                       }
9967                     ++s;
9968
9969                     reg1 = 0;
9970                     while (ISDIGIT (*s))
9971                       {
9972                         reg1 *= 10;
9973                         reg1 += *s - '0';
9974                         ++s;
9975                       }
9976                     SKIP_SPACE_TABS (s);
9977                     if (*s != '-')
9978                       reg2 = reg1;
9979                     else
9980                       {
9981                         ++s;
9982                         if (*s != '$')
9983                           {
9984                             as_bad (_("can't parse register list"));
9985                             break;
9986                           }
9987                         ++s;
9988                         reg2 = 0;
9989                         while (ISDIGIT (*s))
9990                           {
9991                             reg2 *= 10;
9992                             reg2 += *s - '0';
9993                             ++s;
9994                           }
9995                       }
9996
9997                     while (reg1 <= reg2)
9998                       {
9999                         if (reg1 >= 4 && reg1 <= 7)
10000                           {
10001                             if (c == 'm' && !seen_framesz)
10002                                 /* args $a0-$a3 */
10003                                 args |= 1 << (reg1 - 4);
10004                             else
10005                                 /* statics $a0-$a3 */
10006                                 statics |= 1 << (reg1 - 4);
10007                           }
10008                         else if ((reg1 >= 16 && reg1 <= 23) || reg1 == 30)
10009                           {
10010                             /* $s0-$s8 */
10011                             sregs |= 1 << ((reg1 == 30) ? 8 : (reg1 - 16));
10012                           }
10013                         else if (reg1 == 31)
10014                           {
10015                             /* Add $ra to insn.  */
10016                             opcode |= 0x40;
10017                           }
10018                         else
10019                           {
10020                             as_bad (_("unexpected register in list"));
10021                             break;
10022                           }
10023                         if (++reg1 == 24)
10024                           reg1 = 30;
10025                       }
10026                   }
10027
10028                 /* Encode args/statics combination.  */
10029                 if (args & statics)
10030                   as_bad (_("arg/static registers overlap"));
10031                 else if (args == 0xf)
10032                   /* All $a0-$a3 are args.  */
10033                   opcode |= MIPS16_ALL_ARGS << 16;
10034                 else if (statics == 0xf)
10035                   /* All $a0-$a3 are statics.  */
10036                   opcode |= MIPS16_ALL_STATICS << 16;
10037                 else 
10038                   {
10039                     int narg = 0, nstat = 0;
10040
10041                     /* Count arg registers.  */
10042                     while (args & 0x1)
10043                       {
10044                         args >>= 1;
10045                         narg++;
10046                       }
10047                     if (args != 0)
10048                       as_bad (_("invalid arg register list"));
10049
10050                     /* Count static registers.  */
10051                     while (statics & 0x8)
10052                       {
10053                         statics = (statics << 1) & 0xf;
10054                         nstat++;
10055                       }
10056                     if (statics != 0) 
10057                       as_bad (_("invalid static register list"));
10058
10059                     /* Encode args/statics.  */
10060                     opcode |= ((narg << 2) | nstat) << 16;
10061                   }
10062
10063                 /* Encode $s0/$s1.  */
10064                 if (sregs & (1 << 0))           /* $s0 */
10065                   opcode |= 0x20;
10066                 if (sregs & (1 << 1))           /* $s1 */
10067                   opcode |= 0x10;
10068                 sregs >>= 2;
10069
10070                 if (sregs != 0)
10071                   {
10072                     /* Count regs $s2-$s8.  */
10073                     int nsreg = 0;
10074                     while (sregs & 1)
10075                       {
10076                         sregs >>= 1;
10077                         nsreg++;
10078                       }
10079                     if (sregs != 0)
10080                       as_bad (_("invalid static register list"));
10081                     /* Encode $s2-$s8. */
10082                     opcode |= nsreg << 24;
10083                   }
10084
10085                 /* Encode frame size.  */
10086                 if (!seen_framesz)
10087                   as_bad (_("missing frame size"));
10088                 else if ((framesz & 7) != 0 || framesz < 0
10089                          || framesz > 0xff * 8)
10090                   as_bad (_("invalid frame size"));
10091                 else if (framesz != 128 || (opcode >> 16) != 0)
10092                   {
10093                     framesz /= 8;
10094                     opcode |= (((framesz & 0xf0) << 16)
10095                              | (framesz & 0x0f));
10096                   }
10097
10098                 /* Finally build the instruction.  */
10099                 if ((opcode >> 16) != 0 || framesz == 0)
10100                   {
10101                     ip->use_extend = TRUE;
10102                     ip->extend = opcode >> 16;
10103                   }
10104                 ip->insn_opcode |= opcode & 0x7f;
10105               }
10106             continue;
10107
10108             case 'e':           /* extend code */
10109               my_getExpression (&imm_expr, s);
10110               check_absolute_expr (ip, &imm_expr);
10111               if ((unsigned long) imm_expr.X_add_number > 0x7ff)
10112                 {
10113                   as_warn (_("Invalid value for `%s' (%lu)"),
10114                            ip->insn_mo->name,
10115                            (unsigned long) imm_expr.X_add_number);
10116                   imm_expr.X_add_number &= 0x7ff;
10117                 }
10118               ip->insn_opcode |= imm_expr.X_add_number;
10119               imm_expr.X_op = O_absent;
10120               s = expr_end;
10121               continue;
10122
10123             default:
10124               internalError ();
10125             }
10126           break;
10127         }
10128
10129       /* Args don't match.  */
10130       if (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes] &&
10131           strcmp (insn->name, insn[1].name) == 0)
10132         {
10133           ++insn;
10134           s = argsstart;
10135           continue;
10136         }
10137
10138       insn_error = _("illegal operands");
10139
10140       return;
10141     }
10142 }
10143
10144 /* This structure holds information we know about a mips16 immediate
10145    argument type.  */
10146
10147 struct mips16_immed_operand
10148 {
10149   /* The type code used in the argument string in the opcode table.  */
10150   int type;
10151   /* The number of bits in the short form of the opcode.  */
10152   int nbits;
10153   /* The number of bits in the extended form of the opcode.  */
10154   int extbits;
10155   /* The amount by which the short form is shifted when it is used;
10156      for example, the sw instruction has a shift count of 2.  */
10157   int shift;
10158   /* The amount by which the short form is shifted when it is stored
10159      into the instruction code.  */
10160   int op_shift;
10161   /* Non-zero if the short form is unsigned.  */
10162   int unsp;
10163   /* Non-zero if the extended form is unsigned.  */
10164   int extu;
10165   /* Non-zero if the value is PC relative.  */
10166   int pcrel;
10167 };
10168
10169 /* The mips16 immediate operand types.  */
10170
10171 static const struct mips16_immed_operand mips16_immed_operands[] =
10172 {
10173   { '<',  3,  5, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
10174   { '>',  3,  5, 0, MIPS16OP_SH_RX,   1, 1, 0 },
10175   { '[',  3,  6, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
10176   { ']',  3,  6, 0, MIPS16OP_SH_RX,   1, 1, 0 },
10177   { '4',  4, 15, 0, MIPS16OP_SH_IMM4, 0, 0, 0 },
10178   { '5',  5, 16, 0, MIPS16OP_SH_IMM5, 1, 0, 0 },
10179   { 'H',  5, 16, 1, MIPS16OP_SH_IMM5, 1, 0, 0 },
10180   { 'W',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 0 },
10181   { 'D',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 0 },
10182   { 'j',  5, 16, 0, MIPS16OP_SH_IMM5, 0, 0, 0 },
10183   { '8',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 0, 0 },
10184   { 'V',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 0 },
10185   { 'C',  8, 16, 3, MIPS16OP_SH_IMM8, 1, 0, 0 },
10186   { 'U',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 1, 0 },
10187   { 'k',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 0 },
10188   { 'K',  8, 16, 3, MIPS16OP_SH_IMM8, 0, 0, 0 },
10189   { 'p',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
10190   { 'q', 11, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
10191   { 'A',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 1 },
10192   { 'B',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 1 },
10193   { 'E',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 1 }
10194 };
10195
10196 #define MIPS16_NUM_IMMED \
10197   (sizeof mips16_immed_operands / sizeof mips16_immed_operands[0])
10198
10199 /* Handle a mips16 instruction with an immediate value.  This or's the
10200    small immediate value into *INSN.  It sets *USE_EXTEND to indicate
10201    whether an extended value is needed; if one is needed, it sets
10202    *EXTEND to the value.  The argument type is TYPE.  The value is VAL.
10203    If SMALL is true, an unextended opcode was explicitly requested.
10204    If EXT is true, an extended opcode was explicitly requested.  If
10205    WARN is true, warn if EXT does not match reality.  */
10206
10207 static void
10208 mips16_immed (char *file, unsigned int line, int type, offsetT val,
10209               bfd_boolean warn, bfd_boolean small, bfd_boolean ext,
10210               unsigned long *insn, bfd_boolean *use_extend,
10211               unsigned short *extend)
10212 {
10213   register const struct mips16_immed_operand *op;
10214   int mintiny, maxtiny;
10215   bfd_boolean needext;
10216
10217   op = mips16_immed_operands;
10218   while (op->type != type)
10219     {
10220       ++op;
10221       assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
10222     }
10223
10224   if (op->unsp)
10225     {
10226       if (type == '<' || type == '>' || type == '[' || type == ']')
10227         {
10228           mintiny = 1;
10229           maxtiny = 1 << op->nbits;
10230         }
10231       else
10232         {
10233           mintiny = 0;
10234           maxtiny = (1 << op->nbits) - 1;
10235         }
10236     }
10237   else
10238     {
10239       mintiny = - (1 << (op->nbits - 1));
10240       maxtiny = (1 << (op->nbits - 1)) - 1;
10241     }
10242
10243   /* Branch offsets have an implicit 0 in the lowest bit.  */
10244   if (type == 'p' || type == 'q')
10245     val /= 2;
10246
10247   if ((val & ((1 << op->shift) - 1)) != 0
10248       || val < (mintiny << op->shift)
10249       || val > (maxtiny << op->shift))
10250     needext = TRUE;
10251   else
10252     needext = FALSE;
10253
10254   if (warn && ext && ! needext)
10255     as_warn_where (file, line,
10256                    _("extended operand requested but not required"));
10257   if (small && needext)
10258     as_bad_where (file, line, _("invalid unextended operand value"));
10259
10260   if (small || (! ext && ! needext))
10261     {
10262       int insnval;
10263
10264       *use_extend = FALSE;
10265       insnval = ((val >> op->shift) & ((1 << op->nbits) - 1));
10266       insnval <<= op->op_shift;
10267       *insn |= insnval;
10268     }
10269   else
10270     {
10271       long minext, maxext;
10272       int extval;
10273
10274       if (op->extu)
10275         {
10276           minext = 0;
10277           maxext = (1 << op->extbits) - 1;
10278         }
10279       else
10280         {
10281           minext = - (1 << (op->extbits - 1));
10282           maxext = (1 << (op->extbits - 1)) - 1;
10283         }
10284       if (val < minext || val > maxext)
10285         as_bad_where (file, line,
10286                       _("operand value out of range for instruction"));
10287
10288       *use_extend = TRUE;
10289       if (op->extbits == 16)
10290         {
10291           extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
10292           val &= 0x1f;
10293         }
10294       else if (op->extbits == 15)
10295         {
10296           extval = ((val >> 11) & 0xf) | (val & 0x7f0);
10297           val &= 0xf;
10298         }
10299       else
10300         {
10301           extval = ((val & 0x1f) << 6) | (val & 0x20);
10302           val = 0;
10303         }
10304
10305       *extend = (unsigned short) extval;
10306       *insn |= val;
10307     }
10308 }
10309 \f
10310 struct percent_op_match
10311 {
10312   const char *str;
10313   bfd_reloc_code_real_type reloc;
10314 };
10315
10316 static const struct percent_op_match mips_percent_op[] =
10317 {
10318   {"%lo", BFD_RELOC_LO16},
10319 #ifdef OBJ_ELF
10320   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
10321   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
10322   {"%call16", BFD_RELOC_MIPS_CALL16},
10323   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
10324   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
10325   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
10326   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
10327   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
10328   {"%got", BFD_RELOC_MIPS_GOT16},
10329   {"%gp_rel", BFD_RELOC_GPREL16},
10330   {"%half", BFD_RELOC_16},
10331   {"%highest", BFD_RELOC_MIPS_HIGHEST},
10332   {"%higher", BFD_RELOC_MIPS_HIGHER},
10333   {"%neg", BFD_RELOC_MIPS_SUB},
10334   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
10335   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
10336   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
10337   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
10338   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
10339   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
10340   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
10341 #endif
10342   {"%hi", BFD_RELOC_HI16_S}
10343 };
10344
10345 static const struct percent_op_match mips16_percent_op[] =
10346 {
10347   {"%lo", BFD_RELOC_MIPS16_LO16},
10348   {"%gprel", BFD_RELOC_MIPS16_GPREL},
10349   {"%hi", BFD_RELOC_MIPS16_HI16_S}
10350 };
10351
10352
10353 /* Return true if *STR points to a relocation operator.  When returning true,
10354    move *STR over the operator and store its relocation code in *RELOC.
10355    Leave both *STR and *RELOC alone when returning false.  */
10356
10357 static bfd_boolean
10358 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
10359 {
10360   const struct percent_op_match *percent_op;
10361   size_t limit, i;
10362
10363   if (mips_opts.mips16)
10364     {
10365       percent_op = mips16_percent_op;
10366       limit = ARRAY_SIZE (mips16_percent_op);
10367     }
10368   else
10369     {
10370       percent_op = mips_percent_op;
10371       limit = ARRAY_SIZE (mips_percent_op);
10372     }
10373
10374   for (i = 0; i < limit; i++)
10375     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
10376       {
10377         int len = strlen (percent_op[i].str);
10378
10379         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
10380           continue;
10381
10382         *str += strlen (percent_op[i].str);
10383         *reloc = percent_op[i].reloc;
10384
10385         /* Check whether the output BFD supports this relocation.
10386            If not, issue an error and fall back on something safe.  */
10387         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
10388           {
10389             as_bad ("relocation %s isn't supported by the current ABI",
10390                     percent_op[i].str);
10391             *reloc = BFD_RELOC_UNUSED;
10392           }
10393         return TRUE;
10394       }
10395   return FALSE;
10396 }
10397
10398
10399 /* Parse string STR as a 16-bit relocatable operand.  Store the
10400    expression in *EP and the relocations in the array starting
10401    at RELOC.  Return the number of relocation operators used.
10402
10403    On exit, EXPR_END points to the first character after the expression.  */
10404
10405 static size_t
10406 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
10407                        char *str)
10408 {
10409   bfd_reloc_code_real_type reversed_reloc[3];
10410   size_t reloc_index, i;
10411   int crux_depth, str_depth;
10412   char *crux;
10413
10414   /* Search for the start of the main expression, recoding relocations
10415      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
10416      of the main expression and with CRUX_DEPTH containing the number
10417      of open brackets at that point.  */
10418   reloc_index = -1;
10419   str_depth = 0;
10420   do
10421     {
10422       reloc_index++;
10423       crux = str;
10424       crux_depth = str_depth;
10425
10426       /* Skip over whitespace and brackets, keeping count of the number
10427          of brackets.  */
10428       while (*str == ' ' || *str == '\t' || *str == '(')
10429         if (*str++ == '(')
10430           str_depth++;
10431     }
10432   while (*str == '%'
10433          && reloc_index < (HAVE_NEWABI ? 3 : 1)
10434          && parse_relocation (&str, &reversed_reloc[reloc_index]));
10435
10436   my_getExpression (ep, crux);
10437   str = expr_end;
10438
10439   /* Match every open bracket.  */
10440   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
10441     if (*str++ == ')')
10442       crux_depth--;
10443
10444   if (crux_depth > 0)
10445     as_bad ("unclosed '('");
10446
10447   expr_end = str;
10448
10449   if (reloc_index != 0)
10450     {
10451       prev_reloc_op_frag = frag_now;
10452       for (i = 0; i < reloc_index; i++)
10453         reloc[i] = reversed_reloc[reloc_index - 1 - i];
10454     }
10455
10456   return reloc_index;
10457 }
10458
10459 static void
10460 my_getExpression (expressionS *ep, char *str)
10461 {
10462   char *save_in;
10463   valueT val;
10464
10465   save_in = input_line_pointer;
10466   input_line_pointer = str;
10467   expression (ep);
10468   expr_end = input_line_pointer;
10469   input_line_pointer = save_in;
10470
10471   /* If we are in mips16 mode, and this is an expression based on `.',
10472      then we bump the value of the symbol by 1 since that is how other
10473      text symbols are handled.  We don't bother to handle complex
10474      expressions, just `.' plus or minus a constant.  */
10475   if (mips_opts.mips16
10476       && ep->X_op == O_symbol
10477       && strcmp (S_GET_NAME (ep->X_add_symbol), FAKE_LABEL_NAME) == 0
10478       && S_GET_SEGMENT (ep->X_add_symbol) == now_seg
10479       && symbol_get_frag (ep->X_add_symbol) == frag_now
10480       && symbol_constant_p (ep->X_add_symbol)
10481       && (val = S_GET_VALUE (ep->X_add_symbol)) == frag_now_fix ())
10482     S_SET_VALUE (ep->X_add_symbol, val + 1);
10483 }
10484
10485 /* Turn a string in input_line_pointer into a floating point constant
10486    of type TYPE, and store the appropriate bytes in *LITP.  The number
10487    of LITTLENUMS emitted is stored in *SIZEP.  An error message is
10488    returned, or NULL on OK.  */
10489
10490 char *
10491 md_atof (int type, char *litP, int *sizeP)
10492 {
10493   int prec;
10494   LITTLENUM_TYPE words[4];
10495   char *t;
10496   int i;
10497
10498   switch (type)
10499     {
10500     case 'f':
10501       prec = 2;
10502       break;
10503
10504     case 'd':
10505       prec = 4;
10506       break;
10507
10508     default:
10509       *sizeP = 0;
10510       return _("bad call to md_atof");
10511     }
10512
10513   t = atof_ieee (input_line_pointer, type, words);
10514   if (t)
10515     input_line_pointer = t;
10516
10517   *sizeP = prec * 2;
10518
10519   if (! target_big_endian)
10520     {
10521       for (i = prec - 1; i >= 0; i--)
10522         {
10523           md_number_to_chars (litP, words[i], 2);
10524           litP += 2;
10525         }
10526     }
10527   else
10528     {
10529       for (i = 0; i < prec; i++)
10530         {
10531           md_number_to_chars (litP, words[i], 2);
10532           litP += 2;
10533         }
10534     }
10535
10536   return NULL;
10537 }
10538
10539 void
10540 md_number_to_chars (char *buf, valueT val, int n)
10541 {
10542   if (target_big_endian)
10543     number_to_chars_bigendian (buf, val, n);
10544   else
10545     number_to_chars_littleendian (buf, val, n);
10546 }
10547 \f
10548 #ifdef OBJ_ELF
10549 static int support_64bit_objects(void)
10550 {
10551   const char **list, **l;
10552   int yes;
10553
10554   list = bfd_target_list ();
10555   for (l = list; *l != NULL; l++)
10556 #ifdef TE_TMIPS
10557     /* This is traditional mips */
10558     if (strcmp (*l, "elf64-tradbigmips") == 0
10559         || strcmp (*l, "elf64-tradlittlemips") == 0)
10560 #else
10561     if (strcmp (*l, "elf64-bigmips") == 0
10562         || strcmp (*l, "elf64-littlemips") == 0)
10563 #endif
10564       break;
10565   yes = (*l != NULL);
10566   free (list);
10567   return yes;
10568 }
10569 #endif /* OBJ_ELF */
10570
10571 const char *md_shortopts = "O::g::G:";
10572
10573 struct option md_longopts[] =
10574 {
10575   /* Options which specify architecture.  */
10576 #define OPTION_ARCH_BASE    (OPTION_MD_BASE)
10577 #define OPTION_MARCH (OPTION_ARCH_BASE + 0)
10578   {"march", required_argument, NULL, OPTION_MARCH},
10579 #define OPTION_MTUNE (OPTION_ARCH_BASE + 1)
10580   {"mtune", required_argument, NULL, OPTION_MTUNE},
10581 #define OPTION_MIPS1 (OPTION_ARCH_BASE + 2)
10582   {"mips0", no_argument, NULL, OPTION_MIPS1},
10583   {"mips1", no_argument, NULL, OPTION_MIPS1},
10584 #define OPTION_MIPS2 (OPTION_ARCH_BASE + 3)
10585   {"mips2", no_argument, NULL, OPTION_MIPS2},
10586 #define OPTION_MIPS3 (OPTION_ARCH_BASE + 4)
10587   {"mips3", no_argument, NULL, OPTION_MIPS3},
10588 #define OPTION_MIPS4 (OPTION_ARCH_BASE + 5)
10589   {"mips4", no_argument, NULL, OPTION_MIPS4},
10590 #define OPTION_MIPS5 (OPTION_ARCH_BASE + 6)
10591   {"mips5", no_argument, NULL, OPTION_MIPS5},
10592 #define OPTION_MIPS32 (OPTION_ARCH_BASE + 7)
10593   {"mips32", no_argument, NULL, OPTION_MIPS32},
10594 #define OPTION_MIPS64 (OPTION_ARCH_BASE + 8)
10595   {"mips64", no_argument, NULL, OPTION_MIPS64},
10596 #define OPTION_MIPS32R2 (OPTION_ARCH_BASE + 9)
10597   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
10598 #define OPTION_MIPS64R2 (OPTION_ARCH_BASE + 10)
10599   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
10600
10601   /* Options which specify Application Specific Extensions (ASEs).  */
10602 #define OPTION_ASE_BASE (OPTION_ARCH_BASE + 11)
10603 #define OPTION_MIPS16 (OPTION_ASE_BASE + 0)
10604   {"mips16", no_argument, NULL, OPTION_MIPS16},
10605 #define OPTION_NO_MIPS16 (OPTION_ASE_BASE + 1)
10606   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
10607 #define OPTION_MIPS3D (OPTION_ASE_BASE + 2)
10608   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
10609 #define OPTION_NO_MIPS3D (OPTION_ASE_BASE + 3)
10610   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
10611 #define OPTION_MDMX (OPTION_ASE_BASE + 4)
10612   {"mdmx", no_argument, NULL, OPTION_MDMX},
10613 #define OPTION_NO_MDMX (OPTION_ASE_BASE + 5)
10614   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
10615 #define OPTION_DSP (OPTION_ASE_BASE + 6)
10616   {"mdsp", no_argument, NULL, OPTION_DSP},
10617 #define OPTION_NO_DSP (OPTION_ASE_BASE + 7)
10618   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
10619 #define OPTION_MT (OPTION_ASE_BASE + 8)
10620   {"mmt", no_argument, NULL, OPTION_MT},
10621 #define OPTION_NO_MT (OPTION_ASE_BASE + 9)
10622   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
10623
10624   /* Old-style architecture options.  Don't add more of these.  */
10625 #define OPTION_COMPAT_ARCH_BASE (OPTION_ASE_BASE + 10)
10626 #define OPTION_M4650 (OPTION_COMPAT_ARCH_BASE + 0)
10627   {"m4650", no_argument, NULL, OPTION_M4650},
10628 #define OPTION_NO_M4650 (OPTION_COMPAT_ARCH_BASE + 1)
10629   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
10630 #define OPTION_M4010 (OPTION_COMPAT_ARCH_BASE + 2)
10631   {"m4010", no_argument, NULL, OPTION_M4010},
10632 #define OPTION_NO_M4010 (OPTION_COMPAT_ARCH_BASE + 3)
10633   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
10634 #define OPTION_M4100 (OPTION_COMPAT_ARCH_BASE + 4)
10635   {"m4100", no_argument, NULL, OPTION_M4100},
10636 #define OPTION_NO_M4100 (OPTION_COMPAT_ARCH_BASE + 5)
10637   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
10638 #define OPTION_M3900 (OPTION_COMPAT_ARCH_BASE + 6)
10639   {"m3900", no_argument, NULL, OPTION_M3900},
10640 #define OPTION_NO_M3900 (OPTION_COMPAT_ARCH_BASE + 7)
10641   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
10642
10643   /* Options which enable bug fixes.  */
10644 #define OPTION_FIX_BASE    (OPTION_COMPAT_ARCH_BASE + 8)
10645 #define OPTION_M7000_HILO_FIX (OPTION_FIX_BASE + 0)
10646   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
10647 #define OPTION_MNO_7000_HILO_FIX (OPTION_FIX_BASE + 1)
10648   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
10649   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
10650 #define OPTION_FIX_VR4120 (OPTION_FIX_BASE + 2)
10651 #define OPTION_NO_FIX_VR4120 (OPTION_FIX_BASE + 3)
10652   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
10653   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
10654 #define OPTION_FIX_VR4130 (OPTION_FIX_BASE + 4)
10655 #define OPTION_NO_FIX_VR4130 (OPTION_FIX_BASE + 5)
10656   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
10657   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
10658
10659   /* Miscellaneous options.  */
10660 #define OPTION_MISC_BASE (OPTION_FIX_BASE + 6)
10661 #define OPTION_TRAP (OPTION_MISC_BASE + 0)
10662   {"trap", no_argument, NULL, OPTION_TRAP},
10663   {"no-break", no_argument, NULL, OPTION_TRAP},
10664 #define OPTION_BREAK (OPTION_MISC_BASE + 1)
10665   {"break", no_argument, NULL, OPTION_BREAK},
10666   {"no-trap", no_argument, NULL, OPTION_BREAK},
10667 #define OPTION_EB (OPTION_MISC_BASE + 2)
10668   {"EB", no_argument, NULL, OPTION_EB},
10669 #define OPTION_EL (OPTION_MISC_BASE + 3)
10670   {"EL", no_argument, NULL, OPTION_EL},
10671 #define OPTION_FP32 (OPTION_MISC_BASE + 4)
10672   {"mfp32", no_argument, NULL, OPTION_FP32},
10673 #define OPTION_GP32 (OPTION_MISC_BASE + 5)
10674   {"mgp32", no_argument, NULL, OPTION_GP32},
10675 #define OPTION_CONSTRUCT_FLOATS (OPTION_MISC_BASE + 6)
10676   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
10677 #define OPTION_NO_CONSTRUCT_FLOATS (OPTION_MISC_BASE + 7)
10678   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
10679 #define OPTION_FP64 (OPTION_MISC_BASE + 8)
10680   {"mfp64", no_argument, NULL, OPTION_FP64},
10681 #define OPTION_GP64 (OPTION_MISC_BASE + 9)
10682   {"mgp64", no_argument, NULL, OPTION_GP64},
10683 #define OPTION_RELAX_BRANCH (OPTION_MISC_BASE + 10)
10684 #define OPTION_NO_RELAX_BRANCH (OPTION_MISC_BASE + 11)
10685   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
10686   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
10687 #define OPTION_MSHARED (OPTION_MISC_BASE + 12)
10688 #define OPTION_MNO_SHARED (OPTION_MISC_BASE + 13)
10689   {"mshared", no_argument, NULL, OPTION_MSHARED},
10690   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
10691 #define OPTION_MSYM32 (OPTION_MISC_BASE + 14)
10692 #define OPTION_MNO_SYM32 (OPTION_MISC_BASE + 15)
10693   {"msym32", no_argument, NULL, OPTION_MSYM32},
10694   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
10695
10696   /* ELF-specific options.  */
10697 #ifdef OBJ_ELF
10698 #define OPTION_ELF_BASE    (OPTION_MISC_BASE + 16)
10699 #define OPTION_CALL_SHARED (OPTION_ELF_BASE + 0)
10700   {"KPIC",        no_argument, NULL, OPTION_CALL_SHARED},
10701   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
10702 #define OPTION_NON_SHARED  (OPTION_ELF_BASE + 1)
10703   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
10704 #define OPTION_XGOT        (OPTION_ELF_BASE + 2)
10705   {"xgot",        no_argument, NULL, OPTION_XGOT},
10706 #define OPTION_MABI        (OPTION_ELF_BASE + 3)
10707   {"mabi", required_argument, NULL, OPTION_MABI},
10708 #define OPTION_32          (OPTION_ELF_BASE + 4)
10709   {"32",          no_argument, NULL, OPTION_32},
10710 #define OPTION_N32         (OPTION_ELF_BASE + 5)
10711   {"n32",         no_argument, NULL, OPTION_N32},
10712 #define OPTION_64          (OPTION_ELF_BASE + 6)
10713   {"64",          no_argument, NULL, OPTION_64},
10714 #define OPTION_MDEBUG      (OPTION_ELF_BASE + 7)
10715   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
10716 #define OPTION_NO_MDEBUG   (OPTION_ELF_BASE + 8)
10717   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
10718 #define OPTION_PDR         (OPTION_ELF_BASE + 9)
10719   {"mpdr", no_argument, NULL, OPTION_PDR},
10720 #define OPTION_NO_PDR      (OPTION_ELF_BASE + 10)
10721   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
10722 #define OPTION_MVXWORKS_PIC (OPTION_ELF_BASE + 11)
10723   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
10724 #endif /* OBJ_ELF */
10725
10726   {NULL, no_argument, NULL, 0}
10727 };
10728 size_t md_longopts_size = sizeof (md_longopts);
10729
10730 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
10731    NEW_VALUE.  Warn if another value was already specified.  Note:
10732    we have to defer parsing the -march and -mtune arguments in order
10733    to handle 'from-abi' correctly, since the ABI might be specified
10734    in a later argument.  */
10735
10736 static void
10737 mips_set_option_string (const char **string_ptr, const char *new_value)
10738 {
10739   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
10740     as_warn (_("A different %s was already specified, is now %s"),
10741              string_ptr == &mips_arch_string ? "-march" : "-mtune",
10742              new_value);
10743
10744   *string_ptr = new_value;
10745 }
10746
10747 int
10748 md_parse_option (int c, char *arg)
10749 {
10750   switch (c)
10751     {
10752     case OPTION_CONSTRUCT_FLOATS:
10753       mips_disable_float_construction = 0;
10754       break;
10755
10756     case OPTION_NO_CONSTRUCT_FLOATS:
10757       mips_disable_float_construction = 1;
10758       break;
10759
10760     case OPTION_TRAP:
10761       mips_trap = 1;
10762       break;
10763
10764     case OPTION_BREAK:
10765       mips_trap = 0;
10766       break;
10767
10768     case OPTION_EB:
10769       target_big_endian = 1;
10770       break;
10771
10772     case OPTION_EL:
10773       target_big_endian = 0;
10774       break;
10775
10776     case 'O':
10777       if (arg && arg[1] == '0')
10778         mips_optimize = 1;
10779       else
10780         mips_optimize = 2;
10781       break;
10782
10783     case 'g':
10784       if (arg == NULL)
10785         mips_debug = 2;
10786       else
10787         mips_debug = atoi (arg);
10788       /* When the MIPS assembler sees -g or -g2, it does not do
10789          optimizations which limit full symbolic debugging.  We take
10790          that to be equivalent to -O0.  */
10791       if (mips_debug == 2)
10792         mips_optimize = 1;
10793       break;
10794
10795     case OPTION_MIPS1:
10796       file_mips_isa = ISA_MIPS1;
10797       break;
10798
10799     case OPTION_MIPS2:
10800       file_mips_isa = ISA_MIPS2;
10801       break;
10802
10803     case OPTION_MIPS3:
10804       file_mips_isa = ISA_MIPS3;
10805       break;
10806
10807     case OPTION_MIPS4:
10808       file_mips_isa = ISA_MIPS4;
10809       break;
10810
10811     case OPTION_MIPS5:
10812       file_mips_isa = ISA_MIPS5;
10813       break;
10814
10815     case OPTION_MIPS32:
10816       file_mips_isa = ISA_MIPS32;
10817       break;
10818
10819     case OPTION_MIPS32R2:
10820       file_mips_isa = ISA_MIPS32R2;
10821       break;
10822
10823     case OPTION_MIPS64R2:
10824       file_mips_isa = ISA_MIPS64R2;
10825       break;
10826
10827     case OPTION_MIPS64:
10828       file_mips_isa = ISA_MIPS64;
10829       break;
10830
10831     case OPTION_MTUNE:
10832       mips_set_option_string (&mips_tune_string, arg);
10833       break;
10834
10835     case OPTION_MARCH:
10836       mips_set_option_string (&mips_arch_string, arg);
10837       break;
10838
10839     case OPTION_M4650:
10840       mips_set_option_string (&mips_arch_string, "4650");
10841       mips_set_option_string (&mips_tune_string, "4650");
10842       break;
10843
10844     case OPTION_NO_M4650:
10845       break;
10846
10847     case OPTION_M4010:
10848       mips_set_option_string (&mips_arch_string, "4010");
10849       mips_set_option_string (&mips_tune_string, "4010");
10850       break;
10851
10852     case OPTION_NO_M4010:
10853       break;
10854
10855     case OPTION_M4100:
10856       mips_set_option_string (&mips_arch_string, "4100");
10857       mips_set_option_string (&mips_tune_string, "4100");
10858       break;
10859
10860     case OPTION_NO_M4100:
10861       break;
10862
10863     case OPTION_M3900:
10864       mips_set_option_string (&mips_arch_string, "3900");
10865       mips_set_option_string (&mips_tune_string, "3900");
10866       break;
10867
10868     case OPTION_NO_M3900:
10869       break;
10870
10871     case OPTION_MDMX:
10872       mips_opts.ase_mdmx = 1;
10873       break;
10874
10875     case OPTION_NO_MDMX:
10876       mips_opts.ase_mdmx = 0;
10877       break;
10878
10879     case OPTION_DSP:
10880       mips_opts.ase_dsp = 1;
10881       break;
10882
10883     case OPTION_NO_DSP:
10884       mips_opts.ase_dsp = 0;
10885       break;
10886
10887     case OPTION_MT:
10888       mips_opts.ase_mt = 1;
10889       break;
10890
10891     case OPTION_NO_MT:
10892       mips_opts.ase_mt = 0;
10893       break;
10894
10895     case OPTION_MIPS16:
10896       mips_opts.mips16 = 1;
10897       mips_no_prev_insn ();
10898       break;
10899
10900     case OPTION_NO_MIPS16:
10901       mips_opts.mips16 = 0;
10902       mips_no_prev_insn ();
10903       break;
10904
10905     case OPTION_MIPS3D:
10906       mips_opts.ase_mips3d = 1;
10907       break;
10908
10909     case OPTION_NO_MIPS3D:
10910       mips_opts.ase_mips3d = 0;
10911       break;
10912
10913     case OPTION_FIX_VR4120:
10914       mips_fix_vr4120 = 1;
10915       break;
10916
10917     case OPTION_NO_FIX_VR4120:
10918       mips_fix_vr4120 = 0;
10919       break;
10920
10921     case OPTION_FIX_VR4130:
10922       mips_fix_vr4130 = 1;
10923       break;
10924
10925     case OPTION_NO_FIX_VR4130:
10926       mips_fix_vr4130 = 0;
10927       break;
10928
10929     case OPTION_RELAX_BRANCH:
10930       mips_relax_branch = 1;
10931       break;
10932
10933     case OPTION_NO_RELAX_BRANCH:
10934       mips_relax_branch = 0;
10935       break;
10936
10937     case OPTION_MSHARED:
10938       mips_in_shared = TRUE;
10939       break;
10940
10941     case OPTION_MNO_SHARED:
10942       mips_in_shared = FALSE;
10943       break;
10944
10945     case OPTION_MSYM32:
10946       mips_opts.sym32 = TRUE;
10947       break;
10948
10949     case OPTION_MNO_SYM32:
10950       mips_opts.sym32 = FALSE;
10951       break;
10952
10953 #ifdef OBJ_ELF
10954       /* When generating ELF code, we permit -KPIC and -call_shared to
10955          select SVR4_PIC, and -non_shared to select no PIC.  This is
10956          intended to be compatible with Irix 5.  */
10957     case OPTION_CALL_SHARED:
10958       if (OUTPUT_FLAVOR != bfd_target_elf_flavour)
10959         {
10960           as_bad (_("-call_shared is supported only for ELF format"));
10961           return 0;
10962         }
10963       mips_pic = SVR4_PIC;
10964       mips_abicalls = TRUE;
10965       break;
10966
10967     case OPTION_NON_SHARED:
10968       if (OUTPUT_FLAVOR != bfd_target_elf_flavour)
10969         {
10970           as_bad (_("-non_shared is supported only for ELF format"));
10971           return 0;
10972         }
10973       mips_pic = NO_PIC;
10974       mips_abicalls = FALSE;
10975       break;
10976
10977       /* The -xgot option tells the assembler to use 32 bit offsets
10978          when accessing the got in SVR4_PIC mode.  It is for Irix
10979          compatibility.  */
10980     case OPTION_XGOT:
10981       mips_big_got = 1;
10982       break;
10983 #endif /* OBJ_ELF */
10984
10985     case 'G':
10986       g_switch_value = atoi (arg);
10987       g_switch_seen = 1;
10988       break;
10989
10990 #ifdef OBJ_ELF
10991       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
10992          and -mabi=64.  */
10993     case OPTION_32:
10994       if (OUTPUT_FLAVOR != bfd_target_elf_flavour)
10995         {
10996           as_bad (_("-32 is supported for ELF format only"));
10997           return 0;
10998         }
10999       mips_abi = O32_ABI;
11000       break;
11001
11002     case OPTION_N32:
11003       if (OUTPUT_FLAVOR != bfd_target_elf_flavour)
11004         {
11005           as_bad (_("-n32 is supported for ELF format only"));
11006           return 0;
11007         }
11008       mips_abi = N32_ABI;
11009       break;
11010
11011     case OPTION_64:
11012       if (OUTPUT_FLAVOR != bfd_target_elf_flavour)
11013         {
11014           as_bad (_("-64 is supported for ELF format only"));
11015           return 0;
11016         }
11017       mips_abi = N64_ABI;
11018       if (! support_64bit_objects())
11019         as_fatal (_("No compiled in support for 64 bit object file format"));
11020       break;
11021 #endif /* OBJ_ELF */
11022
11023     case OPTION_GP32:
11024       file_mips_gp32 = 1;
11025       break;
11026
11027     case OPTION_GP64:
11028       file_mips_gp32 = 0;
11029       break;
11030
11031     case OPTION_FP32:
11032       file_mips_fp32 = 1;
11033       break;
11034
11035     case OPTION_FP64:
11036       file_mips_fp32 = 0;
11037       break;
11038
11039 #ifdef OBJ_ELF
11040     case OPTION_MABI:
11041       if (OUTPUT_FLAVOR != bfd_target_elf_flavour)
11042         {
11043           as_bad (_("-mabi is supported for ELF format only"));
11044           return 0;
11045         }
11046       if (strcmp (arg, "32") == 0)
11047         mips_abi = O32_ABI;
11048       else if (strcmp (arg, "o64") == 0)
11049         mips_abi = O64_ABI;
11050       else if (strcmp (arg, "n32") == 0)
11051         mips_abi = N32_ABI;
11052       else if (strcmp (arg, "64") == 0)
11053         {
11054           mips_abi = N64_ABI;
11055           if (! support_64bit_objects())
11056             as_fatal (_("No compiled in support for 64 bit object file "
11057                         "format"));
11058         }
11059       else if (strcmp (arg, "eabi") == 0)
11060         mips_abi = EABI_ABI;
11061       else
11062         {
11063           as_fatal (_("invalid abi -mabi=%s"), arg);
11064           return 0;
11065         }
11066       break;
11067 #endif /* OBJ_ELF */
11068
11069     case OPTION_M7000_HILO_FIX:
11070       mips_7000_hilo_fix = TRUE;
11071       break;
11072
11073     case OPTION_MNO_7000_HILO_FIX:
11074       mips_7000_hilo_fix = FALSE;
11075       break;
11076
11077 #ifdef OBJ_ELF
11078     case OPTION_MDEBUG:
11079       mips_flag_mdebug = TRUE;
11080       break;
11081
11082     case OPTION_NO_MDEBUG:
11083       mips_flag_mdebug = FALSE;
11084       break;
11085
11086     case OPTION_PDR:
11087       mips_flag_pdr = TRUE;
11088       break;
11089
11090     case OPTION_NO_PDR:
11091       mips_flag_pdr = FALSE;
11092       break;
11093
11094     case OPTION_MVXWORKS_PIC:
11095       mips_pic = VXWORKS_PIC;
11096       break;
11097 #endif /* OBJ_ELF */
11098
11099     default:
11100       return 0;
11101     }
11102
11103   return 1;
11104 }
11105 \f
11106 /* Set up globals to generate code for the ISA or processor
11107    described by INFO.  */
11108
11109 static void
11110 mips_set_architecture (const struct mips_cpu_info *info)
11111 {
11112   if (info != 0)
11113     {
11114       file_mips_arch = info->cpu;
11115       mips_opts.arch = info->cpu;
11116       mips_opts.isa = info->isa;
11117     }
11118 }
11119
11120
11121 /* Likewise for tuning.  */
11122
11123 static void
11124 mips_set_tune (const struct mips_cpu_info *info)
11125 {
11126   if (info != 0)
11127     mips_tune = info->cpu;
11128 }
11129
11130
11131 void
11132 mips_after_parse_args (void)
11133 {
11134   const struct mips_cpu_info *arch_info = 0;
11135   const struct mips_cpu_info *tune_info = 0;
11136
11137   /* GP relative stuff not working for PE */
11138   if (strncmp (TARGET_OS, "pe", 2) == 0)
11139     {
11140       if (g_switch_seen && g_switch_value != 0)
11141         as_bad (_("-G not supported in this configuration."));
11142       g_switch_value = 0;
11143     }
11144
11145   if (mips_abi == NO_ABI)
11146     mips_abi = MIPS_DEFAULT_ABI;
11147
11148   /* The following code determines the architecture and register size.
11149      Similar code was added to GCC 3.3 (see override_options() in
11150      config/mips/mips.c).  The GAS and GCC code should be kept in sync
11151      as much as possible.  */
11152
11153   if (mips_arch_string != 0)
11154     arch_info = mips_parse_cpu ("-march", mips_arch_string);
11155
11156   if (file_mips_isa != ISA_UNKNOWN)
11157     {
11158       /* Handle -mipsN.  At this point, file_mips_isa contains the
11159          ISA level specified by -mipsN, while arch_info->isa contains
11160          the -march selection (if any).  */
11161       if (arch_info != 0)
11162         {
11163           /* -march takes precedence over -mipsN, since it is more descriptive.
11164              There's no harm in specifying both as long as the ISA levels
11165              are the same.  */
11166           if (file_mips_isa != arch_info->isa)
11167             as_bad (_("-%s conflicts with the other architecture options, which imply -%s"),
11168                     mips_cpu_info_from_isa (file_mips_isa)->name,
11169                     mips_cpu_info_from_isa (arch_info->isa)->name);
11170         }
11171       else
11172         arch_info = mips_cpu_info_from_isa (file_mips_isa);
11173     }
11174
11175   if (arch_info == 0)
11176     arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
11177
11178   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
11179     as_bad ("-march=%s is not compatible with the selected ABI",
11180             arch_info->name);
11181
11182   mips_set_architecture (arch_info);
11183
11184   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
11185   if (mips_tune_string != 0)
11186     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
11187
11188   if (tune_info == 0)
11189     mips_set_tune (arch_info);
11190   else
11191     mips_set_tune (tune_info);
11192
11193   if (file_mips_gp32 >= 0)
11194     {
11195       /* The user specified the size of the integer registers.  Make sure
11196          it agrees with the ABI and ISA.  */
11197       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
11198         as_bad (_("-mgp64 used with a 32-bit processor"));
11199       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
11200         as_bad (_("-mgp32 used with a 64-bit ABI"));
11201       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
11202         as_bad (_("-mgp64 used with a 32-bit ABI"));
11203     }
11204   else
11205     {
11206       /* Infer the integer register size from the ABI and processor.
11207          Restrict ourselves to 32-bit registers if that's all the
11208          processor has, or if the ABI cannot handle 64-bit registers.  */
11209       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
11210                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
11211     }
11212
11213   /* ??? GAS treats single-float processors as though they had 64-bit
11214      float registers (although it complains when double-precision
11215      instructions are used).  As things stand, saying they have 32-bit
11216      registers would lead to spurious "register must be even" messages.
11217      So here we assume float registers are always the same size as
11218      integer ones, unless the user says otherwise.  */
11219   if (file_mips_fp32 < 0)
11220     file_mips_fp32 = file_mips_gp32;
11221
11222   /* End of GCC-shared inference code.  */
11223
11224   /* This flag is set when we have a 64-bit capable CPU but use only
11225      32-bit wide registers.  Note that EABI does not use it.  */
11226   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
11227       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
11228           || mips_abi == O32_ABI))
11229     mips_32bitmode = 1;
11230
11231   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
11232     as_bad (_("trap exception not supported at ISA 1"));
11233
11234   /* If the selected architecture includes support for ASEs, enable
11235      generation of code for them.  */
11236   if (mips_opts.mips16 == -1)
11237     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
11238   if (mips_opts.ase_mips3d == -1)
11239     mips_opts.ase_mips3d = (CPU_HAS_MIPS3D (file_mips_arch)) ? 1 : 0;
11240   if (mips_opts.ase_mdmx == -1)
11241     mips_opts.ase_mdmx = (CPU_HAS_MDMX (file_mips_arch)) ? 1 : 0;
11242   if (mips_opts.ase_dsp == -1)
11243     mips_opts.ase_dsp = (CPU_HAS_DSP (file_mips_arch)) ? 1 : 0;
11244   if (mips_opts.ase_mt == -1)
11245     mips_opts.ase_mt = (CPU_HAS_MT (file_mips_arch)) ? 1 : 0;
11246
11247   file_mips_isa = mips_opts.isa;
11248   file_ase_mips16 = mips_opts.mips16;
11249   file_ase_mips3d = mips_opts.ase_mips3d;
11250   file_ase_mdmx = mips_opts.ase_mdmx;
11251   file_ase_dsp = mips_opts.ase_dsp;
11252   file_ase_mt = mips_opts.ase_mt;
11253   mips_opts.gp32 = file_mips_gp32;
11254   mips_opts.fp32 = file_mips_fp32;
11255
11256   if (mips_flag_mdebug < 0)
11257     {
11258 #ifdef OBJ_MAYBE_ECOFF
11259       if (OUTPUT_FLAVOR == bfd_target_ecoff_flavour)
11260         mips_flag_mdebug = 1;
11261       else
11262 #endif /* OBJ_MAYBE_ECOFF */
11263         mips_flag_mdebug = 0;
11264     }
11265 }
11266 \f
11267 void
11268 mips_init_after_args (void)
11269 {
11270   /* initialize opcodes */
11271   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
11272   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
11273 }
11274
11275 long
11276 md_pcrel_from (fixS *fixP)
11277 {
11278   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
11279   switch (fixP->fx_r_type)
11280     {
11281     case BFD_RELOC_16_PCREL_S2:
11282     case BFD_RELOC_MIPS_JMP:
11283       /* Return the address of the delay slot.  */
11284       return addr + 4;
11285     default:
11286       return addr;
11287     }
11288 }
11289
11290 /* This is called before the symbol table is processed.  In order to
11291    work with gcc when using mips-tfile, we must keep all local labels.
11292    However, in other cases, we want to discard them.  If we were
11293    called with -g, but we didn't see any debugging information, it may
11294    mean that gcc is smuggling debugging information through to
11295    mips-tfile, in which case we must generate all local labels.  */
11296
11297 void
11298 mips_frob_file_before_adjust (void)
11299 {
11300 #ifndef NO_ECOFF_DEBUGGING
11301   if (ECOFF_DEBUGGING
11302       && mips_debug != 0
11303       && ! ecoff_debugging_seen)
11304     flag_keep_locals = 1;
11305 #endif
11306 }
11307
11308 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
11309    the corresponding LO16 reloc.  This is called before md_apply_fix and
11310    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
11311    relocation operators.
11312
11313    For our purposes, a %lo() expression matches a %got() or %hi()
11314    expression if:
11315
11316       (a) it refers to the same symbol; and
11317       (b) the offset applied in the %lo() expression is no lower than
11318           the offset applied in the %got() or %hi().
11319
11320    (b) allows us to cope with code like:
11321
11322         lui     $4,%hi(foo)
11323         lh      $4,%lo(foo+2)($4)
11324
11325    ...which is legal on RELA targets, and has a well-defined behaviour
11326    if the user knows that adding 2 to "foo" will not induce a carry to
11327    the high 16 bits.
11328
11329    When several %lo()s match a particular %got() or %hi(), we use the
11330    following rules to distinguish them:
11331
11332      (1) %lo()s with smaller offsets are a better match than %lo()s with
11333          higher offsets.
11334
11335      (2) %lo()s with no matching %got() or %hi() are better than those
11336          that already have a matching %got() or %hi().
11337
11338      (3) later %lo()s are better than earlier %lo()s.
11339
11340    These rules are applied in order.
11341
11342    (1) means, among other things, that %lo()s with identical offsets are
11343    chosen if they exist.
11344
11345    (2) means that we won't associate several high-part relocations with
11346    the same low-part relocation unless there's no alternative.  Having
11347    several high parts for the same low part is a GNU extension; this rule
11348    allows careful users to avoid it.
11349
11350    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
11351    with the last high-part relocation being at the front of the list.
11352    It therefore makes sense to choose the last matching low-part
11353    relocation, all other things being equal.  It's also easier
11354    to code that way.  */
11355
11356 void
11357 mips_frob_file (void)
11358 {
11359   struct mips_hi_fixup *l;
11360
11361   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
11362     {
11363       segment_info_type *seginfo;
11364       bfd_boolean matched_lo_p;
11365       fixS **hi_pos, **lo_pos, **pos;
11366
11367       assert (reloc_needs_lo_p (l->fixp->fx_r_type));
11368
11369       /* If a GOT16 relocation turns out to be against a global symbol,
11370          there isn't supposed to be a matching LO.  */
11371       if (l->fixp->fx_r_type == BFD_RELOC_MIPS_GOT16
11372           && !pic_need_relax (l->fixp->fx_addsy, l->seg))
11373         continue;
11374
11375       /* Check quickly whether the next fixup happens to be a matching %lo.  */
11376       if (fixup_has_matching_lo_p (l->fixp))
11377         continue;
11378
11379       seginfo = seg_info (l->seg);
11380
11381       /* Set HI_POS to the position of this relocation in the chain.
11382          Set LO_POS to the position of the chosen low-part relocation.
11383          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
11384          relocation that matches an immediately-preceding high-part
11385          relocation.  */
11386       hi_pos = NULL;
11387       lo_pos = NULL;
11388       matched_lo_p = FALSE;
11389       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
11390         {
11391           if (*pos == l->fixp)
11392             hi_pos = pos;
11393
11394           if (((*pos)->fx_r_type == BFD_RELOC_LO16
11395                || (*pos)->fx_r_type == BFD_RELOC_MIPS16_LO16)
11396               && (*pos)->fx_addsy == l->fixp->fx_addsy
11397               && (*pos)->fx_offset >= l->fixp->fx_offset
11398               && (lo_pos == NULL
11399                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
11400                   || (!matched_lo_p
11401                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
11402             lo_pos = pos;
11403
11404           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
11405                           && fixup_has_matching_lo_p (*pos));
11406         }
11407
11408       /* If we found a match, remove the high-part relocation from its
11409          current position and insert it before the low-part relocation.
11410          Make the offsets match so that fixup_has_matching_lo_p()
11411          will return true.
11412
11413          We don't warn about unmatched high-part relocations since some
11414          versions of gcc have been known to emit dead "lui ...%hi(...)"
11415          instructions.  */
11416       if (lo_pos != NULL)
11417         {
11418           l->fixp->fx_offset = (*lo_pos)->fx_offset;
11419           if (l->fixp->fx_next != *lo_pos)
11420             {
11421               *hi_pos = l->fixp->fx_next;
11422               l->fixp->fx_next = *lo_pos;
11423               *lo_pos = l->fixp;
11424             }
11425         }
11426     }
11427 }
11428
11429 /* We may have combined relocations without symbols in the N32/N64 ABI.
11430    We have to prevent gas from dropping them.  */
11431
11432 int
11433 mips_force_relocation (fixS *fixp)
11434 {
11435   if (generic_force_reloc (fixp))
11436     return 1;
11437
11438   if (HAVE_NEWABI
11439       && S_GET_SEGMENT (fixp->fx_addsy) == bfd_abs_section_ptr
11440       && (fixp->fx_r_type == BFD_RELOC_MIPS_SUB
11441           || fixp->fx_r_type == BFD_RELOC_HI16_S
11442           || fixp->fx_r_type == BFD_RELOC_LO16))
11443     return 1;
11444
11445   return 0;
11446 }
11447
11448 /* Apply a fixup to the object file.  */
11449
11450 void
11451 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
11452 {
11453   bfd_byte *buf;
11454   long insn;
11455   reloc_howto_type *howto;
11456
11457   /* We ignore generic BFD relocations we don't know about.  */
11458   howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
11459   if (! howto)
11460     return;
11461
11462   assert (fixP->fx_size == 4
11463           || fixP->fx_r_type == BFD_RELOC_16
11464           || fixP->fx_r_type == BFD_RELOC_64
11465           || fixP->fx_r_type == BFD_RELOC_CTOR
11466           || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
11467           || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
11468           || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY);
11469
11470   buf = (bfd_byte *) (fixP->fx_frag->fr_literal + fixP->fx_where);
11471
11472   assert (! fixP->fx_pcrel || fixP->fx_r_type == BFD_RELOC_16_PCREL_S2);
11473
11474   /* Don't treat parts of a composite relocation as done.  There are two
11475      reasons for this:
11476
11477      (1) The second and third parts will be against 0 (RSS_UNDEF) but
11478          should nevertheless be emitted if the first part is.
11479
11480      (2) In normal usage, composite relocations are never assembly-time
11481          constants.  The easiest way of dealing with the pathological
11482          exceptions is to generate a relocation against STN_UNDEF and
11483          leave everything up to the linker.  */
11484   if (fixP->fx_addsy == NULL && ! fixP->fx_pcrel && fixP->fx_tcbit == 0)
11485     fixP->fx_done = 1;
11486
11487   switch (fixP->fx_r_type)
11488     {
11489     case BFD_RELOC_MIPS_TLS_GD:
11490     case BFD_RELOC_MIPS_TLS_LDM:
11491     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
11492     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
11493     case BFD_RELOC_MIPS_TLS_GOTTPREL:
11494     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
11495     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
11496       S_SET_THREAD_LOCAL (fixP->fx_addsy);
11497       /* fall through */
11498
11499     case BFD_RELOC_MIPS_JMP:
11500     case BFD_RELOC_MIPS_SHIFT5:
11501     case BFD_RELOC_MIPS_SHIFT6:
11502     case BFD_RELOC_MIPS_GOT_DISP:
11503     case BFD_RELOC_MIPS_GOT_PAGE:
11504     case BFD_RELOC_MIPS_GOT_OFST:
11505     case BFD_RELOC_MIPS_SUB:
11506     case BFD_RELOC_MIPS_INSERT_A:
11507     case BFD_RELOC_MIPS_INSERT_B:
11508     case BFD_RELOC_MIPS_DELETE:
11509     case BFD_RELOC_MIPS_HIGHEST:
11510     case BFD_RELOC_MIPS_HIGHER:
11511     case BFD_RELOC_MIPS_SCN_DISP:
11512     case BFD_RELOC_MIPS_REL16:
11513     case BFD_RELOC_MIPS_RELGOT:
11514     case BFD_RELOC_MIPS_JALR:
11515     case BFD_RELOC_HI16:
11516     case BFD_RELOC_HI16_S:
11517     case BFD_RELOC_GPREL16:
11518     case BFD_RELOC_MIPS_LITERAL:
11519     case BFD_RELOC_MIPS_CALL16:
11520     case BFD_RELOC_MIPS_GOT16:
11521     case BFD_RELOC_GPREL32:
11522     case BFD_RELOC_MIPS_GOT_HI16:
11523     case BFD_RELOC_MIPS_GOT_LO16:
11524     case BFD_RELOC_MIPS_CALL_HI16:
11525     case BFD_RELOC_MIPS_CALL_LO16:
11526     case BFD_RELOC_MIPS16_GPREL:
11527     case BFD_RELOC_MIPS16_HI16:
11528     case BFD_RELOC_MIPS16_HI16_S:
11529       /* Nothing needed to do. The value comes from the reloc entry */
11530       break;
11531
11532     case BFD_RELOC_MIPS16_JMP:
11533       /* We currently always generate a reloc against a symbol, which
11534          means that we don't want an addend even if the symbol is
11535          defined.  */
11536       *valP = 0;
11537       break;
11538
11539     case BFD_RELOC_64:
11540       /* This is handled like BFD_RELOC_32, but we output a sign
11541          extended value if we are only 32 bits.  */
11542       if (fixP->fx_done)
11543         {
11544           if (8 <= sizeof (valueT))
11545             md_number_to_chars ((char *) buf, *valP, 8);
11546           else
11547             {
11548               valueT hiv;
11549
11550               if ((*valP & 0x80000000) != 0)
11551                 hiv = 0xffffffff;
11552               else
11553                 hiv = 0;
11554               md_number_to_chars ((char *)(buf + (target_big_endian ? 4 : 0)),
11555                                   *valP, 4);
11556               md_number_to_chars ((char *)(buf + (target_big_endian ? 0 : 4)),
11557                                   hiv, 4);
11558             }
11559         }
11560       break;
11561
11562     case BFD_RELOC_RVA:
11563     case BFD_RELOC_32:
11564       /* If we are deleting this reloc entry, we must fill in the
11565          value now.  This can happen if we have a .word which is not
11566          resolved when it appears but is later defined.   */
11567       if (fixP->fx_done)
11568         md_number_to_chars ((char *) buf, *valP, 4);
11569       break;
11570
11571     case BFD_RELOC_16:
11572       /* If we are deleting this reloc entry, we must fill in the
11573          value now.  */
11574       if (fixP->fx_done)
11575         md_number_to_chars ((char *) buf, *valP, 2);
11576       break;
11577
11578     case BFD_RELOC_LO16:
11579     case BFD_RELOC_MIPS16_LO16:
11580       /* FIXME: Now that embedded-PIC is gone, some of this code/comment
11581          may be safe to remove, but if so it's not obvious.  */
11582       /* When handling an embedded PIC switch statement, we can wind
11583          up deleting a LO16 reloc.  See the 'o' case in mips_ip.  */
11584       if (fixP->fx_done)
11585         {
11586           if (*valP + 0x8000 > 0xffff)
11587             as_bad_where (fixP->fx_file, fixP->fx_line,
11588                           _("relocation overflow"));
11589           if (target_big_endian)
11590             buf += 2;
11591           md_number_to_chars ((char *) buf, *valP, 2);
11592         }
11593       break;
11594
11595     case BFD_RELOC_16_PCREL_S2:
11596       if ((*valP & 0x3) != 0)
11597         as_bad_where (fixP->fx_file, fixP->fx_line,
11598                       _("Branch to misaligned address (%lx)"), (long) *valP);
11599
11600       /*
11601        * We need to save the bits in the instruction since fixup_segment()
11602        * might be deleting the relocation entry (i.e., a branch within
11603        * the current segment).
11604        */
11605       if (! fixP->fx_done)
11606         break;
11607
11608       /* update old instruction data */
11609       if (target_big_endian)
11610         insn = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
11611       else
11612         insn = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf[0];
11613
11614       if (*valP + 0x20000 <= 0x3ffff)
11615         {
11616           insn |= (*valP >> 2) & 0xffff;
11617           md_number_to_chars ((char *) buf, insn, 4);
11618         }
11619       else if (mips_pic == NO_PIC
11620                && fixP->fx_done
11621                && fixP->fx_frag->fr_address >= text_section->vma
11622                && (fixP->fx_frag->fr_address
11623                    < text_section->vma + bfd_get_section_size (text_section))
11624                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
11625                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
11626                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
11627         {
11628           /* The branch offset is too large.  If this is an
11629              unconditional branch, and we are not generating PIC code,
11630              we can convert it to an absolute jump instruction.  */
11631           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
11632             insn = 0x0c000000;  /* jal */
11633           else
11634             insn = 0x08000000;  /* j */
11635           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
11636           fixP->fx_done = 0;
11637           fixP->fx_addsy = section_symbol (text_section);
11638           *valP += md_pcrel_from (fixP);
11639           md_number_to_chars ((char *) buf, insn, 4);
11640         }
11641       else
11642         {
11643           /* If we got here, we have branch-relaxation disabled,
11644              and there's nothing we can do to fix this instruction
11645              without turning it into a longer sequence.  */
11646           as_bad_where (fixP->fx_file, fixP->fx_line,
11647                         _("Branch out of range"));
11648         }
11649       break;
11650
11651     case BFD_RELOC_VTABLE_INHERIT:
11652       fixP->fx_done = 0;
11653       if (fixP->fx_addsy
11654           && !S_IS_DEFINED (fixP->fx_addsy)
11655           && !S_IS_WEAK (fixP->fx_addsy))
11656         S_SET_WEAK (fixP->fx_addsy);
11657       break;
11658
11659     case BFD_RELOC_VTABLE_ENTRY:
11660       fixP->fx_done = 0;
11661       break;
11662
11663     default:
11664       internalError ();
11665     }
11666
11667   /* Remember value for tc_gen_reloc.  */
11668   fixP->fx_addnumber = *valP;
11669 }
11670
11671 static symbolS *
11672 get_symbol (void)
11673 {
11674   int c;
11675   char *name;
11676   symbolS *p;
11677
11678   name = input_line_pointer;
11679   c = get_symbol_end ();
11680   p = (symbolS *) symbol_find_or_make (name);
11681   *input_line_pointer = c;
11682   return p;
11683 }
11684
11685 /* Align the current frag to a given power of two.  The MIPS assembler
11686    also automatically adjusts any preceding label.  */
11687
11688 static void
11689 mips_align (int to, int fill, symbolS *label)
11690 {
11691   mips_emit_delays ();
11692   frag_align (to, fill, 0);
11693   record_alignment (now_seg, to);
11694   if (label != NULL)
11695     {
11696       assert (S_GET_SEGMENT (label) == now_seg);
11697       symbol_set_frag (label, frag_now);
11698       S_SET_VALUE (label, (valueT) frag_now_fix ());
11699     }
11700 }
11701
11702 /* Align to a given power of two.  .align 0 turns off the automatic
11703    alignment used by the data creating pseudo-ops.  */
11704
11705 static void
11706 s_align (int x ATTRIBUTE_UNUSED)
11707 {
11708   register int temp;
11709   register long temp_fill;
11710   long max_alignment = 15;
11711
11712   /*
11713
11714     o  Note that the assembler pulls down any immediately preceding label
11715        to the aligned address.
11716     o  It's not documented but auto alignment is reinstated by
11717        a .align pseudo instruction.
11718     o  Note also that after auto alignment is turned off the mips assembler
11719        issues an error on attempt to assemble an improperly aligned data item.
11720        We don't.
11721
11722     */
11723
11724   temp = get_absolute_expression ();
11725   if (temp > max_alignment)
11726     as_bad (_("Alignment too large: %d. assumed."), temp = max_alignment);
11727   else if (temp < 0)
11728     {
11729       as_warn (_("Alignment negative: 0 assumed."));
11730       temp = 0;
11731     }
11732   if (*input_line_pointer == ',')
11733     {
11734       ++input_line_pointer;
11735       temp_fill = get_absolute_expression ();
11736     }
11737   else
11738     temp_fill = 0;
11739   if (temp)
11740     {
11741       auto_align = 1;
11742       mips_align (temp, (int) temp_fill,
11743                   insn_labels != NULL ? insn_labels->label : NULL);
11744     }
11745   else
11746     {
11747       auto_align = 0;
11748     }
11749
11750   demand_empty_rest_of_line ();
11751 }
11752
11753 static void
11754 s_change_sec (int sec)
11755 {
11756   segT seg;
11757
11758 #ifdef OBJ_ELF
11759   /* The ELF backend needs to know that we are changing sections, so
11760      that .previous works correctly.  We could do something like check
11761      for an obj_section_change_hook macro, but that might be confusing
11762      as it would not be appropriate to use it in the section changing
11763      functions in read.c, since obj-elf.c intercepts those.  FIXME:
11764      This should be cleaner, somehow.  */
11765   obj_elf_section_change_hook ();
11766 #endif
11767
11768   mips_emit_delays ();
11769   switch (sec)
11770     {
11771     case 't':
11772       s_text (0);
11773       break;
11774     case 'd':
11775       s_data (0);
11776       break;
11777     case 'b':
11778       subseg_set (bss_section, (subsegT) get_absolute_expression ());
11779       demand_empty_rest_of_line ();
11780       break;
11781
11782     case 'r':
11783       seg = subseg_new (RDATA_SECTION_NAME,
11784                         (subsegT) get_absolute_expression ());
11785       if (OUTPUT_FLAVOR == bfd_target_elf_flavour)
11786         {
11787           bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
11788                                                   | SEC_READONLY | SEC_RELOC
11789                                                   | SEC_DATA));
11790           if (strcmp (TARGET_OS, "elf") != 0)
11791             record_alignment (seg, 4);
11792         }
11793       demand_empty_rest_of_line ();
11794       break;
11795
11796     case 's':
11797       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
11798       if (OUTPUT_FLAVOR == bfd_target_elf_flavour)
11799         {
11800           bfd_set_section_flags (stdoutput, seg,
11801                                  SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
11802           if (strcmp (TARGET_OS, "elf") != 0)
11803             record_alignment (seg, 4);
11804         }
11805       demand_empty_rest_of_line ();
11806       break;
11807     }
11808
11809   auto_align = 1;
11810 }
11811
11812 void
11813 s_change_section (int ignore ATTRIBUTE_UNUSED)
11814 {
11815 #ifdef OBJ_ELF
11816   char *section_name;
11817   char c;
11818   char next_c = 0;
11819   int section_type;
11820   int section_flag;
11821   int section_entry_size;
11822   int section_alignment;
11823
11824   if (OUTPUT_FLAVOR != bfd_target_elf_flavour)
11825     return;
11826
11827   section_name = input_line_pointer;
11828   c = get_symbol_end ();
11829   if (c)
11830     next_c = *(input_line_pointer + 1);
11831
11832   /* Do we have .section Name<,"flags">?  */
11833   if (c != ',' || (c == ',' && next_c == '"'))
11834     {
11835       /* just after name is now '\0'.  */
11836       *input_line_pointer = c;
11837       input_line_pointer = section_name;
11838       obj_elf_section (ignore);
11839       return;
11840     }
11841   input_line_pointer++;
11842
11843   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
11844   if (c == ',')
11845     section_type = get_absolute_expression ();
11846   else
11847     section_type = 0;
11848   if (*input_line_pointer++ == ',')
11849     section_flag = get_absolute_expression ();
11850   else
11851     section_flag = 0;
11852   if (*input_line_pointer++ == ',')
11853     section_entry_size = get_absolute_expression ();
11854   else
11855     section_entry_size = 0;
11856   if (*input_line_pointer++ == ',')
11857     section_alignment = get_absolute_expression ();
11858   else
11859     section_alignment = 0;
11860
11861   section_name = xstrdup (section_name);
11862
11863   /* When using the generic form of .section (as implemented by obj-elf.c),
11864      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
11865      traditionally had to fall back on the more common @progbits instead.
11866
11867      There's nothing really harmful in this, since bfd will correct
11868      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
11869      means that, for backwards compatibility, the special_section entries
11870      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
11871
11872      Even so, we shouldn't force users of the MIPS .section syntax to
11873      incorrectly label the sections as SHT_PROGBITS.  The best compromise
11874      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
11875      generic type-checking code.  */
11876   if (section_type == SHT_MIPS_DWARF)
11877     section_type = SHT_PROGBITS;
11878
11879   obj_elf_change_section (section_name, section_type, section_flag,
11880                           section_entry_size, 0, 0, 0);
11881
11882   if (now_seg->name != section_name)
11883     free (section_name);
11884 #endif /* OBJ_ELF */
11885 }
11886
11887 void
11888 mips_enable_auto_align (void)
11889 {
11890   auto_align = 1;
11891 }
11892
11893 static void
11894 s_cons (int log_size)
11895 {
11896   symbolS *label;
11897
11898   label = insn_labels != NULL ? insn_labels->label : NULL;
11899   mips_emit_delays ();
11900   if (log_size > 0 && auto_align)
11901     mips_align (log_size, 0, label);
11902   mips_clear_insn_labels ();
11903   cons (1 << log_size);
11904 }
11905
11906 static void
11907 s_float_cons (int type)
11908 {
11909   symbolS *label;
11910
11911   label = insn_labels != NULL ? insn_labels->label : NULL;
11912
11913   mips_emit_delays ();
11914
11915   if (auto_align)
11916     {
11917       if (type == 'd')
11918         mips_align (3, 0, label);
11919       else
11920         mips_align (2, 0, label);
11921     }
11922
11923   mips_clear_insn_labels ();
11924
11925   float_cons (type);
11926 }
11927
11928 /* Handle .globl.  We need to override it because on Irix 5 you are
11929    permitted to say
11930        .globl foo .text
11931    where foo is an undefined symbol, to mean that foo should be
11932    considered to be the address of a function.  */
11933
11934 static void
11935 s_mips_globl (int x ATTRIBUTE_UNUSED)
11936 {
11937   char *name;
11938   int c;
11939   symbolS *symbolP;
11940   flagword flag;
11941
11942   do
11943     {
11944       name = input_line_pointer;
11945       c = get_symbol_end ();
11946       symbolP = symbol_find_or_make (name);
11947       S_SET_EXTERNAL (symbolP);
11948
11949       *input_line_pointer = c;
11950       SKIP_WHITESPACE ();
11951
11952       /* On Irix 5, every global symbol that is not explicitly labelled as
11953          being a function is apparently labelled as being an object.  */
11954       flag = BSF_OBJECT;
11955
11956       if (!is_end_of_line[(unsigned char) *input_line_pointer]
11957           && (*input_line_pointer != ','))
11958         {
11959           char *secname;
11960           asection *sec;
11961
11962           secname = input_line_pointer;
11963           c = get_symbol_end ();
11964           sec = bfd_get_section_by_name (stdoutput, secname);
11965           if (sec == NULL)
11966             as_bad (_("%s: no such section"), secname);
11967           *input_line_pointer = c;
11968
11969           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
11970             flag = BSF_FUNCTION;
11971         }
11972
11973       symbol_get_bfdsym (symbolP)->flags |= flag;
11974
11975       c = *input_line_pointer;
11976       if (c == ',')
11977         {
11978           input_line_pointer++;
11979           SKIP_WHITESPACE ();
11980           if (is_end_of_line[(unsigned char) *input_line_pointer])
11981             c = '\n';
11982         }
11983     }
11984   while (c == ',');
11985
11986   demand_empty_rest_of_line ();
11987 }
11988
11989 static void
11990 s_option (int x ATTRIBUTE_UNUSED)
11991 {
11992   char *opt;
11993   char c;
11994
11995   opt = input_line_pointer;
11996   c = get_symbol_end ();
11997
11998   if (*opt == 'O')
11999     {
12000       /* FIXME: What does this mean?  */
12001     }
12002   else if (strncmp (opt, "pic", 3) == 0)
12003     {
12004       int i;
12005
12006       i = atoi (opt + 3);
12007       if (i == 0)
12008         mips_pic = NO_PIC;
12009       else if (i == 2)
12010         {
12011         mips_pic = SVR4_PIC;
12012           mips_abicalls = TRUE;
12013         }
12014       else
12015         as_bad (_(".option pic%d not supported"), i);
12016
12017       if (mips_pic == SVR4_PIC)
12018         {
12019           if (g_switch_seen && g_switch_value != 0)
12020             as_warn (_("-G may not be used with SVR4 PIC code"));
12021           g_switch_value = 0;
12022           bfd_set_gp_size (stdoutput, 0);
12023         }
12024     }
12025   else
12026     as_warn (_("Unrecognized option \"%s\""), opt);
12027
12028   *input_line_pointer = c;
12029   demand_empty_rest_of_line ();
12030 }
12031
12032 /* This structure is used to hold a stack of .set values.  */
12033
12034 struct mips_option_stack
12035 {
12036   struct mips_option_stack *next;
12037   struct mips_set_options options;
12038 };
12039
12040 static struct mips_option_stack *mips_opts_stack;
12041
12042 /* Handle the .set pseudo-op.  */
12043
12044 static void
12045 s_mipsset (int x ATTRIBUTE_UNUSED)
12046 {
12047   char *name = input_line_pointer, ch;
12048
12049   while (!is_end_of_line[(unsigned char) *input_line_pointer])
12050     ++input_line_pointer;
12051   ch = *input_line_pointer;
12052   *input_line_pointer = '\0';
12053
12054   if (strcmp (name, "reorder") == 0)
12055     {
12056       if (mips_opts.noreorder)
12057         end_noreorder ();
12058     }
12059   else if (strcmp (name, "noreorder") == 0)
12060     {
12061       if (!mips_opts.noreorder)
12062         start_noreorder ();
12063     }
12064   else if (strcmp (name, "at") == 0)
12065     {
12066       mips_opts.noat = 0;
12067     }
12068   else if (strcmp (name, "noat") == 0)
12069     {
12070       mips_opts.noat = 1;
12071     }
12072   else if (strcmp (name, "macro") == 0)
12073     {
12074       mips_opts.warn_about_macros = 0;
12075     }
12076   else if (strcmp (name, "nomacro") == 0)
12077     {
12078       if (mips_opts.noreorder == 0)
12079         as_bad (_("`noreorder' must be set before `nomacro'"));
12080       mips_opts.warn_about_macros = 1;
12081     }
12082   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
12083     {
12084       mips_opts.nomove = 0;
12085     }
12086   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
12087     {
12088       mips_opts.nomove = 1;
12089     }
12090   else if (strcmp (name, "bopt") == 0)
12091     {
12092       mips_opts.nobopt = 0;
12093     }
12094   else if (strcmp (name, "nobopt") == 0)
12095     {
12096       mips_opts.nobopt = 1;
12097     }
12098   else if (strcmp (name, "mips16") == 0
12099            || strcmp (name, "MIPS-16") == 0)
12100     mips_opts.mips16 = 1;
12101   else if (strcmp (name, "nomips16") == 0
12102            || strcmp (name, "noMIPS-16") == 0)
12103     mips_opts.mips16 = 0;
12104   else if (strcmp (name, "mips3d") == 0)
12105     mips_opts.ase_mips3d = 1;
12106   else if (strcmp (name, "nomips3d") == 0)
12107     mips_opts.ase_mips3d = 0;
12108   else if (strcmp (name, "mdmx") == 0)
12109     mips_opts.ase_mdmx = 1;
12110   else if (strcmp (name, "nomdmx") == 0)
12111     mips_opts.ase_mdmx = 0;
12112   else if (strcmp (name, "dsp") == 0)
12113     mips_opts.ase_dsp = 1;
12114   else if (strcmp (name, "nodsp") == 0)
12115     mips_opts.ase_dsp = 0;
12116   else if (strcmp (name, "mt") == 0)
12117     mips_opts.ase_mt = 1;
12118   else if (strcmp (name, "nomt") == 0)
12119     mips_opts.ase_mt = 0;
12120   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
12121     {
12122       int reset = 0;
12123
12124       /* Permit the user to change the ISA and architecture on the fly.
12125          Needless to say, misuse can cause serious problems.  */
12126       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
12127         {
12128           reset = 1;
12129           mips_opts.isa = file_mips_isa;
12130           mips_opts.arch = file_mips_arch;
12131         }
12132       else if (strncmp (name, "arch=", 5) == 0)
12133         {
12134           const struct mips_cpu_info *p;
12135
12136           p = mips_parse_cpu("internal use", name + 5);
12137           if (!p)
12138             as_bad (_("unknown architecture %s"), name + 5);
12139           else
12140             {
12141               mips_opts.arch = p->cpu;
12142               mips_opts.isa = p->isa;
12143             }
12144         }
12145       else if (strncmp (name, "mips", 4) == 0)
12146         {
12147           const struct mips_cpu_info *p;
12148
12149           p = mips_parse_cpu("internal use", name);
12150           if (!p)
12151             as_bad (_("unknown ISA level %s"), name + 4);
12152           else
12153             {
12154               mips_opts.arch = p->cpu;
12155               mips_opts.isa = p->isa;
12156             }
12157         }
12158       else
12159         as_bad (_("unknown ISA or architecture %s"), name);
12160
12161       switch (mips_opts.isa)
12162         {
12163         case  0:
12164           break;
12165         case ISA_MIPS1:
12166         case ISA_MIPS2:
12167         case ISA_MIPS32:
12168         case ISA_MIPS32R2:
12169           mips_opts.gp32 = 1;
12170           mips_opts.fp32 = 1;
12171           break;
12172         case ISA_MIPS3:
12173         case ISA_MIPS4:
12174         case ISA_MIPS5:
12175         case ISA_MIPS64:
12176         case ISA_MIPS64R2:
12177           mips_opts.gp32 = 0;
12178           mips_opts.fp32 = 0;
12179           break;
12180         default:
12181           as_bad (_("unknown ISA level %s"), name + 4);
12182           break;
12183         }
12184       if (reset)
12185         {
12186           mips_opts.gp32 = file_mips_gp32;
12187           mips_opts.fp32 = file_mips_fp32;
12188         }
12189     }
12190   else if (strcmp (name, "autoextend") == 0)
12191     mips_opts.noautoextend = 0;
12192   else if (strcmp (name, "noautoextend") == 0)
12193     mips_opts.noautoextend = 1;
12194   else if (strcmp (name, "push") == 0)
12195     {
12196       struct mips_option_stack *s;
12197
12198       s = (struct mips_option_stack *) xmalloc (sizeof *s);
12199       s->next = mips_opts_stack;
12200       s->options = mips_opts;
12201       mips_opts_stack = s;
12202     }
12203   else if (strcmp (name, "pop") == 0)
12204     {
12205       struct mips_option_stack *s;
12206
12207       s = mips_opts_stack;
12208       if (s == NULL)
12209         as_bad (_(".set pop with no .set push"));
12210       else
12211         {
12212           /* If we're changing the reorder mode we need to handle
12213              delay slots correctly.  */
12214           if (s->options.noreorder && ! mips_opts.noreorder)
12215             start_noreorder ();
12216           else if (! s->options.noreorder && mips_opts.noreorder)
12217             end_noreorder ();
12218
12219           mips_opts = s->options;
12220           mips_opts_stack = s->next;
12221           free (s);
12222         }
12223     }
12224   else if (strcmp (name, "sym32") == 0)
12225     mips_opts.sym32 = TRUE;
12226   else if (strcmp (name, "nosym32") == 0)
12227     mips_opts.sym32 = FALSE;
12228   else
12229     {
12230       as_warn (_("Tried to set unrecognized symbol: %s\n"), name);
12231     }
12232   *input_line_pointer = ch;
12233   demand_empty_rest_of_line ();
12234 }
12235
12236 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
12237    .option pic2.  It means to generate SVR4 PIC calls.  */
12238
12239 static void
12240 s_abicalls (int ignore ATTRIBUTE_UNUSED)
12241 {
12242   mips_pic = SVR4_PIC;
12243   mips_abicalls = TRUE;
12244
12245   if (g_switch_seen && g_switch_value != 0)
12246     as_warn (_("-G may not be used with SVR4 PIC code"));
12247   g_switch_value = 0;
12248
12249   bfd_set_gp_size (stdoutput, 0);
12250   demand_empty_rest_of_line ();
12251 }
12252
12253 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
12254    PIC code.  It sets the $gp register for the function based on the
12255    function address, which is in the register named in the argument.
12256    This uses a relocation against _gp_disp, which is handled specially
12257    by the linker.  The result is:
12258         lui     $gp,%hi(_gp_disp)
12259         addiu   $gp,$gp,%lo(_gp_disp)
12260         addu    $gp,$gp,.cpload argument
12261    The .cpload argument is normally $25 == $t9.
12262
12263    The -mno-shared option changes this to:
12264         lui     $gp,%hi(__gnu_local_gp)
12265         addiu   $gp,$gp,%lo(__gnu_local_gp)
12266    and the argument is ignored.  This saves an instruction, but the
12267    resulting code is not position independent; it uses an absolute
12268    address for __gnu_local_gp.  Thus code assembled with -mno-shared
12269    can go into an ordinary executable, but not into a shared library.  */
12270
12271 static void
12272 s_cpload (int ignore ATTRIBUTE_UNUSED)
12273 {
12274   expressionS ex;
12275   int reg;
12276   int in_shared;
12277
12278   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
12279      .cpload is ignored.  */
12280   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
12281     {
12282       s_ignore (0);
12283       return;
12284     }
12285
12286   /* .cpload should be in a .set noreorder section.  */
12287   if (mips_opts.noreorder == 0)
12288     as_warn (_(".cpload not in noreorder section"));
12289
12290   reg = tc_get_register (0);
12291
12292   /* If we need to produce a 64-bit address, we are better off using
12293      the default instruction sequence.  */
12294   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
12295
12296   ex.X_op = O_symbol;
12297   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
12298                                          "__gnu_local_gp");
12299   ex.X_op_symbol = NULL;
12300   ex.X_add_number = 0;
12301
12302   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
12303   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
12304
12305   macro_start ();
12306   macro_build_lui (&ex, mips_gp_register);
12307   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
12308                mips_gp_register, BFD_RELOC_LO16);
12309   if (in_shared)
12310     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
12311                  mips_gp_register, reg);
12312   macro_end ();
12313
12314   demand_empty_rest_of_line ();
12315 }
12316
12317 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
12318      .cpsetup $reg1, offset|$reg2, label
12319
12320    If offset is given, this results in:
12321      sd         $gp, offset($sp)
12322      lui        $gp, %hi(%neg(%gp_rel(label)))
12323      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
12324      daddu      $gp, $gp, $reg1
12325
12326    If $reg2 is given, this results in:
12327      daddu      $reg2, $gp, $0
12328      lui        $gp, %hi(%neg(%gp_rel(label)))
12329      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
12330      daddu      $gp, $gp, $reg1
12331    $reg1 is normally $25 == $t9.
12332
12333    The -mno-shared option replaces the last three instructions with
12334         lui     $gp,%hi(_gp)
12335         addiu   $gp,$gp,%lo(_gp)
12336    */
12337
12338 static void
12339 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
12340 {
12341   expressionS ex_off;
12342   expressionS ex_sym;
12343   int reg1;
12344
12345   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
12346      We also need NewABI support.  */
12347   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
12348     {
12349       s_ignore (0);
12350       return;
12351     }
12352
12353   reg1 = tc_get_register (0);
12354   SKIP_WHITESPACE ();
12355   if (*input_line_pointer != ',')
12356     {
12357       as_bad (_("missing argument separator ',' for .cpsetup"));
12358       return;
12359     }
12360   else
12361     ++input_line_pointer;
12362   SKIP_WHITESPACE ();
12363   if (*input_line_pointer == '$')
12364     {
12365       mips_cpreturn_register = tc_get_register (0);
12366       mips_cpreturn_offset = -1;
12367     }
12368   else
12369     {
12370       mips_cpreturn_offset = get_absolute_expression ();
12371       mips_cpreturn_register = -1;
12372     }
12373   SKIP_WHITESPACE ();
12374   if (*input_line_pointer != ',')
12375     {
12376       as_bad (_("missing argument separator ',' for .cpsetup"));
12377       return;
12378     }
12379   else
12380     ++input_line_pointer;
12381   SKIP_WHITESPACE ();
12382   expression (&ex_sym);
12383
12384   macro_start ();
12385   if (mips_cpreturn_register == -1)
12386     {
12387       ex_off.X_op = O_constant;
12388       ex_off.X_add_symbol = NULL;
12389       ex_off.X_op_symbol = NULL;
12390       ex_off.X_add_number = mips_cpreturn_offset;
12391
12392       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
12393                    BFD_RELOC_LO16, SP);
12394     }
12395   else
12396     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
12397                  mips_gp_register, 0);
12398
12399   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
12400     {
12401       macro_build (&ex_sym, "lui", "t,u", mips_gp_register,
12402                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
12403                    BFD_RELOC_HI16_S);
12404
12405       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
12406                    mips_gp_register, -1, BFD_RELOC_GPREL16,
12407                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
12408
12409       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
12410                    mips_gp_register, reg1);
12411     }
12412   else
12413     {
12414       expressionS ex;
12415
12416       ex.X_op = O_symbol;
12417       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
12418       ex.X_op_symbol = NULL;
12419       ex.X_add_number = 0;
12420
12421       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
12422       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
12423
12424       macro_build_lui (&ex, mips_gp_register);
12425       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
12426                    mips_gp_register, BFD_RELOC_LO16);
12427     }
12428
12429   macro_end ();
12430
12431   demand_empty_rest_of_line ();
12432 }
12433
12434 static void
12435 s_cplocal (int ignore ATTRIBUTE_UNUSED)
12436 {
12437   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
12438    .cplocal is ignored.  */
12439   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
12440     {
12441       s_ignore (0);
12442       return;
12443     }
12444
12445   mips_gp_register = tc_get_register (0);
12446   demand_empty_rest_of_line ();
12447 }
12448
12449 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
12450    offset from $sp.  The offset is remembered, and after making a PIC
12451    call $gp is restored from that location.  */
12452
12453 static void
12454 s_cprestore (int ignore ATTRIBUTE_UNUSED)
12455 {
12456   expressionS ex;
12457
12458   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
12459      .cprestore is ignored.  */
12460   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
12461     {
12462       s_ignore (0);
12463       return;
12464     }
12465
12466   mips_cprestore_offset = get_absolute_expression ();
12467   mips_cprestore_valid = 1;
12468
12469   ex.X_op = O_constant;
12470   ex.X_add_symbol = NULL;
12471   ex.X_op_symbol = NULL;
12472   ex.X_add_number = mips_cprestore_offset;
12473
12474   macro_start ();
12475   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
12476                                 SP, HAVE_64BIT_ADDRESSES);
12477   macro_end ();
12478
12479   demand_empty_rest_of_line ();
12480 }
12481
12482 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
12483    was given in the preceding .cpsetup, it results in:
12484      ld         $gp, offset($sp)
12485
12486    If a register $reg2 was given there, it results in:
12487      daddu      $gp, $reg2, $0
12488  */
12489 static void
12490 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
12491 {
12492   expressionS ex;
12493
12494   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
12495      We also need NewABI support.  */
12496   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
12497     {
12498       s_ignore (0);
12499       return;
12500     }
12501
12502   macro_start ();
12503   if (mips_cpreturn_register == -1)
12504     {
12505       ex.X_op = O_constant;
12506       ex.X_add_symbol = NULL;
12507       ex.X_op_symbol = NULL;
12508       ex.X_add_number = mips_cpreturn_offset;
12509
12510       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
12511     }
12512   else
12513     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
12514                  mips_cpreturn_register, 0);
12515   macro_end ();
12516
12517   demand_empty_rest_of_line ();
12518 }
12519
12520 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
12521    code.  It sets the offset to use in gp_rel relocations.  */
12522
12523 static void
12524 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
12525 {
12526   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
12527      We also need NewABI support.  */
12528   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
12529     {
12530       s_ignore (0);
12531       return;
12532     }
12533
12534   mips_gprel_offset = get_absolute_expression ();
12535
12536   demand_empty_rest_of_line ();
12537 }
12538
12539 /* Handle the .gpword pseudo-op.  This is used when generating PIC
12540    code.  It generates a 32 bit GP relative reloc.  */
12541
12542 static void
12543 s_gpword (int ignore ATTRIBUTE_UNUSED)
12544 {
12545   symbolS *label;
12546   expressionS ex;
12547   char *p;
12548
12549   /* When not generating PIC code, this is treated as .word.  */
12550   if (mips_pic != SVR4_PIC)
12551     {
12552       s_cons (2);
12553       return;
12554     }
12555
12556   label = insn_labels != NULL ? insn_labels->label : NULL;
12557   mips_emit_delays ();
12558   if (auto_align)
12559     mips_align (2, 0, label);
12560   mips_clear_insn_labels ();
12561
12562   expression (&ex);
12563
12564   if (ex.X_op != O_symbol || ex.X_add_number != 0)
12565     {
12566       as_bad (_("Unsupported use of .gpword"));
12567       ignore_rest_of_line ();
12568     }
12569
12570   p = frag_more (4);
12571   md_number_to_chars (p, 0, 4);
12572   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
12573                BFD_RELOC_GPREL32);
12574
12575   demand_empty_rest_of_line ();
12576 }
12577
12578 static void
12579 s_gpdword (int ignore ATTRIBUTE_UNUSED)
12580 {
12581   symbolS *label;
12582   expressionS ex;
12583   char *p;
12584
12585   /* When not generating PIC code, this is treated as .dword.  */
12586   if (mips_pic != SVR4_PIC)
12587     {
12588       s_cons (3);
12589       return;
12590     }
12591
12592   label = insn_labels != NULL ? insn_labels->label : NULL;
12593   mips_emit_delays ();
12594   if (auto_align)
12595     mips_align (3, 0, label);
12596   mips_clear_insn_labels ();
12597
12598   expression (&ex);
12599
12600   if (ex.X_op != O_symbol || ex.X_add_number != 0)
12601     {
12602       as_bad (_("Unsupported use of .gpdword"));
12603       ignore_rest_of_line ();
12604     }
12605
12606   p = frag_more (8);
12607   md_number_to_chars (p, 0, 8);
12608   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
12609                BFD_RELOC_GPREL32)->fx_tcbit = 1;
12610
12611   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
12612   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
12613            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
12614
12615   demand_empty_rest_of_line ();
12616 }
12617
12618 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
12619    tables in SVR4 PIC code.  */
12620
12621 static void
12622 s_cpadd (int ignore ATTRIBUTE_UNUSED)
12623 {
12624   int reg;
12625
12626   /* This is ignored when not generating SVR4 PIC code.  */
12627   if (mips_pic != SVR4_PIC)
12628     {
12629       s_ignore (0);
12630       return;
12631     }
12632
12633   /* Add $gp to the register named as an argument.  */
12634   macro_start ();
12635   reg = tc_get_register (0);
12636   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
12637   macro_end ();
12638
12639   demand_empty_rest_of_line ();
12640 }
12641
12642 /* Handle the .insn pseudo-op.  This marks instruction labels in
12643    mips16 mode.  This permits the linker to handle them specially,
12644    such as generating jalx instructions when needed.  We also make
12645    them odd for the duration of the assembly, in order to generate the
12646    right sort of code.  We will make them even in the adjust_symtab
12647    routine, while leaving them marked.  This is convenient for the
12648    debugger and the disassembler.  The linker knows to make them odd
12649    again.  */
12650
12651 static void
12652 s_insn (int ignore ATTRIBUTE_UNUSED)
12653 {
12654   mips16_mark_labels ();
12655
12656   demand_empty_rest_of_line ();
12657 }
12658
12659 /* Handle a .stabn directive.  We need these in order to mark a label
12660    as being a mips16 text label correctly.  Sometimes the compiler
12661    will emit a label, followed by a .stabn, and then switch sections.
12662    If the label and .stabn are in mips16 mode, then the label is
12663    really a mips16 text label.  */
12664
12665 static void
12666 s_mips_stab (int type)
12667 {
12668   if (type == 'n')
12669     mips16_mark_labels ();
12670
12671   s_stab (type);
12672 }
12673
12674 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.
12675  */
12676
12677 static void
12678 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
12679 {
12680   char *name;
12681   int c;
12682   symbolS *symbolP;
12683   expressionS exp;
12684
12685   name = input_line_pointer;
12686   c = get_symbol_end ();
12687   symbolP = symbol_find_or_make (name);
12688   S_SET_WEAK (symbolP);
12689   *input_line_pointer = c;
12690
12691   SKIP_WHITESPACE ();
12692
12693   if (! is_end_of_line[(unsigned char) *input_line_pointer])
12694     {
12695       if (S_IS_DEFINED (symbolP))
12696         {
12697           as_bad ("ignoring attempt to redefine symbol %s",
12698                   S_GET_NAME (symbolP));
12699           ignore_rest_of_line ();
12700           return;
12701         }
12702
12703       if (*input_line_pointer == ',')
12704         {
12705           ++input_line_pointer;
12706           SKIP_WHITESPACE ();
12707         }
12708
12709       expression (&exp);
12710       if (exp.X_op != O_symbol)
12711         {
12712           as_bad ("bad .weakext directive");
12713           ignore_rest_of_line ();
12714           return;
12715         }
12716       symbol_set_value_expression (symbolP, &exp);
12717     }
12718
12719   demand_empty_rest_of_line ();
12720 }
12721
12722 /* Parse a register string into a number.  Called from the ECOFF code
12723    to parse .frame.  The argument is non-zero if this is the frame
12724    register, so that we can record it in mips_frame_reg.  */
12725
12726 int
12727 tc_get_register (int frame)
12728 {
12729   int reg;
12730
12731   SKIP_WHITESPACE ();
12732   if (*input_line_pointer++ != '$')
12733     {
12734       as_warn (_("expected `$'"));
12735       reg = ZERO;
12736     }
12737   else if (ISDIGIT (*input_line_pointer))
12738     {
12739       reg = get_absolute_expression ();
12740       if (reg < 0 || reg >= 32)
12741         {
12742           as_warn (_("Bad register number"));
12743           reg = ZERO;
12744         }
12745     }
12746   else
12747     {
12748       if (strncmp (input_line_pointer, "ra", 2) == 0)
12749         {
12750           reg = RA;
12751           input_line_pointer += 2;
12752         }
12753       else if (strncmp (input_line_pointer, "fp", 2) == 0)
12754         {
12755           reg = FP;
12756           input_line_pointer += 2;
12757         }
12758       else if (strncmp (input_line_pointer, "sp", 2) == 0)
12759         {
12760           reg = SP;
12761           input_line_pointer += 2;
12762         }
12763       else if (strncmp (input_line_pointer, "gp", 2) == 0)
12764         {
12765           reg = GP;
12766           input_line_pointer += 2;
12767         }
12768       else if (strncmp (input_line_pointer, "at", 2) == 0)
12769         {
12770           reg = AT;
12771           input_line_pointer += 2;
12772         }
12773       else if (strncmp (input_line_pointer, "kt0", 3) == 0)
12774         {
12775           reg = KT0;
12776           input_line_pointer += 3;
12777         }
12778       else if (strncmp (input_line_pointer, "kt1", 3) == 0)
12779         {
12780           reg = KT1;
12781           input_line_pointer += 3;
12782         }
12783       else if (strncmp (input_line_pointer, "zero", 4) == 0)
12784         {
12785           reg = ZERO;
12786           input_line_pointer += 4;
12787         }
12788       else
12789         {
12790           as_warn (_("Unrecognized register name"));
12791           reg = ZERO;
12792           while (ISALNUM(*input_line_pointer))
12793            input_line_pointer++;
12794         }
12795     }
12796   if (frame)
12797     {
12798       mips_frame_reg = reg != 0 ? reg : SP;
12799       mips_frame_reg_valid = 1;
12800       mips_cprestore_valid = 0;
12801     }
12802   return reg;
12803 }
12804
12805 valueT
12806 md_section_align (asection *seg, valueT addr)
12807 {
12808   int align = bfd_get_section_alignment (stdoutput, seg);
12809
12810 #ifdef OBJ_ELF
12811   /* We don't need to align ELF sections to the full alignment.
12812      However, Irix 5 may prefer that we align them at least to a 16
12813      byte boundary.  We don't bother to align the sections if we are
12814      targeted for an embedded system.  */
12815   if (strcmp (TARGET_OS, "elf") == 0)
12816     return addr;
12817   if (align > 4)
12818     align = 4;
12819 #endif
12820
12821   return ((addr + (1 << align) - 1) & (-1 << align));
12822 }
12823
12824 /* Utility routine, called from above as well.  If called while the
12825    input file is still being read, it's only an approximation.  (For
12826    example, a symbol may later become defined which appeared to be
12827    undefined earlier.)  */
12828
12829 static int
12830 nopic_need_relax (symbolS *sym, int before_relaxing)
12831 {
12832   if (sym == 0)
12833     return 0;
12834
12835   if (g_switch_value > 0)
12836     {
12837       const char *symname;
12838       int change;
12839
12840       /* Find out whether this symbol can be referenced off the $gp
12841          register.  It can be if it is smaller than the -G size or if
12842          it is in the .sdata or .sbss section.  Certain symbols can
12843          not be referenced off the $gp, although it appears as though
12844          they can.  */
12845       symname = S_GET_NAME (sym);
12846       if (symname != (const char *) NULL
12847           && (strcmp (symname, "eprol") == 0
12848               || strcmp (symname, "etext") == 0
12849               || strcmp (symname, "_gp") == 0
12850               || strcmp (symname, "edata") == 0
12851               || strcmp (symname, "_fbss") == 0
12852               || strcmp (symname, "_fdata") == 0
12853               || strcmp (symname, "_ftext") == 0
12854               || strcmp (symname, "end") == 0
12855               || strcmp (symname, "_gp_disp") == 0))
12856         change = 1;
12857       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
12858                && (0
12859 #ifndef NO_ECOFF_DEBUGGING
12860                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
12861                        && (symbol_get_obj (sym)->ecoff_extern_size
12862                            <= g_switch_value))
12863 #endif
12864                    /* We must defer this decision until after the whole
12865                       file has been read, since there might be a .extern
12866                       after the first use of this symbol.  */
12867                    || (before_relaxing
12868 #ifndef NO_ECOFF_DEBUGGING
12869                        && symbol_get_obj (sym)->ecoff_extern_size == 0
12870 #endif
12871                        && S_GET_VALUE (sym) == 0)
12872                    || (S_GET_VALUE (sym) != 0
12873                        && S_GET_VALUE (sym) <= g_switch_value)))
12874         change = 0;
12875       else
12876         {
12877           const char *segname;
12878
12879           segname = segment_name (S_GET_SEGMENT (sym));
12880           assert (strcmp (segname, ".lit8") != 0
12881                   && strcmp (segname, ".lit4") != 0);
12882           change = (strcmp (segname, ".sdata") != 0
12883                     && strcmp (segname, ".sbss") != 0
12884                     && strncmp (segname, ".sdata.", 7) != 0
12885                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
12886         }
12887       return change;
12888     }
12889   else
12890     /* We are not optimizing for the $gp register.  */
12891     return 1;
12892 }
12893
12894
12895 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
12896
12897 static bfd_boolean
12898 pic_need_relax (symbolS *sym, asection *segtype)
12899 {
12900   asection *symsec;
12901   bfd_boolean linkonce;
12902
12903   /* Handle the case of a symbol equated to another symbol.  */
12904   while (symbol_equated_reloc_p (sym))
12905     {
12906       symbolS *n;
12907
12908       /* It's possible to get a loop here in a badly written
12909          program.  */
12910       n = symbol_get_value_expression (sym)->X_add_symbol;
12911       if (n == sym)
12912         break;
12913       sym = n;
12914     }
12915
12916   symsec = S_GET_SEGMENT (sym);
12917
12918   /* duplicate the test for LINK_ONCE sections as in adjust_reloc_syms */
12919   linkonce = FALSE;
12920   if (symsec != segtype && ! S_IS_LOCAL (sym))
12921     {
12922       if ((bfd_get_section_flags (stdoutput, symsec) & SEC_LINK_ONCE)
12923           != 0)
12924         linkonce = TRUE;
12925
12926       /* The GNU toolchain uses an extension for ELF: a section
12927          beginning with the magic string .gnu.linkonce is a linkonce
12928          section.  */
12929       if (strncmp (segment_name (symsec), ".gnu.linkonce",
12930                    sizeof ".gnu.linkonce" - 1) == 0)
12931         linkonce = TRUE;
12932     }
12933
12934   /* This must duplicate the test in adjust_reloc_syms.  */
12935   return (symsec != &bfd_und_section
12936           && symsec != &bfd_abs_section
12937           && ! bfd_is_com_section (symsec)
12938           && !linkonce
12939 #ifdef OBJ_ELF
12940           /* A global or weak symbol is treated as external.  */
12941           && (OUTPUT_FLAVOR != bfd_target_elf_flavour
12942               || (! S_IS_WEAK (sym) && ! S_IS_EXTERNAL (sym)))
12943 #endif
12944           );
12945 }
12946
12947
12948 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
12949    extended opcode.  SEC is the section the frag is in.  */
12950
12951 static int
12952 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
12953 {
12954   int type;
12955   register const struct mips16_immed_operand *op;
12956   offsetT val;
12957   int mintiny, maxtiny;
12958   segT symsec;
12959   fragS *sym_frag;
12960
12961   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
12962     return 0;
12963   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
12964     return 1;
12965
12966   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
12967   op = mips16_immed_operands;
12968   while (op->type != type)
12969     {
12970       ++op;
12971       assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
12972     }
12973
12974   if (op->unsp)
12975     {
12976       if (type == '<' || type == '>' || type == '[' || type == ']')
12977         {
12978           mintiny = 1;
12979           maxtiny = 1 << op->nbits;
12980         }
12981       else
12982         {
12983           mintiny = 0;
12984           maxtiny = (1 << op->nbits) - 1;
12985         }
12986     }
12987   else
12988     {
12989       mintiny = - (1 << (op->nbits - 1));
12990       maxtiny = (1 << (op->nbits - 1)) - 1;
12991     }
12992
12993   sym_frag = symbol_get_frag (fragp->fr_symbol);
12994   val = S_GET_VALUE (fragp->fr_symbol);
12995   symsec = S_GET_SEGMENT (fragp->fr_symbol);
12996
12997   if (op->pcrel)
12998     {
12999       addressT addr;
13000
13001       /* We won't have the section when we are called from
13002          mips_relax_frag.  However, we will always have been called
13003          from md_estimate_size_before_relax first.  If this is a
13004          branch to a different section, we mark it as such.  If SEC is
13005          NULL, and the frag is not marked, then it must be a branch to
13006          the same section.  */
13007       if (sec == NULL)
13008         {
13009           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
13010             return 1;
13011         }
13012       else
13013         {
13014           /* Must have been called from md_estimate_size_before_relax.  */
13015           if (symsec != sec)
13016             {
13017               fragp->fr_subtype =
13018                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
13019
13020               /* FIXME: We should support this, and let the linker
13021                  catch branches and loads that are out of range.  */
13022               as_bad_where (fragp->fr_file, fragp->fr_line,
13023                             _("unsupported PC relative reference to different section"));
13024
13025               return 1;
13026             }
13027           if (fragp != sym_frag && sym_frag->fr_address == 0)
13028             /* Assume non-extended on the first relaxation pass.
13029                The address we have calculated will be bogus if this is
13030                a forward branch to another frag, as the forward frag
13031                will have fr_address == 0.  */
13032             return 0;
13033         }
13034
13035       /* In this case, we know for sure that the symbol fragment is in
13036          the same section.  If the relax_marker of the symbol fragment
13037          differs from the relax_marker of this fragment, we have not
13038          yet adjusted the symbol fragment fr_address.  We want to add
13039          in STRETCH in order to get a better estimate of the address.
13040          This particularly matters because of the shift bits.  */
13041       if (stretch != 0
13042           && sym_frag->relax_marker != fragp->relax_marker)
13043         {
13044           fragS *f;
13045
13046           /* Adjust stretch for any alignment frag.  Note that if have
13047              been expanding the earlier code, the symbol may be
13048              defined in what appears to be an earlier frag.  FIXME:
13049              This doesn't handle the fr_subtype field, which specifies
13050              a maximum number of bytes to skip when doing an
13051              alignment.  */
13052           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
13053             {
13054               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
13055                 {
13056                   if (stretch < 0)
13057                     stretch = - ((- stretch)
13058                                  & ~ ((1 << (int) f->fr_offset) - 1));
13059                   else
13060                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
13061                   if (stretch == 0)
13062                     break;
13063                 }
13064             }
13065           if (f != NULL)
13066             val += stretch;
13067         }
13068
13069       addr = fragp->fr_address + fragp->fr_fix;
13070
13071       /* The base address rules are complicated.  The base address of
13072          a branch is the following instruction.  The base address of a
13073          PC relative load or add is the instruction itself, but if it
13074          is in a delay slot (in which case it can not be extended) use
13075          the address of the instruction whose delay slot it is in.  */
13076       if (type == 'p' || type == 'q')
13077         {
13078           addr += 2;
13079
13080           /* If we are currently assuming that this frag should be
13081              extended, then, the current address is two bytes
13082              higher.  */
13083           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
13084             addr += 2;
13085
13086           /* Ignore the low bit in the target, since it will be set
13087              for a text label.  */
13088           if ((val & 1) != 0)
13089             --val;
13090         }
13091       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
13092         addr -= 4;
13093       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
13094         addr -= 2;
13095
13096       val -= addr & ~ ((1 << op->shift) - 1);
13097
13098       /* Branch offsets have an implicit 0 in the lowest bit.  */
13099       if (type == 'p' || type == 'q')
13100         val /= 2;
13101
13102       /* If any of the shifted bits are set, we must use an extended
13103          opcode.  If the address depends on the size of this
13104          instruction, this can lead to a loop, so we arrange to always
13105          use an extended opcode.  We only check this when we are in
13106          the main relaxation loop, when SEC is NULL.  */
13107       if ((val & ((1 << op->shift) - 1)) != 0 && sec == NULL)
13108         {
13109           fragp->fr_subtype =
13110             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
13111           return 1;
13112         }
13113
13114       /* If we are about to mark a frag as extended because the value
13115          is precisely maxtiny + 1, then there is a chance of an
13116          infinite loop as in the following code:
13117              la $4,foo
13118              .skip      1020
13119              .align     2
13120            foo:
13121          In this case when the la is extended, foo is 0x3fc bytes
13122          away, so the la can be shrunk, but then foo is 0x400 away, so
13123          the la must be extended.  To avoid this loop, we mark the
13124          frag as extended if it was small, and is about to become
13125          extended with a value of maxtiny + 1.  */
13126       if (val == ((maxtiny + 1) << op->shift)
13127           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
13128           && sec == NULL)
13129         {
13130           fragp->fr_subtype =
13131             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
13132           return 1;
13133         }
13134     }
13135   else if (symsec != absolute_section && sec != NULL)
13136     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
13137
13138   if ((val & ((1 << op->shift) - 1)) != 0
13139       || val < (mintiny << op->shift)
13140       || val > (maxtiny << op->shift))
13141     return 1;
13142   else
13143     return 0;
13144 }
13145
13146 /* Compute the length of a branch sequence, and adjust the
13147    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
13148    worst-case length is computed, with UPDATE being used to indicate
13149    whether an unconditional (-1), branch-likely (+1) or regular (0)
13150    branch is to be computed.  */
13151 static int
13152 relaxed_branch_length (fragS *fragp, asection *sec, int update)
13153 {
13154   bfd_boolean toofar;
13155   int length;
13156
13157   if (fragp
13158       && S_IS_DEFINED (fragp->fr_symbol)
13159       && sec == S_GET_SEGMENT (fragp->fr_symbol))
13160     {
13161       addressT addr;
13162       offsetT val;
13163
13164       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
13165
13166       addr = fragp->fr_address + fragp->fr_fix + 4;
13167
13168       val -= addr;
13169
13170       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
13171     }
13172   else if (fragp)
13173     /* If the symbol is not defined or it's in a different segment,
13174        assume the user knows what's going on and emit a short
13175        branch.  */
13176     toofar = FALSE;
13177   else
13178     toofar = TRUE;
13179
13180   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
13181     fragp->fr_subtype
13182       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_UNCOND (fragp->fr_subtype),
13183                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
13184                              RELAX_BRANCH_LINK (fragp->fr_subtype),
13185                              toofar);
13186
13187   length = 4;
13188   if (toofar)
13189     {
13190       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
13191         length += 8;
13192
13193       if (mips_pic != NO_PIC)
13194         {
13195           /* Additional space for PIC loading of target address.  */
13196           length += 8;
13197           if (mips_opts.isa == ISA_MIPS1)
13198             /* Additional space for $at-stabilizing nop.  */
13199             length += 4;
13200         }
13201
13202       /* If branch is conditional.  */
13203       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
13204         length += 8;
13205     }
13206
13207   return length;
13208 }
13209
13210 /* Estimate the size of a frag before relaxing.  Unless this is the
13211    mips16, we are not really relaxing here, and the final size is
13212    encoded in the subtype information.  For the mips16, we have to
13213    decide whether we are using an extended opcode or not.  */
13214
13215 int
13216 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
13217 {
13218   int change;
13219
13220   if (RELAX_BRANCH_P (fragp->fr_subtype))
13221     {
13222
13223       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
13224
13225       return fragp->fr_var;
13226     }
13227
13228   if (RELAX_MIPS16_P (fragp->fr_subtype))
13229     /* We don't want to modify the EXTENDED bit here; it might get us
13230        into infinite loops.  We change it only in mips_relax_frag().  */
13231     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
13232
13233   if (mips_pic == NO_PIC)
13234     change = nopic_need_relax (fragp->fr_symbol, 0);
13235   else if (mips_pic == SVR4_PIC)
13236     change = pic_need_relax (fragp->fr_symbol, segtype);
13237   else if (mips_pic == VXWORKS_PIC)
13238     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
13239     change = 0;
13240   else
13241     abort ();
13242
13243   if (change)
13244     {
13245       fragp->fr_subtype |= RELAX_USE_SECOND;
13246       return -RELAX_FIRST (fragp->fr_subtype);
13247     }
13248   else
13249     return -RELAX_SECOND (fragp->fr_subtype);
13250 }
13251
13252 /* This is called to see whether a reloc against a defined symbol
13253    should be converted into a reloc against a section.  */
13254
13255 int
13256 mips_fix_adjustable (fixS *fixp)
13257 {
13258   /* Don't adjust MIPS16 jump relocations, so we don't have to worry
13259      about the format of the offset in the .o file. */
13260   if (fixp->fx_r_type == BFD_RELOC_MIPS16_JMP)
13261     return 0;
13262
13263   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
13264       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
13265     return 0;
13266
13267   if (fixp->fx_addsy == NULL)
13268     return 1;
13269
13270   /* If symbol SYM is in a mergeable section, relocations of the form
13271      SYM + 0 can usually be made section-relative.  The mergeable data
13272      is then identified by the section offset rather than by the symbol.
13273
13274      However, if we're generating REL LO16 relocations, the offset is split
13275      between the LO16 and parterning high part relocation.  The linker will
13276      need to recalculate the complete offset in order to correctly identify
13277      the merge data.
13278
13279      The linker has traditionally not looked for the parterning high part
13280      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
13281      placed anywhere.  Rather than break backwards compatibility by changing
13282      this, it seems better not to force the issue, and instead keep the
13283      original symbol.  This will work with either linker behavior.  */
13284   if ((fixp->fx_r_type == BFD_RELOC_LO16
13285        || fixp->fx_r_type == BFD_RELOC_MIPS16_LO16
13286        || reloc_needs_lo_p (fixp->fx_r_type))
13287       && HAVE_IN_PLACE_ADDENDS
13288       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
13289     return 0;
13290
13291 #ifdef OBJ_ELF
13292   /* Don't adjust relocations against mips16 symbols, so that the linker
13293      can find them if it needs to set up a stub.  */
13294   if (OUTPUT_FLAVOR == bfd_target_elf_flavour
13295       && S_GET_OTHER (fixp->fx_addsy) == STO_MIPS16
13296       && fixp->fx_subsy == NULL)
13297     return 0;
13298 #endif
13299
13300   return 1;
13301 }
13302
13303 /* Translate internal representation of relocation info to BFD target
13304    format.  */
13305
13306 arelent **
13307 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
13308 {
13309   static arelent *retval[4];
13310   arelent *reloc;
13311   bfd_reloc_code_real_type code;
13312
13313   memset (retval, 0, sizeof(retval));
13314   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
13315   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
13316   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
13317   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
13318
13319   if (fixp->fx_pcrel)
13320     {
13321       assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2);
13322
13323       /* At this point, fx_addnumber is "symbol offset - pcrel address".
13324          Relocations want only the symbol offset.  */
13325       reloc->addend = fixp->fx_addnumber + reloc->address;
13326       if (OUTPUT_FLAVOR != bfd_target_elf_flavour)
13327         {
13328           /* A gruesome hack which is a result of the gruesome gas
13329              reloc handling.  What's worse, for COFF (as opposed to
13330              ECOFF), we might need yet another copy of reloc->address.
13331              See bfd_install_relocation.  */
13332           reloc->addend += reloc->address;
13333         }
13334     }
13335   else
13336     reloc->addend = fixp->fx_addnumber;
13337
13338   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
13339      entry to be used in the relocation's section offset.  */
13340   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
13341     {
13342       reloc->address = reloc->addend;
13343       reloc->addend = 0;
13344     }
13345
13346   code = fixp->fx_r_type;
13347
13348   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
13349   if (reloc->howto == NULL)
13350     {
13351       as_bad_where (fixp->fx_file, fixp->fx_line,
13352                     _("Can not represent %s relocation in this object file format"),
13353                     bfd_get_reloc_code_name (code));
13354       retval[0] = NULL;
13355     }
13356
13357   return retval;
13358 }
13359
13360 /* Relax a machine dependent frag.  This returns the amount by which
13361    the current size of the frag should change.  */
13362
13363 int
13364 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
13365 {
13366   if (RELAX_BRANCH_P (fragp->fr_subtype))
13367     {
13368       offsetT old_var = fragp->fr_var;
13369
13370       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
13371
13372       return fragp->fr_var - old_var;
13373     }
13374
13375   if (! RELAX_MIPS16_P (fragp->fr_subtype))
13376     return 0;
13377
13378   if (mips16_extended_frag (fragp, NULL, stretch))
13379     {
13380       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
13381         return 0;
13382       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
13383       return 2;
13384     }
13385   else
13386     {
13387       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
13388         return 0;
13389       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
13390       return -2;
13391     }
13392
13393   return 0;
13394 }
13395
13396 /* Convert a machine dependent frag.  */
13397
13398 void
13399 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
13400 {
13401   if (RELAX_BRANCH_P (fragp->fr_subtype))
13402     {
13403       bfd_byte *buf;
13404       unsigned long insn;
13405       expressionS exp;
13406       fixS *fixp;
13407
13408       buf = (bfd_byte *)fragp->fr_literal + fragp->fr_fix;
13409
13410       if (target_big_endian)
13411         insn = bfd_getb32 (buf);
13412       else
13413         insn = bfd_getl32 (buf);
13414
13415       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
13416         {
13417           /* We generate a fixup instead of applying it right now
13418              because, if there are linker relaxations, we're going to
13419              need the relocations.  */
13420           exp.X_op = O_symbol;
13421           exp.X_add_symbol = fragp->fr_symbol;
13422           exp.X_add_number = fragp->fr_offset;
13423
13424           fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
13425                               4, &exp, 1, BFD_RELOC_16_PCREL_S2);
13426           fixp->fx_file = fragp->fr_file;
13427           fixp->fx_line = fragp->fr_line;
13428
13429           md_number_to_chars ((char *) buf, insn, 4);
13430           buf += 4;
13431         }
13432       else
13433         {
13434           int i;
13435
13436           as_warn_where (fragp->fr_file, fragp->fr_line,
13437                          _("relaxed out-of-range branch into a jump"));
13438
13439           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
13440             goto uncond;
13441
13442           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
13443             {
13444               /* Reverse the branch.  */
13445               switch ((insn >> 28) & 0xf)
13446                 {
13447                 case 4:
13448                   /* bc[0-3][tf]l? and bc1any[24][ft] instructions can
13449                      have the condition reversed by tweaking a single
13450                      bit, and their opcodes all have 0x4???????.  */
13451                   assert ((insn & 0xf1000000) == 0x41000000);
13452                   insn ^= 0x00010000;
13453                   break;
13454
13455                 case 0:
13456                   /* bltz       0x04000000      bgez    0x04010000
13457                      bltzal     0x04100000      bgezal  0x04110000 */
13458                   assert ((insn & 0xfc0e0000) == 0x04000000);
13459                   insn ^= 0x00010000;
13460                   break;
13461
13462                 case 1:
13463                   /* beq        0x10000000      bne     0x14000000
13464                      blez       0x18000000      bgtz    0x1c000000 */
13465                   insn ^= 0x04000000;
13466                   break;
13467
13468                 default:
13469                   abort ();
13470                 }
13471             }
13472
13473           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
13474             {
13475               /* Clear the and-link bit.  */
13476               assert ((insn & 0xfc1c0000) == 0x04100000);
13477
13478               /* bltzal 0x04100000      bgezal  0x04110000
13479                 bltzall 0x04120000     bgezall  0x04130000 */
13480               insn &= ~0x00100000;
13481             }
13482
13483           /* Branch over the branch (if the branch was likely) or the
13484              full jump (not likely case).  Compute the offset from the
13485              current instruction to branch to.  */
13486           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
13487             i = 16;
13488           else
13489             {
13490               /* How many bytes in instructions we've already emitted?  */
13491               i = buf - (bfd_byte *)fragp->fr_literal - fragp->fr_fix;
13492               /* How many bytes in instructions from here to the end?  */
13493               i = fragp->fr_var - i;
13494             }
13495           /* Convert to instruction count.  */
13496           i >>= 2;
13497           /* Branch counts from the next instruction.  */
13498           i--;
13499           insn |= i;
13500           /* Branch over the jump.  */
13501           md_number_to_chars ((char *) buf, insn, 4);
13502           buf += 4;
13503
13504           /* Nop */
13505           md_number_to_chars ((char *) buf, 0, 4);
13506           buf += 4;
13507
13508           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
13509             {
13510               /* beql $0, $0, 2f */
13511               insn = 0x50000000;
13512               /* Compute the PC offset from the current instruction to
13513                  the end of the variable frag.  */
13514               /* How many bytes in instructions we've already emitted?  */
13515               i = buf - (bfd_byte *)fragp->fr_literal - fragp->fr_fix;
13516               /* How many bytes in instructions from here to the end?  */
13517               i = fragp->fr_var - i;
13518               /* Convert to instruction count.  */
13519               i >>= 2;
13520               /* Don't decrement i, because we want to branch over the
13521                  delay slot.  */
13522
13523               insn |= i;
13524               md_number_to_chars ((char *) buf, insn, 4);
13525               buf += 4;
13526
13527               md_number_to_chars ((char *) buf, 0, 4);
13528               buf += 4;
13529             }
13530
13531         uncond:
13532           if (mips_pic == NO_PIC)
13533             {
13534               /* j or jal.  */
13535               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
13536                       ? 0x0c000000 : 0x08000000);
13537               exp.X_op = O_symbol;
13538               exp.X_add_symbol = fragp->fr_symbol;
13539               exp.X_add_number = fragp->fr_offset;
13540
13541               fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
13542                                   4, &exp, 0, BFD_RELOC_MIPS_JMP);
13543               fixp->fx_file = fragp->fr_file;
13544               fixp->fx_line = fragp->fr_line;
13545
13546               md_number_to_chars ((char *) buf, insn, 4);
13547               buf += 4;
13548             }
13549           else
13550             {
13551               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
13552               insn = HAVE_64BIT_ADDRESSES ? 0xdf810000 : 0x8f810000;
13553               exp.X_op = O_symbol;
13554               exp.X_add_symbol = fragp->fr_symbol;
13555               exp.X_add_number = fragp->fr_offset;
13556
13557               if (fragp->fr_offset)
13558                 {
13559                   exp.X_add_symbol = make_expr_symbol (&exp);
13560                   exp.X_add_number = 0;
13561                 }
13562
13563               fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
13564                                   4, &exp, 0, BFD_RELOC_MIPS_GOT16);
13565               fixp->fx_file = fragp->fr_file;
13566               fixp->fx_line = fragp->fr_line;
13567
13568               md_number_to_chars ((char *) buf, insn, 4);
13569               buf += 4;
13570
13571               if (mips_opts.isa == ISA_MIPS1)
13572                 {
13573                   /* nop */
13574                   md_number_to_chars ((char *) buf, 0, 4);
13575                   buf += 4;
13576                 }
13577
13578               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
13579               insn = HAVE_64BIT_ADDRESSES ? 0x64210000 : 0x24210000;
13580
13581               fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
13582                                   4, &exp, 0, BFD_RELOC_LO16);
13583               fixp->fx_file = fragp->fr_file;
13584               fixp->fx_line = fragp->fr_line;
13585
13586               md_number_to_chars ((char *) buf, insn, 4);
13587               buf += 4;
13588
13589               /* j(al)r $at.  */
13590               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
13591                 insn = 0x0020f809;
13592               else
13593                 insn = 0x00200008;
13594
13595               md_number_to_chars ((char *) buf, insn, 4);
13596               buf += 4;
13597             }
13598         }
13599
13600       assert (buf == (bfd_byte *)fragp->fr_literal
13601               + fragp->fr_fix + fragp->fr_var);
13602
13603       fragp->fr_fix += fragp->fr_var;
13604
13605       return;
13606     }
13607
13608   if (RELAX_MIPS16_P (fragp->fr_subtype))
13609     {
13610       int type;
13611       register const struct mips16_immed_operand *op;
13612       bfd_boolean small, ext;
13613       offsetT val;
13614       bfd_byte *buf;
13615       unsigned long insn;
13616       bfd_boolean use_extend;
13617       unsigned short extend;
13618
13619       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
13620       op = mips16_immed_operands;
13621       while (op->type != type)
13622         ++op;
13623
13624       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
13625         {
13626           small = FALSE;
13627           ext = TRUE;
13628         }
13629       else
13630         {
13631           small = TRUE;
13632           ext = FALSE;
13633         }
13634
13635       resolve_symbol_value (fragp->fr_symbol);
13636       val = S_GET_VALUE (fragp->fr_symbol);
13637       if (op->pcrel)
13638         {
13639           addressT addr;
13640
13641           addr = fragp->fr_address + fragp->fr_fix;
13642
13643           /* The rules for the base address of a PC relative reloc are
13644              complicated; see mips16_extended_frag.  */
13645           if (type == 'p' || type == 'q')
13646             {
13647               addr += 2;
13648               if (ext)
13649                 addr += 2;
13650               /* Ignore the low bit in the target, since it will be
13651                  set for a text label.  */
13652               if ((val & 1) != 0)
13653                 --val;
13654             }
13655           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
13656             addr -= 4;
13657           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
13658             addr -= 2;
13659
13660           addr &= ~ (addressT) ((1 << op->shift) - 1);
13661           val -= addr;
13662
13663           /* Make sure the section winds up with the alignment we have
13664              assumed.  */
13665           if (op->shift > 0)
13666             record_alignment (asec, op->shift);
13667         }
13668
13669       if (ext
13670           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
13671               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
13672         as_warn_where (fragp->fr_file, fragp->fr_line,
13673                        _("extended instruction in delay slot"));
13674
13675       buf = (bfd_byte *) (fragp->fr_literal + fragp->fr_fix);
13676
13677       if (target_big_endian)
13678         insn = bfd_getb16 (buf);
13679       else
13680         insn = bfd_getl16 (buf);
13681
13682       mips16_immed (fragp->fr_file, fragp->fr_line, type, val,
13683                     RELAX_MIPS16_USER_EXT (fragp->fr_subtype),
13684                     small, ext, &insn, &use_extend, &extend);
13685
13686       if (use_extend)
13687         {
13688           md_number_to_chars ((char *) buf, 0xf000 | extend, 2);
13689           fragp->fr_fix += 2;
13690           buf += 2;
13691         }
13692
13693       md_number_to_chars ((char *) buf, insn, 2);
13694       fragp->fr_fix += 2;
13695       buf += 2;
13696     }
13697   else
13698     {
13699       int first, second;
13700       fixS *fixp;
13701
13702       first = RELAX_FIRST (fragp->fr_subtype);
13703       second = RELAX_SECOND (fragp->fr_subtype);
13704       fixp = (fixS *) fragp->fr_opcode;
13705
13706       /* Possibly emit a warning if we've chosen the longer option.  */
13707       if (((fragp->fr_subtype & RELAX_USE_SECOND) != 0)
13708           == ((fragp->fr_subtype & RELAX_SECOND_LONGER) != 0))
13709         {
13710           const char *msg = macro_warning (fragp->fr_subtype);
13711           if (msg != 0)
13712             as_warn_where (fragp->fr_file, fragp->fr_line, msg);
13713         }
13714
13715       /* Go through all the fixups for the first sequence.  Disable them
13716          (by marking them as done) if we're going to use the second
13717          sequence instead.  */
13718       while (fixp
13719              && fixp->fx_frag == fragp
13720              && fixp->fx_where < fragp->fr_fix - second)
13721         {
13722           if (fragp->fr_subtype & RELAX_USE_SECOND)
13723             fixp->fx_done = 1;
13724           fixp = fixp->fx_next;
13725         }
13726
13727       /* Go through the fixups for the second sequence.  Disable them if
13728          we're going to use the first sequence, otherwise adjust their
13729          addresses to account for the relaxation.  */
13730       while (fixp && fixp->fx_frag == fragp)
13731         {
13732           if (fragp->fr_subtype & RELAX_USE_SECOND)
13733             fixp->fx_where -= first;
13734           else
13735             fixp->fx_done = 1;
13736           fixp = fixp->fx_next;
13737         }
13738
13739       /* Now modify the frag contents.  */
13740       if (fragp->fr_subtype & RELAX_USE_SECOND)
13741         {
13742           char *start;
13743
13744           start = fragp->fr_literal + fragp->fr_fix - first - second;
13745           memmove (start, start + first, second);
13746           fragp->fr_fix -= first;
13747         }
13748       else
13749         fragp->fr_fix -= second;
13750     }
13751 }
13752
13753 #ifdef OBJ_ELF
13754
13755 /* This function is called after the relocs have been generated.
13756    We've been storing mips16 text labels as odd.  Here we convert them
13757    back to even for the convenience of the debugger.  */
13758
13759 void
13760 mips_frob_file_after_relocs (void)
13761 {
13762   asymbol **syms;
13763   unsigned int count, i;
13764
13765   if (OUTPUT_FLAVOR != bfd_target_elf_flavour)
13766     return;
13767
13768   syms = bfd_get_outsymbols (stdoutput);
13769   count = bfd_get_symcount (stdoutput);
13770   for (i = 0; i < count; i++, syms++)
13771     {
13772       if (elf_symbol (*syms)->internal_elf_sym.st_other == STO_MIPS16
13773           && ((*syms)->value & 1) != 0)
13774         {
13775           (*syms)->value &= ~1;
13776           /* If the symbol has an odd size, it was probably computed
13777              incorrectly, so adjust that as well.  */
13778           if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
13779             ++elf_symbol (*syms)->internal_elf_sym.st_size;
13780         }
13781     }
13782 }
13783
13784 #endif
13785
13786 /* This function is called whenever a label is defined.  It is used
13787    when handling branch delays; if a branch has a label, we assume we
13788    can not move it.  */
13789
13790 void
13791 mips_define_label (symbolS *sym)
13792 {
13793   struct insn_label_list *l;
13794
13795   if (free_insn_labels == NULL)
13796     l = (struct insn_label_list *) xmalloc (sizeof *l);
13797   else
13798     {
13799       l = free_insn_labels;
13800       free_insn_labels = l->next;
13801     }
13802
13803   l->label = sym;
13804   l->next = insn_labels;
13805   insn_labels = l;
13806
13807 #ifdef OBJ_ELF
13808   dwarf2_emit_label (sym);
13809 #endif
13810 }
13811 \f
13812 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
13813
13814 /* Some special processing for a MIPS ELF file.  */
13815
13816 void
13817 mips_elf_final_processing (void)
13818 {
13819   /* Write out the register information.  */
13820   if (mips_abi != N64_ABI)
13821     {
13822       Elf32_RegInfo s;
13823
13824       s.ri_gprmask = mips_gprmask;
13825       s.ri_cprmask[0] = mips_cprmask[0];
13826       s.ri_cprmask[1] = mips_cprmask[1];
13827       s.ri_cprmask[2] = mips_cprmask[2];
13828       s.ri_cprmask[3] = mips_cprmask[3];
13829       /* The gp_value field is set by the MIPS ELF backend.  */
13830
13831       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
13832                                        ((Elf32_External_RegInfo *)
13833                                         mips_regmask_frag));
13834     }
13835   else
13836     {
13837       Elf64_Internal_RegInfo s;
13838
13839       s.ri_gprmask = mips_gprmask;
13840       s.ri_pad = 0;
13841       s.ri_cprmask[0] = mips_cprmask[0];
13842       s.ri_cprmask[1] = mips_cprmask[1];
13843       s.ri_cprmask[2] = mips_cprmask[2];
13844       s.ri_cprmask[3] = mips_cprmask[3];
13845       /* The gp_value field is set by the MIPS ELF backend.  */
13846
13847       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
13848                                        ((Elf64_External_RegInfo *)
13849                                         mips_regmask_frag));
13850     }
13851
13852   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
13853      sort of BFD interface for this.  */
13854   if (mips_any_noreorder)
13855     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
13856   if (mips_pic != NO_PIC)
13857     {
13858     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
13859       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
13860     }
13861   if (mips_abicalls)
13862     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
13863
13864   /* Set MIPS ELF flags for ASEs.  */
13865   /* We may need to define a new flag for DSP ASE, and set this flag when
13866      file_ase_dsp is true.  */
13867   /* We may need to define a new flag for MT ASE, and set this flag when
13868      file_ase_mt is true.  */
13869   if (file_ase_mips16)
13870     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
13871 #if 0 /* XXX FIXME */
13872   if (file_ase_mips3d)
13873     elf_elfheader (stdoutput)->e_flags |= ???;
13874 #endif
13875   if (file_ase_mdmx)
13876     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
13877
13878   /* Set the MIPS ELF ABI flags.  */
13879   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
13880     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
13881   else if (mips_abi == O64_ABI)
13882     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
13883   else if (mips_abi == EABI_ABI)
13884     {
13885       if (!file_mips_gp32)
13886         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
13887       else
13888         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
13889     }
13890   else if (mips_abi == N32_ABI)
13891     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
13892
13893   /* Nothing to do for N64_ABI.  */
13894
13895   if (mips_32bitmode)
13896     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
13897 }
13898
13899 #endif /* OBJ_ELF || OBJ_MAYBE_ELF */
13900 \f
13901 typedef struct proc {
13902   symbolS *func_sym;
13903   symbolS *func_end_sym;
13904   unsigned long reg_mask;
13905   unsigned long reg_offset;
13906   unsigned long fpreg_mask;
13907   unsigned long fpreg_offset;
13908   unsigned long frame_offset;
13909   unsigned long frame_reg;
13910   unsigned long pc_reg;
13911 } procS;
13912
13913 static procS cur_proc;
13914 static procS *cur_proc_ptr;
13915 static int numprocs;
13916
13917 /* Fill in an rs_align_code fragment.  */
13918
13919 void
13920 mips_handle_align (fragS *fragp)
13921 {
13922   if (fragp->fr_type != rs_align_code)
13923     return;
13924
13925   if (mips_opts.mips16)
13926     {
13927       static const unsigned char be_nop[] = { 0x65, 0x00 };
13928       static const unsigned char le_nop[] = { 0x00, 0x65 };
13929
13930       int bytes;
13931       char *p;
13932
13933       bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
13934       p = fragp->fr_literal + fragp->fr_fix;
13935
13936       if (bytes & 1)
13937         {
13938           *p++ = 0;
13939           fragp->fr_fix++;
13940         }
13941
13942       memcpy (p, (target_big_endian ? be_nop : le_nop), 2);
13943       fragp->fr_var = 2;
13944     }
13945
13946   /* For mips32, a nop is a zero, which we trivially get by doing nothing.  */
13947 }
13948
13949 static void
13950 md_obj_begin (void)
13951 {
13952 }
13953
13954 static void
13955 md_obj_end (void)
13956 {
13957   /* check for premature end, nesting errors, etc */
13958   if (cur_proc_ptr)
13959     as_warn (_("missing .end at end of assembly"));
13960 }
13961
13962 static long
13963 get_number (void)
13964 {
13965   int negative = 0;
13966   long val = 0;
13967
13968   if (*input_line_pointer == '-')
13969     {
13970       ++input_line_pointer;
13971       negative = 1;
13972     }
13973   if (!ISDIGIT (*input_line_pointer))
13974     as_bad (_("expected simple number"));
13975   if (input_line_pointer[0] == '0')
13976     {
13977       if (input_line_pointer[1] == 'x')
13978         {
13979           input_line_pointer += 2;
13980           while (ISXDIGIT (*input_line_pointer))
13981             {
13982               val <<= 4;
13983               val |= hex_value (*input_line_pointer++);
13984             }
13985           return negative ? -val : val;
13986         }
13987       else
13988         {
13989           ++input_line_pointer;
13990           while (ISDIGIT (*input_line_pointer))
13991             {
13992               val <<= 3;
13993               val |= *input_line_pointer++ - '0';
13994             }
13995           return negative ? -val : val;
13996         }
13997     }
13998   if (!ISDIGIT (*input_line_pointer))
13999     {
14000       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
14001               *input_line_pointer, *input_line_pointer);
14002       as_warn (_("invalid number"));
14003       return -1;
14004     }
14005   while (ISDIGIT (*input_line_pointer))
14006     {
14007       val *= 10;
14008       val += *input_line_pointer++ - '0';
14009     }
14010   return negative ? -val : val;
14011 }
14012
14013 /* The .file directive; just like the usual .file directive, but there
14014    is an initial number which is the ECOFF file index.  In the non-ECOFF
14015    case .file implies DWARF-2.  */
14016
14017 static void
14018 s_mips_file (int x ATTRIBUTE_UNUSED)
14019 {
14020   static int first_file_directive = 0;
14021
14022   if (ECOFF_DEBUGGING)
14023     {
14024       get_number ();
14025       s_app_file (0);
14026     }
14027   else
14028     {
14029       char *filename;
14030
14031       filename = dwarf2_directive_file (0);
14032
14033       /* Versions of GCC up to 3.1 start files with a ".file"
14034          directive even for stabs output.  Make sure that this
14035          ".file" is handled.  Note that you need a version of GCC
14036          after 3.1 in order to support DWARF-2 on MIPS.  */
14037       if (filename != NULL && ! first_file_directive)
14038         {
14039           (void) new_logical_line (filename, -1);
14040           s_app_file_string (filename, 0);
14041         }
14042       first_file_directive = 1;
14043     }
14044 }
14045
14046 /* The .loc directive, implying DWARF-2.  */
14047
14048 static void
14049 s_mips_loc (int x ATTRIBUTE_UNUSED)
14050 {
14051   if (!ECOFF_DEBUGGING)
14052     dwarf2_directive_loc (0);
14053 }
14054
14055 /* The .end directive.  */
14056
14057 static void
14058 s_mips_end (int x ATTRIBUTE_UNUSED)
14059 {
14060   symbolS *p;
14061
14062   /* Following functions need their own .frame and .cprestore directives.  */
14063   mips_frame_reg_valid = 0;
14064   mips_cprestore_valid = 0;
14065
14066   if (!is_end_of_line[(unsigned char) *input_line_pointer])
14067     {
14068       p = get_symbol ();
14069       demand_empty_rest_of_line ();
14070     }
14071   else
14072     p = NULL;
14073
14074   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
14075     as_warn (_(".end not in text section"));
14076
14077   if (!cur_proc_ptr)
14078     {
14079       as_warn (_(".end directive without a preceding .ent directive."));
14080       demand_empty_rest_of_line ();
14081       return;
14082     }
14083
14084   if (p != NULL)
14085     {
14086       assert (S_GET_NAME (p));
14087       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
14088         as_warn (_(".end symbol does not match .ent symbol."));
14089
14090       if (debug_type == DEBUG_STABS)
14091         stabs_generate_asm_endfunc (S_GET_NAME (p),
14092                                     S_GET_NAME (p));
14093     }
14094   else
14095     as_warn (_(".end directive missing or unknown symbol"));
14096
14097 #ifdef OBJ_ELF
14098   /* Create an expression to calculate the size of the function.  */
14099   if (p && cur_proc_ptr)
14100     {
14101       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
14102       expressionS *exp = xmalloc (sizeof (expressionS));
14103
14104       obj->size = exp;
14105       exp->X_op = O_subtract;
14106       exp->X_add_symbol = symbol_temp_new_now ();
14107       exp->X_op_symbol = p;
14108       exp->X_add_number = 0;
14109
14110       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
14111     }
14112
14113   /* Generate a .pdr section.  */
14114   if (OUTPUT_FLAVOR == bfd_target_elf_flavour && ! ECOFF_DEBUGGING
14115       && mips_flag_pdr)
14116     {
14117       segT saved_seg = now_seg;
14118       subsegT saved_subseg = now_subseg;
14119       valueT dot;
14120       expressionS exp;
14121       char *fragp;
14122
14123       dot = frag_now_fix ();
14124
14125 #ifdef md_flush_pending_output
14126       md_flush_pending_output ();
14127 #endif
14128
14129       assert (pdr_seg);
14130       subseg_set (pdr_seg, 0);
14131
14132       /* Write the symbol.  */
14133       exp.X_op = O_symbol;
14134       exp.X_add_symbol = p;
14135       exp.X_add_number = 0;
14136       emit_expr (&exp, 4);
14137
14138       fragp = frag_more (7 * 4);
14139
14140       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
14141       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
14142       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
14143       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
14144       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
14145       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
14146       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
14147
14148       subseg_set (saved_seg, saved_subseg);
14149     }
14150 #endif /* OBJ_ELF */
14151
14152   cur_proc_ptr = NULL;
14153 }
14154
14155 /* The .aent and .ent directives.  */
14156
14157 static void
14158 s_mips_ent (int aent)
14159 {
14160   symbolS *symbolP;
14161
14162   symbolP = get_symbol ();
14163   if (*input_line_pointer == ',')
14164     ++input_line_pointer;
14165   SKIP_WHITESPACE ();
14166   if (ISDIGIT (*input_line_pointer)
14167       || *input_line_pointer == '-')
14168     get_number ();
14169
14170   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
14171     as_warn (_(".ent or .aent not in text section."));
14172
14173   if (!aent && cur_proc_ptr)
14174     as_warn (_("missing .end"));
14175
14176   if (!aent)
14177     {
14178       /* This function needs its own .frame and .cprestore directives.  */
14179       mips_frame_reg_valid = 0;
14180       mips_cprestore_valid = 0;
14181
14182       cur_proc_ptr = &cur_proc;
14183       memset (cur_proc_ptr, '\0', sizeof (procS));
14184
14185       cur_proc_ptr->func_sym = symbolP;
14186
14187       symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
14188
14189       ++numprocs;
14190
14191       if (debug_type == DEBUG_STABS)
14192         stabs_generate_asm_func (S_GET_NAME (symbolP),
14193                                  S_GET_NAME (symbolP));
14194     }
14195
14196   demand_empty_rest_of_line ();
14197 }
14198
14199 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
14200    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
14201    s_mips_frame is used so that we can set the PDR information correctly.
14202    We can't use the ecoff routines because they make reference to the ecoff
14203    symbol table (in the mdebug section).  */
14204
14205 static void
14206 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
14207 {
14208 #ifdef OBJ_ELF
14209   if (OUTPUT_FLAVOR == bfd_target_elf_flavour && ! ECOFF_DEBUGGING)
14210     {
14211       long val;
14212
14213       if (cur_proc_ptr == (procS *) NULL)
14214         {
14215           as_warn (_(".frame outside of .ent"));
14216           demand_empty_rest_of_line ();
14217           return;
14218         }
14219
14220       cur_proc_ptr->frame_reg = tc_get_register (1);
14221
14222       SKIP_WHITESPACE ();
14223       if (*input_line_pointer++ != ','
14224           || get_absolute_expression_and_terminator (&val) != ',')
14225         {
14226           as_warn (_("Bad .frame directive"));
14227           --input_line_pointer;
14228           demand_empty_rest_of_line ();
14229           return;
14230         }
14231
14232       cur_proc_ptr->frame_offset = val;
14233       cur_proc_ptr->pc_reg = tc_get_register (0);
14234
14235       demand_empty_rest_of_line ();
14236     }
14237   else
14238 #endif /* OBJ_ELF */
14239     s_ignore (ignore);
14240 }
14241
14242 /* The .fmask and .mask directives. If the mdebug section is present
14243    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
14244    embedded targets, s_mips_mask is used so that we can set the PDR
14245    information correctly. We can't use the ecoff routines because they
14246    make reference to the ecoff symbol table (in the mdebug section).  */
14247
14248 static void
14249 s_mips_mask (int reg_type)
14250 {
14251 #ifdef OBJ_ELF
14252   if (OUTPUT_FLAVOR == bfd_target_elf_flavour && ! ECOFF_DEBUGGING)
14253     {
14254       long mask, off;
14255
14256       if (cur_proc_ptr == (procS *) NULL)
14257         {
14258           as_warn (_(".mask/.fmask outside of .ent"));
14259           demand_empty_rest_of_line ();
14260           return;
14261         }
14262
14263       if (get_absolute_expression_and_terminator (&mask) != ',')
14264         {
14265           as_warn (_("Bad .mask/.fmask directive"));
14266           --input_line_pointer;
14267           demand_empty_rest_of_line ();
14268           return;
14269         }
14270
14271       off = get_absolute_expression ();
14272
14273       if (reg_type == 'F')
14274         {
14275           cur_proc_ptr->fpreg_mask = mask;
14276           cur_proc_ptr->fpreg_offset = off;
14277         }
14278       else
14279         {
14280           cur_proc_ptr->reg_mask = mask;
14281           cur_proc_ptr->reg_offset = off;
14282         }
14283
14284       demand_empty_rest_of_line ();
14285     }
14286   else
14287 #endif /* OBJ_ELF */
14288     s_ignore (reg_type);
14289 }
14290
14291 /* A table describing all the processors gas knows about.  Names are
14292    matched in the order listed.
14293
14294    To ease comparison, please keep this table in the same order as
14295    gcc's mips_cpu_info_table[].  */
14296 static const struct mips_cpu_info mips_cpu_info_table[] =
14297 {
14298   /* Entries for generic ISAs */
14299   { "mips1",          1,      ISA_MIPS1,      CPU_R3000 },
14300   { "mips2",          1,      ISA_MIPS2,      CPU_R6000 },
14301   { "mips3",          1,      ISA_MIPS3,      CPU_R4000 },
14302   { "mips4",          1,      ISA_MIPS4,      CPU_R8000 },
14303   { "mips5",          1,      ISA_MIPS5,      CPU_MIPS5 },
14304   { "mips32",         1,      ISA_MIPS32,     CPU_MIPS32 },
14305   { "mips32r2",       1,      ISA_MIPS32R2,   CPU_MIPS32R2 },
14306   { "mips64",         1,      ISA_MIPS64,     CPU_MIPS64 },
14307   { "mips64r2",       1,      ISA_MIPS64R2,   CPU_MIPS64R2 },
14308
14309   /* MIPS I */
14310   { "r3000",          0,      ISA_MIPS1,      CPU_R3000 },
14311   { "r2000",          0,      ISA_MIPS1,      CPU_R3000 },
14312   { "r3900",          0,      ISA_MIPS1,      CPU_R3900 },
14313
14314   /* MIPS II */
14315   { "r6000",          0,      ISA_MIPS2,      CPU_R6000 },
14316
14317   /* MIPS III */
14318   { "r4000",          0,      ISA_MIPS3,      CPU_R4000 },
14319   { "r4010",          0,      ISA_MIPS2,      CPU_R4010 },
14320   { "vr4100",         0,      ISA_MIPS3,      CPU_VR4100 },
14321   { "vr4111",         0,      ISA_MIPS3,      CPU_R4111 },
14322   { "vr4120",         0,      ISA_MIPS3,      CPU_VR4120 },
14323   { "vr4130",         0,      ISA_MIPS3,      CPU_VR4120 },
14324   { "vr4181",         0,      ISA_MIPS3,      CPU_R4111 },
14325   { "vr4300",         0,      ISA_MIPS3,      CPU_R4300 },
14326   { "r4400",          0,      ISA_MIPS3,      CPU_R4400 },
14327   { "r4600",          0,      ISA_MIPS3,      CPU_R4600 },
14328   { "orion",          0,      ISA_MIPS3,      CPU_R4600 },
14329   { "r4650",          0,      ISA_MIPS3,      CPU_R4650 },
14330
14331   /* MIPS IV */
14332   { "r8000",          0,      ISA_MIPS4,      CPU_R8000 },
14333   { "r10000",         0,      ISA_MIPS4,      CPU_R10000 },
14334   { "r12000",         0,      ISA_MIPS4,      CPU_R12000 },
14335   { "vr5000",         0,      ISA_MIPS4,      CPU_R5000 },
14336   { "vr5400",         0,      ISA_MIPS4,      CPU_VR5400 },
14337   { "vr5500",         0,      ISA_MIPS4,      CPU_VR5500 },
14338   { "rm5200",         0,      ISA_MIPS4,      CPU_R5000 },
14339   { "rm5230",         0,      ISA_MIPS4,      CPU_R5000 },
14340   { "rm5231",         0,      ISA_MIPS4,      CPU_R5000 },
14341   { "rm5261",         0,      ISA_MIPS4,      CPU_R5000 },
14342   { "rm5721",         0,      ISA_MIPS4,      CPU_R5000 },
14343   { "rm7000",         0,      ISA_MIPS4,      CPU_RM7000 },
14344   { "rm9000",         0,      ISA_MIPS4,      CPU_RM9000 },
14345
14346   /* MIPS 32 */
14347   { "4kc",            0,      ISA_MIPS32,     CPU_MIPS32 },
14348   { "4km",            0,      ISA_MIPS32,     CPU_MIPS32 },
14349   { "4kp",            0,      ISA_MIPS32,     CPU_MIPS32 },
14350
14351   /* MIPS32 Release 2 */
14352   { "m4k",            0,      ISA_MIPS32R2,   CPU_MIPS32R2 },
14353   { "24k",            0,      ISA_MIPS32R2,   CPU_MIPS32R2 },
14354   { "24kc",           0,      ISA_MIPS32R2,   CPU_MIPS32R2 },
14355   { "24kf",           0,      ISA_MIPS32R2,   CPU_MIPS32R2 },
14356   { "24kx",           0,      ISA_MIPS32R2,   CPU_MIPS32R2 },
14357
14358   /* MIPS 64 */
14359   { "5kc",            0,      ISA_MIPS64,     CPU_MIPS64 },
14360   { "5kf",            0,      ISA_MIPS64,     CPU_MIPS64 },
14361   { "20kc",           0,      ISA_MIPS64,     CPU_MIPS64 },
14362
14363   /* Broadcom SB-1 CPU core */
14364   { "sb1",            0,      ISA_MIPS64,     CPU_SB1 },
14365
14366   /* End marker */
14367   { NULL, 0, 0, 0 }
14368 };
14369
14370
14371 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
14372    with a final "000" replaced by "k".  Ignore case.
14373
14374    Note: this function is shared between GCC and GAS.  */
14375
14376 static bfd_boolean
14377 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
14378 {
14379   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
14380     given++, canonical++;
14381
14382   return ((*given == 0 && *canonical == 0)
14383           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
14384 }
14385
14386
14387 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
14388    CPU name.  We've traditionally allowed a lot of variation here.
14389
14390    Note: this function is shared between GCC and GAS.  */
14391
14392 static bfd_boolean
14393 mips_matching_cpu_name_p (const char *canonical, const char *given)
14394 {
14395   /* First see if the name matches exactly, or with a final "000"
14396      turned into "k".  */
14397   if (mips_strict_matching_cpu_name_p (canonical, given))
14398     return TRUE;
14399
14400   /* If not, try comparing based on numerical designation alone.
14401      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
14402   if (TOLOWER (*given) == 'r')
14403     given++;
14404   if (!ISDIGIT (*given))
14405     return FALSE;
14406
14407   /* Skip over some well-known prefixes in the canonical name,
14408      hoping to find a number there too.  */
14409   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
14410     canonical += 2;
14411   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
14412     canonical += 2;
14413   else if (TOLOWER (canonical[0]) == 'r')
14414     canonical += 1;
14415
14416   return mips_strict_matching_cpu_name_p (canonical, given);
14417 }
14418
14419
14420 /* Parse an option that takes the name of a processor as its argument.
14421    OPTION is the name of the option and CPU_STRING is the argument.
14422    Return the corresponding processor enumeration if the CPU_STRING is
14423    recognized, otherwise report an error and return null.
14424
14425    A similar function exists in GCC.  */
14426
14427 static const struct mips_cpu_info *
14428 mips_parse_cpu (const char *option, const char *cpu_string)
14429 {
14430   const struct mips_cpu_info *p;
14431
14432   /* 'from-abi' selects the most compatible architecture for the given
14433      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
14434      EABIs, we have to decide whether we're using the 32-bit or 64-bit
14435      version.  Look first at the -mgp options, if given, otherwise base
14436      the choice on MIPS_DEFAULT_64BIT.
14437
14438      Treat NO_ABI like the EABIs.  One reason to do this is that the
14439      plain 'mips' and 'mips64' configs have 'from-abi' as their default
14440      architecture.  This code picks MIPS I for 'mips' and MIPS III for
14441      'mips64', just as we did in the days before 'from-abi'.  */
14442   if (strcasecmp (cpu_string, "from-abi") == 0)
14443     {
14444       if (ABI_NEEDS_32BIT_REGS (mips_abi))
14445         return mips_cpu_info_from_isa (ISA_MIPS1);
14446
14447       if (ABI_NEEDS_64BIT_REGS (mips_abi))
14448         return mips_cpu_info_from_isa (ISA_MIPS3);
14449
14450       if (file_mips_gp32 >= 0)
14451         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
14452
14453       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
14454                                      ? ISA_MIPS3
14455                                      : ISA_MIPS1);
14456     }
14457
14458   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
14459   if (strcasecmp (cpu_string, "default") == 0)
14460     return 0;
14461
14462   for (p = mips_cpu_info_table; p->name != 0; p++)
14463     if (mips_matching_cpu_name_p (p->name, cpu_string))
14464       return p;
14465
14466   as_bad ("Bad value (%s) for %s", cpu_string, option);
14467   return 0;
14468 }
14469
14470 /* Return the canonical processor information for ISA (a member of the
14471    ISA_MIPS* enumeration).  */
14472
14473 static const struct mips_cpu_info *
14474 mips_cpu_info_from_isa (int isa)
14475 {
14476   int i;
14477
14478   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
14479     if (mips_cpu_info_table[i].is_isa
14480         && isa == mips_cpu_info_table[i].isa)
14481       return (&mips_cpu_info_table[i]);
14482
14483   return NULL;
14484 }
14485
14486 static const struct mips_cpu_info *
14487 mips_cpu_info_from_arch (int arch)
14488 {
14489   int i;
14490
14491   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
14492     if (arch == mips_cpu_info_table[i].cpu)
14493       return (&mips_cpu_info_table[i]);
14494
14495   return NULL;
14496 }
14497 \f
14498 static void
14499 show (FILE *stream, const char *string, int *col_p, int *first_p)
14500 {
14501   if (*first_p)
14502     {
14503       fprintf (stream, "%24s", "");
14504       *col_p = 24;
14505     }
14506   else
14507     {
14508       fprintf (stream, ", ");
14509       *col_p += 2;
14510     }
14511
14512   if (*col_p + strlen (string) > 72)
14513     {
14514       fprintf (stream, "\n%24s", "");
14515       *col_p = 24;
14516     }
14517
14518   fprintf (stream, "%s", string);
14519   *col_p += strlen (string);
14520
14521   *first_p = 0;
14522 }
14523
14524 void
14525 md_show_usage (FILE *stream)
14526 {
14527   int column, first;
14528   size_t i;
14529
14530   fprintf (stream, _("\
14531 MIPS options:\n\
14532 -EB                     generate big endian output\n\
14533 -EL                     generate little endian output\n\
14534 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
14535 -G NUM                  allow referencing objects up to NUM bytes\n\
14536                         implicitly with the gp register [default 8]\n"));
14537   fprintf (stream, _("\
14538 -mips1                  generate MIPS ISA I instructions\n\
14539 -mips2                  generate MIPS ISA II instructions\n\
14540 -mips3                  generate MIPS ISA III instructions\n\
14541 -mips4                  generate MIPS ISA IV instructions\n\
14542 -mips5                  generate MIPS ISA V instructions\n\
14543 -mips32                 generate MIPS32 ISA instructions\n\
14544 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
14545 -mips64                 generate MIPS64 ISA instructions\n\
14546 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
14547 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
14548
14549   first = 1;
14550
14551   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
14552     show (stream, mips_cpu_info_table[i].name, &column, &first);
14553   show (stream, "from-abi", &column, &first);
14554   fputc ('\n', stream);
14555
14556   fprintf (stream, _("\
14557 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
14558 -no-mCPU                don't generate code specific to CPU.\n\
14559                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
14560
14561   first = 1;
14562
14563   show (stream, "3900", &column, &first);
14564   show (stream, "4010", &column, &first);
14565   show (stream, "4100", &column, &first);
14566   show (stream, "4650", &column, &first);
14567   fputc ('\n', stream);
14568
14569   fprintf (stream, _("\
14570 -mips16                 generate mips16 instructions\n\
14571 -no-mips16              do not generate mips16 instructions\n"));
14572   fprintf (stream, _("\
14573 -mdsp                   generate DSP instructions\n\
14574 -mno-dsp                do not generate DSP instructions\n"));
14575   fprintf (stream, _("\
14576 -mmt                    generate MT instructions\n\
14577 -mno-mt                 do not generate MT instructions\n"));
14578   fprintf (stream, _("\
14579 -mfix-vr4120            work around certain VR4120 errata\n\
14580 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
14581 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
14582 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
14583 -mno-shared             optimize output for executables\n\
14584 -msym32                 assume all symbols have 32-bit values\n\
14585 -O0                     remove unneeded NOPs, do not swap branches\n\
14586 -O                      remove unneeded NOPs and swap branches\n\
14587 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
14588 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
14589 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
14590 #ifdef OBJ_ELF
14591   fprintf (stream, _("\
14592 -KPIC, -call_shared     generate SVR4 position independent code\n\
14593 -non_shared             do not generate position independent code\n\
14594 -xgot                   assume a 32 bit GOT\n\
14595 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
14596 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
14597                         non-shared code\n\
14598 -mabi=ABI               create ABI conformant object file for:\n"));
14599
14600   first = 1;
14601
14602   show (stream, "32", &column, &first);
14603   show (stream, "o64", &column, &first);
14604   show (stream, "n32", &column, &first);
14605   show (stream, "64", &column, &first);
14606   show (stream, "eabi", &column, &first);
14607
14608   fputc ('\n', stream);
14609
14610   fprintf (stream, _("\
14611 -32                     create o32 ABI object file (default)\n\
14612 -n32                    create n32 ABI object file\n\
14613 -64                     create 64 ABI object file\n"));
14614 #endif
14615 }
14616
14617 enum dwarf2_format
14618 mips_dwarf2_format (void)
14619 {
14620   if (mips_abi == N64_ABI)
14621     {
14622 #ifdef TE_IRIX
14623       return dwarf2_format_64bit_irix;
14624 #else
14625       return dwarf2_format_64bit;
14626 #endif
14627     }
14628   else
14629     return dwarf2_format_32bit;
14630 }
14631
14632 int
14633 mips_dwarf2_addr_size (void)
14634 {
14635   if (mips_abi == N64_ABI)
14636     return 8;
14637   else
14638     return 4;
14639 }
14640
14641 /* Standard calling conventions leave the CFA at SP on entry.  */
14642 void
14643 mips_cfi_frame_initial_instructions (void)
14644 {
14645   cfi_add_CFA_def_cfa_register (SP);
14646 }
14647