* mips.h: Assign 'm'/'M' codes to MIPS16e save/restore
[platform/upstream/binutils.git] / gas / config / tc-mips.c
1 /* tc-mips.c -- assemble code for a MIPS chip.
2    Copyright 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
3    2003, 2004, 2005 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 occured 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_TMIPS
1195       /* This is traditional mips.  */
1196       return (target_big_endian
1197               ? (HAVE_64BIT_OBJECTS
1198                  ? "elf64-tradbigmips"
1199                  : (HAVE_NEWABI
1200                     ? "elf32-ntradbigmips" : "elf32-tradbigmips"))
1201               : (HAVE_64BIT_OBJECTS
1202                  ? "elf64-tradlittlemips"
1203                  : (HAVE_NEWABI
1204                     ? "elf32-ntradlittlemips" : "elf32-tradlittlemips")));
1205 #else
1206       return (target_big_endian
1207               ? (HAVE_64BIT_OBJECTS
1208                  ? "elf64-bigmips"
1209                  : (HAVE_NEWABI
1210                     ? "elf32-nbigmips" : "elf32-bigmips"))
1211               : (HAVE_64BIT_OBJECTS
1212                  ? "elf64-littlemips"
1213                  : (HAVE_NEWABI
1214                     ? "elf32-nlittlemips" : "elf32-littlemips")));
1215 #endif
1216     default:
1217       abort ();
1218       return NULL;
1219     }
1220 }
1221
1222 /* Return the length of instruction INSN.  */
1223
1224 static inline unsigned int
1225 insn_length (const struct mips_cl_insn *insn)
1226 {
1227   if (!mips_opts.mips16)
1228     return 4;
1229   return insn->mips16_absolute_jump_p || insn->use_extend ? 4 : 2;
1230 }
1231
1232 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
1233
1234 static void
1235 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
1236 {
1237   size_t i;
1238
1239   insn->insn_mo = mo;
1240   insn->use_extend = FALSE;
1241   insn->extend = 0;
1242   insn->insn_opcode = mo->match;
1243   insn->frag = NULL;
1244   insn->where = 0;
1245   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
1246     insn->fixp[i] = NULL;
1247   insn->fixed_p = (mips_opts.noreorder > 0);
1248   insn->noreorder_p = (mips_opts.noreorder > 0);
1249   insn->mips16_absolute_jump_p = 0;
1250 }
1251
1252 /* Install INSN at the location specified by its "frag" and "where" fields.  */
1253
1254 static void
1255 install_insn (const struct mips_cl_insn *insn)
1256 {
1257   char *f = insn->frag->fr_literal + insn->where;
1258   if (!mips_opts.mips16)
1259     md_number_to_chars (f, insn->insn_opcode, 4);
1260   else if (insn->mips16_absolute_jump_p)
1261     {
1262       md_number_to_chars (f, insn->insn_opcode >> 16, 2);
1263       md_number_to_chars (f + 2, insn->insn_opcode & 0xffff, 2);
1264     }
1265   else
1266     {
1267       if (insn->use_extend)
1268         {
1269           md_number_to_chars (f, 0xf000 | insn->extend, 2);
1270           f += 2;
1271         }
1272       md_number_to_chars (f, insn->insn_opcode, 2);
1273     }
1274 }
1275
1276 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
1277    and install the opcode in the new location.  */
1278
1279 static void
1280 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
1281 {
1282   size_t i;
1283
1284   insn->frag = frag;
1285   insn->where = where;
1286   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
1287     if (insn->fixp[i] != NULL)
1288       {
1289         insn->fixp[i]->fx_frag = frag;
1290         insn->fixp[i]->fx_where = where;
1291       }
1292   install_insn (insn);
1293 }
1294
1295 /* Add INSN to the end of the output.  */
1296
1297 static void
1298 add_fixed_insn (struct mips_cl_insn *insn)
1299 {
1300   char *f = frag_more (insn_length (insn));
1301   move_insn (insn, frag_now, f - frag_now->fr_literal);
1302 }
1303
1304 /* Start a variant frag and move INSN to the start of the variant part,
1305    marking it as fixed.  The other arguments are as for frag_var.  */
1306
1307 static void
1308 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
1309                   relax_substateT subtype, symbolS *symbol, offsetT offset)
1310 {
1311   frag_grow (max_chars);
1312   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
1313   insn->fixed_p = 1;
1314   frag_var (rs_machine_dependent, max_chars, var,
1315             subtype, symbol, offset, NULL);
1316 }
1317
1318 /* Insert N copies of INSN into the history buffer, starting at
1319    position FIRST.  Neither FIRST nor N need to be clipped.  */
1320
1321 static void
1322 insert_into_history (unsigned int first, unsigned int n,
1323                      const struct mips_cl_insn *insn)
1324 {
1325   if (mips_relax.sequence != 2)
1326     {
1327       unsigned int i;
1328
1329       for (i = ARRAY_SIZE (history); i-- > first;)
1330         if (i >= first + n)
1331           history[i] = history[i - n];
1332         else
1333           history[i] = *insn;
1334     }
1335 }
1336
1337 /* Emit a nop instruction, recording it in the history buffer.  */
1338
1339 static void
1340 emit_nop (void)
1341 {
1342   add_fixed_insn (NOP_INSN);
1343   insert_into_history (0, 1, NOP_INSN);
1344 }
1345
1346 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
1347    the idea is to make it obvious at a glance that each errata is
1348    included.  */
1349
1350 static void
1351 init_vr4120_conflicts (void)
1352 {
1353 #define CONFLICT(FIRST, SECOND) \
1354     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
1355
1356   /* Errata 21 - [D]DIV[U] after [D]MACC */
1357   CONFLICT (MACC, DIV);
1358   CONFLICT (DMACC, DIV);
1359
1360   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
1361   CONFLICT (DMULT, DMULT);
1362   CONFLICT (DMULT, DMACC);
1363   CONFLICT (DMACC, DMULT);
1364   CONFLICT (DMACC, DMACC);
1365
1366   /* Errata 24 - MT{LO,HI} after [D]MACC */
1367   CONFLICT (MACC, MTHILO);
1368   CONFLICT (DMACC, MTHILO);
1369
1370   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
1371      instruction is executed immediately after a MACC or DMACC
1372      instruction, the result of [either instruction] is incorrect."  */
1373   CONFLICT (MACC, MULT);
1374   CONFLICT (MACC, DMULT);
1375   CONFLICT (DMACC, MULT);
1376   CONFLICT (DMACC, DMULT);
1377
1378   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
1379      executed immediately after a DMULT, DMULTU, DIV, DIVU,
1380      DDIV or DDIVU instruction, the result of the MACC or
1381      DMACC instruction is incorrect.".  */
1382   CONFLICT (DMULT, MACC);
1383   CONFLICT (DMULT, DMACC);
1384   CONFLICT (DIV, MACC);
1385   CONFLICT (DIV, DMACC);
1386
1387 #undef CONFLICT
1388 }
1389
1390 /* This function is called once, at assembler startup time.  It should
1391    set up all the tables, etc. that the MD part of the assembler will need.  */
1392
1393 void
1394 md_begin (void)
1395 {
1396   register const char *retval = NULL;
1397   int i = 0;
1398   int broken = 0;
1399
1400   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_arch))
1401     as_warn (_("Could not set architecture and machine"));
1402
1403   op_hash = hash_new ();
1404
1405   for (i = 0; i < NUMOPCODES;)
1406     {
1407       const char *name = mips_opcodes[i].name;
1408
1409       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
1410       if (retval != NULL)
1411         {
1412           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
1413                    mips_opcodes[i].name, retval);
1414           /* Probably a memory allocation problem?  Give up now.  */
1415           as_fatal (_("Broken assembler.  No assembly attempted."));
1416         }
1417       do
1418         {
1419           if (mips_opcodes[i].pinfo != INSN_MACRO)
1420             {
1421               if (!validate_mips_insn (&mips_opcodes[i]))
1422                 broken = 1;
1423               if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
1424                 {
1425                   create_insn (&nop_insn, mips_opcodes + i);
1426                   nop_insn.fixed_p = 1;
1427                 }
1428             }
1429           ++i;
1430         }
1431       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
1432     }
1433
1434   mips16_op_hash = hash_new ();
1435
1436   i = 0;
1437   while (i < bfd_mips16_num_opcodes)
1438     {
1439       const char *name = mips16_opcodes[i].name;
1440
1441       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
1442       if (retval != NULL)
1443         as_fatal (_("internal: can't hash `%s': %s"),
1444                   mips16_opcodes[i].name, retval);
1445       do
1446         {
1447           if (mips16_opcodes[i].pinfo != INSN_MACRO
1448               && ((mips16_opcodes[i].match & mips16_opcodes[i].mask)
1449                   != mips16_opcodes[i].match))
1450             {
1451               fprintf (stderr, _("internal error: bad mips16 opcode: %s %s\n"),
1452                        mips16_opcodes[i].name, mips16_opcodes[i].args);
1453               broken = 1;
1454             }
1455           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
1456             {
1457               create_insn (&mips16_nop_insn, mips16_opcodes + i);
1458               mips16_nop_insn.fixed_p = 1;
1459             }
1460           ++i;
1461         }
1462       while (i < bfd_mips16_num_opcodes
1463              && strcmp (mips16_opcodes[i].name, name) == 0);
1464     }
1465
1466   if (broken)
1467     as_fatal (_("Broken assembler.  No assembly attempted."));
1468
1469   /* We add all the general register names to the symbol table.  This
1470      helps us detect invalid uses of them.  */
1471   for (i = 0; i < 32; i++)
1472     {
1473       char buf[5];
1474
1475       sprintf (buf, "$%d", i);
1476       symbol_table_insert (symbol_new (buf, reg_section, i,
1477                                        &zero_address_frag));
1478     }
1479   symbol_table_insert (symbol_new ("$ra", reg_section, RA,
1480                                    &zero_address_frag));
1481   symbol_table_insert (symbol_new ("$fp", reg_section, FP,
1482                                    &zero_address_frag));
1483   symbol_table_insert (symbol_new ("$sp", reg_section, SP,
1484                                    &zero_address_frag));
1485   symbol_table_insert (symbol_new ("$gp", reg_section, GP,
1486                                    &zero_address_frag));
1487   symbol_table_insert (symbol_new ("$at", reg_section, AT,
1488                                    &zero_address_frag));
1489   symbol_table_insert (symbol_new ("$kt0", reg_section, KT0,
1490                                    &zero_address_frag));
1491   symbol_table_insert (symbol_new ("$kt1", reg_section, KT1,
1492                                    &zero_address_frag));
1493   symbol_table_insert (symbol_new ("$zero", reg_section, ZERO,
1494                                    &zero_address_frag));
1495   symbol_table_insert (symbol_new ("$pc", reg_section, -1,
1496                                    &zero_address_frag));
1497
1498   /* If we don't add these register names to the symbol table, they
1499      may end up being added as regular symbols by operand(), and then
1500      make it to the object file as undefined in case they're not
1501      regarded as local symbols.  They're local in o32, since `$' is a
1502      local symbol prefix, but not in n32 or n64.  */
1503   for (i = 0; i < 8; i++)
1504     {
1505       char buf[6];
1506
1507       sprintf (buf, "$fcc%i", i);
1508       symbol_table_insert (symbol_new (buf, reg_section, -1,
1509                                        &zero_address_frag));
1510     }
1511
1512   mips_no_prev_insn ();
1513
1514   mips_gprmask = 0;
1515   mips_cprmask[0] = 0;
1516   mips_cprmask[1] = 0;
1517   mips_cprmask[2] = 0;
1518   mips_cprmask[3] = 0;
1519
1520   /* set the default alignment for the text section (2**2) */
1521   record_alignment (text_section, 2);
1522
1523   bfd_set_gp_size (stdoutput, g_switch_value);
1524
1525   if (OUTPUT_FLAVOR == bfd_target_elf_flavour)
1526     {
1527       /* On a native system, sections must be aligned to 16 byte
1528          boundaries.  When configured for an embedded ELF target, we
1529          don't bother.  */
1530       if (strcmp (TARGET_OS, "elf") != 0)
1531         {
1532           (void) bfd_set_section_alignment (stdoutput, text_section, 4);
1533           (void) bfd_set_section_alignment (stdoutput, data_section, 4);
1534           (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
1535         }
1536
1537       /* Create a .reginfo section for register masks and a .mdebug
1538          section for debugging information.  */
1539       {
1540         segT seg;
1541         subsegT subseg;
1542         flagword flags;
1543         segT sec;
1544
1545         seg = now_seg;
1546         subseg = now_subseg;
1547
1548         /* The ABI says this section should be loaded so that the
1549            running program can access it.  However, we don't load it
1550            if we are configured for an embedded target */
1551         flags = SEC_READONLY | SEC_DATA;
1552         if (strcmp (TARGET_OS, "elf") != 0)
1553           flags |= SEC_ALLOC | SEC_LOAD;
1554
1555         if (mips_abi != N64_ABI)
1556           {
1557             sec = subseg_new (".reginfo", (subsegT) 0);
1558
1559             bfd_set_section_flags (stdoutput, sec, flags);
1560             bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
1561
1562 #ifdef OBJ_ELF
1563             mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
1564 #endif
1565           }
1566         else
1567           {
1568             /* The 64-bit ABI uses a .MIPS.options section rather than
1569                .reginfo section.  */
1570             sec = subseg_new (".MIPS.options", (subsegT) 0);
1571             bfd_set_section_flags (stdoutput, sec, flags);
1572             bfd_set_section_alignment (stdoutput, sec, 3);
1573
1574 #ifdef OBJ_ELF
1575             /* Set up the option header.  */
1576             {
1577               Elf_Internal_Options opthdr;
1578               char *f;
1579
1580               opthdr.kind = ODK_REGINFO;
1581               opthdr.size = (sizeof (Elf_External_Options)
1582                              + sizeof (Elf64_External_RegInfo));
1583               opthdr.section = 0;
1584               opthdr.info = 0;
1585               f = frag_more (sizeof (Elf_External_Options));
1586               bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
1587                                              (Elf_External_Options *) f);
1588
1589               mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
1590             }
1591 #endif
1592           }
1593
1594         if (ECOFF_DEBUGGING)
1595           {
1596             sec = subseg_new (".mdebug", (subsegT) 0);
1597             (void) bfd_set_section_flags (stdoutput, sec,
1598                                           SEC_HAS_CONTENTS | SEC_READONLY);
1599             (void) bfd_set_section_alignment (stdoutput, sec, 2);
1600           }
1601 #ifdef OBJ_ELF
1602         else if (OUTPUT_FLAVOR == bfd_target_elf_flavour && mips_flag_pdr)
1603           {
1604             pdr_seg = subseg_new (".pdr", (subsegT) 0);
1605             (void) bfd_set_section_flags (stdoutput, pdr_seg,
1606                                           SEC_READONLY | SEC_RELOC
1607                                           | SEC_DEBUGGING);
1608             (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
1609           }
1610 #endif
1611
1612         subseg_set (seg, subseg);
1613       }
1614     }
1615
1616   if (! ECOFF_DEBUGGING)
1617     md_obj_begin ();
1618
1619   if (mips_fix_vr4120)
1620     init_vr4120_conflicts ();
1621 }
1622
1623 void
1624 md_mips_end (void)
1625 {
1626   if (! ECOFF_DEBUGGING)
1627     md_obj_end ();
1628 }
1629
1630 void
1631 md_assemble (char *str)
1632 {
1633   struct mips_cl_insn insn;
1634   bfd_reloc_code_real_type unused_reloc[3]
1635     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1636
1637   imm_expr.X_op = O_absent;
1638   imm2_expr.X_op = O_absent;
1639   offset_expr.X_op = O_absent;
1640   imm_reloc[0] = BFD_RELOC_UNUSED;
1641   imm_reloc[1] = BFD_RELOC_UNUSED;
1642   imm_reloc[2] = BFD_RELOC_UNUSED;
1643   offset_reloc[0] = BFD_RELOC_UNUSED;
1644   offset_reloc[1] = BFD_RELOC_UNUSED;
1645   offset_reloc[2] = BFD_RELOC_UNUSED;
1646
1647   if (mips_opts.mips16)
1648     mips16_ip (str, &insn);
1649   else
1650     {
1651       mips_ip (str, &insn);
1652       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
1653             str, insn.insn_opcode));
1654     }
1655
1656   if (insn_error)
1657     {
1658       as_bad ("%s `%s'", insn_error, str);
1659       return;
1660     }
1661
1662   if (insn.insn_mo->pinfo == INSN_MACRO)
1663     {
1664       macro_start ();
1665       if (mips_opts.mips16)
1666         mips16_macro (&insn);
1667       else
1668         macro (&insn);
1669       macro_end ();
1670     }
1671   else
1672     {
1673       if (imm_expr.X_op != O_absent)
1674         append_insn (&insn, &imm_expr, imm_reloc);
1675       else if (offset_expr.X_op != O_absent)
1676         append_insn (&insn, &offset_expr, offset_reloc);
1677       else
1678         append_insn (&insn, NULL, unused_reloc);
1679     }
1680 }
1681
1682 /* Return true if the given relocation might need a matching %lo().
1683    Note that R_MIPS_GOT16 relocations only need a matching %lo() when
1684    applied to local symbols.  */
1685
1686 static inline bfd_boolean
1687 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
1688 {
1689   return (HAVE_IN_PLACE_ADDENDS
1690           && (reloc == BFD_RELOC_HI16_S
1691               || reloc == BFD_RELOC_MIPS_GOT16
1692               || reloc == BFD_RELOC_MIPS16_HI16_S));
1693 }
1694
1695 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
1696    relocation.  */
1697
1698 static inline bfd_boolean
1699 fixup_has_matching_lo_p (fixS *fixp)
1700 {
1701   return (fixp->fx_next != NULL
1702           && (fixp->fx_next->fx_r_type == BFD_RELOC_LO16
1703              || fixp->fx_next->fx_r_type == BFD_RELOC_MIPS16_LO16)
1704           && fixp->fx_addsy == fixp->fx_next->fx_addsy
1705           && fixp->fx_offset == fixp->fx_next->fx_offset);
1706 }
1707
1708 /* See whether instruction IP reads register REG.  CLASS is the type
1709    of register.  */
1710
1711 static int
1712 insn_uses_reg (const struct mips_cl_insn *ip, unsigned int reg,
1713                enum mips_regclass class)
1714 {
1715   if (class == MIPS16_REG)
1716     {
1717       assert (mips_opts.mips16);
1718       reg = mips16_to_32_reg_map[reg];
1719       class = MIPS_GR_REG;
1720     }
1721
1722   /* Don't report on general register ZERO, since it never changes.  */
1723   if (class == MIPS_GR_REG && reg == ZERO)
1724     return 0;
1725
1726   if (class == MIPS_FP_REG)
1727     {
1728       assert (! mips_opts.mips16);
1729       /* If we are called with either $f0 or $f1, we must check $f0.
1730          This is not optimal, because it will introduce an unnecessary
1731          NOP between "lwc1 $f0" and "swc1 $f1".  To fix this we would
1732          need to distinguish reading both $f0 and $f1 or just one of
1733          them.  Note that we don't have to check the other way,
1734          because there is no instruction that sets both $f0 and $f1
1735          and requires a delay.  */
1736       if ((ip->insn_mo->pinfo & INSN_READ_FPR_S)
1737           && ((EXTRACT_OPERAND (FS, *ip) & ~(unsigned) 1)
1738               == (reg &~ (unsigned) 1)))
1739         return 1;
1740       if ((ip->insn_mo->pinfo & INSN_READ_FPR_T)
1741           && ((EXTRACT_OPERAND (FT, *ip) & ~(unsigned) 1)
1742               == (reg &~ (unsigned) 1)))
1743         return 1;
1744     }
1745   else if (! mips_opts.mips16)
1746     {
1747       if ((ip->insn_mo->pinfo & INSN_READ_GPR_S)
1748           && EXTRACT_OPERAND (RS, *ip) == reg)
1749         return 1;
1750       if ((ip->insn_mo->pinfo & INSN_READ_GPR_T)
1751           && EXTRACT_OPERAND (RT, *ip) == reg)
1752         return 1;
1753     }
1754   else
1755     {
1756       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_X)
1757           && mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)] == reg)
1758         return 1;
1759       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_Y)
1760           && mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)] == reg)
1761         return 1;
1762       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_Z)
1763           && (mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (MOVE32Z, *ip)]
1764               == reg))
1765         return 1;
1766       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_T) && reg == TREG)
1767         return 1;
1768       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_SP) && reg == SP)
1769         return 1;
1770       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_31) && reg == RA)
1771         return 1;
1772       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_GPR_X)
1773           && MIPS16_EXTRACT_OPERAND (REGR32, *ip) == reg)
1774         return 1;
1775     }
1776
1777   return 0;
1778 }
1779
1780 /* This function returns true if modifying a register requires a
1781    delay.  */
1782
1783 static int
1784 reg_needs_delay (unsigned int reg)
1785 {
1786   unsigned long prev_pinfo;
1787
1788   prev_pinfo = history[0].insn_mo->pinfo;
1789   if (! mips_opts.noreorder
1790       && (((prev_pinfo & INSN_LOAD_MEMORY_DELAY)
1791            && ! gpr_interlocks)
1792           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY)
1793               && ! cop_interlocks)))
1794     {
1795       /* A load from a coprocessor or from memory.  All load delays
1796          delay the use of general register rt for one instruction.  */
1797       /* Itbl support may require additional care here.  */
1798       know (prev_pinfo & INSN_WRITE_GPR_T);
1799       if (reg == EXTRACT_OPERAND (RT, history[0]))
1800         return 1;
1801     }
1802
1803   return 0;
1804 }
1805
1806 /* Move all labels in insn_labels to the current insertion point.  */
1807
1808 static void
1809 mips_move_labels (void)
1810 {
1811   struct insn_label_list *l;
1812   valueT val;
1813
1814   for (l = insn_labels; l != NULL; l = l->next)
1815     {
1816       assert (S_GET_SEGMENT (l->label) == now_seg);
1817       symbol_set_frag (l->label, frag_now);
1818       val = (valueT) frag_now_fix ();
1819       /* mips16 text labels are stored as odd.  */
1820       if (mips_opts.mips16)
1821         ++val;
1822       S_SET_VALUE (l->label, val);
1823     }
1824 }
1825
1826 /* Mark instruction labels in mips16 mode.  This permits the linker to
1827    handle them specially, such as generating jalx instructions when
1828    needed.  We also make them odd for the duration of the assembly, in
1829    order to generate the right sort of code.  We will make them even
1830    in the adjust_symtab routine, while leaving them marked.  This is
1831    convenient for the debugger and the disassembler.  The linker knows
1832    to make them odd again.  */
1833
1834 static void
1835 mips16_mark_labels (void)
1836 {
1837   if (mips_opts.mips16)
1838     {
1839       struct insn_label_list *l;
1840       valueT val;
1841
1842       for (l = insn_labels; l != NULL; l = l->next)
1843         {
1844 #ifdef OBJ_ELF
1845           if (OUTPUT_FLAVOR == bfd_target_elf_flavour)
1846             S_SET_OTHER (l->label, STO_MIPS16);
1847 #endif
1848           val = S_GET_VALUE (l->label);
1849           if ((val & 1) == 0)
1850             S_SET_VALUE (l->label, val + 1);
1851         }
1852     }
1853 }
1854
1855 /* End the current frag.  Make it a variant frag and record the
1856    relaxation info.  */
1857
1858 static void
1859 relax_close_frag (void)
1860 {
1861   mips_macro_warning.first_frag = frag_now;
1862   frag_var (rs_machine_dependent, 0, 0,
1863             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
1864             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
1865
1866   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
1867   mips_relax.first_fixup = 0;
1868 }
1869
1870 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
1871    See the comment above RELAX_ENCODE for more details.  */
1872
1873 static void
1874 relax_start (symbolS *symbol)
1875 {
1876   assert (mips_relax.sequence == 0);
1877   mips_relax.sequence = 1;
1878   mips_relax.symbol = symbol;
1879 }
1880
1881 /* Start generating the second version of a relaxable sequence.
1882    See the comment above RELAX_ENCODE for more details.  */
1883
1884 static void
1885 relax_switch (void)
1886 {
1887   assert (mips_relax.sequence == 1);
1888   mips_relax.sequence = 2;
1889 }
1890
1891 /* End the current relaxable sequence.  */
1892
1893 static void
1894 relax_end (void)
1895 {
1896   assert (mips_relax.sequence == 2);
1897   relax_close_frag ();
1898   mips_relax.sequence = 0;
1899 }
1900
1901 /* Classify an instruction according to the FIX_VR4120_* enumeration.
1902    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
1903    by VR4120 errata.  */
1904
1905 static unsigned int
1906 classify_vr4120_insn (const char *name)
1907 {
1908   if (strncmp (name, "macc", 4) == 0)
1909     return FIX_VR4120_MACC;
1910   if (strncmp (name, "dmacc", 5) == 0)
1911     return FIX_VR4120_DMACC;
1912   if (strncmp (name, "mult", 4) == 0)
1913     return FIX_VR4120_MULT;
1914   if (strncmp (name, "dmult", 5) == 0)
1915     return FIX_VR4120_DMULT;
1916   if (strstr (name, "div"))
1917     return FIX_VR4120_DIV;
1918   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
1919     return FIX_VR4120_MTHILO;
1920   return NUM_FIX_VR4120_CLASSES;
1921 }
1922
1923 /* Return the number of instructions that must separate INSN1 and INSN2,
1924    where INSN1 is the earlier instruction.  Return the worst-case value
1925    for any INSN2 if INSN2 is null.  */
1926
1927 static unsigned int
1928 insns_between (const struct mips_cl_insn *insn1,
1929                const struct mips_cl_insn *insn2)
1930 {
1931   unsigned long pinfo1, pinfo2;
1932
1933   /* This function needs to know which pinfo flags are set for INSN2
1934      and which registers INSN2 uses.  The former is stored in PINFO2 and
1935      the latter is tested via INSN2_USES_REG.  If INSN2 is null, PINFO2
1936      will have every flag set and INSN2_USES_REG will always return true.  */
1937   pinfo1 = insn1->insn_mo->pinfo;
1938   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
1939
1940 #define INSN2_USES_REG(REG, CLASS) \
1941    (insn2 == NULL || insn_uses_reg (insn2, REG, CLASS))
1942
1943   /* For most targets, write-after-read dependencies on the HI and LO
1944      registers must be separated by at least two instructions.  */
1945   if (!hilo_interlocks)
1946     {
1947       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
1948         return 2;
1949       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
1950         return 2;
1951     }
1952
1953   /* If we're working around r7000 errata, there must be two instructions
1954      between an mfhi or mflo and any instruction that uses the result.  */
1955   if (mips_7000_hilo_fix
1956       && MF_HILO_INSN (pinfo1)
1957       && INSN2_USES_REG (EXTRACT_OPERAND (RD, *insn1), MIPS_GR_REG))
1958     return 2;
1959
1960   /* If working around VR4120 errata, check for combinations that need
1961      a single intervening instruction.  */
1962   if (mips_fix_vr4120)
1963     {
1964       unsigned int class1, class2;
1965
1966       class1 = classify_vr4120_insn (insn1->insn_mo->name);
1967       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
1968         {
1969           if (insn2 == NULL)
1970             return 1;
1971           class2 = classify_vr4120_insn (insn2->insn_mo->name);
1972           if (vr4120_conflicts[class1] & (1 << class2))
1973             return 1;
1974         }
1975     }
1976
1977   if (!mips_opts.mips16)
1978     {
1979       /* Check for GPR or coprocessor load delays.  All such delays
1980          are on the RT register.  */
1981       /* Itbl support may require additional care here.  */
1982       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY_DELAY))
1983           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
1984         {
1985           know (pinfo1 & INSN_WRITE_GPR_T);
1986           if (INSN2_USES_REG (EXTRACT_OPERAND (RT, *insn1), MIPS_GR_REG))
1987             return 1;
1988         }
1989
1990       /* Check for generic coprocessor hazards.
1991
1992          This case is not handled very well.  There is no special
1993          knowledge of CP0 handling, and the coprocessors other than
1994          the floating point unit are not distinguished at all.  */
1995       /* Itbl support may require additional care here. FIXME!
1996          Need to modify this to include knowledge about
1997          user specified delays!  */
1998       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
1999                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
2000         {
2001           /* Handle cases where INSN1 writes to a known general coprocessor
2002              register.  There must be a one instruction delay before INSN2
2003              if INSN2 reads that register, otherwise no delay is needed.  */
2004           if (pinfo1 & INSN_WRITE_FPR_T)
2005             {
2006               if (INSN2_USES_REG (EXTRACT_OPERAND (FT, *insn1), MIPS_FP_REG))
2007                 return 1;
2008             }
2009           else if (pinfo1 & INSN_WRITE_FPR_S)
2010             {
2011               if (INSN2_USES_REG (EXTRACT_OPERAND (FS, *insn1), MIPS_FP_REG))
2012                 return 1;
2013             }
2014           else
2015             {
2016               /* Read-after-write dependencies on the control registers
2017                  require a two-instruction gap.  */
2018               if ((pinfo1 & INSN_WRITE_COND_CODE)
2019                   && (pinfo2 & INSN_READ_COND_CODE))
2020                 return 2;
2021
2022               /* We don't know exactly what INSN1 does.  If INSN2 is
2023                  also a coprocessor instruction, assume there must be
2024                  a one instruction gap.  */
2025               if (pinfo2 & INSN_COP)
2026                 return 1;
2027             }
2028         }
2029
2030       /* Check for read-after-write dependencies on the coprocessor
2031          control registers in cases where INSN1 does not need a general
2032          coprocessor delay.  This means that INSN1 is a floating point
2033          comparison instruction.  */
2034       /* Itbl support may require additional care here.  */
2035       else if (!cop_interlocks
2036                && (pinfo1 & INSN_WRITE_COND_CODE)
2037                && (pinfo2 & INSN_READ_COND_CODE))
2038         return 1;
2039     }
2040
2041 #undef INSN2_USES_REG
2042
2043   return 0;
2044 }
2045
2046 /* Return the number of nops that would be needed to work around the
2047    VR4130 mflo/mfhi errata if instruction INSN immediately followed
2048    the MAX_VR4130_NOPS instructions described by HISTORY.  */
2049
2050 static int
2051 nops_for_vr4130 (const struct mips_cl_insn *history,
2052                  const struct mips_cl_insn *insn)
2053 {
2054   int i, j, reg;
2055
2056   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
2057      are not affected by the errata.  */
2058   if (insn != 0
2059       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
2060           || strcmp (insn->insn_mo->name, "mtlo") == 0
2061           || strcmp (insn->insn_mo->name, "mthi") == 0))
2062     return 0;
2063
2064   /* Search for the first MFLO or MFHI.  */
2065   for (i = 0; i < MAX_VR4130_NOPS; i++)
2066     if (!history[i].noreorder_p && MF_HILO_INSN (history[i].insn_mo->pinfo))
2067       {
2068         /* Extract the destination register.  */
2069         if (mips_opts.mips16)
2070           reg = mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, history[i])];
2071         else
2072           reg = EXTRACT_OPERAND (RD, history[i]);
2073
2074         /* No nops are needed if INSN reads that register.  */
2075         if (insn != NULL && insn_uses_reg (insn, reg, MIPS_GR_REG))
2076           return 0;
2077
2078         /* ...or if any of the intervening instructions do.  */
2079         for (j = 0; j < i; j++)
2080           if (insn_uses_reg (&history[j], reg, MIPS_GR_REG))
2081             return 0;
2082
2083         return MAX_VR4130_NOPS - i;
2084       }
2085   return 0;
2086 }
2087
2088 /* Return the number of nops that would be needed if instruction INSN
2089    immediately followed the MAX_NOPS instructions given by HISTORY,
2090    where HISTORY[0] is the most recent instruction.  If INSN is null,
2091    return the worse-case number of nops for any instruction.  */
2092
2093 static int
2094 nops_for_insn (const struct mips_cl_insn *history,
2095                const struct mips_cl_insn *insn)
2096 {
2097   int i, nops, tmp_nops;
2098
2099   nops = 0;
2100   for (i = 0; i < MAX_DELAY_NOPS; i++)
2101     if (!history[i].noreorder_p)
2102       {
2103         tmp_nops = insns_between (history + i, insn) - i;
2104         if (tmp_nops > nops)
2105           nops = tmp_nops;
2106       }
2107
2108   if (mips_fix_vr4130)
2109     {
2110       tmp_nops = nops_for_vr4130 (history, insn);
2111       if (tmp_nops > nops)
2112         nops = tmp_nops;
2113     }
2114
2115   return nops;
2116 }
2117
2118 /* The variable arguments provide NUM_INSNS extra instructions that
2119    might be added to HISTORY.  Return the largest number of nops that
2120    would be needed after the extended sequence.  */
2121
2122 static int
2123 nops_for_sequence (int num_insns, const struct mips_cl_insn *history, ...)
2124 {
2125   va_list args;
2126   struct mips_cl_insn buffer[MAX_NOPS];
2127   struct mips_cl_insn *cursor;
2128   int nops;
2129
2130   va_start (args, history);
2131   cursor = buffer + num_insns;
2132   memcpy (cursor, history, (MAX_NOPS - num_insns) * sizeof (*cursor));
2133   while (cursor > buffer)
2134     *--cursor = *va_arg (args, const struct mips_cl_insn *);
2135
2136   nops = nops_for_insn (buffer, NULL);
2137   va_end (args);
2138   return nops;
2139 }
2140
2141 /* Like nops_for_insn, but if INSN is a branch, take into account the
2142    worst-case delay for the branch target.  */
2143
2144 static int
2145 nops_for_insn_or_target (const struct mips_cl_insn *history,
2146                          const struct mips_cl_insn *insn)
2147 {
2148   int nops, tmp_nops;
2149
2150   nops = nops_for_insn (history, insn);
2151   if (insn->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
2152                               | INSN_COND_BRANCH_DELAY
2153                               | INSN_COND_BRANCH_LIKELY))
2154     {
2155       tmp_nops = nops_for_sequence (2, history, insn, NOP_INSN);
2156       if (tmp_nops > nops)
2157         nops = tmp_nops;
2158     }
2159   else if (mips_opts.mips16 && (insn->insn_mo->pinfo & MIPS16_INSN_BRANCH))
2160     {
2161       tmp_nops = nops_for_sequence (1, history, insn);
2162       if (tmp_nops > nops)
2163         nops = tmp_nops;
2164     }
2165   return nops;
2166 }
2167
2168 /* Output an instruction.  IP is the instruction information.
2169    ADDRESS_EXPR is an operand of the instruction to be used with
2170    RELOC_TYPE.  */
2171
2172 static void
2173 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
2174              bfd_reloc_code_real_type *reloc_type)
2175 {
2176   register unsigned long prev_pinfo, pinfo;
2177   relax_stateT prev_insn_frag_type = 0;
2178   bfd_boolean relaxed_branch = FALSE;
2179
2180   /* Mark instruction labels in mips16 mode.  */
2181   mips16_mark_labels ();
2182
2183   prev_pinfo = history[0].insn_mo->pinfo;
2184   pinfo = ip->insn_mo->pinfo;
2185
2186   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
2187     {
2188       /* There are a lot of optimizations we could do that we don't.
2189          In particular, we do not, in general, reorder instructions.
2190          If you use gcc with optimization, it will reorder
2191          instructions and generally do much more optimization then we
2192          do here; repeating all that work in the assembler would only
2193          benefit hand written assembly code, and does not seem worth
2194          it.  */
2195       int nops = (mips_optimize == 0
2196                   ? nops_for_insn (history, NULL)
2197                   : nops_for_insn_or_target (history, ip));
2198       if (nops > 0)
2199         {
2200           fragS *old_frag;
2201           unsigned long old_frag_offset;
2202           int i;
2203
2204           old_frag = frag_now;
2205           old_frag_offset = frag_now_fix ();
2206
2207           for (i = 0; i < nops; i++)
2208             emit_nop ();
2209
2210           if (listing)
2211             {
2212               listing_prev_line ();
2213               /* We may be at the start of a variant frag.  In case we
2214                  are, make sure there is enough space for the frag
2215                  after the frags created by listing_prev_line.  The
2216                  argument to frag_grow here must be at least as large
2217                  as the argument to all other calls to frag_grow in
2218                  this file.  We don't have to worry about being in the
2219                  middle of a variant frag, because the variants insert
2220                  all needed nop instructions themselves.  */
2221               frag_grow (40);
2222             }
2223
2224           mips_move_labels ();
2225
2226 #ifndef NO_ECOFF_DEBUGGING
2227           if (ECOFF_DEBUGGING)
2228             ecoff_fix_loc (old_frag, old_frag_offset);
2229 #endif
2230         }
2231     }
2232   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
2233     {
2234       /* Work out how many nops in prev_nop_frag are needed by IP.  */
2235       int nops = nops_for_insn_or_target (history, ip);
2236       assert (nops <= prev_nop_frag_holds);
2237
2238       /* Enforce NOPS as a minimum.  */
2239       if (nops > prev_nop_frag_required)
2240         prev_nop_frag_required = nops;
2241
2242       if (prev_nop_frag_holds == prev_nop_frag_required)
2243         {
2244           /* Settle for the current number of nops.  Update the history
2245              accordingly (for the benefit of any future .set reorder code).  */
2246           prev_nop_frag = NULL;
2247           insert_into_history (prev_nop_frag_since,
2248                                prev_nop_frag_holds, NOP_INSN);
2249         }
2250       else
2251         {
2252           /* Allow this instruction to replace one of the nops that was
2253              tentatively added to prev_nop_frag.  */
2254           prev_nop_frag->fr_fix -= mips_opts.mips16 ? 2 : 4;
2255           prev_nop_frag_holds--;
2256           prev_nop_frag_since++;
2257         }
2258     }
2259
2260 #ifdef OBJ_ELF
2261   /* The value passed to dwarf2_emit_insn is the distance between
2262      the beginning of the current instruction and the address that
2263      should be recorded in the debug tables.  For MIPS16 debug info
2264      we want to use ISA-encoded addresses, so we pass -1 for an
2265      address higher by one than the current.  */
2266   dwarf2_emit_insn (mips_opts.mips16 ? -1 : 0);
2267 #endif
2268
2269   /* Record the frag type before frag_var.  */
2270   if (history[0].frag)
2271     prev_insn_frag_type = history[0].frag->fr_type;
2272
2273   if (address_expr
2274       && *reloc_type == BFD_RELOC_16_PCREL_S2
2275       && (pinfo & INSN_UNCOND_BRANCH_DELAY || pinfo & INSN_COND_BRANCH_DELAY
2276           || pinfo & INSN_COND_BRANCH_LIKELY)
2277       && mips_relax_branch
2278       /* Don't try branch relaxation within .set nomacro, or within
2279          .set noat if we use $at for PIC computations.  If it turns
2280          out that the branch was out-of-range, we'll get an error.  */
2281       && !mips_opts.warn_about_macros
2282       && !(mips_opts.noat && mips_pic != NO_PIC)
2283       && !mips_opts.mips16)
2284     {
2285       relaxed_branch = TRUE;
2286       add_relaxed_insn (ip, (relaxed_branch_length
2287                              (NULL, NULL,
2288                               (pinfo & INSN_UNCOND_BRANCH_DELAY) ? -1
2289                               : (pinfo & INSN_COND_BRANCH_LIKELY) ? 1
2290                               : 0)), 4,
2291                         RELAX_BRANCH_ENCODE
2292                         (pinfo & INSN_UNCOND_BRANCH_DELAY,
2293                          pinfo & INSN_COND_BRANCH_LIKELY,
2294                          pinfo & INSN_WRITE_GPR_31,
2295                          0),
2296                         address_expr->X_add_symbol,
2297                         address_expr->X_add_number);
2298       *reloc_type = BFD_RELOC_UNUSED;
2299     }
2300   else if (*reloc_type > BFD_RELOC_UNUSED)
2301     {
2302       /* We need to set up a variant frag.  */
2303       assert (mips_opts.mips16 && address_expr != NULL);
2304       add_relaxed_insn (ip, 4, 0,
2305                         RELAX_MIPS16_ENCODE
2306                         (*reloc_type - BFD_RELOC_UNUSED,
2307                          mips16_small, mips16_ext,
2308                          prev_pinfo & INSN_UNCOND_BRANCH_DELAY,
2309                          history[0].mips16_absolute_jump_p),
2310                         make_expr_symbol (address_expr), 0);
2311     }
2312   else if (mips_opts.mips16
2313            && ! ip->use_extend
2314            && *reloc_type != BFD_RELOC_MIPS16_JMP)
2315     {
2316       if ((pinfo & INSN_UNCOND_BRANCH_DELAY) == 0)
2317         /* Make sure there is enough room to swap this instruction with
2318            a following jump instruction.  */
2319         frag_grow (6);
2320       add_fixed_insn (ip);
2321     }
2322   else
2323     {
2324       if (mips_opts.mips16
2325           && mips_opts.noreorder
2326           && (prev_pinfo & INSN_UNCOND_BRANCH_DELAY) != 0)
2327         as_warn (_("extended instruction in delay slot"));
2328
2329       if (mips_relax.sequence)
2330         {
2331           /* If we've reached the end of this frag, turn it into a variant
2332              frag and record the information for the instructions we've
2333              written so far.  */
2334           if (frag_room () < 4)
2335             relax_close_frag ();
2336           mips_relax.sizes[mips_relax.sequence - 1] += 4;
2337         }
2338
2339       if (mips_relax.sequence != 2)
2340         mips_macro_warning.sizes[0] += 4;
2341       if (mips_relax.sequence != 1)
2342         mips_macro_warning.sizes[1] += 4;
2343
2344       if (mips_opts.mips16)
2345         {
2346           ip->fixed_p = 1;
2347           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
2348         }
2349       add_fixed_insn (ip);
2350     }
2351
2352   if (address_expr != NULL && *reloc_type <= BFD_RELOC_UNUSED)
2353     {
2354       if (address_expr->X_op == O_constant)
2355         {
2356           unsigned int tmp;
2357
2358           switch (*reloc_type)
2359             {
2360             case BFD_RELOC_32:
2361               ip->insn_opcode |= address_expr->X_add_number;
2362               break;
2363
2364             case BFD_RELOC_MIPS_HIGHEST:
2365               tmp = (address_expr->X_add_number + 0x800080008000ull) >> 48;
2366               ip->insn_opcode |= tmp & 0xffff;
2367               break;
2368
2369             case BFD_RELOC_MIPS_HIGHER:
2370               tmp = (address_expr->X_add_number + 0x80008000ull) >> 32;
2371               ip->insn_opcode |= tmp & 0xffff;
2372               break;
2373
2374             case BFD_RELOC_HI16_S:
2375               tmp = (address_expr->X_add_number + 0x8000) >> 16;
2376               ip->insn_opcode |= tmp & 0xffff;
2377               break;
2378
2379             case BFD_RELOC_HI16:
2380               ip->insn_opcode |= (address_expr->X_add_number >> 16) & 0xffff;
2381               break;
2382
2383             case BFD_RELOC_UNUSED:
2384             case BFD_RELOC_LO16:
2385             case BFD_RELOC_MIPS_GOT_DISP:
2386               ip->insn_opcode |= address_expr->X_add_number & 0xffff;
2387               break;
2388
2389             case BFD_RELOC_MIPS_JMP:
2390               if ((address_expr->X_add_number & 3) != 0)
2391                 as_bad (_("jump to misaligned address (0x%lx)"),
2392                         (unsigned long) address_expr->X_add_number);
2393               if (address_expr->X_add_number & ~0xfffffff)
2394                 as_bad (_("jump address range overflow (0x%lx)"),
2395                         (unsigned long) address_expr->X_add_number);
2396               ip->insn_opcode |= (address_expr->X_add_number >> 2) & 0x3ffffff;
2397               break;
2398
2399             case BFD_RELOC_MIPS16_JMP:
2400               if ((address_expr->X_add_number & 3) != 0)
2401                 as_bad (_("jump to misaligned address (0x%lx)"),
2402                         (unsigned long) address_expr->X_add_number);
2403               if (address_expr->X_add_number & ~0xfffffff)
2404                 as_bad (_("jump address range overflow (0x%lx)"),
2405                         (unsigned long) address_expr->X_add_number);
2406               ip->insn_opcode |=
2407                 (((address_expr->X_add_number & 0x7c0000) << 3)
2408                  | ((address_expr->X_add_number & 0xf800000) >> 7)
2409                  | ((address_expr->X_add_number & 0x3fffc) >> 2));
2410               break;
2411
2412             case BFD_RELOC_16_PCREL_S2:
2413               goto need_reloc;
2414
2415             default:
2416               internalError ();
2417             }
2418         }
2419       else if (*reloc_type < BFD_RELOC_UNUSED)
2420         need_reloc:
2421         {
2422           reloc_howto_type *howto;
2423           int i;
2424
2425           /* In a compound relocation, it is the final (outermost)
2426              operator that determines the relocated field.  */
2427           for (i = 1; i < 3; i++)
2428             if (reloc_type[i] == BFD_RELOC_UNUSED)
2429               break;
2430
2431           howto = bfd_reloc_type_lookup (stdoutput, reloc_type[i - 1]);
2432           ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
2433                                      bfd_get_reloc_size (howto),
2434                                      address_expr,
2435                                      reloc_type[0] == BFD_RELOC_16_PCREL_S2,
2436                                      reloc_type[0]);
2437
2438           /* These relocations can have an addend that won't fit in
2439              4 octets for 64bit assembly.  */
2440           if (HAVE_64BIT_GPRS
2441               && ! howto->partial_inplace
2442               && (reloc_type[0] == BFD_RELOC_16
2443                   || reloc_type[0] == BFD_RELOC_32
2444                   || reloc_type[0] == BFD_RELOC_MIPS_JMP
2445                   || reloc_type[0] == BFD_RELOC_HI16_S
2446                   || reloc_type[0] == BFD_RELOC_LO16
2447                   || reloc_type[0] == BFD_RELOC_GPREL16
2448                   || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
2449                   || reloc_type[0] == BFD_RELOC_GPREL32
2450                   || reloc_type[0] == BFD_RELOC_64
2451                   || reloc_type[0] == BFD_RELOC_CTOR
2452                   || reloc_type[0] == BFD_RELOC_MIPS_SUB
2453                   || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
2454                   || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
2455                   || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
2456                   || reloc_type[0] == BFD_RELOC_MIPS_REL16
2457                   || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
2458                   || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
2459                   || reloc_type[0] == BFD_RELOC_MIPS16_HI16_S
2460                   || reloc_type[0] == BFD_RELOC_MIPS16_LO16))
2461             ip->fixp[0]->fx_no_overflow = 1;
2462
2463           if (mips_relax.sequence)
2464             {
2465               if (mips_relax.first_fixup == 0)
2466                 mips_relax.first_fixup = ip->fixp[0];
2467             }
2468           else if (reloc_needs_lo_p (*reloc_type))
2469             {
2470               struct mips_hi_fixup *hi_fixup;
2471
2472               /* Reuse the last entry if it already has a matching %lo.  */
2473               hi_fixup = mips_hi_fixup_list;
2474               if (hi_fixup == 0
2475                   || !fixup_has_matching_lo_p (hi_fixup->fixp))
2476                 {
2477                   hi_fixup = ((struct mips_hi_fixup *)
2478                               xmalloc (sizeof (struct mips_hi_fixup)));
2479                   hi_fixup->next = mips_hi_fixup_list;
2480                   mips_hi_fixup_list = hi_fixup;
2481                 }
2482               hi_fixup->fixp = ip->fixp[0];
2483               hi_fixup->seg = now_seg;
2484             }
2485
2486           /* Add fixups for the second and third relocations, if given.
2487              Note that the ABI allows the second relocation to be
2488              against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
2489              moment we only use RSS_UNDEF, but we could add support
2490              for the others if it ever becomes necessary.  */
2491           for (i = 1; i < 3; i++)
2492             if (reloc_type[i] != BFD_RELOC_UNUSED)
2493               {
2494                 ip->fixp[i] = fix_new (ip->frag, ip->where,
2495                                        ip->fixp[0]->fx_size, NULL, 0,
2496                                        FALSE, reloc_type[i]);
2497
2498                 /* Use fx_tcbit to mark compound relocs.  */
2499                 ip->fixp[0]->fx_tcbit = 1;
2500                 ip->fixp[i]->fx_tcbit = 1;
2501               }
2502         }
2503     }
2504   install_insn (ip);
2505
2506   /* Update the register mask information.  */
2507   if (! mips_opts.mips16)
2508     {
2509       if (pinfo & INSN_WRITE_GPR_D)
2510         mips_gprmask |= 1 << EXTRACT_OPERAND (RD, *ip);
2511       if ((pinfo & (INSN_WRITE_GPR_T | INSN_READ_GPR_T)) != 0)
2512         mips_gprmask |= 1 << EXTRACT_OPERAND (RT, *ip);
2513       if (pinfo & INSN_READ_GPR_S)
2514         mips_gprmask |= 1 << EXTRACT_OPERAND (RS, *ip);
2515       if (pinfo & INSN_WRITE_GPR_31)
2516         mips_gprmask |= 1 << RA;
2517       if (pinfo & INSN_WRITE_FPR_D)
2518         mips_cprmask[1] |= 1 << EXTRACT_OPERAND (FD, *ip);
2519       if ((pinfo & (INSN_WRITE_FPR_S | INSN_READ_FPR_S)) != 0)
2520         mips_cprmask[1] |= 1 << EXTRACT_OPERAND (FS, *ip);
2521       if ((pinfo & (INSN_WRITE_FPR_T | INSN_READ_FPR_T)) != 0)
2522         mips_cprmask[1] |= 1 << EXTRACT_OPERAND (FT, *ip);
2523       if ((pinfo & INSN_READ_FPR_R) != 0)
2524         mips_cprmask[1] |= 1 << EXTRACT_OPERAND (FR, *ip);
2525       if (pinfo & INSN_COP)
2526         {
2527           /* We don't keep enough information to sort these cases out.
2528              The itbl support does keep this information however, although
2529              we currently don't support itbl fprmats as part of the cop
2530              instruction.  May want to add this support in the future.  */
2531         }
2532       /* Never set the bit for $0, which is always zero.  */
2533       mips_gprmask &= ~1 << 0;
2534     }
2535   else
2536     {
2537       if (pinfo & (MIPS16_INSN_WRITE_X | MIPS16_INSN_READ_X))
2538         mips_gprmask |= 1 << MIPS16_EXTRACT_OPERAND (RX, *ip);
2539       if (pinfo & (MIPS16_INSN_WRITE_Y | MIPS16_INSN_READ_Y))
2540         mips_gprmask |= 1 << MIPS16_EXTRACT_OPERAND (RY, *ip);
2541       if (pinfo & MIPS16_INSN_WRITE_Z)
2542         mips_gprmask |= 1 << MIPS16_EXTRACT_OPERAND (RZ, *ip);
2543       if (pinfo & (MIPS16_INSN_WRITE_T | MIPS16_INSN_READ_T))
2544         mips_gprmask |= 1 << TREG;
2545       if (pinfo & (MIPS16_INSN_WRITE_SP | MIPS16_INSN_READ_SP))
2546         mips_gprmask |= 1 << SP;
2547       if (pinfo & (MIPS16_INSN_WRITE_31 | MIPS16_INSN_READ_31))
2548         mips_gprmask |= 1 << RA;
2549       if (pinfo & MIPS16_INSN_WRITE_GPR_Y)
2550         mips_gprmask |= 1 << MIPS16OP_EXTRACT_REG32R (ip->insn_opcode);
2551       if (pinfo & MIPS16_INSN_READ_Z)
2552         mips_gprmask |= 1 << MIPS16_EXTRACT_OPERAND (MOVE32Z, *ip);
2553       if (pinfo & MIPS16_INSN_READ_GPR_X)
2554         mips_gprmask |= 1 << MIPS16_EXTRACT_OPERAND (REGR32, *ip);
2555     }
2556
2557   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
2558     {
2559       /* Filling the branch delay slot is more complex.  We try to
2560          switch the branch with the previous instruction, which we can
2561          do if the previous instruction does not set up a condition
2562          that the branch tests and if the branch is not itself the
2563          target of any branch.  */
2564       if ((pinfo & INSN_UNCOND_BRANCH_DELAY)
2565           || (pinfo & INSN_COND_BRANCH_DELAY))
2566         {
2567           if (mips_optimize < 2
2568               /* If we have seen .set volatile or .set nomove, don't
2569                  optimize.  */
2570               || mips_opts.nomove != 0
2571               /* We can't swap if the previous instruction's position
2572                  is fixed.  */
2573               || history[0].fixed_p
2574               /* If the previous previous insn was in a .set
2575                  noreorder, we can't swap.  Actually, the MIPS
2576                  assembler will swap in this situation.  However, gcc
2577                  configured -with-gnu-as will generate code like
2578                    .set noreorder
2579                    lw   $4,XXX
2580                    .set reorder
2581                    INSN
2582                    bne  $4,$0,foo
2583                  in which we can not swap the bne and INSN.  If gcc is
2584                  not configured -with-gnu-as, it does not output the
2585                  .set pseudo-ops.  */
2586               || history[1].noreorder_p
2587               /* If the branch is itself the target of a branch, we
2588                  can not swap.  We cheat on this; all we check for is
2589                  whether there is a label on this instruction.  If
2590                  there are any branches to anything other than a
2591                  label, users must use .set noreorder.  */
2592               || insn_labels != NULL
2593               /* If the previous instruction is in a variant frag
2594                  other than this branch's one, we cannot do the swap.
2595                  This does not apply to the mips16, which uses variant
2596                  frags for different purposes.  */
2597               || (! mips_opts.mips16
2598                   && prev_insn_frag_type == rs_machine_dependent)
2599               /* Check for conflicts between the branch and the instructions
2600                  before the candidate delay slot.  */
2601               || nops_for_insn (history + 1, ip) > 0
2602               /* Check for conflicts between the swapped sequence and the
2603                  target of the branch.  */
2604               || nops_for_sequence (2, history + 1, ip, history) > 0
2605               /* We do not swap with a trap instruction, since it
2606                  complicates trap handlers to have the trap
2607                  instruction be in a delay slot.  */
2608               || (prev_pinfo & INSN_TRAP)
2609               /* If the branch reads a register that the previous
2610                  instruction sets, we can not swap.  */
2611               || (! mips_opts.mips16
2612                   && (prev_pinfo & INSN_WRITE_GPR_T)
2613                   && insn_uses_reg (ip, EXTRACT_OPERAND (RT, history[0]),
2614                                     MIPS_GR_REG))
2615               || (! mips_opts.mips16
2616                   && (prev_pinfo & INSN_WRITE_GPR_D)
2617                   && insn_uses_reg (ip, EXTRACT_OPERAND (RD, history[0]),
2618                                     MIPS_GR_REG))
2619               || (mips_opts.mips16
2620                   && (((prev_pinfo & MIPS16_INSN_WRITE_X)
2621                        && (insn_uses_reg
2622                            (ip, MIPS16_EXTRACT_OPERAND (RX, history[0]),
2623                             MIPS16_REG)))
2624                       || ((prev_pinfo & MIPS16_INSN_WRITE_Y)
2625                           && (insn_uses_reg
2626                               (ip, MIPS16_EXTRACT_OPERAND (RY, history[0]),
2627                                MIPS16_REG)))
2628                       || ((prev_pinfo & MIPS16_INSN_WRITE_Z)
2629                           && (insn_uses_reg
2630                               (ip, MIPS16_EXTRACT_OPERAND (RZ, history[0]),
2631                                MIPS16_REG)))
2632                       || ((prev_pinfo & MIPS16_INSN_WRITE_T)
2633                           && insn_uses_reg (ip, TREG, MIPS_GR_REG))
2634                       || ((prev_pinfo & MIPS16_INSN_WRITE_31)
2635                           && insn_uses_reg (ip, RA, MIPS_GR_REG))
2636                       || ((prev_pinfo & MIPS16_INSN_WRITE_GPR_Y)
2637                           && insn_uses_reg (ip,
2638                                             MIPS16OP_EXTRACT_REG32R
2639                                               (history[0].insn_opcode),
2640                                             MIPS_GR_REG))))
2641               /* If the branch writes a register that the previous
2642                  instruction sets, we can not swap (we know that
2643                  branches write only to RD or to $31).  */
2644               || (! mips_opts.mips16
2645                   && (prev_pinfo & INSN_WRITE_GPR_T)
2646                   && (((pinfo & INSN_WRITE_GPR_D)
2647                        && (EXTRACT_OPERAND (RT, history[0])
2648                            == EXTRACT_OPERAND (RD, *ip)))
2649                       || ((pinfo & INSN_WRITE_GPR_31)
2650                           && EXTRACT_OPERAND (RT, history[0]) == RA)))
2651               || (! mips_opts.mips16
2652                   && (prev_pinfo & INSN_WRITE_GPR_D)
2653                   && (((pinfo & INSN_WRITE_GPR_D)
2654                        && (EXTRACT_OPERAND (RD, history[0])
2655                            == EXTRACT_OPERAND (RD, *ip)))
2656                       || ((pinfo & INSN_WRITE_GPR_31)
2657                           && EXTRACT_OPERAND (RD, history[0]) == RA)))
2658               || (mips_opts.mips16
2659                   && (pinfo & MIPS16_INSN_WRITE_31)
2660                   && ((prev_pinfo & MIPS16_INSN_WRITE_31)
2661                       || ((prev_pinfo & MIPS16_INSN_WRITE_GPR_Y)
2662                           && (MIPS16OP_EXTRACT_REG32R (history[0].insn_opcode)
2663                               == RA))))
2664               /* If the branch writes a register that the previous
2665                  instruction reads, we can not swap (we know that
2666                  branches only write to RD or to $31).  */
2667               || (! mips_opts.mips16
2668                   && (pinfo & INSN_WRITE_GPR_D)
2669                   && insn_uses_reg (&history[0],
2670                                     EXTRACT_OPERAND (RD, *ip),
2671                                     MIPS_GR_REG))
2672               || (! mips_opts.mips16
2673                   && (pinfo & INSN_WRITE_GPR_31)
2674                   && insn_uses_reg (&history[0], RA, MIPS_GR_REG))
2675               || (mips_opts.mips16
2676                   && (pinfo & MIPS16_INSN_WRITE_31)
2677                   && insn_uses_reg (&history[0], RA, MIPS_GR_REG))
2678               /* If one instruction sets a condition code and the
2679                  other one uses a condition code, we can not swap.  */
2680               || ((pinfo & INSN_READ_COND_CODE)
2681                   && (prev_pinfo & INSN_WRITE_COND_CODE))
2682               || ((pinfo & INSN_WRITE_COND_CODE)
2683                   && (prev_pinfo & INSN_READ_COND_CODE))
2684               /* If the previous instruction uses the PC, we can not
2685                  swap.  */
2686               || (mips_opts.mips16
2687                   && (prev_pinfo & MIPS16_INSN_READ_PC))
2688               /* If the previous instruction had a fixup in mips16
2689                  mode, we can not swap.  This normally means that the
2690                  previous instruction was a 4 byte branch anyhow.  */
2691               || (mips_opts.mips16 && history[0].fixp[0])
2692               /* If the previous instruction is a sync, sync.l, or
2693                  sync.p, we can not swap.  */
2694               || (prev_pinfo & INSN_SYNC))
2695             {
2696               if (mips_opts.mips16
2697                   && (pinfo & INSN_UNCOND_BRANCH_DELAY)
2698                   && (pinfo & (MIPS16_INSN_READ_X | MIPS16_INSN_READ_31))
2699                   && (mips_opts.isa == ISA_MIPS32
2700                       || mips_opts.isa == ISA_MIPS32R2
2701                       || mips_opts.isa == ISA_MIPS64
2702                       || mips_opts.isa == ISA_MIPS64R2))
2703                 {
2704                   /* Convert MIPS16 jr/jalr into a "compact" jump.  */
2705                   ip->insn_opcode |= 0x0080;
2706                   install_insn (ip);
2707                   insert_into_history (0, 1, ip);
2708                 } 
2709               else
2710                 {
2711                   /* We could do even better for unconditional branches to
2712                      portions of this object file; we could pick up the
2713                      instruction at the destination, put it in the delay
2714                      slot, and bump the destination address.  */
2715                   insert_into_history (0, 1, ip);
2716                   emit_nop ();
2717                 }
2718                 
2719               if (mips_relax.sequence)
2720                 mips_relax.sizes[mips_relax.sequence - 1] += 4;
2721             }
2722           else
2723             {
2724               /* It looks like we can actually do the swap.  */
2725               struct mips_cl_insn delay = history[0];
2726               if (mips_opts.mips16)
2727                 {
2728                   know (delay.frag == ip->frag);
2729                   move_insn (ip, delay.frag, delay.where);
2730                   move_insn (&delay, ip->frag, ip->where + insn_length (ip));
2731                 }
2732               else if (relaxed_branch)
2733                 {
2734                   /* Add the delay slot instruction to the end of the
2735                      current frag and shrink the fixed part of the
2736                      original frag.  If the branch occupies the tail of
2737                      the latter, move it backwards to cover the gap.  */
2738                   delay.frag->fr_fix -= 4;
2739                   if (delay.frag == ip->frag)
2740                     move_insn (ip, ip->frag, ip->where - 4);
2741                   add_fixed_insn (&delay);
2742                 }
2743               else
2744                 {
2745                   move_insn (&delay, ip->frag, ip->where);
2746                   move_insn (ip, history[0].frag, history[0].where);
2747                 }
2748               history[0] = *ip;
2749               delay.fixed_p = 1;
2750               insert_into_history (0, 1, &delay);
2751             }
2752
2753           /* If that was an unconditional branch, forget the previous
2754              insn information.  */
2755           if (pinfo & INSN_UNCOND_BRANCH_DELAY)
2756             mips_no_prev_insn ();
2757         }
2758       else if (pinfo & INSN_COND_BRANCH_LIKELY)
2759         {
2760           /* We don't yet optimize a branch likely.  What we should do
2761              is look at the target, copy the instruction found there
2762              into the delay slot, and increment the branch to jump to
2763              the next instruction.  */
2764           insert_into_history (0, 1, ip);
2765           emit_nop ();
2766         }
2767       else
2768         insert_into_history (0, 1, ip);
2769     }
2770   else
2771     insert_into_history (0, 1, ip);
2772
2773   /* We just output an insn, so the next one doesn't have a label.  */
2774   mips_clear_insn_labels ();
2775 }
2776
2777 /* Forget that there was any previous instruction or label.  */
2778
2779 static void
2780 mips_no_prev_insn (void)
2781 {
2782   prev_nop_frag = NULL;
2783   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
2784   mips_clear_insn_labels ();
2785 }
2786
2787 /* This function must be called before we emit something other than
2788    instructions.  It is like mips_no_prev_insn except that it inserts
2789    any NOPS that might be needed by previous instructions.  */
2790
2791 void
2792 mips_emit_delays (void)
2793 {
2794   if (! mips_opts.noreorder)
2795     {
2796       int nops = nops_for_insn (history, NULL);
2797       if (nops > 0)
2798         {
2799           while (nops-- > 0)
2800             add_fixed_insn (NOP_INSN);
2801           mips_move_labels ();
2802         }
2803     }
2804   mips_no_prev_insn ();
2805 }
2806
2807 /* Start a (possibly nested) noreorder block.  */
2808
2809 static void
2810 start_noreorder (void)
2811 {
2812   if (mips_opts.noreorder == 0)
2813     {
2814       unsigned int i;
2815       int nops;
2816
2817       /* None of the instructions before the .set noreorder can be moved.  */
2818       for (i = 0; i < ARRAY_SIZE (history); i++)
2819         history[i].fixed_p = 1;
2820
2821       /* Insert any nops that might be needed between the .set noreorder
2822          block and the previous instructions.  We will later remove any
2823          nops that turn out not to be needed.  */
2824       nops = nops_for_insn (history, NULL);
2825       if (nops > 0)
2826         {
2827           if (mips_optimize != 0)
2828             {
2829               /* Record the frag which holds the nop instructions, so
2830                  that we can remove them if we don't need them.  */
2831               frag_grow (mips_opts.mips16 ? nops * 2 : nops * 4);
2832               prev_nop_frag = frag_now;
2833               prev_nop_frag_holds = nops;
2834               prev_nop_frag_required = 0;
2835               prev_nop_frag_since = 0;
2836             }
2837
2838           for (; nops > 0; --nops)
2839             add_fixed_insn (NOP_INSN);
2840
2841           /* Move on to a new frag, so that it is safe to simply
2842              decrease the size of prev_nop_frag.  */
2843           frag_wane (frag_now);
2844           frag_new (0);
2845           mips_move_labels ();
2846         }
2847       mips16_mark_labels ();
2848       mips_clear_insn_labels ();
2849     }
2850   mips_opts.noreorder++;
2851   mips_any_noreorder = 1;
2852 }
2853
2854 /* End a nested noreorder block.  */
2855
2856 static void
2857 end_noreorder (void)
2858 {
2859   mips_opts.noreorder--;
2860   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
2861     {
2862       /* Commit to inserting prev_nop_frag_required nops and go back to
2863          handling nop insertion the .set reorder way.  */
2864       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
2865                                 * (mips_opts.mips16 ? 2 : 4));
2866       insert_into_history (prev_nop_frag_since,
2867                            prev_nop_frag_required, NOP_INSN);
2868       prev_nop_frag = NULL;
2869     }
2870 }
2871
2872 /* Set up global variables for the start of a new macro.  */
2873
2874 static void
2875 macro_start (void)
2876 {
2877   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
2878   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
2879                                      && (history[0].insn_mo->pinfo
2880                                          & (INSN_UNCOND_BRANCH_DELAY
2881                                             | INSN_COND_BRANCH_DELAY
2882                                             | INSN_COND_BRANCH_LIKELY)) != 0);
2883 }
2884
2885 /* Given that a macro is longer than 4 bytes, return the appropriate warning
2886    for it.  Return null if no warning is needed.  SUBTYPE is a bitmask of
2887    RELAX_DELAY_SLOT and RELAX_NOMACRO.  */
2888
2889 static const char *
2890 macro_warning (relax_substateT subtype)
2891 {
2892   if (subtype & RELAX_DELAY_SLOT)
2893     return _("Macro instruction expanded into multiple instructions"
2894              " in a branch delay slot");
2895   else if (subtype & RELAX_NOMACRO)
2896     return _("Macro instruction expanded into multiple instructions");
2897   else
2898     return 0;
2899 }
2900
2901 /* Finish up a macro.  Emit warnings as appropriate.  */
2902
2903 static void
2904 macro_end (void)
2905 {
2906   if (mips_macro_warning.sizes[0] > 4 || mips_macro_warning.sizes[1] > 4)
2907     {
2908       relax_substateT subtype;
2909
2910       /* Set up the relaxation warning flags.  */
2911       subtype = 0;
2912       if (mips_macro_warning.sizes[1] > mips_macro_warning.sizes[0])
2913         subtype |= RELAX_SECOND_LONGER;
2914       if (mips_opts.warn_about_macros)
2915         subtype |= RELAX_NOMACRO;
2916       if (mips_macro_warning.delay_slot_p)
2917         subtype |= RELAX_DELAY_SLOT;
2918
2919       if (mips_macro_warning.sizes[0] > 4 && mips_macro_warning.sizes[1] > 4)
2920         {
2921           /* Either the macro has a single implementation or both
2922              implementations are longer than 4 bytes.  Emit the
2923              warning now.  */
2924           const char *msg = macro_warning (subtype);
2925           if (msg != 0)
2926             as_warn (msg);
2927         }
2928       else
2929         {
2930           /* One implementation might need a warning but the other
2931              definitely doesn't.  */
2932           mips_macro_warning.first_frag->fr_subtype |= subtype;
2933         }
2934     }
2935 }
2936
2937 /* Read a macro's relocation codes from *ARGS and store them in *R.
2938    The first argument in *ARGS will be either the code for a single
2939    relocation or -1 followed by the three codes that make up a
2940    composite relocation.  */
2941
2942 static void
2943 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
2944 {
2945   int i, next;
2946
2947   next = va_arg (*args, int);
2948   if (next >= 0)
2949     r[0] = (bfd_reloc_code_real_type) next;
2950   else
2951     for (i = 0; i < 3; i++)
2952       r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
2953 }
2954
2955 /* Build an instruction created by a macro expansion.  This is passed
2956    a pointer to the count of instructions created so far, an
2957    expression, the name of the instruction to build, an operand format
2958    string, and corresponding arguments.  */
2959
2960 static void
2961 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
2962 {
2963   const struct mips_opcode *mo;
2964   struct mips_cl_insn insn;
2965   bfd_reloc_code_real_type r[3];
2966   va_list args;
2967
2968   va_start (args, fmt);
2969
2970   if (mips_opts.mips16)
2971     {
2972       mips16_macro_build (ep, name, fmt, args);
2973       va_end (args);
2974       return;
2975     }
2976
2977   r[0] = BFD_RELOC_UNUSED;
2978   r[1] = BFD_RELOC_UNUSED;
2979   r[2] = BFD_RELOC_UNUSED;
2980   mo = (struct mips_opcode *) hash_find (op_hash, name);
2981   assert (mo);
2982   assert (strcmp (name, mo->name) == 0);
2983
2984   /* Search until we get a match for NAME.  It is assumed here that
2985      macros will never generate MDMX or MIPS-3D instructions.  */
2986   while (strcmp (fmt, mo->args) != 0
2987          || mo->pinfo == INSN_MACRO
2988          || !OPCODE_IS_MEMBER (mo,
2989                                (mips_opts.isa
2990                                 | (file_ase_mips16 ? INSN_MIPS16 : 0)),
2991                                mips_opts.arch)
2992          || (mips_opts.arch == CPU_R4650 && (mo->pinfo & FP_D) != 0))
2993     {
2994       ++mo;
2995       assert (mo->name);
2996       assert (strcmp (name, mo->name) == 0);
2997     }
2998
2999   create_insn (&insn, mo);
3000   for (;;)
3001     {
3002       switch (*fmt++)
3003         {
3004         case '\0':
3005           break;
3006
3007         case ',':
3008         case '(':
3009         case ')':
3010           continue;
3011
3012         case '+':
3013           switch (*fmt++)
3014             {
3015             case 'A':
3016             case 'E':
3017               INSERT_OPERAND (SHAMT, insn, va_arg (args, int));
3018               continue;
3019
3020             case 'B':
3021             case 'F':
3022               /* Note that in the macro case, these arguments are already
3023                  in MSB form.  (When handling the instruction in the
3024                  non-macro case, these arguments are sizes from which
3025                  MSB values must be calculated.)  */
3026               INSERT_OPERAND (INSMSB, insn, va_arg (args, int));
3027               continue;
3028
3029             case 'C':
3030             case 'G':
3031             case 'H':
3032               /* Note that in the macro case, these arguments are already
3033                  in MSBD form.  (When handling the instruction in the
3034                  non-macro case, these arguments are sizes from which
3035                  MSBD values must be calculated.)  */
3036               INSERT_OPERAND (EXTMSBD, insn, va_arg (args, int));
3037               continue;
3038
3039             default:
3040               internalError ();
3041             }
3042           continue;
3043
3044         case 't':
3045         case 'w':
3046         case 'E':
3047           INSERT_OPERAND (RT, insn, va_arg (args, int));
3048           continue;
3049
3050         case 'c':
3051           INSERT_OPERAND (CODE, insn, va_arg (args, int));
3052           continue;
3053
3054         case 'T':
3055         case 'W':
3056           INSERT_OPERAND (FT, insn, va_arg (args, int));
3057           continue;
3058
3059         case 'd':
3060         case 'G':
3061         case 'K':
3062           INSERT_OPERAND (RD, insn, va_arg (args, int));
3063           continue;
3064
3065         case 'U':
3066           {
3067             int tmp = va_arg (args, int);
3068
3069             INSERT_OPERAND (RT, insn, tmp);
3070             INSERT_OPERAND (RD, insn, tmp);
3071             continue;
3072           }
3073
3074         case 'V':
3075         case 'S':
3076           INSERT_OPERAND (FS, insn, va_arg (args, int));
3077           continue;
3078
3079         case 'z':
3080           continue;
3081
3082         case '<':
3083           INSERT_OPERAND (SHAMT, insn, va_arg (args, int));
3084           continue;
3085
3086         case 'D':
3087           INSERT_OPERAND (FD, insn, va_arg (args, int));
3088           continue;
3089
3090         case 'B':
3091           INSERT_OPERAND (CODE20, insn, va_arg (args, int));
3092           continue;
3093
3094         case 'J':
3095           INSERT_OPERAND (CODE19, insn, va_arg (args, int));
3096           continue;
3097
3098         case 'q':
3099           INSERT_OPERAND (CODE2, insn, va_arg (args, int));
3100           continue;
3101
3102         case 'b':
3103         case 's':
3104         case 'r':
3105         case 'v':
3106           INSERT_OPERAND (RS, insn, va_arg (args, int));
3107           continue;
3108
3109         case 'i':
3110         case 'j':
3111         case 'o':
3112           macro_read_relocs (&args, r);
3113           assert (*r == BFD_RELOC_GPREL16
3114                   || *r == BFD_RELOC_MIPS_LITERAL
3115                   || *r == BFD_RELOC_MIPS_HIGHER
3116                   || *r == BFD_RELOC_HI16_S
3117                   || *r == BFD_RELOC_LO16
3118                   || *r == BFD_RELOC_MIPS_GOT16
3119                   || *r == BFD_RELOC_MIPS_CALL16
3120                   || *r == BFD_RELOC_MIPS_GOT_DISP
3121                   || *r == BFD_RELOC_MIPS_GOT_PAGE
3122                   || *r == BFD_RELOC_MIPS_GOT_OFST
3123                   || *r == BFD_RELOC_MIPS_GOT_LO16
3124                   || *r == BFD_RELOC_MIPS_CALL_LO16);
3125           continue;
3126
3127         case 'u':
3128           macro_read_relocs (&args, r);
3129           assert (ep != NULL
3130                   && (ep->X_op == O_constant
3131                       || (ep->X_op == O_symbol
3132                           && (*r == BFD_RELOC_MIPS_HIGHEST
3133                               || *r == BFD_RELOC_HI16_S
3134                               || *r == BFD_RELOC_HI16
3135                               || *r == BFD_RELOC_GPREL16
3136                               || *r == BFD_RELOC_MIPS_GOT_HI16
3137                               || *r == BFD_RELOC_MIPS_CALL_HI16))));
3138           continue;
3139
3140         case 'p':
3141           assert (ep != NULL);
3142           /*
3143            * This allows macro() to pass an immediate expression for
3144            * creating short branches without creating a symbol.
3145            * Note that the expression still might come from the assembly
3146            * input, in which case the value is not checked for range nor
3147            * is a relocation entry generated (yuck).
3148            */
3149           if (ep->X_op == O_constant)
3150             {
3151               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
3152               ep = NULL;
3153             }
3154           else
3155             *r = BFD_RELOC_16_PCREL_S2;
3156           continue;
3157
3158         case 'a':
3159           assert (ep != NULL);
3160           *r = BFD_RELOC_MIPS_JMP;
3161           continue;
3162
3163         case 'C':
3164           insn.insn_opcode |= va_arg (args, unsigned long);
3165           continue;
3166
3167         default:
3168           internalError ();
3169         }
3170       break;
3171     }
3172   va_end (args);
3173   assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
3174
3175   append_insn (&insn, ep, r);
3176 }
3177
3178 static void
3179 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
3180                     va_list args)
3181 {
3182   struct mips_opcode *mo;
3183   struct mips_cl_insn insn;
3184   bfd_reloc_code_real_type r[3]
3185     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
3186
3187   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
3188   assert (mo);
3189   assert (strcmp (name, mo->name) == 0);
3190
3191   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
3192     {
3193       ++mo;
3194       assert (mo->name);
3195       assert (strcmp (name, mo->name) == 0);
3196     }
3197
3198   create_insn (&insn, mo);
3199   for (;;)
3200     {
3201       int c;
3202
3203       c = *fmt++;
3204       switch (c)
3205         {
3206         case '\0':
3207           break;
3208
3209         case ',':
3210         case '(':
3211         case ')':
3212           continue;
3213
3214         case 'y':
3215         case 'w':
3216           MIPS16_INSERT_OPERAND (RY, insn, va_arg (args, int));
3217           continue;
3218
3219         case 'x':
3220         case 'v':
3221           MIPS16_INSERT_OPERAND (RX, insn, va_arg (args, int));
3222           continue;
3223
3224         case 'z':
3225           MIPS16_INSERT_OPERAND (RZ, insn, va_arg (args, int));
3226           continue;
3227
3228         case 'Z':
3229           MIPS16_INSERT_OPERAND (MOVE32Z, insn, va_arg (args, int));
3230           continue;
3231
3232         case '0':
3233         case 'S':
3234         case 'P':
3235         case 'R':
3236           continue;
3237
3238         case 'X':
3239           MIPS16_INSERT_OPERAND (REGR32, insn, va_arg (args, int));
3240           continue;
3241
3242         case 'Y':
3243           {
3244             int regno;
3245
3246             regno = va_arg (args, int);
3247             regno = ((regno & 7) << 2) | ((regno & 0x18) >> 3);
3248             insn.insn_opcode |= regno << MIPS16OP_SH_REG32R;
3249           }
3250           continue;
3251
3252         case '<':
3253         case '>':
3254         case '4':
3255         case '5':
3256         case 'H':
3257         case 'W':
3258         case 'D':
3259         case 'j':
3260         case '8':
3261         case 'V':
3262         case 'C':
3263         case 'U':
3264         case 'k':
3265         case 'K':
3266         case 'p':
3267         case 'q':
3268           {
3269             assert (ep != NULL);
3270
3271             if (ep->X_op != O_constant)
3272               *r = (int) BFD_RELOC_UNUSED + c;
3273             else
3274               {
3275                 mips16_immed (NULL, 0, c, ep->X_add_number, FALSE, FALSE,
3276                               FALSE, &insn.insn_opcode, &insn.use_extend,
3277                               &insn.extend);
3278                 ep = NULL;
3279                 *r = BFD_RELOC_UNUSED;
3280               }
3281           }
3282           continue;
3283
3284         case '6':
3285           MIPS16_INSERT_OPERAND (IMM6, insn, va_arg (args, int));
3286           continue;
3287         }
3288
3289       break;
3290     }
3291
3292   assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
3293
3294   append_insn (&insn, ep, r);
3295 }
3296
3297 /*
3298  * Sign-extend 32-bit mode constants that have bit 31 set and all
3299  * higher bits unset.
3300  */
3301 static void
3302 normalize_constant_expr (expressionS *ex)
3303 {
3304   if (ex->X_op == O_constant
3305       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
3306     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
3307                         - 0x80000000);
3308 }
3309
3310 /*
3311  * Sign-extend 32-bit mode address offsets that have bit 31 set and
3312  * all higher bits unset.
3313  */
3314 static void
3315 normalize_address_expr (expressionS *ex)
3316 {
3317   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
3318         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
3319       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
3320     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
3321                         - 0x80000000);
3322 }
3323
3324 /*
3325  * Generate a "jalr" instruction with a relocation hint to the called
3326  * function.  This occurs in NewABI PIC code.
3327  */
3328 static void
3329 macro_build_jalr (expressionS *ep)
3330 {
3331   char *f = NULL;
3332
3333   if (HAVE_NEWABI)
3334     {
3335       frag_grow (8);
3336       f = frag_more (0);
3337     }
3338   macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
3339   if (HAVE_NEWABI)
3340     fix_new_exp (frag_now, f - frag_now->fr_literal,
3341                  4, ep, FALSE, BFD_RELOC_MIPS_JALR);
3342 }
3343
3344 /*
3345  * Generate a "lui" instruction.
3346  */
3347 static void
3348 macro_build_lui (expressionS *ep, int regnum)
3349 {
3350   expressionS high_expr;
3351   const struct mips_opcode *mo;
3352   struct mips_cl_insn insn;
3353   bfd_reloc_code_real_type r[3]
3354     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
3355   const char *name = "lui";
3356   const char *fmt = "t,u";
3357
3358   assert (! mips_opts.mips16);
3359
3360   high_expr = *ep;
3361
3362   if (high_expr.X_op == O_constant)
3363     {
3364       /* we can compute the instruction now without a relocation entry */
3365       high_expr.X_add_number = ((high_expr.X_add_number + 0x8000)
3366                                 >> 16) & 0xffff;
3367       *r = BFD_RELOC_UNUSED;
3368     }
3369   else
3370     {
3371       assert (ep->X_op == O_symbol);
3372       /* _gp_disp is a special case, used from s_cpload.
3373          __gnu_local_gp is used if mips_no_shared.  */
3374       assert (mips_pic == NO_PIC
3375               || (! HAVE_NEWABI
3376                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
3377               || (! mips_in_shared
3378                   && strcmp (S_GET_NAME (ep->X_add_symbol),
3379                              "__gnu_local_gp") == 0));
3380       *r = BFD_RELOC_HI16_S;
3381     }
3382
3383   mo = hash_find (op_hash, name);
3384   assert (strcmp (name, mo->name) == 0);
3385   assert (strcmp (fmt, mo->args) == 0);
3386   create_insn (&insn, mo);
3387
3388   insn.insn_opcode = insn.insn_mo->match;
3389   INSERT_OPERAND (RT, insn, regnum);
3390   if (*r == BFD_RELOC_UNUSED)
3391     {
3392       insn.insn_opcode |= high_expr.X_add_number;
3393       append_insn (&insn, NULL, r);
3394     }
3395   else
3396     append_insn (&insn, &high_expr, r);
3397 }
3398
3399 /* Generate a sequence of instructions to do a load or store from a constant
3400    offset off of a base register (breg) into/from a target register (treg),
3401    using AT if necessary.  */
3402 static void
3403 macro_build_ldst_constoffset (expressionS *ep, const char *op,
3404                               int treg, int breg, int dbl)
3405 {
3406   assert (ep->X_op == O_constant);
3407
3408   /* Sign-extending 32-bit constants makes their handling easier.  */
3409   if (!dbl)
3410     normalize_constant_expr (ep);
3411
3412   /* Right now, this routine can only handle signed 32-bit constants.  */
3413   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
3414     as_warn (_("operand overflow"));
3415
3416   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
3417     {
3418       /* Signed 16-bit offset will fit in the op.  Easy!  */
3419       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
3420     }
3421   else
3422     {
3423       /* 32-bit offset, need multiple instructions and AT, like:
3424            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
3425            addu     $tempreg,$tempreg,$breg
3426            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
3427          to handle the complete offset.  */
3428       macro_build_lui (ep, AT);
3429       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
3430       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
3431
3432       if (mips_opts.noat)
3433         as_bad (_("Macro used $at after \".set noat\""));
3434     }
3435 }
3436
3437 /*                      set_at()
3438  * Generates code to set the $at register to true (one)
3439  * if reg is less than the immediate expression.
3440  */
3441 static void
3442 set_at (int reg, int unsignedp)
3443 {
3444   if (imm_expr.X_op == O_constant
3445       && imm_expr.X_add_number >= -0x8000
3446       && imm_expr.X_add_number < 0x8000)
3447     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
3448                  AT, reg, BFD_RELOC_LO16);
3449   else
3450     {
3451       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
3452       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
3453     }
3454 }
3455
3456 /* Warn if an expression is not a constant.  */
3457
3458 static void
3459 check_absolute_expr (struct mips_cl_insn *ip, expressionS *ex)
3460 {
3461   if (ex->X_op == O_big)
3462     as_bad (_("unsupported large constant"));
3463   else if (ex->X_op != O_constant)
3464     as_bad (_("Instruction %s requires absolute expression"),
3465             ip->insn_mo->name);
3466
3467   if (HAVE_32BIT_GPRS)
3468     normalize_constant_expr (ex);
3469 }
3470
3471 /* Count the leading zeroes by performing a binary chop. This is a
3472    bulky bit of source, but performance is a LOT better for the
3473    majority of values than a simple loop to count the bits:
3474        for (lcnt = 0; (lcnt < 32); lcnt++)
3475          if ((v) & (1 << (31 - lcnt)))
3476            break;
3477   However it is not code size friendly, and the gain will drop a bit
3478   on certain cached systems.
3479 */
3480 #define COUNT_TOP_ZEROES(v)             \
3481   (((v) & ~0xffff) == 0                 \
3482    ? ((v) & ~0xff) == 0                 \
3483      ? ((v) & ~0xf) == 0                \
3484        ? ((v) & ~0x3) == 0              \
3485          ? ((v) & ~0x1) == 0            \
3486            ? !(v)                       \
3487              ? 32                       \
3488              : 31                       \
3489            : 30                         \
3490          : ((v) & ~0x7) == 0            \
3491            ? 29                         \
3492            : 28                         \
3493        : ((v) & ~0x3f) == 0             \
3494          ? ((v) & ~0x1f) == 0           \
3495            ? 27                         \
3496            : 26                         \
3497          : ((v) & ~0x7f) == 0           \
3498            ? 25                         \
3499            : 24                         \
3500      : ((v) & ~0xfff) == 0              \
3501        ? ((v) & ~0x3ff) == 0            \
3502          ? ((v) & ~0x1ff) == 0          \
3503            ? 23                         \
3504            : 22                         \
3505          : ((v) & ~0x7ff) == 0          \
3506            ? 21                         \
3507            : 20                         \
3508        : ((v) & ~0x3fff) == 0           \
3509          ? ((v) & ~0x1fff) == 0         \
3510            ? 19                         \
3511            : 18                         \
3512          : ((v) & ~0x7fff) == 0         \
3513            ? 17                         \
3514            : 16                         \
3515    : ((v) & ~0xffffff) == 0             \
3516      ? ((v) & ~0xfffff) == 0            \
3517        ? ((v) & ~0x3ffff) == 0          \
3518          ? ((v) & ~0x1ffff) == 0        \
3519            ? 15                         \
3520            : 14                         \
3521          : ((v) & ~0x7ffff) == 0        \
3522            ? 13                         \
3523            : 12                         \
3524        : ((v) & ~0x3fffff) == 0         \
3525          ? ((v) & ~0x1fffff) == 0       \
3526            ? 11                         \
3527            : 10                         \
3528          : ((v) & ~0x7fffff) == 0       \
3529            ? 9                          \
3530            : 8                          \
3531      : ((v) & ~0xfffffff) == 0          \
3532        ? ((v) & ~0x3ffffff) == 0        \
3533          ? ((v) & ~0x1ffffff) == 0      \
3534            ? 7                          \
3535            : 6                          \
3536          : ((v) & ~0x7ffffff) == 0      \
3537            ? 5                          \
3538            : 4                          \
3539        : ((v) & ~0x3fffffff) == 0       \
3540          ? ((v) & ~0x1fffffff) == 0     \
3541            ? 3                          \
3542            : 2                          \
3543          : ((v) & ~0x7fffffff) == 0     \
3544            ? 1                          \
3545            : 0)
3546
3547 /*                      load_register()
3548  *  This routine generates the least number of instructions necessary to load
3549  *  an absolute expression value into a register.
3550  */
3551 static void
3552 load_register (int reg, expressionS *ep, int dbl)
3553 {
3554   int freg;
3555   expressionS hi32, lo32;
3556
3557   if (ep->X_op != O_big)
3558     {
3559       assert (ep->X_op == O_constant);
3560
3561       /* Sign-extending 32-bit constants makes their handling easier.  */
3562       if (!dbl)
3563         normalize_constant_expr (ep);
3564
3565       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
3566         {
3567           /* We can handle 16 bit signed values with an addiu to
3568              $zero.  No need to ever use daddiu here, since $zero and
3569              the result are always correct in 32 bit mode.  */
3570           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
3571           return;
3572         }
3573       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
3574         {
3575           /* We can handle 16 bit unsigned values with an ori to
3576              $zero.  */
3577           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
3578           return;
3579         }
3580       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
3581         {
3582           /* 32 bit values require an lui.  */
3583           macro_build (ep, "lui", "t,u", reg, BFD_RELOC_HI16);
3584           if ((ep->X_add_number & 0xffff) != 0)
3585             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
3586           return;
3587         }
3588     }
3589
3590   /* The value is larger than 32 bits.  */
3591
3592   if (!dbl || HAVE_32BIT_GPRS)
3593     {
3594       char value[32];
3595
3596       sprintf_vma (value, ep->X_add_number);
3597       as_bad (_("Number (0x%s) larger than 32 bits"), value);
3598       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
3599       return;
3600     }
3601
3602   if (ep->X_op != O_big)
3603     {
3604       hi32 = *ep;
3605       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
3606       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
3607       hi32.X_add_number &= 0xffffffff;
3608       lo32 = *ep;
3609       lo32.X_add_number &= 0xffffffff;
3610     }
3611   else
3612     {
3613       assert (ep->X_add_number > 2);
3614       if (ep->X_add_number == 3)
3615         generic_bignum[3] = 0;
3616       else if (ep->X_add_number > 4)
3617         as_bad (_("Number larger than 64 bits"));
3618       lo32.X_op = O_constant;
3619       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
3620       hi32.X_op = O_constant;
3621       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
3622     }
3623
3624   if (hi32.X_add_number == 0)
3625     freg = 0;
3626   else
3627     {
3628       int shift, bit;
3629       unsigned long hi, lo;
3630
3631       if (hi32.X_add_number == (offsetT) 0xffffffff)
3632         {
3633           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
3634             {
3635               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
3636               return;
3637             }
3638           if (lo32.X_add_number & 0x80000000)
3639             {
3640               macro_build (&lo32, "lui", "t,u", reg, BFD_RELOC_HI16);
3641               if (lo32.X_add_number & 0xffff)
3642                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
3643               return;
3644             }
3645         }
3646
3647       /* Check for 16bit shifted constant.  We know that hi32 is
3648          non-zero, so start the mask on the first bit of the hi32
3649          value.  */
3650       shift = 17;
3651       do
3652         {
3653           unsigned long himask, lomask;
3654
3655           if (shift < 32)
3656             {
3657               himask = 0xffff >> (32 - shift);
3658               lomask = (0xffff << shift) & 0xffffffff;
3659             }
3660           else
3661             {
3662               himask = 0xffff << (shift - 32);
3663               lomask = 0;
3664             }
3665           if ((hi32.X_add_number & ~(offsetT) himask) == 0
3666               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
3667             {
3668               expressionS tmp;
3669
3670               tmp.X_op = O_constant;
3671               if (shift < 32)
3672                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
3673                                     | (lo32.X_add_number >> shift));
3674               else
3675                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
3676               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
3677               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", "d,w,<",
3678                            reg, reg, (shift >= 32) ? shift - 32 : shift);
3679               return;
3680             }
3681           ++shift;
3682         }
3683       while (shift <= (64 - 16));
3684
3685       /* Find the bit number of the lowest one bit, and store the
3686          shifted value in hi/lo.  */
3687       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
3688       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
3689       if (lo != 0)
3690         {
3691           bit = 0;
3692           while ((lo & 1) == 0)
3693             {
3694               lo >>= 1;
3695               ++bit;
3696             }
3697           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
3698           hi >>= bit;
3699         }
3700       else
3701         {
3702           bit = 32;
3703           while ((hi & 1) == 0)
3704             {
3705               hi >>= 1;
3706               ++bit;
3707             }
3708           lo = hi;
3709           hi = 0;
3710         }
3711
3712       /* Optimize if the shifted value is a (power of 2) - 1.  */
3713       if ((hi == 0 && ((lo + 1) & lo) == 0)
3714           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
3715         {
3716           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
3717           if (shift != 0)
3718             {
3719               expressionS tmp;
3720
3721               /* This instruction will set the register to be all
3722                  ones.  */
3723               tmp.X_op = O_constant;
3724               tmp.X_add_number = (offsetT) -1;
3725               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
3726               if (bit != 0)
3727                 {
3728                   bit += shift;
3729                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", "d,w,<",
3730                                reg, reg, (bit >= 32) ? bit - 32 : bit);
3731                 }
3732               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", "d,w,<",
3733                            reg, reg, (shift >= 32) ? shift - 32 : shift);
3734               return;
3735             }
3736         }
3737
3738       /* Sign extend hi32 before calling load_register, because we can
3739          generally get better code when we load a sign extended value.  */
3740       if ((hi32.X_add_number & 0x80000000) != 0)
3741         hi32.X_add_number |= ~(offsetT) 0xffffffff;
3742       load_register (reg, &hi32, 0);
3743       freg = reg;
3744     }
3745   if ((lo32.X_add_number & 0xffff0000) == 0)
3746     {
3747       if (freg != 0)
3748         {
3749           macro_build (NULL, "dsll32", "d,w,<", reg, freg, 0);
3750           freg = reg;
3751         }
3752     }
3753   else
3754     {
3755       expressionS mid16;
3756
3757       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
3758         {
3759           macro_build (&lo32, "lui", "t,u", reg, BFD_RELOC_HI16);
3760           macro_build (NULL, "dsrl32", "d,w,<", reg, reg, 0);
3761           return;
3762         }
3763
3764       if (freg != 0)
3765         {
3766           macro_build (NULL, "dsll", "d,w,<", reg, freg, 16);
3767           freg = reg;
3768         }
3769       mid16 = lo32;
3770       mid16.X_add_number >>= 16;
3771       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
3772       macro_build (NULL, "dsll", "d,w,<", reg, reg, 16);
3773       freg = reg;
3774     }
3775   if ((lo32.X_add_number & 0xffff) != 0)
3776     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
3777 }
3778
3779 static inline void
3780 load_delay_nop (void)
3781 {
3782   if (!gpr_interlocks)
3783     macro_build (NULL, "nop", "");
3784 }
3785
3786 /* Load an address into a register.  */
3787
3788 static void
3789 load_address (int reg, expressionS *ep, int *used_at)
3790 {
3791   if (ep->X_op != O_constant
3792       && ep->X_op != O_symbol)
3793     {
3794       as_bad (_("expression too complex"));
3795       ep->X_op = O_constant;
3796     }
3797
3798   if (ep->X_op == O_constant)
3799     {
3800       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
3801       return;
3802     }
3803
3804   if (mips_pic == NO_PIC)
3805     {
3806       /* If this is a reference to a GP relative symbol, we want
3807            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
3808          Otherwise we want
3809            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
3810            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
3811          If we have an addend, we always use the latter form.
3812
3813          With 64bit address space and a usable $at we want
3814            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
3815            lui          $at,<sym>               (BFD_RELOC_HI16_S)
3816            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
3817            daddiu       $at,<sym>               (BFD_RELOC_LO16)
3818            dsll32       $reg,0
3819            daddu        $reg,$reg,$at
3820
3821          If $at is already in use, we use a path which is suboptimal
3822          on superscalar processors.
3823            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
3824            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
3825            dsll         $reg,16
3826            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
3827            dsll         $reg,16
3828            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
3829
3830          For GP relative symbols in 64bit address space we can use
3831          the same sequence as in 32bit address space.  */
3832       if (HAVE_64BIT_SYMBOLS)
3833         {
3834           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
3835               && !nopic_need_relax (ep->X_add_symbol, 1))
3836             {
3837               relax_start (ep->X_add_symbol);
3838               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
3839                            mips_gp_register, BFD_RELOC_GPREL16);
3840               relax_switch ();
3841             }
3842
3843           if (*used_at == 0 && !mips_opts.noat)
3844             {
3845               macro_build (ep, "lui", "t,u", reg, BFD_RELOC_MIPS_HIGHEST);
3846               macro_build (ep, "lui", "t,u", AT, BFD_RELOC_HI16_S);
3847               macro_build (ep, "daddiu", "t,r,j", reg, reg,
3848                            BFD_RELOC_MIPS_HIGHER);
3849               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
3850               macro_build (NULL, "dsll32", "d,w,<", reg, reg, 0);
3851               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
3852               *used_at = 1;
3853             }
3854           else
3855             {
3856               macro_build (ep, "lui", "t,u", reg, BFD_RELOC_MIPS_HIGHEST);
3857               macro_build (ep, "daddiu", "t,r,j", reg, reg,
3858                            BFD_RELOC_MIPS_HIGHER);
3859               macro_build (NULL, "dsll", "d,w,<", reg, reg, 16);
3860               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
3861               macro_build (NULL, "dsll", "d,w,<", reg, reg, 16);
3862               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
3863             }
3864
3865           if (mips_relax.sequence)
3866             relax_end ();
3867         }
3868       else
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           macro_build_lui (ep, reg);
3879           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
3880                        reg, reg, BFD_RELOC_LO16);
3881           if (mips_relax.sequence)
3882             relax_end ();
3883         }
3884     }
3885   else if (mips_pic == SVR4_PIC && ! mips_big_got)
3886     {
3887       expressionS ex;
3888
3889       /* If this is a reference to an external symbol, we want
3890            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
3891          Otherwise we want
3892            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
3893            nop
3894            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
3895          If there is a constant, it must be added in after.
3896
3897          If we have NewABI, we want
3898            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
3899          unless we're referencing a global symbol with a non-zero
3900          offset, in which case cst must be added separately.  */
3901       if (HAVE_NEWABI)
3902         {
3903           if (ep->X_add_number)
3904             {
3905               ex.X_add_number = ep->X_add_number;
3906               ep->X_add_number = 0;
3907               relax_start (ep->X_add_symbol);
3908               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
3909                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
3910               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
3911                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
3912               ex.X_op = O_constant;
3913               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
3914                            reg, reg, BFD_RELOC_LO16);
3915               ep->X_add_number = ex.X_add_number;
3916               relax_switch ();
3917             }
3918           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
3919                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
3920           if (mips_relax.sequence)
3921             relax_end ();
3922         }
3923       else
3924         {
3925           ex.X_add_number = ep->X_add_number;
3926           ep->X_add_number = 0;
3927           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
3928                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
3929           load_delay_nop ();
3930           relax_start (ep->X_add_symbol);
3931           relax_switch ();
3932           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
3933                        BFD_RELOC_LO16);
3934           relax_end ();
3935
3936           if (ex.X_add_number != 0)
3937             {
3938               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
3939                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
3940               ex.X_op = O_constant;
3941               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
3942                            reg, reg, BFD_RELOC_LO16);
3943             }
3944         }
3945     }
3946   else if (mips_pic == SVR4_PIC)
3947     {
3948       expressionS ex;
3949
3950       /* This is the large GOT case.  If this is a reference to an
3951          external symbol, we want
3952            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
3953            addu         $reg,$reg,$gp
3954            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
3955
3956          Otherwise, for a reference to a local symbol in old ABI, we want
3957            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
3958            nop
3959            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
3960          If there is a constant, it must be added in after.
3961
3962          In the NewABI, for local symbols, with or without offsets, we want:
3963            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
3964            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
3965       */
3966       if (HAVE_NEWABI)
3967         {
3968           ex.X_add_number = ep->X_add_number;
3969           ep->X_add_number = 0;
3970           relax_start (ep->X_add_symbol);
3971           macro_build (ep, "lui", "t,u", reg, BFD_RELOC_MIPS_GOT_HI16);
3972           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
3973                        reg, reg, mips_gp_register);
3974           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
3975                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
3976           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
3977             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
3978           else if (ex.X_add_number)
3979             {
3980               ex.X_op = O_constant;
3981               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
3982                            BFD_RELOC_LO16);
3983             }
3984
3985           ep->X_add_number = ex.X_add_number;
3986           relax_switch ();
3987           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
3988                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
3989           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
3990                        BFD_RELOC_MIPS_GOT_OFST);
3991           relax_end ();
3992         }
3993       else
3994         {
3995           ex.X_add_number = ep->X_add_number;
3996           ep->X_add_number = 0;
3997           relax_start (ep->X_add_symbol);
3998           macro_build (ep, "lui", "t,u", reg, BFD_RELOC_MIPS_GOT_HI16);
3999           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
4000                        reg, reg, mips_gp_register);
4001           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
4002                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
4003           relax_switch ();
4004           if (reg_needs_delay (mips_gp_register))
4005             {
4006               /* We need a nop before loading from $gp.  This special
4007                  check is required because the lui which starts the main
4008                  instruction stream does not refer to $gp, and so will not
4009                  insert the nop which may be required.  */
4010               macro_build (NULL, "nop", "");
4011             }
4012           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
4013                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
4014           load_delay_nop ();
4015           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
4016                        BFD_RELOC_LO16);
4017           relax_end ();
4018
4019           if (ex.X_add_number != 0)
4020             {
4021               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
4022                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
4023               ex.X_op = O_constant;
4024               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
4025                            BFD_RELOC_LO16);
4026             }
4027         }
4028     }
4029   else
4030     abort ();
4031
4032   if (mips_opts.noat && *used_at == 1)
4033     as_bad (_("Macro used $at after \".set noat\""));
4034 }
4035
4036 /* Move the contents of register SOURCE into register DEST.  */
4037
4038 static void
4039 move_register (int dest, int source)
4040 {
4041   macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
4042                dest, source, 0);
4043 }
4044
4045 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
4046    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
4047    The two alternatives are:
4048
4049    Global symbol                Local sybmol
4050    -------------                ------------
4051    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
4052    ...                          ...
4053    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
4054
4055    load_got_offset emits the first instruction and add_got_offset
4056    emits the second for a 16-bit offset or add_got_offset_hilo emits
4057    a sequence to add a 32-bit offset using a scratch register.  */
4058
4059 static void
4060 load_got_offset (int dest, expressionS *local)
4061 {
4062   expressionS global;
4063
4064   global = *local;
4065   global.X_add_number = 0;
4066
4067   relax_start (local->X_add_symbol);
4068   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
4069                BFD_RELOC_MIPS_GOT16, mips_gp_register);
4070   relax_switch ();
4071   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
4072                BFD_RELOC_MIPS_GOT16, mips_gp_register);
4073   relax_end ();
4074 }
4075
4076 static void
4077 add_got_offset (int dest, expressionS *local)
4078 {
4079   expressionS global;
4080
4081   global.X_op = O_constant;
4082   global.X_op_symbol = NULL;
4083   global.X_add_symbol = NULL;
4084   global.X_add_number = local->X_add_number;
4085
4086   relax_start (local->X_add_symbol);
4087   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
4088                dest, dest, BFD_RELOC_LO16);
4089   relax_switch ();
4090   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
4091   relax_end ();
4092 }
4093
4094 static void
4095 add_got_offset_hilo (int dest, expressionS *local, int tmp)
4096 {
4097   expressionS global;
4098   int hold_mips_optimize;
4099
4100   global.X_op = O_constant;
4101   global.X_op_symbol = NULL;
4102   global.X_add_symbol = NULL;
4103   global.X_add_number = local->X_add_number;
4104
4105   relax_start (local->X_add_symbol);
4106   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
4107   relax_switch ();
4108   /* Set mips_optimize around the lui instruction to avoid
4109      inserting an unnecessary nop after the lw.  */
4110   hold_mips_optimize = mips_optimize;
4111   mips_optimize = 2;
4112   macro_build_lui (&global, tmp);
4113   mips_optimize = hold_mips_optimize;
4114   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
4115   relax_end ();
4116
4117   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
4118 }
4119
4120 /*
4121  *                      Build macros
4122  *   This routine implements the seemingly endless macro or synthesized
4123  * instructions and addressing modes in the mips assembly language. Many
4124  * of these macros are simple and are similar to each other. These could
4125  * probably be handled by some kind of table or grammar approach instead of
4126  * this verbose method. Others are not simple macros but are more like
4127  * optimizing code generation.
4128  *   One interesting optimization is when several store macros appear
4129  * consecutively that would load AT with the upper half of the same address.
4130  * The ensuing load upper instructions are ommited. This implies some kind
4131  * of global optimization. We currently only optimize within a single macro.
4132  *   For many of the load and store macros if the address is specified as a
4133  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
4134  * first load register 'at' with zero and use it as the base register. The
4135  * mips assembler simply uses register $zero. Just one tiny optimization
4136  * we're missing.
4137  */
4138 static void
4139 macro (struct mips_cl_insn *ip)
4140 {
4141   register int treg, sreg, dreg, breg;
4142   int tempreg;
4143   int mask;
4144   int used_at = 0;
4145   expressionS expr1;
4146   const char *s;
4147   const char *s2;
4148   const char *fmt;
4149   int likely = 0;
4150   int dbl = 0;
4151   int coproc = 0;
4152   int lr = 0;
4153   int imm = 0;
4154   int call = 0;
4155   int off;
4156   offsetT maxnum;
4157   bfd_reloc_code_real_type r;
4158   int hold_mips_optimize;
4159
4160   assert (! mips_opts.mips16);
4161
4162   treg = (ip->insn_opcode >> 16) & 0x1f;
4163   dreg = (ip->insn_opcode >> 11) & 0x1f;
4164   sreg = breg = (ip->insn_opcode >> 21) & 0x1f;
4165   mask = ip->insn_mo->mask;
4166
4167   expr1.X_op = O_constant;
4168   expr1.X_op_symbol = NULL;
4169   expr1.X_add_symbol = NULL;
4170   expr1.X_add_number = 1;
4171
4172   switch (mask)
4173     {
4174     case M_DABS:
4175       dbl = 1;
4176     case M_ABS:
4177       /* bgez $a0,.+12
4178          move v0,$a0
4179          sub v0,$zero,$a0
4180          */
4181
4182       start_noreorder ();
4183
4184       expr1.X_add_number = 8;
4185       macro_build (&expr1, "bgez", "s,p", sreg);
4186       if (dreg == sreg)
4187         macro_build (NULL, "nop", "", 0);
4188       else
4189         move_register (dreg, sreg);
4190       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", dreg, 0, sreg);
4191
4192       end_noreorder ();
4193       break;
4194
4195     case M_ADD_I:
4196       s = "addi";
4197       s2 = "add";
4198       goto do_addi;
4199     case M_ADDU_I:
4200       s = "addiu";
4201       s2 = "addu";
4202       goto do_addi;
4203     case M_DADD_I:
4204       dbl = 1;
4205       s = "daddi";
4206       s2 = "dadd";
4207       goto do_addi;
4208     case M_DADDU_I:
4209       dbl = 1;
4210       s = "daddiu";
4211       s2 = "daddu";
4212     do_addi:
4213       if (imm_expr.X_op == O_constant
4214           && imm_expr.X_add_number >= -0x8000
4215           && imm_expr.X_add_number < 0x8000)
4216         {
4217           macro_build (&imm_expr, s, "t,r,j", treg, sreg, BFD_RELOC_LO16);
4218           break;
4219         }
4220       used_at = 1;
4221       load_register (AT, &imm_expr, dbl);
4222       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
4223       break;
4224
4225     case M_AND_I:
4226       s = "andi";
4227       s2 = "and";
4228       goto do_bit;
4229     case M_OR_I:
4230       s = "ori";
4231       s2 = "or";
4232       goto do_bit;
4233     case M_NOR_I:
4234       s = "";
4235       s2 = "nor";
4236       goto do_bit;
4237     case M_XOR_I:
4238       s = "xori";
4239       s2 = "xor";
4240     do_bit:
4241       if (imm_expr.X_op == O_constant
4242           && imm_expr.X_add_number >= 0
4243           && imm_expr.X_add_number < 0x10000)
4244         {
4245           if (mask != M_NOR_I)
4246             macro_build (&imm_expr, s, "t,r,i", treg, sreg, BFD_RELOC_LO16);
4247           else
4248             {
4249               macro_build (&imm_expr, "ori", "t,r,i",
4250                            treg, sreg, BFD_RELOC_LO16);
4251               macro_build (NULL, "nor", "d,v,t", treg, treg, 0);
4252             }
4253           break;
4254         }
4255
4256       used_at = 1;
4257       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
4258       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
4259       break;
4260
4261     case M_BEQ_I:
4262       s = "beq";
4263       goto beq_i;
4264     case M_BEQL_I:
4265       s = "beql";
4266       likely = 1;
4267       goto beq_i;
4268     case M_BNE_I:
4269       s = "bne";
4270       goto beq_i;
4271     case M_BNEL_I:
4272       s = "bnel";
4273       likely = 1;
4274     beq_i:
4275       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
4276         {
4277           macro_build (&offset_expr, s, "s,t,p", sreg, 0);
4278           break;
4279         }
4280       used_at = 1;
4281       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
4282       macro_build (&offset_expr, s, "s,t,p", sreg, AT);
4283       break;
4284
4285     case M_BGEL:
4286       likely = 1;
4287     case M_BGE:
4288       if (treg == 0)
4289         {
4290           macro_build (&offset_expr, likely ? "bgezl" : "bgez", "s,p", sreg);
4291           break;
4292         }
4293       if (sreg == 0)
4294         {
4295           macro_build (&offset_expr, likely ? "blezl" : "blez", "s,p", treg);
4296           break;
4297         }
4298       used_at = 1;
4299       macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
4300       macro_build (&offset_expr, likely ? "beql" : "beq", "s,t,p", AT, 0);
4301       break;
4302
4303     case M_BGTL_I:
4304       likely = 1;
4305     case M_BGT_I:
4306       /* check for > max integer */
4307       maxnum = 0x7fffffff;
4308       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
4309         {
4310           maxnum <<= 16;
4311           maxnum |= 0xffff;
4312           maxnum <<= 16;
4313           maxnum |= 0xffff;
4314         }
4315       if (imm_expr.X_op == O_constant
4316           && imm_expr.X_add_number >= maxnum
4317           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
4318         {
4319         do_false:
4320           /* result is always false */
4321           if (! likely)
4322             macro_build (NULL, "nop", "", 0);
4323           else
4324             macro_build (&offset_expr, "bnel", "s,t,p", 0, 0);
4325           break;
4326         }
4327       if (imm_expr.X_op != O_constant)
4328         as_bad (_("Unsupported large constant"));
4329       ++imm_expr.X_add_number;
4330       /* FALLTHROUGH */
4331     case M_BGE_I:
4332     case M_BGEL_I:
4333       if (mask == M_BGEL_I)
4334         likely = 1;
4335       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
4336         {
4337           macro_build (&offset_expr, likely ? "bgezl" : "bgez", "s,p", sreg);
4338           break;
4339         }
4340       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
4341         {
4342           macro_build (&offset_expr, likely ? "bgtzl" : "bgtz", "s,p", sreg);
4343           break;
4344         }
4345       maxnum = 0x7fffffff;
4346       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
4347         {
4348           maxnum <<= 16;
4349           maxnum |= 0xffff;
4350           maxnum <<= 16;
4351           maxnum |= 0xffff;
4352         }
4353       maxnum = - maxnum - 1;
4354       if (imm_expr.X_op == O_constant
4355           && imm_expr.X_add_number <= maxnum
4356           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
4357         {
4358         do_true:
4359           /* result is always true */
4360           as_warn (_("Branch %s is always true"), ip->insn_mo->name);
4361           macro_build (&offset_expr, "b", "p");
4362           break;
4363         }
4364       used_at = 1;
4365       set_at (sreg, 0);
4366       macro_build (&offset_expr, likely ? "beql" : "beq", "s,t,p", AT, 0);
4367       break;
4368
4369     case M_BGEUL:
4370       likely = 1;
4371     case M_BGEU:
4372       if (treg == 0)
4373         goto do_true;
4374       if (sreg == 0)
4375         {
4376           macro_build (&offset_expr, likely ? "beql" : "beq",
4377                        "s,t,p", 0, treg);
4378           break;
4379         }
4380       used_at = 1;
4381       macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
4382       macro_build (&offset_expr, likely ? "beql" : "beq", "s,t,p", AT, 0);
4383       break;
4384
4385     case M_BGTUL_I:
4386       likely = 1;
4387     case M_BGTU_I:
4388       if (sreg == 0
4389           || (HAVE_32BIT_GPRS
4390               && imm_expr.X_op == O_constant
4391               && imm_expr.X_add_number == (offsetT) 0xffffffff))
4392         goto do_false;
4393       if (imm_expr.X_op != O_constant)
4394         as_bad (_("Unsupported large constant"));
4395       ++imm_expr.X_add_number;
4396       /* FALLTHROUGH */
4397     case M_BGEU_I:
4398     case M_BGEUL_I:
4399       if (mask == M_BGEUL_I)
4400         likely = 1;
4401       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
4402         goto do_true;
4403       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
4404         {
4405           macro_build (&offset_expr, likely ? "bnel" : "bne",
4406                        "s,t,p", sreg, 0);
4407           break;
4408         }
4409       used_at = 1;
4410       set_at (sreg, 1);
4411       macro_build (&offset_expr, likely ? "beql" : "beq", "s,t,p", AT, 0);
4412       break;
4413
4414     case M_BGTL:
4415       likely = 1;
4416     case M_BGT:
4417       if (treg == 0)
4418         {
4419           macro_build (&offset_expr, likely ? "bgtzl" : "bgtz", "s,p", sreg);
4420           break;
4421         }
4422       if (sreg == 0)
4423         {
4424           macro_build (&offset_expr, likely ? "bltzl" : "bltz", "s,p", treg);
4425           break;
4426         }
4427       used_at = 1;
4428       macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
4429       macro_build (&offset_expr, likely ? "bnel" : "bne", "s,t,p", AT, 0);
4430       break;
4431
4432     case M_BGTUL:
4433       likely = 1;
4434     case M_BGTU:
4435       if (treg == 0)
4436         {
4437           macro_build (&offset_expr, likely ? "bnel" : "bne",
4438                        "s,t,p", sreg, 0);
4439           break;
4440         }
4441       if (sreg == 0)
4442         goto do_false;
4443       used_at = 1;
4444       macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
4445       macro_build (&offset_expr, likely ? "bnel" : "bne", "s,t,p", AT, 0);
4446       break;
4447
4448     case M_BLEL:
4449       likely = 1;
4450     case M_BLE:
4451       if (treg == 0)
4452         {
4453           macro_build (&offset_expr, likely ? "blezl" : "blez", "s,p", sreg);
4454           break;
4455         }
4456       if (sreg == 0)
4457         {
4458           macro_build (&offset_expr, likely ? "bgezl" : "bgez", "s,p", treg);
4459           break;
4460         }
4461       used_at = 1;
4462       macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
4463       macro_build (&offset_expr, likely ? "beql" : "beq", "s,t,p", AT, 0);
4464       break;
4465
4466     case M_BLEL_I:
4467       likely = 1;
4468     case M_BLE_I:
4469       maxnum = 0x7fffffff;
4470       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
4471         {
4472           maxnum <<= 16;
4473           maxnum |= 0xffff;
4474           maxnum <<= 16;
4475           maxnum |= 0xffff;
4476         }
4477       if (imm_expr.X_op == O_constant
4478           && imm_expr.X_add_number >= maxnum
4479           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
4480         goto do_true;
4481       if (imm_expr.X_op != O_constant)
4482         as_bad (_("Unsupported large constant"));
4483       ++imm_expr.X_add_number;
4484       /* FALLTHROUGH */
4485     case M_BLT_I:
4486     case M_BLTL_I:
4487       if (mask == M_BLTL_I)
4488         likely = 1;
4489       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
4490         {
4491           macro_build (&offset_expr, likely ? "bltzl" : "bltz", "s,p", sreg);
4492           break;
4493         }
4494       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
4495         {
4496           macro_build (&offset_expr, likely ? "blezl" : "blez", "s,p", sreg);
4497           break;
4498         }
4499       used_at = 1;
4500       set_at (sreg, 0);
4501       macro_build (&offset_expr, likely ? "bnel" : "bne", "s,t,p", AT, 0);
4502       break;
4503
4504     case M_BLEUL:
4505       likely = 1;
4506     case M_BLEU:
4507       if (treg == 0)
4508         {
4509           macro_build (&offset_expr, likely ? "beql" : "beq",
4510                        "s,t,p", sreg, 0);
4511           break;
4512         }
4513       if (sreg == 0)
4514         goto do_true;
4515       used_at = 1;
4516       macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
4517       macro_build (&offset_expr, likely ? "beql" : "beq", "s,t,p", AT, 0);
4518       break;
4519
4520     case M_BLEUL_I:
4521       likely = 1;
4522     case M_BLEU_I:
4523       if (sreg == 0
4524           || (HAVE_32BIT_GPRS
4525               && imm_expr.X_op == O_constant
4526               && imm_expr.X_add_number == (offsetT) 0xffffffff))
4527         goto do_true;
4528       if (imm_expr.X_op != O_constant)
4529         as_bad (_("Unsupported large constant"));
4530       ++imm_expr.X_add_number;
4531       /* FALLTHROUGH */
4532     case M_BLTU_I:
4533     case M_BLTUL_I:
4534       if (mask == M_BLTUL_I)
4535         likely = 1;
4536       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
4537         goto do_false;
4538       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
4539         {
4540           macro_build (&offset_expr, likely ? "beql" : "beq",
4541                        "s,t,p", sreg, 0);
4542           break;
4543         }
4544       used_at = 1;
4545       set_at (sreg, 1);
4546       macro_build (&offset_expr, likely ? "bnel" : "bne", "s,t,p", AT, 0);
4547       break;
4548
4549     case M_BLTL:
4550       likely = 1;
4551     case M_BLT:
4552       if (treg == 0)
4553         {
4554           macro_build (&offset_expr, likely ? "bltzl" : "bltz", "s,p", sreg);
4555           break;
4556         }
4557       if (sreg == 0)
4558         {
4559           macro_build (&offset_expr, likely ? "bgtzl" : "bgtz", "s,p", treg);
4560           break;
4561         }
4562       used_at = 1;
4563       macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
4564       macro_build (&offset_expr, likely ? "bnel" : "bne", "s,t,p", AT, 0);
4565       break;
4566
4567     case M_BLTUL:
4568       likely = 1;
4569     case M_BLTU:
4570       if (treg == 0)
4571         goto do_false;
4572       if (sreg == 0)
4573         {
4574           macro_build (&offset_expr, likely ? "bnel" : "bne",
4575                        "s,t,p", 0, treg);
4576           break;
4577         }
4578       used_at = 1;
4579       macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
4580       macro_build (&offset_expr, likely ? "bnel" : "bne", "s,t,p", AT, 0);
4581       break;
4582
4583     case M_DEXT:
4584       {
4585         unsigned long pos;
4586         unsigned long size;
4587
4588         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
4589           {
4590             as_bad (_("Unsupported large constant"));
4591             pos = size = 1;
4592           }
4593         else
4594           {
4595             pos = (unsigned long) imm_expr.X_add_number;
4596             size = (unsigned long) imm2_expr.X_add_number;
4597           }
4598
4599         if (pos > 63)
4600           {
4601             as_bad (_("Improper position (%lu)"), pos);
4602             pos = 1;
4603           }
4604         if (size == 0 || size > 64
4605             || (pos + size - 1) > 63)
4606           {
4607             as_bad (_("Improper extract size (%lu, position %lu)"),
4608                     size, pos);
4609             size = 1;
4610           }
4611
4612         if (size <= 32 && pos < 32)
4613           {
4614             s = "dext";
4615             fmt = "t,r,+A,+C";
4616           }
4617         else if (size <= 32)
4618           {
4619             s = "dextu";
4620             fmt = "t,r,+E,+H";
4621           }
4622         else
4623           {
4624             s = "dextm";
4625             fmt = "t,r,+A,+G";
4626           }
4627         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, pos, size - 1);
4628       }
4629       break;
4630
4631     case M_DINS:
4632       {
4633         unsigned long pos;
4634         unsigned long size;
4635
4636         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
4637           {
4638             as_bad (_("Unsupported large constant"));
4639             pos = size = 1;
4640           }
4641         else
4642           {
4643             pos = (unsigned long) imm_expr.X_add_number;
4644             size = (unsigned long) imm2_expr.X_add_number;
4645           }
4646
4647         if (pos > 63)
4648           {
4649             as_bad (_("Improper position (%lu)"), pos);
4650             pos = 1;
4651           }
4652         if (size == 0 || size > 64
4653             || (pos + size - 1) > 63)
4654           {
4655             as_bad (_("Improper insert size (%lu, position %lu)"),
4656                     size, pos);
4657             size = 1;
4658           }
4659
4660         if (pos < 32 && (pos + size - 1) < 32)
4661           {
4662             s = "dins";
4663             fmt = "t,r,+A,+B";
4664           }
4665         else if (pos >= 32)
4666           {
4667             s = "dinsu";
4668             fmt = "t,r,+E,+F";
4669           }
4670         else
4671           {
4672             s = "dinsm";
4673             fmt = "t,r,+A,+F";
4674           }
4675         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, pos,
4676                      pos + size - 1);
4677       }
4678       break;
4679
4680     case M_DDIV_3:
4681       dbl = 1;
4682     case M_DIV_3:
4683       s = "mflo";
4684       goto do_div3;
4685     case M_DREM_3:
4686       dbl = 1;
4687     case M_REM_3:
4688       s = "mfhi";
4689     do_div3:
4690       if (treg == 0)
4691         {
4692           as_warn (_("Divide by zero."));
4693           if (mips_trap)
4694             macro_build (NULL, "teq", "s,t,q", 0, 0, 7);
4695           else
4696             macro_build (NULL, "break", "c", 7);
4697           break;
4698         }
4699
4700       start_noreorder ();
4701       if (mips_trap)
4702         {
4703           macro_build (NULL, "teq", "s,t,q", treg, 0, 7);
4704           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
4705         }
4706       else
4707         {
4708           expr1.X_add_number = 8;
4709           macro_build (&expr1, "bne", "s,t,p", treg, 0);
4710           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
4711           macro_build (NULL, "break", "c", 7);
4712         }
4713       expr1.X_add_number = -1;
4714       used_at = 1;
4715       load_register (AT, &expr1, dbl);
4716       expr1.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
4717       macro_build (&expr1, "bne", "s,t,p", treg, AT);
4718       if (dbl)
4719         {
4720           expr1.X_add_number = 1;
4721           load_register (AT, &expr1, dbl);
4722           macro_build (NULL, "dsll32", "d,w,<", AT, AT, 31);
4723         }
4724       else
4725         {
4726           expr1.X_add_number = 0x80000000;
4727           macro_build (&expr1, "lui", "t,u", AT, BFD_RELOC_HI16);
4728         }
4729       if (mips_trap)
4730         {
4731           macro_build (NULL, "teq", "s,t,q", sreg, AT, 6);
4732           /* We want to close the noreorder block as soon as possible, so
4733              that later insns are available for delay slot filling.  */
4734           end_noreorder ();
4735         }
4736       else
4737         {
4738           expr1.X_add_number = 8;
4739           macro_build (&expr1, "bne", "s,t,p", sreg, AT);
4740           macro_build (NULL, "nop", "", 0);
4741
4742           /* We want to close the noreorder block as soon as possible, so
4743              that later insns are available for delay slot filling.  */
4744           end_noreorder ();
4745
4746           macro_build (NULL, "break", "c", 6);
4747         }
4748       macro_build (NULL, s, "d", dreg);
4749       break;
4750
4751     case M_DIV_3I:
4752       s = "div";
4753       s2 = "mflo";
4754       goto do_divi;
4755     case M_DIVU_3I:
4756       s = "divu";
4757       s2 = "mflo";
4758       goto do_divi;
4759     case M_REM_3I:
4760       s = "div";
4761       s2 = "mfhi";
4762       goto do_divi;
4763     case M_REMU_3I:
4764       s = "divu";
4765       s2 = "mfhi";
4766       goto do_divi;
4767     case M_DDIV_3I:
4768       dbl = 1;
4769       s = "ddiv";
4770       s2 = "mflo";
4771       goto do_divi;
4772     case M_DDIVU_3I:
4773       dbl = 1;
4774       s = "ddivu";
4775       s2 = "mflo";
4776       goto do_divi;
4777     case M_DREM_3I:
4778       dbl = 1;
4779       s = "ddiv";
4780       s2 = "mfhi";
4781       goto do_divi;
4782     case M_DREMU_3I:
4783       dbl = 1;
4784       s = "ddivu";
4785       s2 = "mfhi";
4786     do_divi:
4787       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
4788         {
4789           as_warn (_("Divide by zero."));
4790           if (mips_trap)
4791             macro_build (NULL, "teq", "s,t,q", 0, 0, 7);
4792           else
4793             macro_build (NULL, "break", "c", 7);
4794           break;
4795         }
4796       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
4797         {
4798           if (strcmp (s2, "mflo") == 0)
4799             move_register (dreg, sreg);
4800           else
4801             move_register (dreg, 0);
4802           break;
4803         }
4804       if (imm_expr.X_op == O_constant
4805           && imm_expr.X_add_number == -1
4806           && s[strlen (s) - 1] != 'u')
4807         {
4808           if (strcmp (s2, "mflo") == 0)
4809             {
4810               macro_build (NULL, dbl ? "dneg" : "neg", "d,w", dreg, sreg);
4811             }
4812           else
4813             move_register (dreg, 0);
4814           break;
4815         }
4816
4817       used_at = 1;
4818       load_register (AT, &imm_expr, dbl);
4819       macro_build (NULL, s, "z,s,t", sreg, AT);
4820       macro_build (NULL, s2, "d", dreg);
4821       break;
4822
4823     case M_DIVU_3:
4824       s = "divu";
4825       s2 = "mflo";
4826       goto do_divu3;
4827     case M_REMU_3:
4828       s = "divu";
4829       s2 = "mfhi";
4830       goto do_divu3;
4831     case M_DDIVU_3:
4832       s = "ddivu";
4833       s2 = "mflo";
4834       goto do_divu3;
4835     case M_DREMU_3:
4836       s = "ddivu";
4837       s2 = "mfhi";
4838     do_divu3:
4839       start_noreorder ();
4840       if (mips_trap)
4841         {
4842           macro_build (NULL, "teq", "s,t,q", treg, 0, 7);
4843           macro_build (NULL, s, "z,s,t", sreg, treg);
4844           /* We want to close the noreorder block as soon as possible, so
4845              that later insns are available for delay slot filling.  */
4846           end_noreorder ();
4847         }
4848       else
4849         {
4850           expr1.X_add_number = 8;
4851           macro_build (&expr1, "bne", "s,t,p", treg, 0);
4852           macro_build (NULL, s, "z,s,t", sreg, treg);
4853
4854           /* We want to close the noreorder block as soon as possible, so
4855              that later insns are available for delay slot filling.  */
4856           end_noreorder ();
4857           macro_build (NULL, "break", "c", 7);
4858         }
4859       macro_build (NULL, s2, "d", dreg);
4860       break;
4861
4862     case M_DLCA_AB:
4863       dbl = 1;
4864     case M_LCA_AB:
4865       call = 1;
4866       goto do_la;
4867     case M_DLA_AB:
4868       dbl = 1;
4869     case M_LA_AB:
4870     do_la:
4871       /* Load the address of a symbol into a register.  If breg is not
4872          zero, we then add a base register to it.  */
4873
4874       if (dbl && HAVE_32BIT_GPRS)
4875         as_warn (_("dla used to load 32-bit register"));
4876
4877       if (! dbl && HAVE_64BIT_OBJECTS)
4878         as_warn (_("la used to load 64-bit address"));
4879
4880       if (offset_expr.X_op == O_constant
4881           && offset_expr.X_add_number >= -0x8000
4882           && offset_expr.X_add_number < 0x8000)
4883         {
4884           macro_build (&offset_expr, ADDRESS_ADDI_INSN,
4885                        "t,r,j", treg, sreg, BFD_RELOC_LO16);
4886           break;
4887         }
4888
4889       if (!mips_opts.noat && (treg == breg))
4890         {
4891           tempreg = AT;
4892           used_at = 1;
4893         }
4894       else
4895         {
4896           tempreg = treg;
4897         }
4898
4899       if (offset_expr.X_op != O_symbol
4900           && offset_expr.X_op != O_constant)
4901         {
4902           as_bad (_("expression too complex"));
4903           offset_expr.X_op = O_constant;
4904         }
4905
4906       if (offset_expr.X_op == O_constant)
4907         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
4908       else if (mips_pic == NO_PIC)
4909         {
4910           /* If this is a reference to a GP relative symbol, we want
4911                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
4912              Otherwise we want
4913                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
4914                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
4915              If we have a constant, we need two instructions anyhow,
4916              so we may as well always use the latter form.
4917
4918              With 64bit address space and a usable $at we want
4919                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
4920                lui      $at,<sym>               (BFD_RELOC_HI16_S)
4921                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
4922                daddiu   $at,<sym>               (BFD_RELOC_LO16)
4923                dsll32   $tempreg,0
4924                daddu    $tempreg,$tempreg,$at
4925
4926              If $at is already in use, we use a path which is suboptimal
4927              on superscalar processors.
4928                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
4929                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
4930                dsll     $tempreg,16
4931                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
4932                dsll     $tempreg,16
4933                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
4934
4935              For GP relative symbols in 64bit address space we can use
4936              the same sequence as in 32bit address space.  */
4937           if (HAVE_64BIT_SYMBOLS)
4938             {
4939               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
4940                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
4941                 {
4942                   relax_start (offset_expr.X_add_symbol);
4943                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
4944                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
4945                   relax_switch ();
4946                 }
4947
4948               if (used_at == 0 && !mips_opts.noat)
4949                 {
4950                   macro_build (&offset_expr, "lui", "t,u",
4951                                tempreg, BFD_RELOC_MIPS_HIGHEST);
4952                   macro_build (&offset_expr, "lui", "t,u",
4953                                AT, BFD_RELOC_HI16_S);
4954                   macro_build (&offset_expr, "daddiu", "t,r,j",
4955                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
4956                   macro_build (&offset_expr, "daddiu", "t,r,j",
4957                                AT, AT, BFD_RELOC_LO16);
4958                   macro_build (NULL, "dsll32", "d,w,<", tempreg, tempreg, 0);
4959                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
4960                   used_at = 1;
4961                 }
4962               else
4963                 {
4964                   macro_build (&offset_expr, "lui", "t,u",
4965                                tempreg, BFD_RELOC_MIPS_HIGHEST);
4966                   macro_build (&offset_expr, "daddiu", "t,r,j",
4967                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
4968                   macro_build (NULL, "dsll", "d,w,<", tempreg, tempreg, 16);
4969                   macro_build (&offset_expr, "daddiu", "t,r,j",
4970                                tempreg, tempreg, BFD_RELOC_HI16_S);
4971                   macro_build (NULL, "dsll", "d,w,<", tempreg, tempreg, 16);
4972                   macro_build (&offset_expr, "daddiu", "t,r,j",
4973                                tempreg, tempreg, BFD_RELOC_LO16);
4974                 }
4975
4976               if (mips_relax.sequence)
4977                 relax_end ();
4978             }
4979           else
4980             {
4981               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
4982                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
4983                 {
4984                   relax_start (offset_expr.X_add_symbol);
4985                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
4986                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
4987                   relax_switch ();
4988                 }
4989               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
4990                 as_bad (_("offset too large"));
4991               macro_build_lui (&offset_expr, tempreg);
4992               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
4993                            tempreg, tempreg, BFD_RELOC_LO16);
4994               if (mips_relax.sequence)
4995                 relax_end ();
4996             }
4997         }
4998       else if (mips_pic == SVR4_PIC && ! mips_big_got && ! HAVE_NEWABI)
4999         {
5000           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
5001
5002           /* If this is a reference to an external symbol, and there
5003              is no constant, we want
5004                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5005              or for lca or if tempreg is PIC_CALL_REG
5006                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
5007              For a local symbol, we want
5008                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5009                nop
5010                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
5011
5012              If we have a small constant, and this is a reference to
5013              an external symbol, we want
5014                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5015                nop
5016                addiu    $tempreg,$tempreg,<constant>
5017              For a local symbol, we want the same instruction
5018              sequence, but we output a BFD_RELOC_LO16 reloc on the
5019              addiu instruction.
5020
5021              If we have a large constant, and this is a reference to
5022              an external symbol, we want
5023                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5024                lui      $at,<hiconstant>
5025                addiu    $at,$at,<loconstant>
5026                addu     $tempreg,$tempreg,$at
5027              For a local symbol, we want the same instruction
5028              sequence, but we output a BFD_RELOC_LO16 reloc on the
5029              addiu instruction.
5030            */
5031
5032           if (offset_expr.X_add_number == 0)
5033             {
5034               if (breg == 0 && (call || tempreg == PIC_CALL_REG))
5035                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
5036
5037               relax_start (offset_expr.X_add_symbol);
5038               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5039                            lw_reloc_type, mips_gp_register);
5040               if (breg != 0)
5041                 {
5042                   /* We're going to put in an addu instruction using
5043                      tempreg, so we may as well insert the nop right
5044                      now.  */
5045                   load_delay_nop ();
5046                 }
5047               relax_switch ();
5048               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5049                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
5050               load_delay_nop ();
5051               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
5052                            tempreg, tempreg, BFD_RELOC_LO16);
5053               relax_end ();
5054               /* FIXME: If breg == 0, and the next instruction uses
5055                  $tempreg, then if this variant case is used an extra
5056                  nop will be generated.  */
5057             }
5058           else if (offset_expr.X_add_number >= -0x8000
5059                    && offset_expr.X_add_number < 0x8000)
5060             {
5061               load_got_offset (tempreg, &offset_expr);
5062               load_delay_nop ();
5063               add_got_offset (tempreg, &offset_expr);
5064             }
5065           else
5066             {
5067               expr1.X_add_number = offset_expr.X_add_number;
5068               offset_expr.X_add_number =
5069                 ((offset_expr.X_add_number + 0x8000) & 0xffff) - 0x8000;
5070               load_got_offset (tempreg, &offset_expr);
5071               offset_expr.X_add_number = expr1.X_add_number;
5072               /* If we are going to add in a base register, and the
5073                  target register and the base register are the same,
5074                  then we are using AT as a temporary register.  Since
5075                  we want to load the constant into AT, we add our
5076                  current AT (from the global offset table) and the
5077                  register into the register now, and pretend we were
5078                  not using a base register.  */
5079               if (breg == treg)
5080                 {
5081                   load_delay_nop ();
5082                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5083                                treg, AT, breg);
5084                   breg = 0;
5085                   tempreg = treg;
5086                 }
5087               add_got_offset_hilo (tempreg, &offset_expr, AT);
5088               used_at = 1;
5089             }
5090         }
5091       else if (mips_pic == SVR4_PIC && ! mips_big_got && HAVE_NEWABI)
5092         {
5093           int add_breg_early = 0;
5094
5095           /* If this is a reference to an external, and there is no
5096              constant, or local symbol (*), with or without a
5097              constant, we want
5098                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
5099              or for lca or if tempreg is PIC_CALL_REG
5100                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
5101
5102              If we have a small constant, and this is a reference to
5103              an external symbol, we want
5104                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
5105                addiu    $tempreg,$tempreg,<constant>
5106
5107              If we have a large constant, and this is a reference to
5108              an external symbol, we want
5109                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
5110                lui      $at,<hiconstant>
5111                addiu    $at,$at,<loconstant>
5112                addu     $tempreg,$tempreg,$at
5113
5114              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
5115              local symbols, even though it introduces an additional
5116              instruction.  */
5117
5118           if (offset_expr.X_add_number)
5119             {
5120               expr1.X_add_number = offset_expr.X_add_number;
5121               offset_expr.X_add_number = 0;
5122
5123               relax_start (offset_expr.X_add_symbol);
5124               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5125                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
5126
5127               if (expr1.X_add_number >= -0x8000
5128                   && expr1.X_add_number < 0x8000)
5129                 {
5130                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
5131                                tempreg, tempreg, BFD_RELOC_LO16);
5132                 }
5133               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
5134                 {
5135                   int dreg;
5136
5137                   /* If we are going to add in a base register, and the
5138                      target register and the base register are the same,
5139                      then we are using AT as a temporary register.  Since
5140                      we want to load the constant into AT, we add our
5141                      current AT (from the global offset table) and the
5142                      register into the register now, and pretend we were
5143                      not using a base register.  */
5144                   if (breg != treg)
5145                     dreg = tempreg;
5146                   else
5147                     {
5148                       assert (tempreg == AT);
5149                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5150                                    treg, AT, breg);
5151                       dreg = treg;
5152                       add_breg_early = 1;
5153                     }
5154
5155                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
5156                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5157                                dreg, dreg, AT);
5158
5159                   used_at = 1;
5160                 }
5161               else
5162                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
5163
5164               relax_switch ();
5165               offset_expr.X_add_number = expr1.X_add_number;
5166
5167               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5168                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
5169               if (add_breg_early)
5170                 {
5171                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5172                                treg, tempreg, breg);
5173                   breg = 0;
5174                   tempreg = treg;
5175                 }
5176               relax_end ();
5177             }
5178           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
5179             {
5180               relax_start (offset_expr.X_add_symbol);
5181               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5182                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
5183               relax_switch ();
5184               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5185                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
5186               relax_end ();
5187             }
5188           else
5189             {
5190               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5191                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
5192             }
5193         }
5194       else if (mips_pic == SVR4_PIC && ! HAVE_NEWABI)
5195         {
5196           int gpdelay;
5197           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
5198           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
5199           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
5200
5201           /* This is the large GOT case.  If this is a reference to an
5202              external symbol, and there is no constant, we want
5203                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
5204                addu     $tempreg,$tempreg,$gp
5205                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
5206              or for lca or if tempreg is PIC_CALL_REG
5207                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
5208                addu     $tempreg,$tempreg,$gp
5209                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
5210              For a local symbol, we want
5211                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5212                nop
5213                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
5214
5215              If we have a small constant, and this is a reference to
5216              an external symbol, we want
5217                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
5218                addu     $tempreg,$tempreg,$gp
5219                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
5220                nop
5221                addiu    $tempreg,$tempreg,<constant>
5222              For a local symbol, we want
5223                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5224                nop
5225                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
5226
5227              If we have a large constant, and this is a reference to
5228              an external symbol, we want
5229                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
5230                addu     $tempreg,$tempreg,$gp
5231                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
5232                lui      $at,<hiconstant>
5233                addiu    $at,$at,<loconstant>
5234                addu     $tempreg,$tempreg,$at
5235              For a local symbol, we want
5236                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5237                lui      $at,<hiconstant>
5238                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
5239                addu     $tempreg,$tempreg,$at
5240           */
5241
5242           expr1.X_add_number = offset_expr.X_add_number;
5243           offset_expr.X_add_number = 0;
5244           relax_start (offset_expr.X_add_symbol);
5245           gpdelay = reg_needs_delay (mips_gp_register);
5246           if (expr1.X_add_number == 0 && breg == 0
5247               && (call || tempreg == PIC_CALL_REG))
5248             {
5249               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
5250               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
5251             }
5252           macro_build (&offset_expr, "lui", "t,u", tempreg, lui_reloc_type);
5253           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5254                        tempreg, tempreg, mips_gp_register);
5255           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5256                        tempreg, lw_reloc_type, tempreg);
5257           if (expr1.X_add_number == 0)
5258             {
5259               if (breg != 0)
5260                 {
5261                   /* We're going to put in an addu instruction using
5262                      tempreg, so we may as well insert the nop right
5263                      now.  */
5264                   load_delay_nop ();
5265                 }
5266             }
5267           else if (expr1.X_add_number >= -0x8000
5268                    && expr1.X_add_number < 0x8000)
5269             {
5270               load_delay_nop ();
5271               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
5272                            tempreg, tempreg, BFD_RELOC_LO16);
5273             }
5274           else
5275             {
5276               int dreg;
5277
5278               /* If we are going to add in a base register, and the
5279                  target register and the base register are the same,
5280                  then we are using AT as a temporary register.  Since
5281                  we want to load the constant into AT, we add our
5282                  current AT (from the global offset table) and the
5283                  register into the register now, and pretend we were
5284                  not using a base register.  */
5285               if (breg != treg)
5286                 dreg = tempreg;
5287               else
5288                 {
5289                   assert (tempreg == AT);
5290                   load_delay_nop ();
5291                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5292                                treg, AT, breg);
5293                   dreg = treg;
5294                 }
5295
5296               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
5297               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
5298
5299               used_at = 1;
5300             }
5301           offset_expr.X_add_number =
5302             ((expr1.X_add_number + 0x8000) & 0xffff) - 0x8000;
5303           relax_switch ();
5304
5305           if (gpdelay)
5306             {
5307               /* This is needed because this instruction uses $gp, but
5308                  the first instruction on the main stream does not.  */
5309               macro_build (NULL, "nop", "");
5310             }
5311
5312           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5313                        local_reloc_type, mips_gp_register);
5314           if (expr1.X_add_number >= -0x8000
5315               && expr1.X_add_number < 0x8000)
5316             {
5317               load_delay_nop ();
5318               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
5319                            tempreg, tempreg, BFD_RELOC_LO16);
5320               /* FIXME: If add_number is 0, and there was no base
5321                  register, the external symbol case ended with a load,
5322                  so if the symbol turns out to not be external, and
5323                  the next instruction uses tempreg, an unnecessary nop
5324                  will be inserted.  */
5325             }
5326           else
5327             {
5328               if (breg == treg)
5329                 {
5330                   /* We must add in the base register now, as in the
5331                      external symbol case.  */
5332                   assert (tempreg == AT);
5333                   load_delay_nop ();
5334                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5335                                treg, AT, breg);
5336                   tempreg = treg;
5337                   /* We set breg to 0 because we have arranged to add
5338                      it in in both cases.  */
5339                   breg = 0;
5340                 }
5341
5342               macro_build_lui (&expr1, AT);
5343               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
5344                            AT, AT, BFD_RELOC_LO16);
5345               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5346                            tempreg, tempreg, AT);
5347               used_at = 1;
5348             }
5349           relax_end ();
5350         }
5351       else if (mips_pic == SVR4_PIC && HAVE_NEWABI)
5352         {
5353           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
5354           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
5355           int add_breg_early = 0;
5356
5357           /* This is the large GOT case.  If this is a reference to an
5358              external symbol, and there is no constant, we want
5359                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
5360                add      $tempreg,$tempreg,$gp
5361                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
5362              or for lca or if tempreg is PIC_CALL_REG
5363                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
5364                add      $tempreg,$tempreg,$gp
5365                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
5366
5367              If we have a small constant, and this is a reference to
5368              an external symbol, we want
5369                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
5370                add      $tempreg,$tempreg,$gp
5371                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
5372                addi     $tempreg,$tempreg,<constant>
5373
5374              If we have a large constant, and this is a reference to
5375              an external symbol, we want
5376                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
5377                addu     $tempreg,$tempreg,$gp
5378                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
5379                lui      $at,<hiconstant>
5380                addi     $at,$at,<loconstant>
5381                add      $tempreg,$tempreg,$at
5382
5383              If we have NewABI, and we know it's a local symbol, we want
5384                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
5385                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
5386              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
5387
5388           relax_start (offset_expr.X_add_symbol);
5389
5390           expr1.X_add_number = offset_expr.X_add_number;
5391           offset_expr.X_add_number = 0;
5392
5393           if (expr1.X_add_number == 0 && breg == 0
5394               && (call || tempreg == PIC_CALL_REG))
5395             {
5396               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
5397               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
5398             }
5399           macro_build (&offset_expr, "lui", "t,u", tempreg, lui_reloc_type);
5400           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5401                        tempreg, tempreg, mips_gp_register);
5402           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5403                        tempreg, lw_reloc_type, tempreg);
5404
5405           if (expr1.X_add_number == 0)
5406             ;
5407           else if (expr1.X_add_number >= -0x8000
5408                    && expr1.X_add_number < 0x8000)
5409             {
5410               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
5411                            tempreg, tempreg, BFD_RELOC_LO16);
5412             }
5413           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
5414             {
5415               int dreg;
5416
5417               /* If we are going to add in a base register, and the
5418                  target register and the base register are the same,
5419                  then we are using AT as a temporary register.  Since
5420                  we want to load the constant into AT, we add our
5421                  current AT (from the global offset table) and the
5422                  register into the register now, and pretend we were
5423                  not using a base register.  */
5424               if (breg != treg)
5425                 dreg = tempreg;
5426               else
5427                 {
5428                   assert (tempreg == AT);
5429                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5430                                treg, AT, breg);
5431                   dreg = treg;
5432                   add_breg_early = 1;
5433                 }
5434
5435               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
5436               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
5437
5438               used_at = 1;
5439             }
5440           else
5441             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
5442
5443           relax_switch ();
5444           offset_expr.X_add_number = expr1.X_add_number;
5445           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5446                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
5447           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
5448                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
5449           if (add_breg_early)
5450             {
5451               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5452                            treg, tempreg, breg);
5453               breg = 0;
5454               tempreg = treg;
5455             }
5456           relax_end ();
5457         }
5458       else
5459         abort ();
5460
5461       if (breg != 0)
5462         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", treg, tempreg, breg);
5463       break;
5464
5465     case M_J_A:
5466       /* The j instruction may not be used in PIC code, since it
5467          requires an absolute address.  We convert it to a b
5468          instruction.  */
5469       if (mips_pic == NO_PIC)
5470         macro_build (&offset_expr, "j", "a");
5471       else
5472         macro_build (&offset_expr, "b", "p");
5473       break;
5474
5475       /* The jal instructions must be handled as macros because when
5476          generating PIC code they expand to multi-instruction
5477          sequences.  Normally they are simple instructions.  */
5478     case M_JAL_1:
5479       dreg = RA;
5480       /* Fall through.  */
5481     case M_JAL_2:
5482       if (mips_pic == NO_PIC)
5483         macro_build (NULL, "jalr", "d,s", dreg, sreg);
5484       else if (mips_pic == SVR4_PIC)
5485         {
5486           if (sreg != PIC_CALL_REG)
5487             as_warn (_("MIPS PIC call to register other than $25"));
5488
5489           macro_build (NULL, "jalr", "d,s", dreg, sreg);
5490           if (! HAVE_NEWABI)
5491             {
5492               if (mips_cprestore_offset < 0)
5493                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
5494               else
5495                 {
5496                   if (! mips_frame_reg_valid)
5497                     {
5498                       as_warn (_("No .frame pseudo-op used in PIC code"));
5499                       /* Quiet this warning.  */
5500                       mips_frame_reg_valid = 1;
5501                     }
5502                   if (! mips_cprestore_valid)
5503                     {
5504                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
5505                       /* Quiet this warning.  */
5506                       mips_cprestore_valid = 1;
5507                     }
5508                   expr1.X_add_number = mips_cprestore_offset;
5509                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
5510                                                 mips_gp_register,
5511                                                 mips_frame_reg,
5512                                                 HAVE_64BIT_ADDRESSES);
5513                 }
5514             }
5515         }
5516       else
5517         abort ();
5518
5519       break;
5520
5521     case M_JAL_A:
5522       if (mips_pic == NO_PIC)
5523         macro_build (&offset_expr, "jal", "a");
5524       else if (mips_pic == SVR4_PIC)
5525         {
5526           /* If this is a reference to an external symbol, and we are
5527              using a small GOT, we want
5528                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
5529                nop
5530                jalr     $ra,$25
5531                nop
5532                lw       $gp,cprestore($sp)
5533              The cprestore value is set using the .cprestore
5534              pseudo-op.  If we are using a big GOT, we want
5535                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
5536                addu     $25,$25,$gp
5537                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
5538                nop
5539                jalr     $ra,$25
5540                nop
5541                lw       $gp,cprestore($sp)
5542              If the symbol is not external, we want
5543                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
5544                nop
5545                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
5546                jalr     $ra,$25
5547                nop
5548                lw $gp,cprestore($sp)
5549
5550              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
5551              sequences above, minus nops, unless the symbol is local,
5552              which enables us to use GOT_PAGE/GOT_OFST (big got) or
5553              GOT_DISP.  */
5554           if (HAVE_NEWABI)
5555             {
5556               if (! mips_big_got)
5557                 {
5558                   relax_start (offset_expr.X_add_symbol);
5559                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5560                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
5561                                mips_gp_register);
5562                   relax_switch ();
5563                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5564                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
5565                                mips_gp_register);
5566                   relax_end ();
5567                 }
5568               else
5569                 {
5570                   relax_start (offset_expr.X_add_symbol);
5571                   macro_build (&offset_expr, "lui", "t,u", PIC_CALL_REG,
5572                                BFD_RELOC_MIPS_CALL_HI16);
5573                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
5574                                PIC_CALL_REG, mips_gp_register);
5575                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5576                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
5577                                PIC_CALL_REG);
5578                   relax_switch ();
5579                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5580                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
5581                                mips_gp_register);
5582                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
5583                                PIC_CALL_REG, PIC_CALL_REG,
5584                                BFD_RELOC_MIPS_GOT_OFST);
5585                   relax_end ();
5586                 }
5587
5588               macro_build_jalr (&offset_expr);
5589             }
5590           else
5591             {
5592               relax_start (offset_expr.X_add_symbol);
5593               if (! mips_big_got)
5594                 {
5595                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5596                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
5597                                mips_gp_register);
5598                   load_delay_nop ();
5599                   relax_switch ();
5600                 }
5601               else
5602                 {
5603                   int gpdelay;
5604
5605                   gpdelay = reg_needs_delay (mips_gp_register);
5606                   macro_build (&offset_expr, "lui", "t,u", PIC_CALL_REG,
5607                                BFD_RELOC_MIPS_CALL_HI16);
5608                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
5609                                PIC_CALL_REG, mips_gp_register);
5610                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5611                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
5612                                PIC_CALL_REG);
5613                   load_delay_nop ();
5614                   relax_switch ();
5615                   if (gpdelay)
5616                     macro_build (NULL, "nop", "");
5617                 }
5618               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5619                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
5620                            mips_gp_register);
5621               load_delay_nop ();
5622               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
5623                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
5624               relax_end ();
5625               macro_build_jalr (&offset_expr);
5626
5627               if (mips_cprestore_offset < 0)
5628                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
5629               else
5630                 {
5631                   if (! mips_frame_reg_valid)
5632                     {
5633                       as_warn (_("No .frame pseudo-op used in PIC code"));
5634                       /* Quiet this warning.  */
5635                       mips_frame_reg_valid = 1;
5636                     }
5637                   if (! mips_cprestore_valid)
5638                     {
5639                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
5640                       /* Quiet this warning.  */
5641                       mips_cprestore_valid = 1;
5642                     }
5643                   if (mips_opts.noreorder)
5644                     macro_build (NULL, "nop", "");
5645                   expr1.X_add_number = mips_cprestore_offset;
5646                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
5647                                                 mips_gp_register,
5648                                                 mips_frame_reg,
5649                                                 HAVE_64BIT_ADDRESSES);
5650                 }
5651             }
5652         }
5653       else
5654         abort ();
5655
5656       break;
5657
5658     case M_LB_AB:
5659       s = "lb";
5660       goto ld;
5661     case M_LBU_AB:
5662       s = "lbu";
5663       goto ld;
5664     case M_LH_AB:
5665       s = "lh";
5666       goto ld;
5667     case M_LHU_AB:
5668       s = "lhu";
5669       goto ld;
5670     case M_LW_AB:
5671       s = "lw";
5672       goto ld;
5673     case M_LWC0_AB:
5674       s = "lwc0";
5675       /* Itbl support may require additional care here.  */
5676       coproc = 1;
5677       goto ld;
5678     case M_LWC1_AB:
5679       s = "lwc1";
5680       /* Itbl support may require additional care here.  */
5681       coproc = 1;
5682       goto ld;
5683     case M_LWC2_AB:
5684       s = "lwc2";
5685       /* Itbl support may require additional care here.  */
5686       coproc = 1;
5687       goto ld;
5688     case M_LWC3_AB:
5689       s = "lwc3";
5690       /* Itbl support may require additional care here.  */
5691       coproc = 1;
5692       goto ld;
5693     case M_LWL_AB:
5694       s = "lwl";
5695       lr = 1;
5696       goto ld;
5697     case M_LWR_AB:
5698       s = "lwr";
5699       lr = 1;
5700       goto ld;
5701     case M_LDC1_AB:
5702       if (mips_opts.arch == CPU_R4650)
5703         {
5704           as_bad (_("opcode not supported on this processor"));
5705           break;
5706         }
5707       s = "ldc1";
5708       /* Itbl support may require additional care here.  */
5709       coproc = 1;
5710       goto ld;
5711     case M_LDC2_AB:
5712       s = "ldc2";
5713       /* Itbl support may require additional care here.  */
5714       coproc = 1;
5715       goto ld;
5716     case M_LDC3_AB:
5717       s = "ldc3";
5718       /* Itbl support may require additional care here.  */
5719       coproc = 1;
5720       goto ld;
5721     case M_LDL_AB:
5722       s = "ldl";
5723       lr = 1;
5724       goto ld;
5725     case M_LDR_AB:
5726       s = "ldr";
5727       lr = 1;
5728       goto ld;
5729     case M_LL_AB:
5730       s = "ll";
5731       goto ld;
5732     case M_LLD_AB:
5733       s = "lld";
5734       goto ld;
5735     case M_LWU_AB:
5736       s = "lwu";
5737     ld:
5738       if (breg == treg || coproc || lr)
5739         {
5740           tempreg = AT;
5741           used_at = 1;
5742         }
5743       else
5744         {
5745           tempreg = treg;
5746         }
5747       goto ld_st;
5748     case M_SB_AB:
5749       s = "sb";
5750       goto st;
5751     case M_SH_AB:
5752       s = "sh";
5753       goto st;
5754     case M_SW_AB:
5755       s = "sw";
5756       goto st;
5757     case M_SWC0_AB:
5758       s = "swc0";
5759       /* Itbl support may require additional care here.  */
5760       coproc = 1;
5761       goto st;
5762     case M_SWC1_AB:
5763       s = "swc1";
5764       /* Itbl support may require additional care here.  */
5765       coproc = 1;
5766       goto st;
5767     case M_SWC2_AB:
5768       s = "swc2";
5769       /* Itbl support may require additional care here.  */
5770       coproc = 1;
5771       goto st;
5772     case M_SWC3_AB:
5773       s = "swc3";
5774       /* Itbl support may require additional care here.  */
5775       coproc = 1;
5776       goto st;
5777     case M_SWL_AB:
5778       s = "swl";
5779       goto st;
5780     case M_SWR_AB:
5781       s = "swr";
5782       goto st;
5783     case M_SC_AB:
5784       s = "sc";
5785       goto st;
5786     case M_SCD_AB:
5787       s = "scd";
5788       goto st;
5789     case M_SDC1_AB:
5790       if (mips_opts.arch == CPU_R4650)
5791         {
5792           as_bad (_("opcode not supported on this processor"));
5793           break;
5794         }
5795       s = "sdc1";
5796       coproc = 1;
5797       /* Itbl support may require additional care here.  */
5798       goto st;
5799     case M_SDC2_AB:
5800       s = "sdc2";
5801       /* Itbl support may require additional care here.  */
5802       coproc = 1;
5803       goto st;
5804     case M_SDC3_AB:
5805       s = "sdc3";
5806       /* Itbl support may require additional care here.  */
5807       coproc = 1;
5808       goto st;
5809     case M_SDL_AB:
5810       s = "sdl";
5811       goto st;
5812     case M_SDR_AB:
5813       s = "sdr";
5814     st:
5815       tempreg = AT;
5816       used_at = 1;
5817     ld_st:
5818       /* Itbl support may require additional care here.  */
5819       if (mask == M_LWC1_AB
5820           || mask == M_SWC1_AB
5821           || mask == M_LDC1_AB
5822           || mask == M_SDC1_AB
5823           || mask == M_L_DAB
5824           || mask == M_S_DAB)
5825         fmt = "T,o(b)";
5826       else if (coproc)
5827         fmt = "E,o(b)";
5828       else
5829         fmt = "t,o(b)";
5830
5831       if (offset_expr.X_op != O_constant
5832           && offset_expr.X_op != O_symbol)
5833         {
5834           as_bad (_("expression too complex"));
5835           offset_expr.X_op = O_constant;
5836         }
5837
5838       if (HAVE_32BIT_ADDRESSES
5839           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
5840         {
5841           char value [32];
5842
5843           sprintf_vma (value, offset_expr.X_add_number);
5844           as_bad (_("Number (0x%s) larger than 32 bits"), value);
5845         }
5846
5847       /* A constant expression in PIC code can be handled just as it
5848          is in non PIC code.  */
5849       if (offset_expr.X_op == O_constant)
5850         {
5851           expr1.X_add_number = ((offset_expr.X_add_number + 0x8000)
5852                                 & ~(bfd_vma) 0xffff);
5853           normalize_address_expr (&expr1);
5854           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
5855           if (breg != 0)
5856             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5857                          tempreg, tempreg, breg);
5858           macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16, tempreg);
5859         }
5860       else if (mips_pic == NO_PIC)
5861         {
5862           /* If this is a reference to a GP relative symbol, and there
5863              is no base register, we want
5864                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
5865              Otherwise, if there is no base register, we want
5866                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
5867                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
5868              If we have a constant, we need two instructions anyhow,
5869              so we always use the latter form.
5870
5871              If we have a base register, and this is a reference to a
5872              GP relative symbol, we want
5873                addu     $tempreg,$breg,$gp
5874                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_GPREL16)
5875              Otherwise we want
5876                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
5877                addu     $tempreg,$tempreg,$breg
5878                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
5879              With a constant we always use the latter case.
5880
5881              With 64bit address space and no base register and $at usable,
5882              we want
5883                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
5884                lui      $at,<sym>               (BFD_RELOC_HI16_S)
5885                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
5886                dsll32   $tempreg,0
5887                daddu    $tempreg,$at
5888                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
5889              If we have a base register, we want
5890                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
5891                lui      $at,<sym>               (BFD_RELOC_HI16_S)
5892                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
5893                daddu    $at,$breg
5894                dsll32   $tempreg,0
5895                daddu    $tempreg,$at
5896                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
5897
5898              Without $at we can't generate the optimal path for superscalar
5899              processors here since this would require two temporary registers.
5900                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
5901                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
5902                dsll     $tempreg,16
5903                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
5904                dsll     $tempreg,16
5905                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
5906              If we have a base register, we want
5907                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
5908                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
5909                dsll     $tempreg,16
5910                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
5911                dsll     $tempreg,16
5912                daddu    $tempreg,$tempreg,$breg
5913                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
5914
5915              For GP relative symbols in 64bit address space we can use
5916              the same sequence as in 32bit address space.  */
5917           if (HAVE_64BIT_SYMBOLS)
5918             {
5919               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
5920                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
5921                 {
5922                   relax_start (offset_expr.X_add_symbol);
5923                   if (breg == 0)
5924                     {
5925                       macro_build (&offset_expr, s, fmt, treg,
5926                                    BFD_RELOC_GPREL16, mips_gp_register);
5927                     }
5928                   else
5929                     {
5930                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5931                                    tempreg, breg, mips_gp_register);
5932                       macro_build (&offset_expr, s, fmt, treg,
5933                                    BFD_RELOC_GPREL16, tempreg);
5934                     }
5935                   relax_switch ();
5936                 }
5937
5938               if (used_at == 0 && !mips_opts.noat)
5939                 {
5940                   macro_build (&offset_expr, "lui", "t,u", tempreg,
5941                                BFD_RELOC_MIPS_HIGHEST);
5942                   macro_build (&offset_expr, "lui", "t,u", AT,
5943                                BFD_RELOC_HI16_S);
5944                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
5945                                tempreg, BFD_RELOC_MIPS_HIGHER);
5946                   if (breg != 0)
5947                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
5948                   macro_build (NULL, "dsll32", "d,w,<", tempreg, tempreg, 0);
5949                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
5950                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16,
5951                                tempreg);
5952                   used_at = 1;
5953                 }
5954               else
5955                 {
5956                   macro_build (&offset_expr, "lui", "t,u", tempreg,
5957                                BFD_RELOC_MIPS_HIGHEST);
5958                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
5959                                tempreg, BFD_RELOC_MIPS_HIGHER);
5960                   macro_build (NULL, "dsll", "d,w,<", tempreg, tempreg, 16);
5961                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
5962                                tempreg, BFD_RELOC_HI16_S);
5963                   macro_build (NULL, "dsll", "d,w,<", tempreg, tempreg, 16);
5964                   if (breg != 0)
5965                     macro_build (NULL, "daddu", "d,v,t",
5966                                  tempreg, tempreg, breg);
5967                   macro_build (&offset_expr, s, fmt, treg,
5968                                BFD_RELOC_LO16, tempreg);
5969                 }
5970
5971               if (mips_relax.sequence)
5972                 relax_end ();
5973               break;
5974             }
5975
5976           if (breg == 0)
5977             {
5978               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
5979                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
5980                 {
5981                   relax_start (offset_expr.X_add_symbol);
5982                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_GPREL16,
5983                                mips_gp_register);
5984                   relax_switch ();
5985                 }
5986               macro_build_lui (&offset_expr, tempreg);
5987               macro_build (&offset_expr, s, fmt, treg,
5988                            BFD_RELOC_LO16, tempreg);
5989               if (mips_relax.sequence)
5990                 relax_end ();
5991             }
5992           else
5993             {
5994               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
5995                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
5996                 {
5997                   relax_start (offset_expr.X_add_symbol);
5998                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5999                                tempreg, breg, mips_gp_register);
6000                   macro_build (&offset_expr, s, fmt, treg,
6001                                BFD_RELOC_GPREL16, tempreg);
6002                   relax_switch ();
6003                 }
6004               macro_build_lui (&offset_expr, tempreg);
6005               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6006                            tempreg, tempreg, breg);
6007               macro_build (&offset_expr, s, fmt, treg,
6008                            BFD_RELOC_LO16, tempreg);
6009               if (mips_relax.sequence)
6010                 relax_end ();
6011             }
6012         }
6013       else if (mips_pic == SVR4_PIC && ! mips_big_got)
6014         {
6015           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
6016
6017           /* If this is a reference to an external symbol, we want
6018                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
6019                nop
6020                <op>     $treg,0($tempreg)
6021              Otherwise we want
6022                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
6023                nop
6024                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
6025                <op>     $treg,0($tempreg)
6026
6027              For NewABI, we want
6028                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
6029                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
6030
6031              If there is a base register, we add it to $tempreg before
6032              the <op>.  If there is a constant, we stick it in the
6033              <op> instruction.  We don't handle constants larger than
6034              16 bits, because we have no way to load the upper 16 bits
6035              (actually, we could handle them for the subset of cases
6036              in which we are not using $at).  */
6037           assert (offset_expr.X_op == O_symbol);
6038           if (HAVE_NEWABI)
6039             {
6040               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
6041                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
6042               if (breg != 0)
6043                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6044                              tempreg, tempreg, breg);
6045               macro_build (&offset_expr, s, fmt, treg,
6046                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
6047               break;
6048             }
6049           expr1.X_add_number = offset_expr.X_add_number;
6050           offset_expr.X_add_number = 0;
6051           if (expr1.X_add_number < -0x8000
6052               || expr1.X_add_number >= 0x8000)
6053             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6054           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
6055                        lw_reloc_type, mips_gp_register);
6056           load_delay_nop ();
6057           relax_start (offset_expr.X_add_symbol);
6058           relax_switch ();
6059           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
6060                        tempreg, BFD_RELOC_LO16);
6061           relax_end ();
6062           if (breg != 0)
6063             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6064                          tempreg, tempreg, breg);
6065           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
6066         }
6067       else if (mips_pic == SVR4_PIC && ! HAVE_NEWABI)
6068         {
6069           int gpdelay;
6070
6071           /* If this is a reference to an external symbol, we want
6072                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
6073                addu     $tempreg,$tempreg,$gp
6074                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
6075                <op>     $treg,0($tempreg)
6076              Otherwise we want
6077                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
6078                nop
6079                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
6080                <op>     $treg,0($tempreg)
6081              If there is a base register, we add it to $tempreg before
6082              the <op>.  If there is a constant, we stick it in the
6083              <op> instruction.  We don't handle constants larger than
6084              16 bits, because we have no way to load the upper 16 bits
6085              (actually, we could handle them for the subset of cases
6086              in which we are not using $at).  */
6087           assert (offset_expr.X_op == O_symbol);
6088           expr1.X_add_number = offset_expr.X_add_number;
6089           offset_expr.X_add_number = 0;
6090           if (expr1.X_add_number < -0x8000
6091               || expr1.X_add_number >= 0x8000)
6092             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6093           gpdelay = reg_needs_delay (mips_gp_register);
6094           relax_start (offset_expr.X_add_symbol);
6095           macro_build (&offset_expr, "lui", "t,u", tempreg,
6096                        BFD_RELOC_MIPS_GOT_HI16);
6097           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
6098                        mips_gp_register);
6099           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
6100                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
6101           relax_switch ();
6102           if (gpdelay)
6103             macro_build (NULL, "nop", "");
6104           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
6105                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
6106           load_delay_nop ();
6107           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
6108                        tempreg, BFD_RELOC_LO16);
6109           relax_end ();
6110
6111           if (breg != 0)
6112             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6113                          tempreg, tempreg, breg);
6114           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
6115         }
6116       else if (mips_pic == SVR4_PIC && HAVE_NEWABI)
6117         {
6118           /* If this is a reference to an external symbol, we want
6119                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
6120                add      $tempreg,$tempreg,$gp
6121                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
6122                <op>     $treg,<ofst>($tempreg)
6123              Otherwise, for local symbols, we want:
6124                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
6125                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
6126           assert (offset_expr.X_op == O_symbol);
6127           expr1.X_add_number = offset_expr.X_add_number;
6128           offset_expr.X_add_number = 0;
6129           if (expr1.X_add_number < -0x8000
6130               || expr1.X_add_number >= 0x8000)
6131             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6132           relax_start (offset_expr.X_add_symbol);
6133           macro_build (&offset_expr, "lui", "t,u", tempreg,
6134                        BFD_RELOC_MIPS_GOT_HI16);
6135           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
6136                        mips_gp_register);
6137           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
6138                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
6139           if (breg != 0)
6140             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6141                          tempreg, tempreg, breg);
6142           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
6143
6144           relax_switch ();
6145           offset_expr.X_add_number = expr1.X_add_number;
6146           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
6147                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
6148           if (breg != 0)
6149             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6150                          tempreg, tempreg, breg);
6151           macro_build (&offset_expr, s, fmt, treg,
6152                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
6153           relax_end ();
6154         }
6155       else
6156         abort ();
6157
6158       break;
6159
6160     case M_LI:
6161     case M_LI_S:
6162       load_register (treg, &imm_expr, 0);
6163       break;
6164
6165     case M_DLI:
6166       load_register (treg, &imm_expr, 1);
6167       break;
6168
6169     case M_LI_SS:
6170       if (imm_expr.X_op == O_constant)
6171         {
6172           used_at = 1;
6173           load_register (AT, &imm_expr, 0);
6174           macro_build (NULL, "mtc1", "t,G", AT, treg);
6175           break;
6176         }
6177       else
6178         {
6179           assert (offset_expr.X_op == O_symbol
6180                   && strcmp (segment_name (S_GET_SEGMENT
6181                                            (offset_expr.X_add_symbol)),
6182                              ".lit4") == 0
6183                   && offset_expr.X_add_number == 0);
6184           macro_build (&offset_expr, "lwc1", "T,o(b)", treg,
6185                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
6186           break;
6187         }
6188
6189     case M_LI_D:
6190       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
6191          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
6192          order 32 bits of the value and the low order 32 bits are either
6193          zero or in OFFSET_EXPR.  */
6194       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
6195         {
6196           if (HAVE_64BIT_GPRS)
6197             load_register (treg, &imm_expr, 1);
6198           else
6199             {
6200               int hreg, lreg;
6201
6202               if (target_big_endian)
6203                 {
6204                   hreg = treg;
6205                   lreg = treg + 1;
6206                 }
6207               else
6208                 {
6209                   hreg = treg + 1;
6210                   lreg = treg;
6211                 }
6212
6213               if (hreg <= 31)
6214                 load_register (hreg, &imm_expr, 0);
6215               if (lreg <= 31)
6216                 {
6217                   if (offset_expr.X_op == O_absent)
6218                     move_register (lreg, 0);
6219                   else
6220                     {
6221                       assert (offset_expr.X_op == O_constant);
6222                       load_register (lreg, &offset_expr, 0);
6223                     }
6224                 }
6225             }
6226           break;
6227         }
6228
6229       /* We know that sym is in the .rdata section.  First we get the
6230          upper 16 bits of the address.  */
6231       if (mips_pic == NO_PIC)
6232         {
6233           macro_build_lui (&offset_expr, AT);
6234           used_at = 1;
6235         }
6236       else if (mips_pic == SVR4_PIC)
6237         {
6238           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
6239                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
6240           used_at = 1;
6241         }
6242       else
6243         abort ();
6244
6245       /* Now we load the register(s).  */
6246       if (HAVE_64BIT_GPRS)
6247         {
6248           used_at = 1;
6249           macro_build (&offset_expr, "ld", "t,o(b)", treg, BFD_RELOC_LO16, AT);
6250         }
6251       else
6252         {
6253           used_at = 1;
6254           macro_build (&offset_expr, "lw", "t,o(b)", treg, BFD_RELOC_LO16, AT);
6255           if (treg != RA)
6256             {
6257               /* FIXME: How in the world do we deal with the possible
6258                  overflow here?  */
6259               offset_expr.X_add_number += 4;
6260               macro_build (&offset_expr, "lw", "t,o(b)",
6261                            treg + 1, BFD_RELOC_LO16, AT);
6262             }
6263         }
6264       break;
6265
6266     case M_LI_DD:
6267       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
6268          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
6269          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
6270          the value and the low order 32 bits are either zero or in
6271          OFFSET_EXPR.  */
6272       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
6273         {
6274           used_at = 1;
6275           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
6276           if (HAVE_64BIT_FPRS)
6277             {
6278               assert (HAVE_64BIT_GPRS);
6279               macro_build (NULL, "dmtc1", "t,S", AT, treg);
6280             }
6281           else
6282             {
6283               macro_build (NULL, "mtc1", "t,G", AT, treg + 1);
6284               if (offset_expr.X_op == O_absent)
6285                 macro_build (NULL, "mtc1", "t,G", 0, treg);
6286               else
6287                 {
6288                   assert (offset_expr.X_op == O_constant);
6289                   load_register (AT, &offset_expr, 0);
6290                   macro_build (NULL, "mtc1", "t,G", AT, treg);
6291                 }
6292             }
6293           break;
6294         }
6295
6296       assert (offset_expr.X_op == O_symbol
6297               && offset_expr.X_add_number == 0);
6298       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
6299       if (strcmp (s, ".lit8") == 0)
6300         {
6301           if (mips_opts.isa != ISA_MIPS1)
6302             {
6303               macro_build (&offset_expr, "ldc1", "T,o(b)", treg,
6304                            BFD_RELOC_MIPS_LITERAL, mips_gp_register);
6305               break;
6306             }
6307           breg = mips_gp_register;
6308           r = BFD_RELOC_MIPS_LITERAL;
6309           goto dob;
6310         }
6311       else
6312         {
6313           assert (strcmp (s, RDATA_SECTION_NAME) == 0);
6314           used_at = 1;
6315           if (mips_pic == SVR4_PIC)
6316             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
6317                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
6318           else
6319             {
6320               /* FIXME: This won't work for a 64 bit address.  */
6321               macro_build_lui (&offset_expr, AT);
6322             }
6323
6324           if (mips_opts.isa != ISA_MIPS1)
6325             {
6326               macro_build (&offset_expr, "ldc1", "T,o(b)",
6327                            treg, BFD_RELOC_LO16, AT);
6328               break;
6329             }
6330           breg = AT;
6331           r = BFD_RELOC_LO16;
6332           goto dob;
6333         }
6334
6335     case M_L_DOB:
6336       if (mips_opts.arch == CPU_R4650)
6337         {
6338           as_bad (_("opcode not supported on this processor"));
6339           break;
6340         }
6341       /* Even on a big endian machine $fn comes before $fn+1.  We have
6342          to adjust when loading from memory.  */
6343       r = BFD_RELOC_LO16;
6344     dob:
6345       assert (mips_opts.isa == ISA_MIPS1);
6346       macro_build (&offset_expr, "lwc1", "T,o(b)",
6347                    target_big_endian ? treg + 1 : treg, r, breg);
6348       /* FIXME: A possible overflow which I don't know how to deal
6349          with.  */
6350       offset_expr.X_add_number += 4;
6351       macro_build (&offset_expr, "lwc1", "T,o(b)",
6352                    target_big_endian ? treg : treg + 1, r, breg);
6353       break;
6354
6355     case M_L_DAB:
6356       /*
6357        * The MIPS assembler seems to check for X_add_number not
6358        * being double aligned and generating:
6359        *        lui     at,%hi(foo+1)
6360        *        addu    at,at,v1
6361        *        addiu   at,at,%lo(foo+1)
6362        *        lwc1    f2,0(at)
6363        *        lwc1    f3,4(at)
6364        * But, the resulting address is the same after relocation so why
6365        * generate the extra instruction?
6366        */
6367       if (mips_opts.arch == CPU_R4650)
6368         {
6369           as_bad (_("opcode not supported on this processor"));
6370           break;
6371         }
6372       /* Itbl support may require additional care here.  */
6373       coproc = 1;
6374       if (mips_opts.isa != ISA_MIPS1)
6375         {
6376           s = "ldc1";
6377           goto ld;
6378         }
6379
6380       s = "lwc1";
6381       fmt = "T,o(b)";
6382       goto ldd_std;
6383
6384     case M_S_DAB:
6385       if (mips_opts.arch == CPU_R4650)
6386         {
6387           as_bad (_("opcode not supported on this processor"));
6388           break;
6389         }
6390
6391       if (mips_opts.isa != ISA_MIPS1)
6392         {
6393           s = "sdc1";
6394           goto st;
6395         }
6396
6397       s = "swc1";
6398       fmt = "T,o(b)";
6399       /* Itbl support may require additional care here.  */
6400       coproc = 1;
6401       goto ldd_std;
6402
6403     case M_LD_AB:
6404       if (HAVE_64BIT_GPRS)
6405         {
6406           s = "ld";
6407           goto ld;
6408         }
6409
6410       s = "lw";
6411       fmt = "t,o(b)";
6412       goto ldd_std;
6413
6414     case M_SD_AB:
6415       if (HAVE_64BIT_GPRS)
6416         {
6417           s = "sd";
6418           goto st;
6419         }
6420
6421       s = "sw";
6422       fmt = "t,o(b)";
6423
6424     ldd_std:
6425       if (offset_expr.X_op != O_symbol
6426           && offset_expr.X_op != O_constant)
6427         {
6428           as_bad (_("expression too complex"));
6429           offset_expr.X_op = O_constant;
6430         }
6431
6432       if (HAVE_32BIT_ADDRESSES
6433           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
6434         {
6435           char value [32];
6436
6437           sprintf_vma (value, offset_expr.X_add_number);
6438           as_bad (_("Number (0x%s) larger than 32 bits"), value);
6439         }
6440
6441       /* Even on a big endian machine $fn comes before $fn+1.  We have
6442          to adjust when loading from memory.  We set coproc if we must
6443          load $fn+1 first.  */
6444       /* Itbl support may require additional care here.  */
6445       if (! target_big_endian)
6446         coproc = 0;
6447
6448       if (mips_pic == NO_PIC
6449           || offset_expr.X_op == O_constant)
6450         {
6451           /* If this is a reference to a GP relative symbol, we want
6452                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
6453                <op>     $treg+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
6454              If we have a base register, we use this
6455                addu     $at,$breg,$gp
6456                <op>     $treg,<sym>($at)        (BFD_RELOC_GPREL16)
6457                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
6458              If this is not a GP relative symbol, we want
6459                lui      $at,<sym>               (BFD_RELOC_HI16_S)
6460                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
6461                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
6462              If there is a base register, we add it to $at after the
6463              lui instruction.  If there is a constant, we always use
6464              the last case.  */
6465           if (offset_expr.X_op == O_symbol
6466               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
6467               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
6468             {
6469               relax_start (offset_expr.X_add_symbol);
6470               if (breg == 0)
6471                 {
6472                   tempreg = mips_gp_register;
6473                 }
6474               else
6475                 {
6476                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6477                                AT, breg, mips_gp_register);
6478                   tempreg = AT;
6479                   used_at = 1;
6480                 }
6481
6482               /* Itbl support may require additional care here.  */
6483               macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
6484                            BFD_RELOC_GPREL16, tempreg);
6485               offset_expr.X_add_number += 4;
6486
6487               /* Set mips_optimize to 2 to avoid inserting an
6488                  undesired nop.  */
6489               hold_mips_optimize = mips_optimize;
6490               mips_optimize = 2;
6491               /* Itbl support may require additional care here.  */
6492               macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
6493                            BFD_RELOC_GPREL16, tempreg);
6494               mips_optimize = hold_mips_optimize;
6495
6496               relax_switch ();
6497
6498               /* We just generated two relocs.  When tc_gen_reloc
6499                  handles this case, it will skip the first reloc and
6500                  handle the second.  The second reloc already has an
6501                  extra addend of 4, which we added above.  We must
6502                  subtract it out, and then subtract another 4 to make
6503                  the first reloc come out right.  The second reloc
6504                  will come out right because we are going to add 4 to
6505                  offset_expr when we build its instruction below.
6506
6507                  If we have a symbol, then we don't want to include
6508                  the offset, because it will wind up being included
6509                  when we generate the reloc.  */
6510
6511               if (offset_expr.X_op == O_constant)
6512                 offset_expr.X_add_number -= 8;
6513               else
6514                 {
6515                   offset_expr.X_add_number = -4;
6516                   offset_expr.X_op = O_constant;
6517                 }
6518             }
6519           used_at = 1;
6520           macro_build_lui (&offset_expr, AT);
6521           if (breg != 0)
6522             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
6523           /* Itbl support may require additional care here.  */
6524           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
6525                        BFD_RELOC_LO16, AT);
6526           /* FIXME: How do we handle overflow here?  */
6527           offset_expr.X_add_number += 4;
6528           /* Itbl support may require additional care here.  */
6529           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
6530                        BFD_RELOC_LO16, AT);
6531           if (mips_relax.sequence)
6532             relax_end ();
6533         }
6534       else if (mips_pic == SVR4_PIC && ! mips_big_got)
6535         {
6536           /* If this is a reference to an external symbol, we want
6537                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
6538                nop
6539                <op>     $treg,0($at)
6540                <op>     $treg+1,4($at)
6541              Otherwise we want
6542                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
6543                nop
6544                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
6545                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
6546              If there is a base register we add it to $at before the
6547              lwc1 instructions.  If there is a constant we include it
6548              in the lwc1 instructions.  */
6549           used_at = 1;
6550           expr1.X_add_number = offset_expr.X_add_number;
6551           if (expr1.X_add_number < -0x8000
6552               || expr1.X_add_number >= 0x8000 - 4)
6553             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6554           load_got_offset (AT, &offset_expr);
6555           load_delay_nop ();
6556           if (breg != 0)
6557             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
6558
6559           /* Set mips_optimize to 2 to avoid inserting an undesired
6560              nop.  */
6561           hold_mips_optimize = mips_optimize;
6562           mips_optimize = 2;
6563
6564           /* Itbl support may require additional care here.  */
6565           relax_start (offset_expr.X_add_symbol);
6566           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
6567                        BFD_RELOC_LO16, AT);
6568           expr1.X_add_number += 4;
6569           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
6570                        BFD_RELOC_LO16, AT);
6571           relax_switch ();
6572           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
6573                        BFD_RELOC_LO16, AT);
6574           offset_expr.X_add_number += 4;
6575           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
6576                        BFD_RELOC_LO16, AT);
6577           relax_end ();
6578
6579           mips_optimize = hold_mips_optimize;
6580         }
6581       else if (mips_pic == SVR4_PIC)
6582         {
6583           int gpdelay;
6584
6585           /* If this is a reference to an external symbol, we want
6586                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
6587                addu     $at,$at,$gp
6588                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
6589                nop
6590                <op>     $treg,0($at)
6591                <op>     $treg+1,4($at)
6592              Otherwise we want
6593                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
6594                nop
6595                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
6596                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
6597              If there is a base register we add it to $at before the
6598              lwc1 instructions.  If there is a constant we include it
6599              in the lwc1 instructions.  */
6600           used_at = 1;
6601           expr1.X_add_number = offset_expr.X_add_number;
6602           offset_expr.X_add_number = 0;
6603           if (expr1.X_add_number < -0x8000
6604               || expr1.X_add_number >= 0x8000 - 4)
6605             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6606           gpdelay = reg_needs_delay (mips_gp_register);
6607           relax_start (offset_expr.X_add_symbol);
6608           macro_build (&offset_expr, "lui", "t,u",
6609                        AT, BFD_RELOC_MIPS_GOT_HI16);
6610           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6611                        AT, AT, mips_gp_register);
6612           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
6613                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
6614           load_delay_nop ();
6615           if (breg != 0)
6616             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
6617           /* Itbl support may require additional care here.  */
6618           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
6619                        BFD_RELOC_LO16, AT);
6620           expr1.X_add_number += 4;
6621
6622           /* Set mips_optimize to 2 to avoid inserting an undesired
6623              nop.  */
6624           hold_mips_optimize = mips_optimize;
6625           mips_optimize = 2;
6626           /* Itbl support may require additional care here.  */
6627           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
6628                        BFD_RELOC_LO16, AT);
6629           mips_optimize = hold_mips_optimize;
6630           expr1.X_add_number -= 4;
6631
6632           relax_switch ();
6633           offset_expr.X_add_number = expr1.X_add_number;
6634           if (gpdelay)
6635             macro_build (NULL, "nop", "");
6636           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
6637                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
6638           load_delay_nop ();
6639           if (breg != 0)
6640             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
6641           /* Itbl support may require additional care here.  */
6642           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
6643                        BFD_RELOC_LO16, AT);
6644           offset_expr.X_add_number += 4;
6645
6646           /* Set mips_optimize to 2 to avoid inserting an undesired
6647              nop.  */
6648           hold_mips_optimize = mips_optimize;
6649           mips_optimize = 2;
6650           /* Itbl support may require additional care here.  */
6651           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
6652                        BFD_RELOC_LO16, AT);
6653           mips_optimize = hold_mips_optimize;
6654           relax_end ();
6655         }
6656       else
6657         abort ();
6658
6659       break;
6660
6661     case M_LD_OB:
6662       s = "lw";
6663       goto sd_ob;
6664     case M_SD_OB:
6665       s = "sw";
6666     sd_ob:
6667       assert (HAVE_32BIT_ADDRESSES);
6668       macro_build (&offset_expr, s, "t,o(b)", treg, BFD_RELOC_LO16, breg);
6669       offset_expr.X_add_number += 4;
6670       macro_build (&offset_expr, s, "t,o(b)", treg + 1, BFD_RELOC_LO16, breg);
6671       break;
6672
6673    /* New code added to support COPZ instructions.
6674       This code builds table entries out of the macros in mip_opcodes.
6675       R4000 uses interlocks to handle coproc delays.
6676       Other chips (like the R3000) require nops to be inserted for delays.
6677
6678       FIXME: Currently, we require that the user handle delays.
6679       In order to fill delay slots for non-interlocked chips,
6680       we must have a way to specify delays based on the coprocessor.
6681       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
6682       What are the side-effects of the cop instruction?
6683       What cache support might we have and what are its effects?
6684       Both coprocessor & memory require delays. how long???
6685       What registers are read/set/modified?
6686
6687       If an itbl is provided to interpret cop instructions,
6688       this knowledge can be encoded in the itbl spec.  */
6689
6690     case M_COP0:
6691       s = "c0";
6692       goto copz;
6693     case M_COP1:
6694       s = "c1";
6695       goto copz;
6696     case M_COP2:
6697       s = "c2";
6698       goto copz;
6699     case M_COP3:
6700       s = "c3";
6701     copz:
6702       /* For now we just do C (same as Cz).  The parameter will be
6703          stored in insn_opcode by mips_ip.  */
6704       macro_build (NULL, s, "C", ip->insn_opcode);
6705       break;
6706
6707     case M_MOVE:
6708       move_register (dreg, sreg);
6709       break;
6710
6711 #ifdef LOSING_COMPILER
6712     default:
6713       /* Try and see if this is a new itbl instruction.
6714          This code builds table entries out of the macros in mip_opcodes.
6715          FIXME: For now we just assemble the expression and pass it's
6716          value along as a 32-bit immediate.
6717          We may want to have the assembler assemble this value,
6718          so that we gain the assembler's knowledge of delay slots,
6719          symbols, etc.
6720          Would it be more efficient to use mask (id) here? */
6721       if (itbl_have_entries
6722           && (immed_expr = itbl_assemble (ip->insn_mo->name, "")))
6723         {
6724           s = ip->insn_mo->name;
6725           s2 = "cop3";
6726           coproc = ITBL_DECODE_PNUM (immed_expr);;
6727           macro_build (&immed_expr, s, "C");
6728           break;
6729         }
6730       macro2 (ip);
6731       break;
6732     }
6733   if (mips_opts.noat && used_at)
6734     as_bad (_("Macro used $at after \".set noat\""));
6735 }
6736
6737 static void
6738 macro2 (struct mips_cl_insn *ip)
6739 {
6740   register int treg, sreg, dreg, breg;
6741   int tempreg;
6742   int mask;
6743   int used_at;
6744   expressionS expr1;
6745   const char *s;
6746   const char *s2;
6747   const char *fmt;
6748   int likely = 0;
6749   int dbl = 0;
6750   int coproc = 0;
6751   int lr = 0;
6752   int imm = 0;
6753   int off;
6754   offsetT maxnum;
6755   bfd_reloc_code_real_type r;
6756
6757   treg = (ip->insn_opcode >> 16) & 0x1f;
6758   dreg = (ip->insn_opcode >> 11) & 0x1f;
6759   sreg = breg = (ip->insn_opcode >> 21) & 0x1f;
6760   mask = ip->insn_mo->mask;
6761
6762   expr1.X_op = O_constant;
6763   expr1.X_op_symbol = NULL;
6764   expr1.X_add_symbol = NULL;
6765   expr1.X_add_number = 1;
6766
6767   switch (mask)
6768     {
6769 #endif /* LOSING_COMPILER */
6770
6771     case M_DMUL:
6772       dbl = 1;
6773     case M_MUL:
6774       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", sreg, treg);
6775       macro_build (NULL, "mflo", "d", dreg);
6776       break;
6777
6778     case M_DMUL_I:
6779       dbl = 1;
6780     case M_MUL_I:
6781       /* The MIPS assembler some times generates shifts and adds.  I'm
6782          not trying to be that fancy. GCC should do this for us
6783          anyway.  */
6784       used_at = 1;
6785       load_register (AT, &imm_expr, dbl);
6786       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, AT);
6787       macro_build (NULL, "mflo", "d", dreg);
6788       break;
6789
6790     case M_DMULO_I:
6791       dbl = 1;
6792     case M_MULO_I:
6793       imm = 1;
6794       goto do_mulo;
6795
6796     case M_DMULO:
6797       dbl = 1;
6798     case M_MULO:
6799     do_mulo:
6800       start_noreorder ();
6801       used_at = 1;
6802       if (imm)
6803         load_register (AT, &imm_expr, dbl);
6804       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, imm ? AT : treg);
6805       macro_build (NULL, "mflo", "d", dreg);
6806       macro_build (NULL, dbl ? "dsra32" : "sra", "d,w,<", dreg, dreg, RA);
6807       macro_build (NULL, "mfhi", "d", AT);
6808       if (mips_trap)
6809         macro_build (NULL, "tne", "s,t,q", dreg, AT, 6);
6810       else
6811         {
6812           expr1.X_add_number = 8;
6813           macro_build (&expr1, "beq", "s,t,p", dreg, AT);
6814           macro_build (NULL, "nop", "", 0);
6815           macro_build (NULL, "break", "c", 6);
6816         }
6817       end_noreorder ();
6818       macro_build (NULL, "mflo", "d", dreg);
6819       break;
6820
6821     case M_DMULOU_I:
6822       dbl = 1;
6823     case M_MULOU_I:
6824       imm = 1;
6825       goto do_mulou;
6826
6827     case M_DMULOU:
6828       dbl = 1;
6829     case M_MULOU:
6830     do_mulou:
6831       start_noreorder ();
6832       used_at = 1;
6833       if (imm)
6834         load_register (AT, &imm_expr, dbl);
6835       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
6836                    sreg, imm ? AT : treg);
6837       macro_build (NULL, "mfhi", "d", AT);
6838       macro_build (NULL, "mflo", "d", dreg);
6839       if (mips_trap)
6840         macro_build (NULL, "tne", "s,t,q", AT, 0, 6);
6841       else
6842         {
6843           expr1.X_add_number = 8;
6844           macro_build (&expr1, "beq", "s,t,p", AT, 0);
6845           macro_build (NULL, "nop", "", 0);
6846           macro_build (NULL, "break", "c", 6);
6847         }
6848       end_noreorder ();
6849       break;
6850
6851     case M_DROL:
6852       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
6853         {
6854           if (dreg == sreg)
6855             {
6856               tempreg = AT;
6857               used_at = 1;
6858             }
6859           else
6860             {
6861               tempreg = dreg;
6862             }
6863           macro_build (NULL, "dnegu", "d,w", tempreg, treg);
6864           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, tempreg);
6865           break;
6866         }
6867       used_at = 1;
6868       macro_build (NULL, "dsubu", "d,v,t", AT, 0, treg);
6869       macro_build (NULL, "dsrlv", "d,t,s", AT, sreg, AT);
6870       macro_build (NULL, "dsllv", "d,t,s", dreg, sreg, treg);
6871       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
6872       break;
6873
6874     case M_ROL:
6875       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
6876         {
6877           if (dreg == sreg)
6878             {
6879               tempreg = AT;
6880               used_at = 1;
6881             }
6882           else
6883             {
6884               tempreg = dreg;
6885             }
6886           macro_build (NULL, "negu", "d,w", tempreg, treg);
6887           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, tempreg);
6888           break;
6889         }
6890       used_at = 1;
6891       macro_build (NULL, "subu", "d,v,t", AT, 0, treg);
6892       macro_build (NULL, "srlv", "d,t,s", AT, sreg, AT);
6893       macro_build (NULL, "sllv", "d,t,s", dreg, sreg, treg);
6894       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
6895       break;
6896
6897     case M_DROL_I:
6898       {
6899         unsigned int rot;
6900         char *l, *r;
6901
6902         if (imm_expr.X_op != O_constant)
6903           as_bad (_("Improper rotate count"));
6904         rot = imm_expr.X_add_number & 0x3f;
6905         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
6906           {
6907             rot = (64 - rot) & 0x3f;
6908             if (rot >= 32)
6909               macro_build (NULL, "dror32", "d,w,<", dreg, sreg, rot - 32);
6910             else
6911               macro_build (NULL, "dror", "d,w,<", dreg, sreg, rot);
6912             break;
6913           }
6914         if (rot == 0)
6915           {
6916             macro_build (NULL, "dsrl", "d,w,<", dreg, sreg, 0);
6917             break;
6918           }
6919         l = (rot < 0x20) ? "dsll" : "dsll32";
6920         r = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
6921         rot &= 0x1f;
6922         used_at = 1;
6923         macro_build (NULL, l, "d,w,<", AT, sreg, rot);
6924         macro_build (NULL, r, "d,w,<", dreg, sreg, (0x20 - rot) & 0x1f);
6925         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
6926       }
6927       break;
6928
6929     case M_ROL_I:
6930       {
6931         unsigned int rot;
6932
6933         if (imm_expr.X_op != O_constant)
6934           as_bad (_("Improper rotate count"));
6935         rot = imm_expr.X_add_number & 0x1f;
6936         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
6937           {
6938             macro_build (NULL, "ror", "d,w,<", dreg, sreg, (32 - rot) & 0x1f);
6939             break;
6940           }
6941         if (rot == 0)
6942           {
6943             macro_build (NULL, "srl", "d,w,<", dreg, sreg, 0);
6944             break;
6945           }
6946         used_at = 1;
6947         macro_build (NULL, "sll", "d,w,<", AT, sreg, rot);
6948         macro_build (NULL, "srl", "d,w,<", dreg, sreg, (0x20 - rot) & 0x1f);
6949         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
6950       }
6951       break;
6952
6953     case M_DROR:
6954       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
6955         {
6956           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, treg);
6957           break;
6958         }
6959       used_at = 1;
6960       macro_build (NULL, "dsubu", "d,v,t", AT, 0, treg);
6961       macro_build (NULL, "dsllv", "d,t,s", AT, sreg, AT);
6962       macro_build (NULL, "dsrlv", "d,t,s", dreg, sreg, treg);
6963       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
6964       break;
6965
6966     case M_ROR:
6967       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
6968         {
6969           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, treg);
6970           break;
6971         }
6972       used_at = 1;
6973       macro_build (NULL, "subu", "d,v,t", AT, 0, treg);
6974       macro_build (NULL, "sllv", "d,t,s", AT, sreg, AT);
6975       macro_build (NULL, "srlv", "d,t,s", dreg, sreg, treg);
6976       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
6977       break;
6978
6979     case M_DROR_I:
6980       {
6981         unsigned int rot;
6982         char *l, *r;
6983
6984         if (imm_expr.X_op != O_constant)
6985           as_bad (_("Improper rotate count"));
6986         rot = imm_expr.X_add_number & 0x3f;
6987         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
6988           {
6989             if (rot >= 32)
6990               macro_build (NULL, "dror32", "d,w,<", dreg, sreg, rot - 32);
6991             else
6992               macro_build (NULL, "dror", "d,w,<", dreg, sreg, rot);
6993             break;
6994           }
6995         if (rot == 0)
6996           {
6997             macro_build (NULL, "dsrl", "d,w,<", dreg, sreg, 0);
6998             break;
6999           }
7000         r = (rot < 0x20) ? "dsrl" : "dsrl32";
7001         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
7002         rot &= 0x1f;
7003         used_at = 1;
7004         macro_build (NULL, r, "d,w,<", AT, sreg, rot);
7005         macro_build (NULL, l, "d,w,<", dreg, sreg, (0x20 - rot) & 0x1f);
7006         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
7007       }
7008       break;
7009
7010     case M_ROR_I:
7011       {
7012         unsigned int rot;
7013
7014         if (imm_expr.X_op != O_constant)
7015           as_bad (_("Improper rotate count"));
7016         rot = imm_expr.X_add_number & 0x1f;
7017         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
7018           {
7019             macro_build (NULL, "ror", "d,w,<", dreg, sreg, rot);
7020             break;
7021           }
7022         if (rot == 0)
7023           {
7024             macro_build (NULL, "srl", "d,w,<", dreg, sreg, 0);
7025             break;
7026           }
7027         used_at = 1;
7028         macro_build (NULL, "srl", "d,w,<", AT, sreg, rot);
7029         macro_build (NULL, "sll", "d,w,<", dreg, sreg, (0x20 - rot) & 0x1f);
7030         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
7031       }
7032       break;
7033
7034     case M_S_DOB:
7035       if (mips_opts.arch == CPU_R4650)
7036         {
7037           as_bad (_("opcode not supported on this processor"));
7038           break;
7039         }
7040       assert (mips_opts.isa == ISA_MIPS1);
7041       /* Even on a big endian machine $fn comes before $fn+1.  We have
7042          to adjust when storing to memory.  */
7043       macro_build (&offset_expr, "swc1", "T,o(b)",
7044                    target_big_endian ? treg + 1 : treg, BFD_RELOC_LO16, breg);
7045       offset_expr.X_add_number += 4;
7046       macro_build (&offset_expr, "swc1", "T,o(b)",
7047                    target_big_endian ? treg : treg + 1, BFD_RELOC_LO16, breg);
7048       break;
7049
7050     case M_SEQ:
7051       if (sreg == 0)
7052         macro_build (&expr1, "sltiu", "t,r,j", dreg, treg, BFD_RELOC_LO16);
7053       else if (treg == 0)
7054         macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
7055       else
7056         {
7057           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
7058           macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
7059         }
7060       break;
7061
7062     case M_SEQ_I:
7063       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7064         {
7065           macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
7066           break;
7067         }
7068       if (sreg == 0)
7069         {
7070           as_warn (_("Instruction %s: result is always false"),
7071                    ip->insn_mo->name);
7072           move_register (dreg, 0);
7073           break;
7074         }
7075       if (imm_expr.X_op == O_constant
7076           && imm_expr.X_add_number >= 0
7077           && imm_expr.X_add_number < 0x10000)
7078         {
7079           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
7080         }
7081       else if (imm_expr.X_op == O_constant
7082                && imm_expr.X_add_number > -0x8000
7083                && imm_expr.X_add_number < 0)
7084         {
7085           imm_expr.X_add_number = -imm_expr.X_add_number;
7086           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
7087                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
7088         }
7089       else
7090         {
7091           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7092           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
7093           used_at = 1;
7094         }
7095       macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
7096       break;
7097
7098     case M_SGE:         /* sreg >= treg <==> not (sreg < treg) */
7099       s = "slt";
7100       goto sge;
7101     case M_SGEU:
7102       s = "sltu";
7103     sge:
7104       macro_build (NULL, s, "d,v,t", dreg, sreg, treg);
7105       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
7106       break;
7107
7108     case M_SGE_I:               /* sreg >= I <==> not (sreg < I) */
7109     case M_SGEU_I:
7110       if (imm_expr.X_op == O_constant
7111           && imm_expr.X_add_number >= -0x8000
7112           && imm_expr.X_add_number < 0x8000)
7113         {
7114           macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
7115                        dreg, sreg, BFD_RELOC_LO16);
7116         }
7117       else
7118         {
7119           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7120           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
7121                        dreg, sreg, AT);
7122           used_at = 1;
7123         }
7124       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
7125       break;
7126
7127     case M_SGT:         /* sreg > treg  <==>  treg < sreg */
7128       s = "slt";
7129       goto sgt;
7130     case M_SGTU:
7131       s = "sltu";
7132     sgt:
7133       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
7134       break;
7135
7136     case M_SGT_I:               /* sreg > I  <==>  I < sreg */
7137       s = "slt";
7138       goto sgti;
7139     case M_SGTU_I:
7140       s = "sltu";
7141     sgti:
7142       used_at = 1;
7143       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7144       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
7145       break;
7146
7147     case M_SLE: /* sreg <= treg  <==>  treg >= sreg  <==>  not (treg < sreg) */
7148       s = "slt";
7149       goto sle;
7150     case M_SLEU:
7151       s = "sltu";
7152     sle:
7153       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
7154       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
7155       break;
7156
7157     case M_SLE_I:       /* sreg <= I <==> I >= sreg <==> not (I < sreg) */
7158       s = "slt";
7159       goto slei;
7160     case M_SLEU_I:
7161       s = "sltu";
7162     slei:
7163       used_at = 1;
7164       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7165       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
7166       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
7167       break;
7168
7169     case M_SLT_I:
7170       if (imm_expr.X_op == O_constant
7171           && imm_expr.X_add_number >= -0x8000
7172           && imm_expr.X_add_number < 0x8000)
7173         {
7174           macro_build (&imm_expr, "slti", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
7175           break;
7176         }
7177       used_at = 1;
7178       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7179       macro_build (NULL, "slt", "d,v,t", dreg, sreg, AT);
7180       break;
7181
7182     case M_SLTU_I:
7183       if (imm_expr.X_op == O_constant
7184           && imm_expr.X_add_number >= -0x8000
7185           && imm_expr.X_add_number < 0x8000)
7186         {
7187           macro_build (&imm_expr, "sltiu", "t,r,j", dreg, sreg,
7188                        BFD_RELOC_LO16);
7189           break;
7190         }
7191       used_at = 1;
7192       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7193       macro_build (NULL, "sltu", "d,v,t", dreg, sreg, AT);
7194       break;
7195
7196     case M_SNE:
7197       if (sreg == 0)
7198         macro_build (NULL, "sltu", "d,v,t", dreg, 0, treg);
7199       else if (treg == 0)
7200         macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
7201       else
7202         {
7203           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
7204           macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
7205         }
7206       break;
7207
7208     case M_SNE_I:
7209       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7210         {
7211           macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
7212           break;
7213         }
7214       if (sreg == 0)
7215         {
7216           as_warn (_("Instruction %s: result is always true"),
7217                    ip->insn_mo->name);
7218           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
7219                        dreg, 0, BFD_RELOC_LO16);
7220           break;
7221         }
7222       if (imm_expr.X_op == O_constant
7223           && imm_expr.X_add_number >= 0
7224           && imm_expr.X_add_number < 0x10000)
7225         {
7226           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
7227         }
7228       else if (imm_expr.X_op == O_constant
7229                && imm_expr.X_add_number > -0x8000
7230                && imm_expr.X_add_number < 0)
7231         {
7232           imm_expr.X_add_number = -imm_expr.X_add_number;
7233           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
7234                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
7235         }
7236       else
7237         {
7238           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7239           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
7240           used_at = 1;
7241         }
7242       macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
7243       break;
7244
7245     case M_DSUB_I:
7246       dbl = 1;
7247     case M_SUB_I:
7248       if (imm_expr.X_op == O_constant
7249           && imm_expr.X_add_number > -0x8000
7250           && imm_expr.X_add_number <= 0x8000)
7251         {
7252           imm_expr.X_add_number = -imm_expr.X_add_number;
7253           macro_build (&imm_expr, dbl ? "daddi" : "addi", "t,r,j",
7254                        dreg, sreg, BFD_RELOC_LO16);
7255           break;
7256         }
7257       used_at = 1;
7258       load_register (AT, &imm_expr, dbl);
7259       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", dreg, sreg, AT);
7260       break;
7261
7262     case M_DSUBU_I:
7263       dbl = 1;
7264     case M_SUBU_I:
7265       if (imm_expr.X_op == O_constant
7266           && imm_expr.X_add_number > -0x8000
7267           && imm_expr.X_add_number <= 0x8000)
7268         {
7269           imm_expr.X_add_number = -imm_expr.X_add_number;
7270           macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "t,r,j",
7271                        dreg, sreg, BFD_RELOC_LO16);
7272           break;
7273         }
7274       used_at = 1;
7275       load_register (AT, &imm_expr, dbl);
7276       macro_build (NULL, dbl ? "dsubu" : "subu", "d,v,t", dreg, sreg, AT);
7277       break;
7278
7279     case M_TEQ_I:
7280       s = "teq";
7281       goto trap;
7282     case M_TGE_I:
7283       s = "tge";
7284       goto trap;
7285     case M_TGEU_I:
7286       s = "tgeu";
7287       goto trap;
7288     case M_TLT_I:
7289       s = "tlt";
7290       goto trap;
7291     case M_TLTU_I:
7292       s = "tltu";
7293       goto trap;
7294     case M_TNE_I:
7295       s = "tne";
7296     trap:
7297       used_at = 1;
7298       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7299       macro_build (NULL, s, "s,t", sreg, AT);
7300       break;
7301
7302     case M_TRUNCWS:
7303     case M_TRUNCWD:
7304       assert (mips_opts.isa == ISA_MIPS1);
7305       used_at = 1;
7306       sreg = (ip->insn_opcode >> 11) & 0x1f;    /* floating reg */
7307       dreg = (ip->insn_opcode >> 06) & 0x1f;    /* floating reg */
7308
7309       /*
7310        * Is the double cfc1 instruction a bug in the mips assembler;
7311        * or is there a reason for it?
7312        */
7313       start_noreorder ();
7314       macro_build (NULL, "cfc1", "t,G", treg, RA);
7315       macro_build (NULL, "cfc1", "t,G", treg, RA);
7316       macro_build (NULL, "nop", "");
7317       expr1.X_add_number = 3;
7318       macro_build (&expr1, "ori", "t,r,i", AT, treg, BFD_RELOC_LO16);
7319       expr1.X_add_number = 2;
7320       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
7321       macro_build (NULL, "ctc1", "t,G", AT, RA);
7322       macro_build (NULL, "nop", "");
7323       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
7324                    dreg, sreg);
7325       macro_build (NULL, "ctc1", "t,G", treg, RA);
7326       macro_build (NULL, "nop", "");
7327       end_noreorder ();
7328       break;
7329
7330     case M_ULH:
7331       s = "lb";
7332       goto ulh;
7333     case M_ULHU:
7334       s = "lbu";
7335     ulh:
7336       used_at = 1;
7337       if (offset_expr.X_add_number >= 0x7fff)
7338         as_bad (_("operand overflow"));
7339       if (! target_big_endian)
7340         ++offset_expr.X_add_number;
7341       macro_build (&offset_expr, s, "t,o(b)", AT, BFD_RELOC_LO16, breg);
7342       if (! target_big_endian)
7343         --offset_expr.X_add_number;
7344       else
7345         ++offset_expr.X_add_number;
7346       macro_build (&offset_expr, "lbu", "t,o(b)", treg, BFD_RELOC_LO16, breg);
7347       macro_build (NULL, "sll", "d,w,<", AT, AT, 8);
7348       macro_build (NULL, "or", "d,v,t", treg, treg, AT);
7349       break;
7350
7351     case M_ULD:
7352       s = "ldl";
7353       s2 = "ldr";
7354       off = 7;
7355       goto ulw;
7356     case M_ULW:
7357       s = "lwl";
7358       s2 = "lwr";
7359       off = 3;
7360     ulw:
7361       if (offset_expr.X_add_number >= 0x8000 - off)
7362         as_bad (_("operand overflow"));
7363       if (treg != breg)
7364         tempreg = treg;
7365       else
7366         {
7367           used_at = 1;
7368           tempreg = AT;
7369         }
7370       if (! target_big_endian)
7371         offset_expr.X_add_number += off;
7372       macro_build (&offset_expr, s, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
7373       if (! target_big_endian)
7374         offset_expr.X_add_number -= off;
7375       else
7376         offset_expr.X_add_number += off;
7377       macro_build (&offset_expr, s2, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
7378
7379       /* If necessary, move the result in tempreg the final destination.  */
7380       if (treg == tempreg)
7381         break;
7382       /* Protect second load's delay slot.  */
7383       load_delay_nop ();
7384       move_register (treg, tempreg);
7385       break;
7386
7387     case M_ULD_A:
7388       s = "ldl";
7389       s2 = "ldr";
7390       off = 7;
7391       goto ulwa;
7392     case M_ULW_A:
7393       s = "lwl";
7394       s2 = "lwr";
7395       off = 3;
7396     ulwa:
7397       used_at = 1;
7398       load_address (AT, &offset_expr, &used_at);
7399       if (breg != 0)
7400         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
7401       if (! target_big_endian)
7402         expr1.X_add_number = off;
7403       else
7404         expr1.X_add_number = 0;
7405       macro_build (&expr1, s, "t,o(b)", treg, BFD_RELOC_LO16, AT);
7406       if (! target_big_endian)
7407         expr1.X_add_number = 0;
7408       else
7409         expr1.X_add_number = off;
7410       macro_build (&expr1, s2, "t,o(b)", treg, BFD_RELOC_LO16, AT);
7411       break;
7412
7413     case M_ULH_A:
7414     case M_ULHU_A:
7415       used_at = 1;
7416       load_address (AT, &offset_expr, &used_at);
7417       if (breg != 0)
7418         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
7419       if (target_big_endian)
7420         expr1.X_add_number = 0;
7421       macro_build (&expr1, mask == M_ULH_A ? "lb" : "lbu", "t,o(b)",
7422                    treg, BFD_RELOC_LO16, AT);
7423       if (target_big_endian)
7424         expr1.X_add_number = 1;
7425       else
7426         expr1.X_add_number = 0;
7427       macro_build (&expr1, "lbu", "t,o(b)", AT, BFD_RELOC_LO16, AT);
7428       macro_build (NULL, "sll", "d,w,<", treg, treg, 8);
7429       macro_build (NULL, "or", "d,v,t", treg, treg, AT);
7430       break;
7431
7432     case M_USH:
7433       used_at = 1;
7434       if (offset_expr.X_add_number >= 0x7fff)
7435         as_bad (_("operand overflow"));
7436       if (target_big_endian)
7437         ++offset_expr.X_add_number;
7438       macro_build (&offset_expr, "sb", "t,o(b)", treg, BFD_RELOC_LO16, breg);
7439       macro_build (NULL, "srl", "d,w,<", AT, treg, 8);
7440       if (target_big_endian)
7441         --offset_expr.X_add_number;
7442       else
7443         ++offset_expr.X_add_number;
7444       macro_build (&offset_expr, "sb", "t,o(b)", AT, BFD_RELOC_LO16, breg);
7445       break;
7446
7447     case M_USD:
7448       s = "sdl";
7449       s2 = "sdr";
7450       off = 7;
7451       goto usw;
7452     case M_USW:
7453       s = "swl";
7454       s2 = "swr";
7455       off = 3;
7456     usw:
7457       if (offset_expr.X_add_number >= 0x8000 - off)
7458         as_bad (_("operand overflow"));
7459       if (! target_big_endian)
7460         offset_expr.X_add_number += off;
7461       macro_build (&offset_expr, s, "t,o(b)", treg, BFD_RELOC_LO16, breg);
7462       if (! target_big_endian)
7463         offset_expr.X_add_number -= off;
7464       else
7465         offset_expr.X_add_number += off;
7466       macro_build (&offset_expr, s2, "t,o(b)", treg, BFD_RELOC_LO16, breg);
7467       break;
7468
7469     case M_USD_A:
7470       s = "sdl";
7471       s2 = "sdr";
7472       off = 7;
7473       goto uswa;
7474     case M_USW_A:
7475       s = "swl";
7476       s2 = "swr";
7477       off = 3;
7478     uswa:
7479       used_at = 1;
7480       load_address (AT, &offset_expr, &used_at);
7481       if (breg != 0)
7482         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
7483       if (! target_big_endian)
7484         expr1.X_add_number = off;
7485       else
7486         expr1.X_add_number = 0;
7487       macro_build (&expr1, s, "t,o(b)", treg, BFD_RELOC_LO16, AT);
7488       if (! target_big_endian)
7489         expr1.X_add_number = 0;
7490       else
7491         expr1.X_add_number = off;
7492       macro_build (&expr1, s2, "t,o(b)", treg, BFD_RELOC_LO16, AT);
7493       break;
7494
7495     case M_USH_A:
7496       used_at = 1;
7497       load_address (AT, &offset_expr, &used_at);
7498       if (breg != 0)
7499         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
7500       if (! target_big_endian)
7501         expr1.X_add_number = 0;
7502       macro_build (&expr1, "sb", "t,o(b)", treg, BFD_RELOC_LO16, AT);
7503       macro_build (NULL, "srl", "d,w,<", treg, treg, 8);
7504       if (! target_big_endian)
7505         expr1.X_add_number = 1;
7506       else
7507         expr1.X_add_number = 0;
7508       macro_build (&expr1, "sb", "t,o(b)", treg, BFD_RELOC_LO16, AT);
7509       if (! target_big_endian)
7510         expr1.X_add_number = 0;
7511       else
7512         expr1.X_add_number = 1;
7513       macro_build (&expr1, "lbu", "t,o(b)", AT, BFD_RELOC_LO16, AT);
7514       macro_build (NULL, "sll", "d,w,<", treg, treg, 8);
7515       macro_build (NULL, "or", "d,v,t", treg, treg, AT);
7516       break;
7517
7518     default:
7519       /* FIXME: Check if this is one of the itbl macros, since they
7520          are added dynamically.  */
7521       as_bad (_("Macro %s not implemented yet"), ip->insn_mo->name);
7522       break;
7523     }
7524   if (mips_opts.noat && used_at)
7525     as_bad (_("Macro used $at after \".set noat\""));
7526 }
7527
7528 /* Implement macros in mips16 mode.  */
7529
7530 static void
7531 mips16_macro (struct mips_cl_insn *ip)
7532 {
7533   int mask;
7534   int xreg, yreg, zreg, tmp;
7535   expressionS expr1;
7536   int dbl;
7537   const char *s, *s2, *s3;
7538
7539   mask = ip->insn_mo->mask;
7540
7541   xreg = MIPS16_EXTRACT_OPERAND (RX, *ip);
7542   yreg = MIPS16_EXTRACT_OPERAND (RY, *ip);
7543   zreg = MIPS16_EXTRACT_OPERAND (RZ, *ip);
7544
7545   expr1.X_op = O_constant;
7546   expr1.X_op_symbol = NULL;
7547   expr1.X_add_symbol = NULL;
7548   expr1.X_add_number = 1;
7549
7550   dbl = 0;
7551
7552   switch (mask)
7553     {
7554     default:
7555       internalError ();
7556
7557     case M_DDIV_3:
7558       dbl = 1;
7559     case M_DIV_3:
7560       s = "mflo";
7561       goto do_div3;
7562     case M_DREM_3:
7563       dbl = 1;
7564     case M_REM_3:
7565       s = "mfhi";
7566     do_div3:
7567       start_noreorder ();
7568       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", xreg, yreg);
7569       expr1.X_add_number = 2;
7570       macro_build (&expr1, "bnez", "x,p", yreg);
7571       macro_build (NULL, "break", "6", 7);
7572
7573       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
7574          since that causes an overflow.  We should do that as well,
7575          but I don't see how to do the comparisons without a temporary
7576          register.  */
7577       end_noreorder ();
7578       macro_build (NULL, s, "x", zreg);
7579       break;
7580
7581     case M_DIVU_3:
7582       s = "divu";
7583       s2 = "mflo";
7584       goto do_divu3;
7585     case M_REMU_3:
7586       s = "divu";
7587       s2 = "mfhi";
7588       goto do_divu3;
7589     case M_DDIVU_3:
7590       s = "ddivu";
7591       s2 = "mflo";
7592       goto do_divu3;
7593     case M_DREMU_3:
7594       s = "ddivu";
7595       s2 = "mfhi";
7596     do_divu3:
7597       start_noreorder ();
7598       macro_build (NULL, s, "0,x,y", xreg, yreg);
7599       expr1.X_add_number = 2;
7600       macro_build (&expr1, "bnez", "x,p", yreg);
7601       macro_build (NULL, "break", "6", 7);
7602       end_noreorder ();
7603       macro_build (NULL, s2, "x", zreg);
7604       break;
7605
7606     case M_DMUL:
7607       dbl = 1;
7608     case M_MUL:
7609       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", xreg, yreg);
7610       macro_build (NULL, "mflo", "x", zreg);
7611       break;
7612
7613     case M_DSUBU_I:
7614       dbl = 1;
7615       goto do_subu;
7616     case M_SUBU_I:
7617     do_subu:
7618       if (imm_expr.X_op != O_constant)
7619         as_bad (_("Unsupported large constant"));
7620       imm_expr.X_add_number = -imm_expr.X_add_number;
7621       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", yreg, xreg);
7622       break;
7623
7624     case M_SUBU_I_2:
7625       if (imm_expr.X_op != O_constant)
7626         as_bad (_("Unsupported large constant"));
7627       imm_expr.X_add_number = -imm_expr.X_add_number;
7628       macro_build (&imm_expr, "addiu", "x,k", xreg);
7629       break;
7630
7631     case M_DSUBU_I_2:
7632       if (imm_expr.X_op != O_constant)
7633         as_bad (_("Unsupported large constant"));
7634       imm_expr.X_add_number = -imm_expr.X_add_number;
7635       macro_build (&imm_expr, "daddiu", "y,j", yreg);
7636       break;
7637
7638     case M_BEQ:
7639       s = "cmp";
7640       s2 = "bteqz";
7641       goto do_branch;
7642     case M_BNE:
7643       s = "cmp";
7644       s2 = "btnez";
7645       goto do_branch;
7646     case M_BLT:
7647       s = "slt";
7648       s2 = "btnez";
7649       goto do_branch;
7650     case M_BLTU:
7651       s = "sltu";
7652       s2 = "btnez";
7653       goto do_branch;
7654     case M_BLE:
7655       s = "slt";
7656       s2 = "bteqz";
7657       goto do_reverse_branch;
7658     case M_BLEU:
7659       s = "sltu";
7660       s2 = "bteqz";
7661       goto do_reverse_branch;
7662     case M_BGE:
7663       s = "slt";
7664       s2 = "bteqz";
7665       goto do_branch;
7666     case M_BGEU:
7667       s = "sltu";
7668       s2 = "bteqz";
7669       goto do_branch;
7670     case M_BGT:
7671       s = "slt";
7672       s2 = "btnez";
7673       goto do_reverse_branch;
7674     case M_BGTU:
7675       s = "sltu";
7676       s2 = "btnez";
7677
7678     do_reverse_branch:
7679       tmp = xreg;
7680       xreg = yreg;
7681       yreg = tmp;
7682
7683     do_branch:
7684       macro_build (NULL, s, "x,y", xreg, yreg);
7685       macro_build (&offset_expr, s2, "p");
7686       break;
7687
7688     case M_BEQ_I:
7689       s = "cmpi";
7690       s2 = "bteqz";
7691       s3 = "x,U";
7692       goto do_branch_i;
7693     case M_BNE_I:
7694       s = "cmpi";
7695       s2 = "btnez";
7696       s3 = "x,U";
7697       goto do_branch_i;
7698     case M_BLT_I:
7699       s = "slti";
7700       s2 = "btnez";
7701       s3 = "x,8";
7702       goto do_branch_i;
7703     case M_BLTU_I:
7704       s = "sltiu";
7705       s2 = "btnez";
7706       s3 = "x,8";
7707       goto do_branch_i;
7708     case M_BLE_I:
7709       s = "slti";
7710       s2 = "btnez";
7711       s3 = "x,8";
7712       goto do_addone_branch_i;
7713     case M_BLEU_I:
7714       s = "sltiu";
7715       s2 = "btnez";
7716       s3 = "x,8";
7717       goto do_addone_branch_i;
7718     case M_BGE_I:
7719       s = "slti";
7720       s2 = "bteqz";
7721       s3 = "x,8";
7722       goto do_branch_i;
7723     case M_BGEU_I:
7724       s = "sltiu";
7725       s2 = "bteqz";
7726       s3 = "x,8";
7727       goto do_branch_i;
7728     case M_BGT_I:
7729       s = "slti";
7730       s2 = "bteqz";
7731       s3 = "x,8";
7732       goto do_addone_branch_i;
7733     case M_BGTU_I:
7734       s = "sltiu";
7735       s2 = "bteqz";
7736       s3 = "x,8";
7737
7738     do_addone_branch_i:
7739       if (imm_expr.X_op != O_constant)
7740         as_bad (_("Unsupported large constant"));
7741       ++imm_expr.X_add_number;
7742
7743     do_branch_i:
7744       macro_build (&imm_expr, s, s3, xreg);
7745       macro_build (&offset_expr, s2, "p");
7746       break;
7747
7748     case M_ABS:
7749       expr1.X_add_number = 0;
7750       macro_build (&expr1, "slti", "x,8", yreg);
7751       if (xreg != yreg)
7752         move_register (xreg, yreg);
7753       expr1.X_add_number = 2;
7754       macro_build (&expr1, "bteqz", "p");
7755       macro_build (NULL, "neg", "x,w", xreg, xreg);
7756     }
7757 }
7758
7759 /* For consistency checking, verify that all bits are specified either
7760    by the match/mask part of the instruction definition, or by the
7761    operand list.  */
7762 static int
7763 validate_mips_insn (const struct mips_opcode *opc)
7764 {
7765   const char *p = opc->args;
7766   char c;
7767   unsigned long used_bits = opc->mask;
7768
7769   if ((used_bits & opc->match) != opc->match)
7770     {
7771       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
7772               opc->name, opc->args);
7773       return 0;
7774     }
7775 #define USE_BITS(mask,shift)    (used_bits |= ((mask) << (shift)))
7776   while (*p)
7777     switch (c = *p++)
7778       {
7779       case ',': break;
7780       case '(': break;
7781       case ')': break;
7782       case '+':
7783         switch (c = *p++)
7784           {
7785           case 'A': USE_BITS (OP_MASK_SHAMT,    OP_SH_SHAMT);   break;
7786           case 'B': USE_BITS (OP_MASK_INSMSB,   OP_SH_INSMSB);  break;
7787           case 'C': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
7788           case 'D': USE_BITS (OP_MASK_RD,       OP_SH_RD);
7789                     USE_BITS (OP_MASK_SEL,      OP_SH_SEL);     break;
7790           case 'E': USE_BITS (OP_MASK_SHAMT,    OP_SH_SHAMT);   break;
7791           case 'F': USE_BITS (OP_MASK_INSMSB,   OP_SH_INSMSB);  break;
7792           case 'G': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
7793           case 'H': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
7794           case 'I': break;
7795           case 't': USE_BITS (OP_MASK_RT,       OP_SH_RT);      break;
7796           case 'T': USE_BITS (OP_MASK_RT,       OP_SH_RT);
7797                     USE_BITS (OP_MASK_SEL,      OP_SH_SEL);     break;
7798           default:
7799             as_bad (_("internal: bad mips opcode (unknown extension operand type `+%c'): %s %s"),
7800                     c, opc->name, opc->args);
7801             return 0;
7802           }
7803         break;
7804       case '<': USE_BITS (OP_MASK_SHAMT,        OP_SH_SHAMT);   break;
7805       case '>': USE_BITS (OP_MASK_SHAMT,        OP_SH_SHAMT);   break;
7806       case 'A': break;
7807       case 'B': USE_BITS (OP_MASK_CODE20,       OP_SH_CODE20);  break;
7808       case 'C': USE_BITS (OP_MASK_COPZ,         OP_SH_COPZ);    break;
7809       case 'D': USE_BITS (OP_MASK_FD,           OP_SH_FD);      break;
7810       case 'E': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
7811       case 'F': break;
7812       case 'G': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
7813       case 'H': USE_BITS (OP_MASK_SEL,          OP_SH_SEL);     break;
7814       case 'I': break;
7815       case 'J': USE_BITS (OP_MASK_CODE19,       OP_SH_CODE19);  break;
7816       case 'K': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
7817       case 'L': break;
7818       case 'M': USE_BITS (OP_MASK_CCC,          OP_SH_CCC);     break;
7819       case 'N': USE_BITS (OP_MASK_BCC,          OP_SH_BCC);     break;
7820       case 'O': USE_BITS (OP_MASK_ALN,          OP_SH_ALN);     break;
7821       case 'Q': USE_BITS (OP_MASK_VSEL,         OP_SH_VSEL);
7822                 USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
7823       case 'R': USE_BITS (OP_MASK_FR,           OP_SH_FR);      break;
7824       case 'S': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
7825       case 'T': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
7826       case 'V': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
7827       case 'W': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
7828       case 'X': USE_BITS (OP_MASK_FD,           OP_SH_FD);      break;
7829       case 'Y': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
7830       case 'Z': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
7831       case 'a': USE_BITS (OP_MASK_TARGET,       OP_SH_TARGET);  break;
7832       case 'b': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
7833       case 'c': USE_BITS (OP_MASK_CODE,         OP_SH_CODE);    break;
7834       case 'd': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
7835       case 'f': break;
7836       case 'h': USE_BITS (OP_MASK_PREFX,        OP_SH_PREFX);   break;
7837       case 'i': USE_BITS (OP_MASK_IMMEDIATE,    OP_SH_IMMEDIATE); break;
7838       case 'j': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
7839       case 'k': USE_BITS (OP_MASK_CACHE,        OP_SH_CACHE);   break;
7840       case 'l': break;
7841       case 'o': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
7842       case 'p': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
7843       case 'q': USE_BITS (OP_MASK_CODE2,        OP_SH_CODE2);   break;
7844       case 'r': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
7845       case 's': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
7846       case 't': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
7847       case 'u': USE_BITS (OP_MASK_IMMEDIATE,    OP_SH_IMMEDIATE); break;
7848       case 'v': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
7849       case 'w': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
7850       case 'x': break;
7851       case 'z': break;
7852       case 'P': USE_BITS (OP_MASK_PERFREG,      OP_SH_PERFREG); break;
7853       case 'U': USE_BITS (OP_MASK_RD,           OP_SH_RD);
7854                 USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
7855       case 'e': USE_BITS (OP_MASK_VECBYTE,      OP_SH_VECBYTE); break;
7856       case '%': USE_BITS (OP_MASK_VECALIGN,     OP_SH_VECALIGN); break;
7857       case '[': break;
7858       case ']': break;
7859       case '3': USE_BITS (OP_MASK_SA3,          OP_SH_SA3);     break;
7860       case '4': USE_BITS (OP_MASK_SA4,          OP_SH_SA4);     break;
7861       case '5': USE_BITS (OP_MASK_IMM8,         OP_SH_IMM8);    break;
7862       case '6': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
7863       case '7': USE_BITS (OP_MASK_DSPACC,       OP_SH_DSPACC);  break;
7864       case '8': USE_BITS (OP_MASK_WRDSP,        OP_SH_WRDSP);   break;
7865       case '9': USE_BITS (OP_MASK_DSPACC_S,     OP_SH_DSPACC_S);break;
7866       case '0': USE_BITS (OP_MASK_DSPSFT,       OP_SH_DSPSFT);  break;
7867       case '\'': USE_BITS (OP_MASK_RDDSP,       OP_SH_RDDSP);   break;
7868       case ':': USE_BITS (OP_MASK_DSPSFT_7,     OP_SH_DSPSFT_7);break;
7869       case '@': USE_BITS (OP_MASK_IMM10,        OP_SH_IMM10);   break;
7870       case '!': USE_BITS (OP_MASK_MT_U,         OP_SH_MT_U);    break;
7871       case '$': USE_BITS (OP_MASK_MT_H,         OP_SH_MT_H);    break;
7872       case '*': USE_BITS (OP_MASK_MTACC_T,      OP_SH_MTACC_T); break;
7873       case '&': USE_BITS (OP_MASK_MTACC_D,      OP_SH_MTACC_D); break;
7874       case 'g': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
7875       default:
7876         as_bad (_("internal: bad mips opcode (unknown operand type `%c'): %s %s"),
7877                 c, opc->name, opc->args);
7878         return 0;
7879       }
7880 #undef USE_BITS
7881   if (used_bits != 0xffffffff)
7882     {
7883       as_bad (_("internal: bad mips opcode (bits 0x%lx undefined): %s %s"),
7884               ~used_bits & 0xffffffff, opc->name, opc->args);
7885       return 0;
7886     }
7887   return 1;
7888 }
7889
7890 /* This routine assembles an instruction into its binary format.  As a
7891    side effect, it sets one of the global variables imm_reloc or
7892    offset_reloc to the type of relocation to do if one of the operands
7893    is an address expression.  */
7894
7895 static void
7896 mips_ip (char *str, struct mips_cl_insn *ip)
7897 {
7898   char *s;
7899   const char *args;
7900   char c = 0;
7901   struct mips_opcode *insn;
7902   char *argsStart;
7903   unsigned int regno;
7904   unsigned int lastregno = 0;
7905   unsigned int lastpos = 0;
7906   unsigned int limlo, limhi;
7907   char *s_reset;
7908   char save_c = 0;
7909   offsetT min_range, max_range;
7910
7911   insn_error = NULL;
7912
7913   /* If the instruction contains a '.', we first try to match an instruction
7914      including the '.'.  Then we try again without the '.'.  */
7915   insn = NULL;
7916   for (s = str; *s != '\0' && !ISSPACE (*s); ++s)
7917     continue;
7918
7919   /* If we stopped on whitespace, then replace the whitespace with null for
7920      the call to hash_find.  Save the character we replaced just in case we
7921      have to re-parse the instruction.  */
7922   if (ISSPACE (*s))
7923     {
7924       save_c = *s;
7925       *s++ = '\0';
7926     }
7927
7928   insn = (struct mips_opcode *) hash_find (op_hash, str);
7929
7930   /* If we didn't find the instruction in the opcode table, try again, but
7931      this time with just the instruction up to, but not including the
7932      first '.'.  */
7933   if (insn == NULL)
7934     {
7935       /* Restore the character we overwrite above (if any).  */
7936       if (save_c)
7937         *(--s) = save_c;
7938
7939       /* Scan up to the first '.' or whitespace.  */
7940       for (s = str;
7941            *s != '\0' && *s != '.' && !ISSPACE (*s);
7942            ++s)
7943         continue;
7944
7945       /* If we did not find a '.', then we can quit now.  */
7946       if (*s != '.')
7947         {
7948           insn_error = "unrecognized opcode";
7949           return;
7950         }
7951
7952       /* Lookup the instruction in the hash table.  */
7953       *s++ = '\0';
7954       if ((insn = (struct mips_opcode *) hash_find (op_hash, str)) == NULL)
7955         {
7956           insn_error = "unrecognized opcode";
7957           return;
7958         }
7959     }
7960
7961   argsStart = s;
7962   for (;;)
7963     {
7964       bfd_boolean ok;
7965
7966       assert (strcmp (insn->name, str) == 0);
7967
7968       if (OPCODE_IS_MEMBER (insn,
7969                             (mips_opts.isa
7970                              | (file_ase_mips16 ? INSN_MIPS16 : 0)
7971                              | (mips_opts.ase_mdmx ? INSN_MDMX : 0)
7972                              | (mips_opts.ase_dsp ? INSN_DSP : 0)
7973                              | (mips_opts.ase_mt ? INSN_MT : 0)
7974                              | (mips_opts.ase_mips3d ? INSN_MIPS3D : 0)),
7975                             mips_opts.arch))
7976         ok = TRUE;
7977       else
7978         ok = FALSE;
7979
7980       if (insn->pinfo != INSN_MACRO)
7981         {
7982           if (mips_opts.arch == CPU_R4650 && (insn->pinfo & FP_D) != 0)
7983             ok = FALSE;
7984         }
7985
7986       if (! ok)
7987         {
7988           if (insn + 1 < &mips_opcodes[NUMOPCODES]
7989               && strcmp (insn->name, insn[1].name) == 0)
7990             {
7991               ++insn;
7992               continue;
7993             }
7994           else
7995             {
7996               if (!insn_error)
7997                 {
7998                   static char buf[100];
7999                   sprintf (buf,
8000                            _("opcode not supported on this processor: %s (%s)"),
8001                            mips_cpu_info_from_arch (mips_opts.arch)->name,
8002                            mips_cpu_info_from_isa (mips_opts.isa)->name);
8003                   insn_error = buf;
8004                 }
8005               if (save_c)
8006                 *(--s) = save_c;
8007               return;
8008             }
8009         }
8010
8011       create_insn (ip, insn);
8012       insn_error = NULL;
8013       for (args = insn->args;; ++args)
8014         {
8015           int is_mdmx;
8016
8017           s += strspn (s, " \t");
8018           is_mdmx = 0;
8019           switch (*args)
8020             {
8021             case '\0':          /* end of args */
8022               if (*s == '\0')
8023                 return;
8024               break;
8025
8026             case '3': /* dsp 3-bit unsigned immediate in bit 21 */
8027               my_getExpression (&imm_expr, s);
8028               check_absolute_expr (ip, &imm_expr);
8029               if (imm_expr.X_add_number & ~OP_MASK_SA3)
8030                 {
8031                   as_warn (_("DSP immediate not in range 0..%d (%lu)"),
8032                            OP_MASK_SA3, (unsigned long) imm_expr.X_add_number);
8033                   imm_expr.X_add_number &= OP_MASK_SA3;
8034                 }
8035               ip->insn_opcode |= imm_expr.X_add_number << OP_SH_SA3;
8036               imm_expr.X_op = O_absent;
8037               s = expr_end;
8038               continue;
8039
8040             case '4': /* dsp 4-bit unsigned immediate in bit 21 */
8041               my_getExpression (&imm_expr, s);
8042               check_absolute_expr (ip, &imm_expr);
8043               if (imm_expr.X_add_number & ~OP_MASK_SA4)
8044                 {
8045                   as_warn (_("DSP immediate not in range 0..%d (%lu)"),
8046                            OP_MASK_SA4, (unsigned long) imm_expr.X_add_number);
8047                   imm_expr.X_add_number &= OP_MASK_SA4;
8048                 }
8049               ip->insn_opcode |= imm_expr.X_add_number << OP_SH_SA4;
8050               imm_expr.X_op = O_absent;
8051               s = expr_end;
8052               continue;
8053
8054             case '5': /* dsp 8-bit unsigned immediate in bit 16 */
8055               my_getExpression (&imm_expr, s);
8056               check_absolute_expr (ip, &imm_expr);
8057               if (imm_expr.X_add_number & ~OP_MASK_IMM8)
8058                 {
8059                   as_warn (_("DSP immediate not in range 0..%d (%lu)"),
8060                            OP_MASK_IMM8, (unsigned long) imm_expr.X_add_number);
8061                   imm_expr.X_add_number &= OP_MASK_IMM8;
8062                 }
8063               ip->insn_opcode |= imm_expr.X_add_number << OP_SH_IMM8;
8064               imm_expr.X_op = O_absent;
8065               s = expr_end;
8066               continue;
8067
8068             case '6': /* dsp 5-bit unsigned immediate in bit 21 */
8069               my_getExpression (&imm_expr, s);
8070               check_absolute_expr (ip, &imm_expr);
8071               if (imm_expr.X_add_number & ~OP_MASK_RS)
8072                 {
8073                   as_warn (_("DSP immediate not in range 0..%d (%lu)"),
8074                            OP_MASK_RS, (unsigned long) imm_expr.X_add_number);
8075                   imm_expr.X_add_number &= OP_MASK_RS;
8076                 }
8077               ip->insn_opcode |= imm_expr.X_add_number << OP_SH_RS;
8078               imm_expr.X_op = O_absent;
8079               s = expr_end;
8080               continue;
8081
8082             case '7': /* four dsp accumulators in bits 11,12 */ 
8083               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
8084                   s[3] >= '0' && s[3] <= '3')
8085                 {
8086                   regno = s[3] - '0';
8087                   s += 4;
8088                   ip->insn_opcode |= regno << OP_SH_DSPACC;
8089                   continue;
8090                 }
8091               else
8092                 as_bad (_("Invalid dsp acc register"));
8093               break;
8094
8095             case '8': /* dsp 6-bit unsigned immediate in bit 11 */
8096               my_getExpression (&imm_expr, s);
8097               check_absolute_expr (ip, &imm_expr);
8098               if (imm_expr.X_add_number & ~OP_MASK_WRDSP)
8099                 {
8100                   as_warn (_("DSP immediate not in range 0..%d (%lu)"),
8101                            OP_MASK_WRDSP,
8102                            (unsigned long) imm_expr.X_add_number);
8103                   imm_expr.X_add_number &= OP_MASK_WRDSP;
8104                 }
8105               ip->insn_opcode |= imm_expr.X_add_number << OP_SH_WRDSP;
8106               imm_expr.X_op = O_absent;
8107               s = expr_end;
8108               continue;
8109
8110             case '9': /* four dsp accumulators in bits 21,22 */
8111               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
8112                   s[3] >= '0' && s[3] <= '3')
8113                 {
8114                   regno = s[3] - '0';
8115                   s += 4;
8116                   ip->insn_opcode |= regno << OP_SH_DSPACC_S;
8117                   continue;
8118                 }
8119               else
8120                 as_bad (_("Invalid dsp acc register"));
8121               break;
8122
8123             case '0': /* dsp 6-bit signed immediate in bit 20 */
8124               my_getExpression (&imm_expr, s);
8125               check_absolute_expr (ip, &imm_expr);
8126               min_range = -((OP_MASK_DSPSFT + 1) >> 1);
8127               max_range = ((OP_MASK_DSPSFT + 1) >> 1) - 1;
8128               if (imm_expr.X_add_number < min_range ||
8129                   imm_expr.X_add_number > max_range)
8130                 {
8131                   as_warn (_("DSP immediate not in range %ld..%ld (%ld)"),
8132                            (long) min_range, (long) max_range,
8133                            (long) imm_expr.X_add_number);
8134                 }
8135               imm_expr.X_add_number &= OP_MASK_DSPSFT;
8136               ip->insn_opcode |= ((unsigned long) imm_expr.X_add_number
8137                                   << OP_SH_DSPSFT);
8138               imm_expr.X_op = O_absent;
8139               s = expr_end;
8140               continue;
8141
8142             case '\'': /* dsp 6-bit unsigned immediate in bit 16 */
8143               my_getExpression (&imm_expr, s);
8144               check_absolute_expr (ip, &imm_expr);
8145               if (imm_expr.X_add_number & ~OP_MASK_RDDSP)
8146                 {
8147                   as_warn (_("DSP immediate not in range 0..%d (%lu)"),
8148                            OP_MASK_RDDSP,
8149                            (unsigned long) imm_expr.X_add_number);
8150                   imm_expr.X_add_number &= OP_MASK_RDDSP;
8151                 }
8152               ip->insn_opcode |= imm_expr.X_add_number << OP_SH_RDDSP;
8153               imm_expr.X_op = O_absent;
8154               s = expr_end;
8155               continue;
8156
8157             case ':': /* dsp 7-bit signed immediate in bit 19 */
8158               my_getExpression (&imm_expr, s);
8159               check_absolute_expr (ip, &imm_expr);
8160               min_range = -((OP_MASK_DSPSFT_7 + 1) >> 1);
8161               max_range = ((OP_MASK_DSPSFT_7 + 1) >> 1) - 1;
8162               if (imm_expr.X_add_number < min_range ||
8163                   imm_expr.X_add_number > max_range)
8164                 {
8165                   as_warn (_("DSP immediate not in range %ld..%ld (%ld)"),
8166                            (long) min_range, (long) max_range,
8167                            (long) imm_expr.X_add_number);
8168                 }
8169               imm_expr.X_add_number &= OP_MASK_DSPSFT_7;
8170               ip->insn_opcode |= ((unsigned long) imm_expr.X_add_number
8171                                   << OP_SH_DSPSFT_7);
8172               imm_expr.X_op = O_absent;
8173               s = expr_end;
8174               continue;
8175
8176             case '@': /* dsp 10-bit signed immediate in bit 16 */
8177               my_getExpression (&imm_expr, s);
8178               check_absolute_expr (ip, &imm_expr);
8179               min_range = -((OP_MASK_IMM10 + 1) >> 1);
8180               max_range = ((OP_MASK_IMM10 + 1) >> 1) - 1;
8181               if (imm_expr.X_add_number < min_range ||
8182                   imm_expr.X_add_number > max_range)
8183                 {
8184                   as_warn (_("DSP immediate not in range %ld..%ld (%ld)"),
8185                            (long) min_range, (long) max_range,
8186                            (long) imm_expr.X_add_number);
8187                 }
8188               imm_expr.X_add_number &= OP_MASK_IMM10;
8189               ip->insn_opcode |= ((unsigned long) imm_expr.X_add_number
8190                                   << OP_SH_IMM10);
8191               imm_expr.X_op = O_absent;
8192               s = expr_end;
8193               continue;
8194
8195             case '!': /* mt 1-bit unsigned immediate in bit 5 */
8196               my_getExpression (&imm_expr, s);
8197               check_absolute_expr (ip, &imm_expr);
8198               if (imm_expr.X_add_number & ~OP_MASK_MT_U)
8199                 {
8200                   as_warn (_("MT immediate not in range 0..%d (%lu)"),
8201                            OP_MASK_MT_U, (unsigned long) imm_expr.X_add_number);
8202                   imm_expr.X_add_number &= OP_MASK_MT_U;
8203                 }
8204               ip->insn_opcode |= imm_expr.X_add_number << OP_SH_MT_U;
8205               imm_expr.X_op = O_absent;
8206               s = expr_end;
8207               continue;
8208
8209             case '$': /* mt 1-bit unsigned immediate in bit 4 */
8210               my_getExpression (&imm_expr, s);
8211               check_absolute_expr (ip, &imm_expr);
8212               if (imm_expr.X_add_number & ~OP_MASK_MT_H)
8213                 {
8214                   as_warn (_("MT immediate not in range 0..%d (%lu)"),
8215                            OP_MASK_MT_H, (unsigned long) imm_expr.X_add_number);
8216                   imm_expr.X_add_number &= OP_MASK_MT_H;
8217                 }
8218               ip->insn_opcode |= imm_expr.X_add_number << OP_SH_MT_H;
8219               imm_expr.X_op = O_absent;
8220               s = expr_end;
8221               continue;
8222
8223             case '*': /* four dsp accumulators in bits 18,19 */ 
8224               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
8225                   s[3] >= '0' && s[3] <= '3')
8226                 {
8227                   regno = s[3] - '0';
8228                   s += 4;
8229                   ip->insn_opcode |= regno << OP_SH_MTACC_T;
8230                   continue;
8231                 }
8232               else
8233                 as_bad (_("Invalid dsp/smartmips acc register"));
8234               break;
8235
8236             case '&': /* four dsp accumulators in bits 13,14 */ 
8237               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
8238                   s[3] >= '0' && s[3] <= '3')
8239                 {
8240                   regno = s[3] - '0';
8241                   s += 4;
8242                   ip->insn_opcode |= regno << OP_SH_MTACC_D;
8243                   continue;
8244                 }
8245               else
8246                 as_bad (_("Invalid dsp/smartmips acc register"));
8247               break;
8248
8249             case ',':
8250               if (*s++ == *args)
8251                 continue;
8252               s--;
8253               switch (*++args)
8254                 {
8255                 case 'r':
8256                 case 'v':
8257                   INSERT_OPERAND (RS, *ip, lastregno);
8258                   continue;
8259
8260                 case 'w':
8261                   INSERT_OPERAND (RT, *ip, lastregno);
8262                   continue;
8263
8264                 case 'W':
8265                   INSERT_OPERAND (FT, *ip, lastregno);
8266                   continue;
8267
8268                 case 'V':
8269                   INSERT_OPERAND (FS, *ip, lastregno);
8270                   continue;
8271                 }
8272               break;
8273
8274             case '(':
8275               /* Handle optional base register.
8276                  Either the base register is omitted or
8277                  we must have a left paren.  */
8278               /* This is dependent on the next operand specifier
8279                  is a base register specification.  */
8280               assert (args[1] == 'b' || args[1] == '5'
8281                       || args[1] == '-' || args[1] == '4');
8282               if (*s == '\0')
8283                 return;
8284
8285             case ')':           /* these must match exactly */
8286             case '[':
8287             case ']':
8288               if (*s++ == *args)
8289                 continue;
8290               break;
8291
8292             case '+':           /* Opcode extension character.  */
8293               switch (*++args)
8294                 {
8295                 case 'A':               /* ins/ext position, becomes LSB.  */
8296                   limlo = 0;
8297                   limhi = 31;
8298                   goto do_lsb;
8299                 case 'E':
8300                   limlo = 32;
8301                   limhi = 63;
8302                   goto do_lsb;
8303 do_lsb:
8304                   my_getExpression (&imm_expr, s);
8305                   check_absolute_expr (ip, &imm_expr);
8306                   if ((unsigned long) imm_expr.X_add_number < limlo
8307                       || (unsigned long) imm_expr.X_add_number > limhi)
8308                     {
8309                       as_bad (_("Improper position (%lu)"),
8310                               (unsigned long) imm_expr.X_add_number);
8311                       imm_expr.X_add_number = limlo;
8312                     }
8313                   lastpos = imm_expr.X_add_number;
8314                   INSERT_OPERAND (SHAMT, *ip, imm_expr.X_add_number);
8315                   imm_expr.X_op = O_absent;
8316                   s = expr_end;
8317                   continue;
8318
8319                 case 'B':               /* ins size, becomes MSB.  */
8320                   limlo = 1;
8321                   limhi = 32;
8322                   goto do_msb;
8323                 case 'F':
8324                   limlo = 33;
8325                   limhi = 64;
8326                   goto do_msb;
8327 do_msb:
8328                   my_getExpression (&imm_expr, s);
8329                   check_absolute_expr (ip, &imm_expr);
8330                   /* Check for negative input so that small negative numbers
8331                      will not succeed incorrectly.  The checks against
8332                      (pos+size) transitively check "size" itself,
8333                      assuming that "pos" is reasonable.  */
8334                   if ((long) imm_expr.X_add_number < 0
8335                       || ((unsigned long) imm_expr.X_add_number
8336                           + lastpos) < limlo
8337                       || ((unsigned long) imm_expr.X_add_number
8338                           + lastpos) > limhi)
8339                     {
8340                       as_bad (_("Improper insert size (%lu, position %lu)"),
8341                               (unsigned long) imm_expr.X_add_number,
8342                               (unsigned long) lastpos);
8343                       imm_expr.X_add_number = limlo - lastpos;
8344                     }
8345                   INSERT_OPERAND (INSMSB, *ip,
8346                                  lastpos + imm_expr.X_add_number - 1);
8347                   imm_expr.X_op = O_absent;
8348                   s = expr_end;
8349                   continue;
8350
8351                 case 'C':               /* ext size, becomes MSBD.  */
8352                   limlo = 1;
8353                   limhi = 32;
8354                   goto do_msbd;
8355                 case 'G':
8356                   limlo = 33;
8357                   limhi = 64;
8358                   goto do_msbd;
8359                 case 'H':
8360                   limlo = 33;
8361                   limhi = 64;
8362                   goto do_msbd;
8363 do_msbd:
8364                   my_getExpression (&imm_expr, s);
8365                   check_absolute_expr (ip, &imm_expr);
8366                   /* Check for negative input so that small negative numbers
8367                      will not succeed incorrectly.  The checks against
8368                      (pos+size) transitively check "size" itself,
8369                      assuming that "pos" is reasonable.  */
8370                   if ((long) imm_expr.X_add_number < 0
8371                       || ((unsigned long) imm_expr.X_add_number
8372                           + lastpos) < limlo
8373                       || ((unsigned long) imm_expr.X_add_number
8374                           + lastpos) > limhi)
8375                     {
8376                       as_bad (_("Improper extract size (%lu, position %lu)"),
8377                               (unsigned long) imm_expr.X_add_number,
8378                               (unsigned long) lastpos);
8379                       imm_expr.X_add_number = limlo - lastpos;
8380                     }
8381                   INSERT_OPERAND (EXTMSBD, *ip, imm_expr.X_add_number - 1);
8382                   imm_expr.X_op = O_absent;
8383                   s = expr_end;
8384                   continue;
8385
8386                 case 'D':
8387                   /* +D is for disassembly only; never match.  */
8388                   break;
8389
8390                 case 'I':
8391                   /* "+I" is like "I", except that imm2_expr is used.  */
8392                   my_getExpression (&imm2_expr, s);
8393                   if (imm2_expr.X_op != O_big
8394                       && imm2_expr.X_op != O_constant)
8395                   insn_error = _("absolute expression required");
8396                   if (HAVE_32BIT_GPRS)
8397                     normalize_constant_expr (&imm2_expr);
8398                   s = expr_end;
8399                   continue;
8400
8401                 case 'T': /* Coprocessor register */
8402                   /* +T is for disassembly only; never match.  */
8403                   break;
8404
8405                 case 't': /* Coprocessor register number */
8406                   if (s[0] == '$' && ISDIGIT (s[1]))
8407                     {
8408                       ++s;
8409                       regno = 0;
8410                       do
8411                         {
8412                           regno *= 10;
8413                           regno += *s - '0';
8414                           ++s;
8415                         }
8416                       while (ISDIGIT (*s));
8417                       if (regno > 31)
8418                         as_bad (_("Invalid register number (%d)"), regno);
8419                       else
8420                         {
8421                           ip->insn_opcode |= regno << OP_SH_RT;
8422                           continue;
8423                         }
8424                     }
8425                   else
8426                     as_bad (_("Invalid coprocessor 0 register number"));
8427                   break;
8428
8429                 default:
8430                   as_bad (_("internal: bad mips opcode (unknown extension operand type `+%c'): %s %s"),
8431                     *args, insn->name, insn->args);
8432                   /* Further processing is fruitless.  */
8433                   return;
8434                 }
8435               break;
8436
8437             case '<':           /* must be at least one digit */
8438               /*
8439                * According to the manual, if the shift amount is greater
8440                * than 31 or less than 0, then the shift amount should be
8441                * mod 32.  In reality the mips assembler issues an error.
8442                * We issue a warning and mask out all but the low 5 bits.
8443                */
8444               my_getExpression (&imm_expr, s);
8445               check_absolute_expr (ip, &imm_expr);
8446               if ((unsigned long) imm_expr.X_add_number > 31)
8447                 as_warn (_("Improper shift amount (%lu)"),
8448                          (unsigned long) imm_expr.X_add_number);
8449               INSERT_OPERAND (SHAMT, *ip, imm_expr.X_add_number);
8450               imm_expr.X_op = O_absent;
8451               s = expr_end;
8452               continue;
8453
8454             case '>':           /* shift amount minus 32 */
8455               my_getExpression (&imm_expr, s);
8456               check_absolute_expr (ip, &imm_expr);
8457               if ((unsigned long) imm_expr.X_add_number < 32
8458                   || (unsigned long) imm_expr.X_add_number > 63)
8459                 break;
8460               INSERT_OPERAND (SHAMT, *ip, imm_expr.X_add_number - 32);
8461               imm_expr.X_op = O_absent;
8462               s = expr_end;
8463               continue;
8464
8465             case 'k':           /* cache code */
8466             case 'h':           /* prefx code */
8467               my_getExpression (&imm_expr, s);
8468               check_absolute_expr (ip, &imm_expr);
8469               if ((unsigned long) imm_expr.X_add_number > 31)
8470                 as_warn (_("Invalid value for `%s' (%lu)"),
8471                          ip->insn_mo->name,
8472                          (unsigned long) imm_expr.X_add_number);
8473               if (*args == 'k')
8474                 INSERT_OPERAND (CACHE, *ip, imm_expr.X_add_number);
8475               else
8476                 INSERT_OPERAND (PREFX, *ip, imm_expr.X_add_number);
8477               imm_expr.X_op = O_absent;
8478               s = expr_end;
8479               continue;
8480
8481             case 'c':           /* break code */
8482               my_getExpression (&imm_expr, s);
8483               check_absolute_expr (ip, &imm_expr);
8484               if ((unsigned long) imm_expr.X_add_number > 1023)
8485                 as_warn (_("Illegal break code (%lu)"),
8486                          (unsigned long) imm_expr.X_add_number);
8487               INSERT_OPERAND (CODE, *ip, imm_expr.X_add_number);
8488               imm_expr.X_op = O_absent;
8489               s = expr_end;
8490               continue;
8491
8492             case 'q':           /* lower break code */
8493               my_getExpression (&imm_expr, s);
8494               check_absolute_expr (ip, &imm_expr);
8495               if ((unsigned long) imm_expr.X_add_number > 1023)
8496                 as_warn (_("Illegal lower break code (%lu)"),
8497                          (unsigned long) imm_expr.X_add_number);
8498               INSERT_OPERAND (CODE2, *ip, imm_expr.X_add_number);
8499               imm_expr.X_op = O_absent;
8500               s = expr_end;
8501               continue;
8502
8503             case 'B':           /* 20-bit syscall/break code.  */
8504               my_getExpression (&imm_expr, s);
8505               check_absolute_expr (ip, &imm_expr);
8506               if ((unsigned long) imm_expr.X_add_number > OP_MASK_CODE20)
8507                 as_warn (_("Illegal 20-bit code (%lu)"),
8508                          (unsigned long) imm_expr.X_add_number);
8509               INSERT_OPERAND (CODE20, *ip, imm_expr.X_add_number);
8510               imm_expr.X_op = O_absent;
8511               s = expr_end;
8512               continue;
8513
8514             case 'C':           /* Coprocessor code */
8515               my_getExpression (&imm_expr, s);
8516               check_absolute_expr (ip, &imm_expr);
8517               if ((unsigned long) imm_expr.X_add_number >= (1 << 25))
8518                 {
8519                   as_warn (_("Coproccesor code > 25 bits (%lu)"),
8520                            (unsigned long) imm_expr.X_add_number);
8521                   imm_expr.X_add_number &= ((1 << 25) - 1);
8522                 }
8523               ip->insn_opcode |= imm_expr.X_add_number;
8524               imm_expr.X_op = O_absent;
8525               s = expr_end;
8526               continue;
8527
8528             case 'J':           /* 19-bit wait code.  */
8529               my_getExpression (&imm_expr, s);
8530               check_absolute_expr (ip, &imm_expr);
8531               if ((unsigned long) imm_expr.X_add_number > OP_MASK_CODE19)
8532                 as_warn (_("Illegal 19-bit code (%lu)"),
8533                          (unsigned long) imm_expr.X_add_number);
8534               INSERT_OPERAND (CODE19, *ip, imm_expr.X_add_number);
8535               imm_expr.X_op = O_absent;
8536               s = expr_end;
8537               continue;
8538
8539             case 'P':           /* Performance register */
8540               my_getExpression (&imm_expr, s);
8541               check_absolute_expr (ip, &imm_expr);
8542               if (imm_expr.X_add_number != 0 && imm_expr.X_add_number != 1)
8543                 as_warn (_("Invalid performance register (%lu)"),
8544                          (unsigned long) imm_expr.X_add_number);
8545               INSERT_OPERAND (PERFREG, *ip, imm_expr.X_add_number);
8546               imm_expr.X_op = O_absent;
8547               s = expr_end;
8548               continue;
8549
8550             case 'b':           /* base register */
8551             case 'd':           /* destination register */
8552             case 's':           /* source register */
8553             case 't':           /* target register */
8554             case 'r':           /* both target and source */
8555             case 'v':           /* both dest and source */
8556             case 'w':           /* both dest and target */
8557             case 'E':           /* coprocessor target register */
8558             case 'G':           /* coprocessor destination register */
8559             case 'K':           /* 'rdhwr' destination register */
8560             case 'x':           /* ignore register name */
8561             case 'z':           /* must be zero register */
8562             case 'U':           /* destination register (clo/clz).  */
8563             case 'g':           /* coprocessor destination register */
8564               s_reset = s;
8565               if (s[0] == '$')
8566                 {
8567                   if (ISDIGIT (s[1]))
8568                     {
8569                       ++s;
8570                       regno = 0;
8571                       do
8572                         {
8573                           regno *= 10;
8574                           regno += *s - '0';
8575                           ++s;
8576                         }
8577                       while (ISDIGIT (*s));
8578                       if (regno > 31)
8579                         as_bad (_("Invalid register number (%d)"), regno);
8580                     }
8581                   else if (*args == 'E' || *args == 'G' || *args == 'K')
8582                     goto notreg;
8583                   else
8584                     {
8585                       if (s[1] == 'r' && s[2] == 'a')
8586                         {
8587                           s += 3;
8588                           regno = RA;
8589                         }
8590                       else if (s[1] == 'f' && s[2] == 'p')
8591                         {
8592                           s += 3;
8593                           regno = FP;
8594                         }
8595                       else if (s[1] == 's' && s[2] == 'p')
8596                         {
8597                           s += 3;
8598                           regno = SP;
8599                         }
8600                       else if (s[1] == 'g' && s[2] == 'p')
8601                         {
8602                           s += 3;
8603                           regno = GP;
8604                         }
8605                       else if (s[1] == 'a' && s[2] == 't')
8606                         {
8607                           s += 3;
8608                           regno = AT;
8609                         }
8610                       else if (s[1] == 'k' && s[2] == 't' && s[3] == '0')
8611                         {
8612                           s += 4;
8613                           regno = KT0;
8614                         }
8615                       else if (s[1] == 'k' && s[2] == 't' && s[3] == '1')
8616                         {
8617                           s += 4;
8618                           regno = KT1;
8619                         }
8620                       else if (s[1] == 'z' && s[2] == 'e' && s[3] == 'r' && s[4] == 'o')
8621                         {
8622                           s += 5;
8623                           regno = ZERO;
8624                         }
8625                       else if (itbl_have_entries)
8626                         {
8627                           char *p, *n;
8628                           unsigned long r;
8629
8630                           p = s + 1;    /* advance past '$' */
8631                           n = itbl_get_field (&p);  /* n is name */
8632
8633                           /* See if this is a register defined in an
8634                              itbl entry.  */
8635                           if (itbl_get_reg_val (n, &r))
8636                             {
8637                               /* Get_field advances to the start of
8638                                  the next field, so we need to back
8639                                  rack to the end of the last field.  */
8640                               if (p)
8641                                 s = p - 1;
8642                               else
8643                                 s = strchr (s, '\0');
8644                               regno = r;
8645                             }
8646                           else
8647                             goto notreg;
8648                         }
8649                       else
8650                         goto notreg;
8651                     }
8652                   if (regno == AT
8653                       && ! mips_opts.noat
8654                       && *args != 'E'
8655                       && *args != 'G'
8656                       && *args != 'K')
8657                     as_warn (_("Used $at without \".set noat\""));
8658                   c = *args;
8659                   if (*s == ' ')
8660                     ++s;
8661                   if (args[1] != *s)
8662                     {
8663                       if (c == 'r' || c == 'v' || c == 'w')
8664                         {
8665                           regno = lastregno;
8666                           s = s_reset;
8667                           ++args;
8668                         }
8669                     }
8670                   /* 'z' only matches $0.  */
8671                   if (c == 'z' && regno != 0)
8672                     break;
8673
8674         /* Now that we have assembled one operand, we use the args string
8675          * to figure out where it goes in the instruction.  */
8676                   switch (c)
8677                     {
8678                     case 'r':
8679                     case 's':
8680                     case 'v':
8681                     case 'b':
8682                       INSERT_OPERAND (RS, *ip, regno);
8683                       break;
8684                     case 'd':
8685                     case 'G':
8686                     case 'K':
8687                     case 'g':
8688                       INSERT_OPERAND (RD, *ip, regno);
8689                       break;
8690                     case 'U':
8691                       INSERT_OPERAND (RD, *ip, regno);
8692                       INSERT_OPERAND (RT, *ip, regno);
8693                       break;
8694                     case 'w':
8695                     case 't':
8696                     case 'E':
8697                       INSERT_OPERAND (RT, *ip, regno);
8698                       break;
8699                     case 'x':
8700                       /* This case exists because on the r3000 trunc
8701                          expands into a macro which requires a gp
8702                          register.  On the r6000 or r4000 it is
8703                          assembled into a single instruction which
8704                          ignores the register.  Thus the insn version
8705                          is MIPS_ISA2 and uses 'x', and the macro
8706                          version is MIPS_ISA1 and uses 't'.  */
8707                       break;
8708                     case 'z':
8709                       /* This case is for the div instruction, which
8710                          acts differently if the destination argument
8711                          is $0.  This only matches $0, and is checked
8712                          outside the switch.  */
8713                       break;
8714                     case 'D':
8715                       /* Itbl operand; not yet implemented. FIXME ?? */
8716                       break;
8717                       /* What about all other operands like 'i', which
8718                          can be specified in the opcode table? */
8719                     }
8720                   lastregno = regno;
8721                   continue;
8722                 }
8723             notreg:
8724               switch (*args++)
8725                 {
8726                 case 'r':
8727                 case 'v':
8728                   INSERT_OPERAND (RS, *ip, lastregno);
8729                   continue;
8730                 case 'w':
8731                   INSERT_OPERAND (RT, *ip, lastregno);
8732                   continue;
8733                 }
8734               break;
8735
8736             case 'O':           /* MDMX alignment immediate constant.  */
8737               my_getExpression (&imm_expr, s);
8738               check_absolute_expr (ip, &imm_expr);
8739               if ((unsigned long) imm_expr.X_add_number > OP_MASK_ALN)
8740                 as_warn ("Improper align amount (%ld), using low bits",
8741                          (long) imm_expr.X_add_number);
8742               INSERT_OPERAND (ALN, *ip, imm_expr.X_add_number);
8743               imm_expr.X_op = O_absent;
8744               s = expr_end;
8745               continue;
8746
8747             case 'Q':           /* MDMX vector, element sel, or const.  */
8748               if (s[0] != '$')
8749                 {
8750                   /* MDMX Immediate.  */
8751                   my_getExpression (&imm_expr, s);
8752                   check_absolute_expr (ip, &imm_expr);
8753                   if ((unsigned long) imm_expr.X_add_number > OP_MASK_FT)
8754                     as_warn (_("Invalid MDMX Immediate (%ld)"),
8755                              (long) imm_expr.X_add_number);
8756                   INSERT_OPERAND (FT, *ip, imm_expr.X_add_number);
8757                   if (ip->insn_opcode & (OP_MASK_VSEL << OP_SH_VSEL))
8758                     ip->insn_opcode |= MDMX_FMTSEL_IMM_QH << OP_SH_VSEL;
8759                   else
8760                     ip->insn_opcode |= MDMX_FMTSEL_IMM_OB << OP_SH_VSEL;
8761                   imm_expr.X_op = O_absent;
8762                   s = expr_end;
8763                   continue;
8764                 }
8765               /* Not MDMX Immediate.  Fall through.  */
8766             case 'X':           /* MDMX destination register.  */
8767             case 'Y':           /* MDMX source register.  */
8768             case 'Z':           /* MDMX target register.  */
8769               is_mdmx = 1;
8770             case 'D':           /* floating point destination register */
8771             case 'S':           /* floating point source register */
8772             case 'T':           /* floating point target register */
8773             case 'R':           /* floating point source register */
8774             case 'V':
8775             case 'W':
8776               s_reset = s;
8777               /* Accept $fN for FP and MDMX register numbers, and in
8778                  addition accept $vN for MDMX register numbers.  */
8779               if ((s[0] == '$' && s[1] == 'f' && ISDIGIT (s[2]))
8780                   || (is_mdmx != 0 && s[0] == '$' && s[1] == 'v'
8781                       && ISDIGIT (s[2])))
8782                 {
8783                   s += 2;
8784                   regno = 0;
8785                   do
8786                     {
8787                       regno *= 10;
8788                       regno += *s - '0';
8789                       ++s;
8790                     }
8791                   while (ISDIGIT (*s));
8792
8793                   if (regno > 31)
8794                     as_bad (_("Invalid float register number (%d)"), regno);
8795
8796                   if ((regno & 1) != 0
8797                       && HAVE_32BIT_FPRS
8798                       && ! (strcmp (str, "mtc1") == 0
8799                             || strcmp (str, "mfc1") == 0
8800                             || strcmp (str, "lwc1") == 0
8801                             || strcmp (str, "swc1") == 0
8802                             || strcmp (str, "l.s") == 0
8803                             || strcmp (str, "s.s") == 0
8804                             || strcmp (str, "mftc1") == 0
8805                             || strcmp (str, "mfthc1") == 0
8806                             || strcmp (str, "cftc1") == 0
8807                             || strcmp (str, "mttc1") == 0
8808                             || strcmp (str, "mtthc1") == 0
8809                             || strcmp (str, "cttc1") == 0))
8810                     as_warn (_("Float register should be even, was %d"),
8811                              regno);
8812
8813                   c = *args;
8814                   if (*s == ' ')
8815                     ++s;
8816                   if (args[1] != *s)
8817                     {
8818                       if (c == 'V' || c == 'W')
8819                         {
8820                           regno = lastregno;
8821                           s = s_reset;
8822                           ++args;
8823                         }
8824                     }
8825                   switch (c)
8826                     {
8827                     case 'D':
8828                     case 'X':
8829                       INSERT_OPERAND (FD, *ip, regno);
8830                       break;
8831                     case 'V':
8832                     case 'S':
8833                     case 'Y':
8834                       INSERT_OPERAND (FS, *ip, regno);
8835                       break;
8836                     case 'Q':
8837                       /* This is like 'Z', but also needs to fix the MDMX
8838                          vector/scalar select bits.  Note that the
8839                          scalar immediate case is handled above.  */
8840                       if (*s == '[')
8841                         {
8842                           int is_qh = (ip->insn_opcode & (1 << OP_SH_VSEL));
8843                           int max_el = (is_qh ? 3 : 7);
8844                           s++;
8845                           my_getExpression(&imm_expr, s);
8846                           check_absolute_expr (ip, &imm_expr);
8847                           s = expr_end;
8848                           if (imm_expr.X_add_number > max_el)
8849                             as_bad(_("Bad element selector %ld"),
8850                                    (long) imm_expr.X_add_number);
8851                           imm_expr.X_add_number &= max_el;
8852                           ip->insn_opcode |= (imm_expr.X_add_number
8853                                               << (OP_SH_VSEL +
8854                                                   (is_qh ? 2 : 1)));
8855                           imm_expr.X_op = O_absent;
8856                           if (*s != ']')
8857                             as_warn(_("Expecting ']' found '%s'"), s);
8858                           else
8859                             s++;
8860                         }
8861                       else
8862                         {
8863                           if (ip->insn_opcode & (OP_MASK_VSEL << OP_SH_VSEL))
8864                             ip->insn_opcode |= (MDMX_FMTSEL_VEC_QH
8865                                                 << OP_SH_VSEL);
8866                           else
8867                             ip->insn_opcode |= (MDMX_FMTSEL_VEC_OB <<
8868                                                 OP_SH_VSEL);
8869                         }
8870                       /* Fall through */
8871                     case 'W':
8872                     case 'T':
8873                     case 'Z':
8874                       INSERT_OPERAND (FT, *ip, regno);
8875                       break;
8876                     case 'R':
8877                       INSERT_OPERAND (FR, *ip, regno);
8878                       break;
8879                     }
8880                   lastregno = regno;
8881                   continue;
8882                 }
8883
8884               switch (*args++)
8885                 {
8886                 case 'V':
8887                   INSERT_OPERAND (FS, *ip, lastregno);
8888                   continue;
8889                 case 'W':
8890                   INSERT_OPERAND (FT, *ip, lastregno);
8891                   continue;
8892                 }
8893               break;
8894
8895             case 'I':
8896               my_getExpression (&imm_expr, s);
8897               if (imm_expr.X_op != O_big
8898                   && imm_expr.X_op != O_constant)
8899                 insn_error = _("absolute expression required");
8900               if (HAVE_32BIT_GPRS)
8901                 normalize_constant_expr (&imm_expr);
8902               s = expr_end;
8903               continue;
8904
8905             case 'A':
8906               my_getExpression (&offset_expr, s);
8907               normalize_address_expr (&offset_expr);
8908               *imm_reloc = BFD_RELOC_32;
8909               s = expr_end;
8910               continue;
8911
8912             case 'F':
8913             case 'L':
8914             case 'f':
8915             case 'l':
8916               {
8917                 int f64;
8918                 int using_gprs;
8919                 char *save_in;
8920                 char *err;
8921                 unsigned char temp[8];
8922                 int len;
8923                 unsigned int length;
8924                 segT seg;
8925                 subsegT subseg;
8926                 char *p;
8927
8928                 /* These only appear as the last operand in an
8929                    instruction, and every instruction that accepts
8930                    them in any variant accepts them in all variants.
8931                    This means we don't have to worry about backing out
8932                    any changes if the instruction does not match.
8933
8934                    The difference between them is the size of the
8935                    floating point constant and where it goes.  For 'F'
8936                    and 'L' the constant is 64 bits; for 'f' and 'l' it
8937                    is 32 bits.  Where the constant is placed is based
8938                    on how the MIPS assembler does things:
8939                     F -- .rdata
8940                     L -- .lit8
8941                     f -- immediate value
8942                     l -- .lit4
8943
8944                     The .lit4 and .lit8 sections are only used if
8945                     permitted by the -G argument.
8946
8947                     The code below needs to know whether the target register
8948                     is 32 or 64 bits wide.  It relies on the fact 'f' and
8949                     'F' are used with GPR-based instructions and 'l' and
8950                     'L' are used with FPR-based instructions.  */
8951
8952                 f64 = *args == 'F' || *args == 'L';
8953                 using_gprs = *args == 'F' || *args == 'f';
8954
8955                 save_in = input_line_pointer;
8956                 input_line_pointer = s;
8957                 err = md_atof (f64 ? 'd' : 'f', (char *) temp, &len);
8958                 length = len;
8959                 s = input_line_pointer;
8960                 input_line_pointer = save_in;
8961                 if (err != NULL && *err != '\0')
8962                   {
8963                     as_bad (_("Bad floating point constant: %s"), err);
8964                     memset (temp, '\0', sizeof temp);
8965                     length = f64 ? 8 : 4;
8966                   }
8967
8968                 assert (length == (unsigned) (f64 ? 8 : 4));
8969
8970                 if (*args == 'f'
8971                     || (*args == 'l'
8972                         && (g_switch_value < 4
8973                             || (temp[0] == 0 && temp[1] == 0)
8974                             || (temp[2] == 0 && temp[3] == 0))))
8975                   {
8976                     imm_expr.X_op = O_constant;
8977                     if (! target_big_endian)
8978                       imm_expr.X_add_number = bfd_getl32 (temp);
8979                     else
8980                       imm_expr.X_add_number = bfd_getb32 (temp);
8981                   }
8982                 else if (length > 4
8983                          && ! mips_disable_float_construction
8984                          /* Constants can only be constructed in GPRs and
8985                             copied to FPRs if the GPRs are at least as wide
8986                             as the FPRs.  Force the constant into memory if
8987                             we are using 64-bit FPRs but the GPRs are only
8988                             32 bits wide.  */
8989                          && (using_gprs
8990                              || ! (HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
8991                          && ((temp[0] == 0 && temp[1] == 0)
8992                              || (temp[2] == 0 && temp[3] == 0))
8993                          && ((temp[4] == 0 && temp[5] == 0)
8994                              || (temp[6] == 0 && temp[7] == 0)))
8995                   {
8996                     /* The value is simple enough to load with a couple of
8997                        instructions.  If using 32-bit registers, set
8998                        imm_expr to the high order 32 bits and offset_expr to
8999                        the low order 32 bits.  Otherwise, set imm_expr to
9000                        the entire 64 bit constant.  */
9001                     if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
9002                       {
9003                         imm_expr.X_op = O_constant;
9004                         offset_expr.X_op = O_constant;
9005                         if (! target_big_endian)
9006                           {
9007                             imm_expr.X_add_number = bfd_getl32 (temp + 4);
9008                             offset_expr.X_add_number = bfd_getl32 (temp);
9009                           }
9010                         else
9011                           {
9012                             imm_expr.X_add_number = bfd_getb32 (temp);
9013                             offset_expr.X_add_number = bfd_getb32 (temp + 4);
9014                           }
9015                         if (offset_expr.X_add_number == 0)
9016                           offset_expr.X_op = O_absent;
9017                       }
9018                     else if (sizeof (imm_expr.X_add_number) > 4)
9019                       {
9020                         imm_expr.X_op = O_constant;
9021                         if (! target_big_endian)
9022                           imm_expr.X_add_number = bfd_getl64 (temp);
9023                         else
9024                           imm_expr.X_add_number = bfd_getb64 (temp);
9025                       }
9026                     else
9027                       {
9028                         imm_expr.X_op = O_big;
9029                         imm_expr.X_add_number = 4;
9030                         if (! target_big_endian)
9031                           {
9032                             generic_bignum[0] = bfd_getl16 (temp);
9033                             generic_bignum[1] = bfd_getl16 (temp + 2);
9034                             generic_bignum[2] = bfd_getl16 (temp + 4);
9035                             generic_bignum[3] = bfd_getl16 (temp + 6);
9036                           }
9037                         else
9038                           {
9039                             generic_bignum[0] = bfd_getb16 (temp + 6);
9040                             generic_bignum[1] = bfd_getb16 (temp + 4);
9041                             generic_bignum[2] = bfd_getb16 (temp + 2);
9042                             generic_bignum[3] = bfd_getb16 (temp);
9043                           }
9044                       }
9045                   }
9046                 else
9047                   {
9048                     const char *newname;
9049                     segT new_seg;
9050
9051                     /* Switch to the right section.  */
9052                     seg = now_seg;
9053                     subseg = now_subseg;
9054                     switch (*args)
9055                       {
9056                       default: /* unused default case avoids warnings.  */
9057                       case 'L':
9058                         newname = RDATA_SECTION_NAME;
9059                         if (g_switch_value >= 8)
9060                           newname = ".lit8";
9061                         break;
9062                       case 'F':
9063                         newname = RDATA_SECTION_NAME;
9064                         break;
9065                       case 'l':
9066                         assert (g_switch_value >= 4);
9067                         newname = ".lit4";
9068                         break;
9069                       }
9070                     new_seg = subseg_new (newname, (subsegT) 0);
9071                     if (OUTPUT_FLAVOR == bfd_target_elf_flavour)
9072                       bfd_set_section_flags (stdoutput, new_seg,
9073                                              (SEC_ALLOC
9074                                               | SEC_LOAD
9075                                               | SEC_READONLY
9076                                               | SEC_DATA));
9077                     frag_align (*args == 'l' ? 2 : 3, 0, 0);
9078                     if (OUTPUT_FLAVOR == bfd_target_elf_flavour
9079                         && strcmp (TARGET_OS, "elf") != 0)
9080                       record_alignment (new_seg, 4);
9081                     else
9082                       record_alignment (new_seg, *args == 'l' ? 2 : 3);
9083                     if (seg == now_seg)
9084                       as_bad (_("Can't use floating point insn in this section"));
9085
9086                     /* Set the argument to the current address in the
9087                        section.  */
9088                     offset_expr.X_op = O_symbol;
9089                     offset_expr.X_add_symbol =
9090                       symbol_new ("L0\001", now_seg,
9091                                   (valueT) frag_now_fix (), frag_now);
9092                     offset_expr.X_add_number = 0;
9093
9094                     /* Put the floating point number into the section.  */
9095                     p = frag_more ((int) length);
9096                     memcpy (p, temp, length);
9097
9098                     /* Switch back to the original section.  */
9099                     subseg_set (seg, subseg);
9100                   }
9101               }
9102               continue;
9103
9104             case 'i':           /* 16 bit unsigned immediate */
9105             case 'j':           /* 16 bit signed immediate */
9106               *imm_reloc = BFD_RELOC_LO16;
9107               if (my_getSmallExpression (&imm_expr, imm_reloc, s) == 0)
9108                 {
9109                   int more;
9110                   offsetT minval, maxval;
9111
9112                   more = (insn + 1 < &mips_opcodes[NUMOPCODES]
9113                           && strcmp (insn->name, insn[1].name) == 0);
9114
9115                   /* If the expression was written as an unsigned number,
9116                      only treat it as signed if there are no more
9117                      alternatives.  */
9118                   if (more
9119                       && *args == 'j'
9120                       && sizeof (imm_expr.X_add_number) <= 4
9121                       && imm_expr.X_op == O_constant
9122                       && imm_expr.X_add_number < 0
9123                       && imm_expr.X_unsigned
9124                       && HAVE_64BIT_GPRS)
9125                     break;
9126
9127                   /* For compatibility with older assemblers, we accept
9128                      0x8000-0xffff as signed 16-bit numbers when only
9129                      signed numbers are allowed.  */
9130                   if (*args == 'i')
9131                     minval = 0, maxval = 0xffff;
9132                   else if (more)
9133                     minval = -0x8000, maxval = 0x7fff;
9134                   else
9135                     minval = -0x8000, maxval = 0xffff;
9136
9137                   if (imm_expr.X_op != O_constant
9138                       || imm_expr.X_add_number < minval
9139                       || imm_expr.X_add_number > maxval)
9140                     {
9141                       if (more)
9142                         break;
9143                       if (imm_expr.X_op == O_constant
9144                           || imm_expr.X_op == O_big)
9145                         as_bad (_("expression out of range"));
9146                     }
9147                 }
9148               s = expr_end;
9149               continue;
9150
9151             case 'o':           /* 16 bit offset */
9152               /* Check whether there is only a single bracketed expression
9153                  left.  If so, it must be the base register and the
9154                  constant must be zero.  */
9155               if (*s == '(' && strchr (s + 1, '(') == 0)
9156                 {
9157                   offset_expr.X_op = O_constant;
9158                   offset_expr.X_add_number = 0;
9159                   continue;
9160                 }
9161
9162               /* If this value won't fit into a 16 bit offset, then go
9163                  find a macro that will generate the 32 bit offset
9164                  code pattern.  */
9165               if (my_getSmallExpression (&offset_expr, offset_reloc, s) == 0
9166                   && (offset_expr.X_op != O_constant
9167                       || offset_expr.X_add_number >= 0x8000
9168                       || offset_expr.X_add_number < -0x8000))
9169                 break;
9170
9171               s = expr_end;
9172               continue;
9173
9174             case 'p':           /* pc relative offset */
9175               *offset_reloc = BFD_RELOC_16_PCREL_S2;
9176               my_getExpression (&offset_expr, s);
9177               s = expr_end;
9178               continue;
9179
9180             case 'u':           /* upper 16 bits */
9181               if (my_getSmallExpression (&imm_expr, imm_reloc, s) == 0
9182                   && imm_expr.X_op == O_constant
9183                   && (imm_expr.X_add_number < 0
9184                       || imm_expr.X_add_number >= 0x10000))
9185                 as_bad (_("lui expression not in range 0..65535"));
9186               s = expr_end;
9187               continue;
9188
9189             case 'a':           /* 26 bit address */
9190               my_getExpression (&offset_expr, s);
9191               s = expr_end;
9192               *offset_reloc = BFD_RELOC_MIPS_JMP;
9193               continue;
9194
9195             case 'N':           /* 3 bit branch condition code */
9196             case 'M':           /* 3 bit compare condition code */
9197               if (strncmp (s, "$fcc", 4) != 0)
9198                 break;
9199               s += 4;
9200               regno = 0;
9201               do
9202                 {
9203                   regno *= 10;
9204                   regno += *s - '0';
9205                   ++s;
9206                 }
9207               while (ISDIGIT (*s));
9208               if (regno > 7)
9209                 as_bad (_("Invalid condition code register $fcc%d"), regno);
9210               if ((strcmp(str + strlen(str) - 3, ".ps") == 0
9211                    || strcmp(str + strlen(str) - 5, "any2f") == 0
9212                    || strcmp(str + strlen(str) - 5, "any2t") == 0)
9213                   && (regno & 1) != 0)
9214                 as_warn(_("Condition code register should be even for %s, was %d"),
9215                         str, regno);
9216               if ((strcmp(str + strlen(str) - 5, "any4f") == 0
9217                    || strcmp(str + strlen(str) - 5, "any4t") == 0)
9218                   && (regno & 3) != 0)
9219                 as_warn(_("Condition code register should be 0 or 4 for %s, was %d"),
9220                         str, regno);
9221               if (*args == 'N')
9222                 INSERT_OPERAND (BCC, *ip, regno);
9223               else
9224                 INSERT_OPERAND (CCC, *ip, regno);
9225               continue;
9226
9227             case 'H':
9228               if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
9229                 s += 2;
9230               if (ISDIGIT (*s))
9231                 {
9232                   c = 0;
9233                   do
9234                     {
9235                       c *= 10;
9236                       c += *s - '0';
9237                       ++s;
9238                     }
9239                   while (ISDIGIT (*s));
9240                 }
9241               else
9242                 c = 8; /* Invalid sel value.  */
9243
9244               if (c > 7)
9245                 as_bad (_("invalid coprocessor sub-selection value (0-7)"));
9246               ip->insn_opcode |= c;
9247               continue;
9248
9249             case 'e':
9250               /* Must be at least one digit.  */
9251               my_getExpression (&imm_expr, s);
9252               check_absolute_expr (ip, &imm_expr);
9253
9254               if ((unsigned long) imm_expr.X_add_number
9255                   > (unsigned long) OP_MASK_VECBYTE)
9256                 {
9257                   as_bad (_("bad byte vector index (%ld)"),
9258                            (long) imm_expr.X_add_number);
9259                   imm_expr.X_add_number = 0;
9260                 }
9261
9262               INSERT_OPERAND (VECBYTE, *ip, imm_expr.X_add_number);
9263               imm_expr.X_op = O_absent;
9264               s = expr_end;
9265               continue;
9266
9267             case '%':
9268               my_getExpression (&imm_expr, s);
9269               check_absolute_expr (ip, &imm_expr);
9270
9271               if ((unsigned long) imm_expr.X_add_number
9272                   > (unsigned long) OP_MASK_VECALIGN)
9273                 {
9274                   as_bad (_("bad byte vector index (%ld)"),
9275                            (long) imm_expr.X_add_number);
9276                   imm_expr.X_add_number = 0;
9277                 }
9278
9279               INSERT_OPERAND (VECALIGN, *ip, imm_expr.X_add_number);
9280               imm_expr.X_op = O_absent;
9281               s = expr_end;
9282               continue;
9283
9284             default:
9285               as_bad (_("bad char = '%c'\n"), *args);
9286               internalError ();
9287             }
9288           break;
9289         }
9290       /* Args don't match.  */
9291       if (insn + 1 < &mips_opcodes[NUMOPCODES] &&
9292           !strcmp (insn->name, insn[1].name))
9293         {
9294           ++insn;
9295           s = argsStart;
9296           insn_error = _("illegal operands");
9297           continue;
9298         }
9299       if (save_c)
9300         *(--s) = save_c;
9301       insn_error = _("illegal operands");
9302       return;
9303     }
9304 }
9305
9306 #define SKIP_SPACE_TABS(S) { while (*(S) == ' ' || *(S) == '\t') ++(S); }
9307
9308 /* This routine assembles an instruction into its binary format when
9309    assembling for the mips16.  As a side effect, it sets one of the
9310    global variables imm_reloc or offset_reloc to the type of
9311    relocation to do if one of the operands is an address expression.
9312    It also sets mips16_small and mips16_ext if the user explicitly
9313    requested a small or extended instruction.  */
9314
9315 static void
9316 mips16_ip (char *str, struct mips_cl_insn *ip)
9317 {
9318   char *s;
9319   const char *args;
9320   struct mips_opcode *insn;
9321   char *argsstart;
9322   unsigned int regno;
9323   unsigned int lastregno = 0;
9324   char *s_reset;
9325   size_t i;
9326
9327   insn_error = NULL;
9328
9329   mips16_small = FALSE;
9330   mips16_ext = FALSE;
9331
9332   for (s = str; ISLOWER (*s); ++s)
9333     ;
9334   switch (*s)
9335     {
9336     case '\0':
9337       break;
9338
9339     case ' ':
9340       *s++ = '\0';
9341       break;
9342
9343     case '.':
9344       if (s[1] == 't' && s[2] == ' ')
9345         {
9346           *s = '\0';
9347           mips16_small = TRUE;
9348           s += 3;
9349           break;
9350         }
9351       else if (s[1] == 'e' && s[2] == ' ')
9352         {
9353           *s = '\0';
9354           mips16_ext = TRUE;
9355           s += 3;
9356           break;
9357         }
9358       /* Fall through.  */
9359     default:
9360       insn_error = _("unknown opcode");
9361       return;
9362     }
9363
9364   if (mips_opts.noautoextend && ! mips16_ext)
9365     mips16_small = TRUE;
9366
9367   if ((insn = (struct mips_opcode *) hash_find (mips16_op_hash, str)) == NULL)
9368     {
9369       insn_error = _("unrecognized opcode");
9370       return;
9371     }
9372
9373   argsstart = s;
9374   for (;;)
9375     {
9376       assert (strcmp (insn->name, str) == 0);
9377
9378       create_insn (ip, insn);
9379       imm_expr.X_op = O_absent;
9380       imm_reloc[0] = BFD_RELOC_UNUSED;
9381       imm_reloc[1] = BFD_RELOC_UNUSED;
9382       imm_reloc[2] = BFD_RELOC_UNUSED;
9383       imm2_expr.X_op = O_absent;
9384       offset_expr.X_op = O_absent;
9385       offset_reloc[0] = BFD_RELOC_UNUSED;
9386       offset_reloc[1] = BFD_RELOC_UNUSED;
9387       offset_reloc[2] = BFD_RELOC_UNUSED;
9388       for (args = insn->args; 1; ++args)
9389         {
9390           int c;
9391
9392           if (*s == ' ')
9393             ++s;
9394
9395           /* In this switch statement we call break if we did not find
9396              a match, continue if we did find a match, or return if we
9397              are done.  */
9398
9399           c = *args;
9400           switch (c)
9401             {
9402             case '\0':
9403               if (*s == '\0')
9404                 {
9405                   /* Stuff the immediate value in now, if we can.  */
9406                   if (imm_expr.X_op == O_constant
9407                       && *imm_reloc > BFD_RELOC_UNUSED
9408                       && insn->pinfo != INSN_MACRO)
9409                     {
9410                       valueT tmp;
9411
9412                       switch (*offset_reloc)
9413                         {
9414                           case BFD_RELOC_MIPS16_HI16_S:
9415                             tmp = (imm_expr.X_add_number + 0x8000) >> 16;
9416                             break;
9417
9418                           case BFD_RELOC_MIPS16_HI16:
9419                             tmp = imm_expr.X_add_number >> 16;
9420                             break;
9421
9422                           case BFD_RELOC_MIPS16_LO16:
9423                             tmp = ((imm_expr.X_add_number + 0x8000) & 0xffff)
9424                                   - 0x8000;
9425                             break;
9426
9427                           case BFD_RELOC_UNUSED:
9428                             tmp = imm_expr.X_add_number;
9429                             break;
9430
9431                           default:
9432                             internalError ();
9433                         }
9434                       *offset_reloc = BFD_RELOC_UNUSED;
9435
9436                       mips16_immed (NULL, 0, *imm_reloc - BFD_RELOC_UNUSED,
9437                                     tmp, TRUE, mips16_small,
9438                                     mips16_ext, &ip->insn_opcode,
9439                                     &ip->use_extend, &ip->extend);
9440                       imm_expr.X_op = O_absent;
9441                       *imm_reloc = BFD_RELOC_UNUSED;
9442                     }
9443
9444                   return;
9445                 }
9446               break;
9447
9448             case ',':
9449               if (*s++ == c)
9450                 continue;
9451               s--;
9452               switch (*++args)
9453                 {
9454                 case 'v':
9455                   MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
9456                   continue;
9457                 case 'w':
9458                   MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
9459                   continue;
9460                 }
9461               break;
9462
9463             case '(':
9464             case ')':
9465               if (*s++ == c)
9466                 continue;
9467               break;
9468
9469             case 'v':
9470             case 'w':
9471               if (s[0] != '$')
9472                 {
9473                   if (c == 'v')
9474                     MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
9475                   else
9476                     MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
9477                   ++args;
9478                   continue;
9479                 }
9480               /* Fall through.  */
9481             case 'x':
9482             case 'y':
9483             case 'z':
9484             case 'Z':
9485             case '0':
9486             case 'S':
9487             case 'R':
9488             case 'X':
9489             case 'Y':
9490               if (s[0] != '$')
9491                 break;
9492               s_reset = s;
9493               if (ISDIGIT (s[1]))
9494                 {
9495                   ++s;
9496                   regno = 0;
9497                   do
9498                     {
9499                       regno *= 10;
9500                       regno += *s - '0';
9501                       ++s;
9502                     }
9503                   while (ISDIGIT (*s));
9504                   if (regno > 31)
9505                     {
9506                       as_bad (_("invalid register number (%d)"), regno);
9507                       regno = 2;
9508                     }
9509                 }
9510               else
9511                 {
9512                   if (s[1] == 'r' && s[2] == 'a')
9513                     {
9514                       s += 3;
9515                       regno = RA;
9516                     }
9517                   else if (s[1] == 'f' && s[2] == 'p')
9518                     {
9519                       s += 3;
9520                       regno = FP;
9521                     }
9522                   else if (s[1] == 's' && s[2] == 'p')
9523                     {
9524                       s += 3;
9525                       regno = SP;
9526                     }
9527                   else if (s[1] == 'g' && s[2] == 'p')
9528                     {
9529                       s += 3;
9530                       regno = GP;
9531                     }
9532                   else if (s[1] == 'a' && s[2] == 't')
9533                     {
9534                       s += 3;
9535                       regno = AT;
9536                     }
9537                   else if (s[1] == 'k' && s[2] == 't' && s[3] == '0')
9538                     {
9539                       s += 4;
9540                       regno = KT0;
9541                     }
9542                   else if (s[1] == 'k' && s[2] == 't' && s[3] == '1')
9543                     {
9544                       s += 4;
9545                       regno = KT1;
9546                     }
9547                   else if (s[1] == 'z' && s[2] == 'e' && s[3] == 'r' && s[4] == 'o')
9548                     {
9549                       s += 5;
9550                       regno = ZERO;
9551                     }
9552                   else
9553                     break;
9554                 }
9555
9556               if (*s == ' ')
9557                 ++s;
9558               if (args[1] != *s)
9559                 {
9560                   if (c == 'v' || c == 'w')
9561                     {
9562                       regno = mips16_to_32_reg_map[lastregno];
9563                       s = s_reset;
9564                       ++args;
9565                     }
9566                 }
9567
9568               switch (c)
9569                 {
9570                 case 'x':
9571                 case 'y':
9572                 case 'z':
9573                 case 'v':
9574                 case 'w':
9575                 case 'Z':
9576                   regno = mips32_to_16_reg_map[regno];
9577                   break;
9578
9579                 case '0':
9580                   if (regno != 0)
9581                     regno = ILLEGAL_REG;
9582                   break;
9583
9584                 case 'S':
9585                   if (regno != SP)
9586                     regno = ILLEGAL_REG;
9587                   break;
9588
9589                 case 'R':
9590                   if (regno != RA)
9591                     regno = ILLEGAL_REG;
9592                   break;
9593
9594                 case 'X':
9595                 case 'Y':
9596                   if (regno == AT && ! mips_opts.noat)
9597                     as_warn (_("used $at without \".set noat\""));
9598                   break;
9599
9600                 default:
9601                   internalError ();
9602                 }
9603
9604               if (regno == ILLEGAL_REG)
9605                 break;
9606
9607               switch (c)
9608                 {
9609                 case 'x':
9610                 case 'v':
9611                   MIPS16_INSERT_OPERAND (RX, *ip, regno);
9612                   break;
9613                 case 'y':
9614                 case 'w':
9615                   MIPS16_INSERT_OPERAND (RY, *ip, regno);
9616                   break;
9617                 case 'z':
9618                   MIPS16_INSERT_OPERAND (RZ, *ip, regno);
9619                   break;
9620                 case 'Z':
9621                   MIPS16_INSERT_OPERAND (MOVE32Z, *ip, regno);
9622                 case '0':
9623                 case 'S':
9624                 case 'R':
9625                   break;
9626                 case 'X':
9627                   MIPS16_INSERT_OPERAND (REGR32, *ip, regno);
9628                   break;
9629                 case 'Y':
9630                   regno = ((regno & 7) << 2) | ((regno & 0x18) >> 3);
9631                   MIPS16_INSERT_OPERAND (REG32R, *ip, regno);
9632                   break;
9633                 default:
9634                   internalError ();
9635                 }
9636
9637               lastregno = regno;
9638               continue;
9639
9640             case 'P':
9641               if (strncmp (s, "$pc", 3) == 0)
9642                 {
9643                   s += 3;
9644                   continue;
9645                 }
9646               break;
9647
9648             case '5':
9649             case 'H':
9650             case 'W':
9651             case 'D':
9652             case 'j':
9653             case 'V':
9654             case 'C':
9655             case 'U':
9656             case 'k':
9657             case 'K':
9658               i = my_getSmallExpression (&imm_expr, imm_reloc, s);
9659               if (i > 0)
9660                 {
9661                   if (imm_expr.X_op != O_constant)
9662                     {
9663                       mips16_ext = TRUE;
9664                       ip->use_extend = TRUE;
9665                       ip->extend = 0;
9666                     }
9667                   else
9668                     {
9669                       /* We need to relax this instruction.  */
9670                       *offset_reloc = *imm_reloc;
9671                       *imm_reloc = (int) BFD_RELOC_UNUSED + c;
9672                     }
9673                   s = expr_end;
9674                   continue;
9675                 }
9676               *imm_reloc = BFD_RELOC_UNUSED;
9677               /* Fall through.  */
9678             case '<':
9679             case '>':
9680             case '[':
9681             case ']':
9682             case '4':
9683             case '8':
9684               my_getExpression (&imm_expr, s);
9685               if (imm_expr.X_op == O_register)
9686                 {
9687                   /* What we thought was an expression turned out to
9688                      be a register.  */
9689
9690                   if (s[0] == '(' && args[1] == '(')
9691                     {
9692                       /* It looks like the expression was omitted
9693                          before a register indirection, which means
9694                          that the expression is implicitly zero.  We
9695                          still set up imm_expr, so that we handle
9696                          explicit extensions correctly.  */
9697                       imm_expr.X_op = O_constant;
9698                       imm_expr.X_add_number = 0;
9699                       *imm_reloc = (int) BFD_RELOC_UNUSED + c;
9700                       continue;
9701                     }
9702
9703                   break;
9704                 }
9705
9706               /* We need to relax this instruction.  */
9707               *imm_reloc = (int) BFD_RELOC_UNUSED + c;
9708               s = expr_end;
9709               continue;
9710
9711             case 'p':
9712             case 'q':
9713             case 'A':
9714             case 'B':
9715             case 'E':
9716               /* We use offset_reloc rather than imm_reloc for the PC
9717                  relative operands.  This lets macros with both
9718                  immediate and address operands work correctly.  */
9719               my_getExpression (&offset_expr, s);
9720
9721               if (offset_expr.X_op == O_register)
9722                 break;
9723
9724               /* We need to relax this instruction.  */
9725               *offset_reloc = (int) BFD_RELOC_UNUSED + c;
9726               s = expr_end;
9727               continue;
9728
9729             case '6':           /* break code */
9730               my_getExpression (&imm_expr, s);
9731               check_absolute_expr (ip, &imm_expr);
9732               if ((unsigned long) imm_expr.X_add_number > 63)
9733                 as_warn (_("Invalid value for `%s' (%lu)"),
9734                          ip->insn_mo->name,
9735                          (unsigned long) imm_expr.X_add_number);
9736               MIPS16_INSERT_OPERAND (IMM6, *ip, imm_expr.X_add_number);
9737               imm_expr.X_op = O_absent;
9738               s = expr_end;
9739               continue;
9740
9741             case 'a':           /* 26 bit address */
9742               my_getExpression (&offset_expr, s);
9743               s = expr_end;
9744               *offset_reloc = BFD_RELOC_MIPS16_JMP;
9745               ip->insn_opcode <<= 16;
9746               continue;
9747
9748             case 'l':           /* register list for entry macro */
9749             case 'L':           /* register list for exit macro */
9750               {
9751                 int mask;
9752
9753                 if (c == 'l')
9754                   mask = 0;
9755                 else
9756                   mask = 7 << 3;
9757                 while (*s != '\0')
9758                   {
9759                     int freg, reg1, reg2;
9760
9761                     while (*s == ' ' || *s == ',')
9762                       ++s;
9763                     if (*s != '$')
9764                       {
9765                         as_bad (_("can't parse register list"));
9766                         break;
9767                       }
9768                     ++s;
9769                     if (*s != 'f')
9770                       freg = 0;
9771                     else
9772                       {
9773                         freg = 1;
9774                         ++s;
9775                       }
9776                     reg1 = 0;
9777                     while (ISDIGIT (*s))
9778                       {
9779                         reg1 *= 10;
9780                         reg1 += *s - '0';
9781                         ++s;
9782                       }
9783                     if (*s == ' ')
9784                       ++s;
9785                     if (*s != '-')
9786                       reg2 = reg1;
9787                     else
9788                       {
9789                         ++s;
9790                         if (*s != '$')
9791                           break;
9792                         ++s;
9793                         if (freg)
9794                           {
9795                             if (*s == 'f')
9796                               ++s;
9797                             else
9798                               {
9799                                 as_bad (_("invalid register list"));
9800                                 break;
9801                               }
9802                           }
9803                         reg2 = 0;
9804                         while (ISDIGIT (*s))
9805                           {
9806                             reg2 *= 10;
9807                             reg2 += *s - '0';
9808                             ++s;
9809                           }
9810                       }
9811                     if (freg && reg1 == 0 && reg2 == 0 && c == 'L')
9812                       {
9813                         mask &= ~ (7 << 3);
9814                         mask |= 5 << 3;
9815                       }
9816                     else if (freg && reg1 == 0 && reg2 == 1 && c == 'L')
9817                       {
9818                         mask &= ~ (7 << 3);
9819                         mask |= 6 << 3;
9820                       }
9821                     else if (reg1 == 4 && reg2 >= 4 && reg2 <= 7 && c != 'L')
9822                       mask |= (reg2 - 3) << 3;
9823                     else if (reg1 == 16 && reg2 >= 16 && reg2 <= 17)
9824                       mask |= (reg2 - 15) << 1;
9825                     else if (reg1 == RA && reg2 == RA)
9826                       mask |= 1;
9827                     else
9828                       {
9829                         as_bad (_("invalid register list"));
9830                         break;
9831                       }
9832                   }
9833                 /* The mask is filled in in the opcode table for the
9834                    benefit of the disassembler.  We remove it before
9835                    applying the actual mask.  */
9836                 ip->insn_opcode &= ~ ((7 << 3) << MIPS16OP_SH_IMM6);
9837                 ip->insn_opcode |= mask << MIPS16OP_SH_IMM6;
9838               }
9839             continue;
9840
9841             case 'm':           /* Register list for save insn.  */
9842             case 'M':           /* Register list for restore insn.  */
9843               {
9844                 int opcode = 0;
9845                 int framesz = 0, seen_framesz = 0;
9846                 int args = 0, statics = 0, sregs = 0;
9847
9848                 while (*s != '\0')
9849                   {
9850                     unsigned int reg1, reg2;
9851
9852                     SKIP_SPACE_TABS (s);
9853                     while (*s == ',')
9854                       ++s;
9855                     SKIP_SPACE_TABS (s);
9856
9857                     my_getExpression (&imm_expr, s);
9858                     if (imm_expr.X_op == O_constant)
9859                       {
9860                         /* Handle the frame size.  */
9861                         if (seen_framesz)
9862                           {
9863                             as_bad (_("more than one frame size in list"));
9864                             break;
9865                           }
9866                         seen_framesz = 1;
9867                         framesz = imm_expr.X_add_number;
9868                         imm_expr.X_op = O_absent;
9869                         s = expr_end;
9870                         continue;
9871                       }
9872
9873                     if (*s != '$')
9874                       {
9875                         as_bad (_("can't parse register list"));
9876                         break;
9877                       }
9878                     ++s;
9879
9880                     reg1 = 0;
9881                     while (ISDIGIT (*s))
9882                       {
9883                         reg1 *= 10;
9884                         reg1 += *s - '0';
9885                         ++s;
9886                       }
9887                     SKIP_SPACE_TABS (s);
9888                     if (*s != '-')
9889                       reg2 = reg1;
9890                     else
9891                       {
9892                         ++s;
9893                         if (*s != '$')
9894                           {
9895                             as_bad (_("can't parse register list"));
9896                             break;
9897                           }
9898                         ++s;
9899                         reg2 = 0;
9900                         while (ISDIGIT (*s))
9901                           {
9902                             reg2 *= 10;
9903                             reg2 += *s - '0';
9904                             ++s;
9905                           }
9906                       }
9907
9908                     while (reg1 <= reg2)
9909                       {
9910                         if (reg1 >= 4 && reg1 <= 7)
9911                           {
9912                             if (c == 'm' && !seen_framesz)
9913                                 /* args $a0-$a3 */
9914                                 args |= 1 << (reg1 - 4);
9915                             else
9916                                 /* statics $a0-$a3 */
9917                                 statics |= 1 << (reg1 - 4);
9918                           }
9919                         else if ((reg1 >= 16 && reg1 <= 23) || reg1 == 30)
9920                           {
9921                             /* $s0-$s8 */
9922                             sregs |= 1 << ((reg1 == 30) ? 8 : (reg1 - 16));
9923                           }
9924                         else if (reg1 == 31)
9925                           {
9926                             /* Add $ra to insn.  */
9927                             opcode |= 0x40;
9928                           }
9929                         else
9930                           {
9931                             as_bad (_("unexpected register in list"));
9932                             break;
9933                           }
9934                         if (++reg1 == 24)
9935                           reg1 = 30;
9936                       }
9937                   }
9938
9939                 /* Encode args/statics combination.  */
9940                 if (args & statics)
9941                   as_bad (_("arg/static registers overlap"));
9942                 else if (args == 0xf)
9943                   /* All $a0-$a3 are args.  */
9944                   opcode |= MIPS16_ALL_ARGS << 16;
9945                 else if (statics == 0xf)
9946                   /* All $a0-$a3 are statics.  */
9947                   opcode |= MIPS16_ALL_STATICS << 16;
9948                 else 
9949                   {
9950                     int narg = 0, nstat = 0;
9951
9952                     /* Count arg registers.  */
9953                     while (args & 0x1)
9954                       {
9955                         args >>= 1;
9956                         narg++;
9957                       }
9958                     if (args != 0)
9959                       as_bad (_("invalid arg register list"));
9960
9961                     /* Count static registers.  */
9962                     while (statics & 0x8)
9963                       {
9964                         statics = (statics << 1) & 0xf;
9965                         nstat++;
9966                       }
9967                     if (statics != 0) 
9968                       as_bad (_("invalid static register list"));
9969
9970                     /* Encode args/statics.  */
9971                     opcode |= ((narg << 2) | nstat) << 16;
9972                   }
9973
9974                 /* Encode $s0/$s1.  */
9975                 if (sregs & (1 << 0))           /* $s0 */
9976                   opcode |= 0x20;
9977                 if (sregs & (1 << 1))           /* $s1 */
9978                   opcode |= 0x10;
9979                 sregs >>= 2;
9980
9981                 if (sregs != 0)
9982                   {
9983                     /* Count regs $s2-$s8.  */
9984                     int nsreg = 0;
9985                     while (sregs & 1)
9986                       {
9987                         sregs >>= 1;
9988                         nsreg++;
9989                       }
9990                     if (sregs != 0)
9991                       as_bad (_("invalid static register list"));
9992                     /* Encode $s2-$s8. */
9993                     opcode |= nsreg << 24;
9994                   }
9995
9996                 /* Encode frame size.  */
9997                 if (!seen_framesz)
9998                   as_bad (_("missing frame size"));
9999                 else if ((framesz & 7) != 0 || framesz < 0
10000                          || framesz > 0xff * 8)
10001                   as_bad (_("invalid frame size"));
10002                 else if (framesz != 128 || (opcode >> 16) != 0)
10003                   {
10004                     framesz /= 8;
10005                     opcode |= (((framesz & 0xf0) << 16)
10006                              | (framesz & 0x0f));
10007                   }
10008
10009                 /* Finally build the instruction.  */
10010                 if ((opcode >> 16) != 0 || framesz == 0)
10011                   {
10012                     ip->use_extend = TRUE;
10013                     ip->extend = opcode >> 16;
10014                   }
10015                 ip->insn_opcode |= opcode & 0x7f;
10016               }
10017             continue;
10018
10019             case 'e':           /* extend code */
10020               my_getExpression (&imm_expr, s);
10021               check_absolute_expr (ip, &imm_expr);
10022               if ((unsigned long) imm_expr.X_add_number > 0x7ff)
10023                 {
10024                   as_warn (_("Invalid value for `%s' (%lu)"),
10025                            ip->insn_mo->name,
10026                            (unsigned long) imm_expr.X_add_number);
10027                   imm_expr.X_add_number &= 0x7ff;
10028                 }
10029               ip->insn_opcode |= imm_expr.X_add_number;
10030               imm_expr.X_op = O_absent;
10031               s = expr_end;
10032               continue;
10033
10034             default:
10035               internalError ();
10036             }
10037           break;
10038         }
10039
10040       /* Args don't match.  */
10041       if (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes] &&
10042           strcmp (insn->name, insn[1].name) == 0)
10043         {
10044           ++insn;
10045           s = argsstart;
10046           continue;
10047         }
10048
10049       insn_error = _("illegal operands");
10050
10051       return;
10052     }
10053 }
10054
10055 /* This structure holds information we know about a mips16 immediate
10056    argument type.  */
10057
10058 struct mips16_immed_operand
10059 {
10060   /* The type code used in the argument string in the opcode table.  */
10061   int type;
10062   /* The number of bits in the short form of the opcode.  */
10063   int nbits;
10064   /* The number of bits in the extended form of the opcode.  */
10065   int extbits;
10066   /* The amount by which the short form is shifted when it is used;
10067      for example, the sw instruction has a shift count of 2.  */
10068   int shift;
10069   /* The amount by which the short form is shifted when it is stored
10070      into the instruction code.  */
10071   int op_shift;
10072   /* Non-zero if the short form is unsigned.  */
10073   int unsp;
10074   /* Non-zero if the extended form is unsigned.  */
10075   int extu;
10076   /* Non-zero if the value is PC relative.  */
10077   int pcrel;
10078 };
10079
10080 /* The mips16 immediate operand types.  */
10081
10082 static const struct mips16_immed_operand mips16_immed_operands[] =
10083 {
10084   { '<',  3,  5, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
10085   { '>',  3,  5, 0, MIPS16OP_SH_RX,   1, 1, 0 },
10086   { '[',  3,  6, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
10087   { ']',  3,  6, 0, MIPS16OP_SH_RX,   1, 1, 0 },
10088   { '4',  4, 15, 0, MIPS16OP_SH_IMM4, 0, 0, 0 },
10089   { '5',  5, 16, 0, MIPS16OP_SH_IMM5, 1, 0, 0 },
10090   { 'H',  5, 16, 1, MIPS16OP_SH_IMM5, 1, 0, 0 },
10091   { 'W',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 0 },
10092   { 'D',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 0 },
10093   { 'j',  5, 16, 0, MIPS16OP_SH_IMM5, 0, 0, 0 },
10094   { '8',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 0, 0 },
10095   { 'V',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 0 },
10096   { 'C',  8, 16, 3, MIPS16OP_SH_IMM8, 1, 0, 0 },
10097   { 'U',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 1, 0 },
10098   { 'k',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 0 },
10099   { 'K',  8, 16, 3, MIPS16OP_SH_IMM8, 0, 0, 0 },
10100   { 'p',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
10101   { 'q', 11, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
10102   { 'A',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 1 },
10103   { 'B',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 1 },
10104   { 'E',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 1 }
10105 };
10106
10107 #define MIPS16_NUM_IMMED \
10108   (sizeof mips16_immed_operands / sizeof mips16_immed_operands[0])
10109
10110 /* Handle a mips16 instruction with an immediate value.  This or's the
10111    small immediate value into *INSN.  It sets *USE_EXTEND to indicate
10112    whether an extended value is needed; if one is needed, it sets
10113    *EXTEND to the value.  The argument type is TYPE.  The value is VAL.
10114    If SMALL is true, an unextended opcode was explicitly requested.
10115    If EXT is true, an extended opcode was explicitly requested.  If
10116    WARN is true, warn if EXT does not match reality.  */
10117
10118 static void
10119 mips16_immed (char *file, unsigned int line, int type, offsetT val,
10120               bfd_boolean warn, bfd_boolean small, bfd_boolean ext,
10121               unsigned long *insn, bfd_boolean *use_extend,
10122               unsigned short *extend)
10123 {
10124   register const struct mips16_immed_operand *op;
10125   int mintiny, maxtiny;
10126   bfd_boolean needext;
10127
10128   op = mips16_immed_operands;
10129   while (op->type != type)
10130     {
10131       ++op;
10132       assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
10133     }
10134
10135   if (op->unsp)
10136     {
10137       if (type == '<' || type == '>' || type == '[' || type == ']')
10138         {
10139           mintiny = 1;
10140           maxtiny = 1 << op->nbits;
10141         }
10142       else
10143         {
10144           mintiny = 0;
10145           maxtiny = (1 << op->nbits) - 1;
10146         }
10147     }
10148   else
10149     {
10150       mintiny = - (1 << (op->nbits - 1));
10151       maxtiny = (1 << (op->nbits - 1)) - 1;
10152     }
10153
10154   /* Branch offsets have an implicit 0 in the lowest bit.  */
10155   if (type == 'p' || type == 'q')
10156     val /= 2;
10157
10158   if ((val & ((1 << op->shift) - 1)) != 0
10159       || val < (mintiny << op->shift)
10160       || val > (maxtiny << op->shift))
10161     needext = TRUE;
10162   else
10163     needext = FALSE;
10164
10165   if (warn && ext && ! needext)
10166     as_warn_where (file, line,
10167                    _("extended operand requested but not required"));
10168   if (small && needext)
10169     as_bad_where (file, line, _("invalid unextended operand value"));
10170
10171   if (small || (! ext && ! needext))
10172     {
10173       int insnval;
10174
10175       *use_extend = FALSE;
10176       insnval = ((val >> op->shift) & ((1 << op->nbits) - 1));
10177       insnval <<= op->op_shift;
10178       *insn |= insnval;
10179     }
10180   else
10181     {
10182       long minext, maxext;
10183       int extval;
10184
10185       if (op->extu)
10186         {
10187           minext = 0;
10188           maxext = (1 << op->extbits) - 1;
10189         }
10190       else
10191         {
10192           minext = - (1 << (op->extbits - 1));
10193           maxext = (1 << (op->extbits - 1)) - 1;
10194         }
10195       if (val < minext || val > maxext)
10196         as_bad_where (file, line,
10197                       _("operand value out of range for instruction"));
10198
10199       *use_extend = TRUE;
10200       if (op->extbits == 16)
10201         {
10202           extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
10203           val &= 0x1f;
10204         }
10205       else if (op->extbits == 15)
10206         {
10207           extval = ((val >> 11) & 0xf) | (val & 0x7f0);
10208           val &= 0xf;
10209         }
10210       else
10211         {
10212           extval = ((val & 0x1f) << 6) | (val & 0x20);
10213           val = 0;
10214         }
10215
10216       *extend = (unsigned short) extval;
10217       *insn |= val;
10218     }
10219 }
10220 \f
10221 struct percent_op_match
10222 {
10223   const char *str;
10224   bfd_reloc_code_real_type reloc;
10225 };
10226
10227 static const struct percent_op_match mips_percent_op[] =
10228 {
10229   {"%lo", BFD_RELOC_LO16},
10230 #ifdef OBJ_ELF
10231   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
10232   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
10233   {"%call16", BFD_RELOC_MIPS_CALL16},
10234   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
10235   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
10236   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
10237   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
10238   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
10239   {"%got", BFD_RELOC_MIPS_GOT16},
10240   {"%gp_rel", BFD_RELOC_GPREL16},
10241   {"%half", BFD_RELOC_16},
10242   {"%highest", BFD_RELOC_MIPS_HIGHEST},
10243   {"%higher", BFD_RELOC_MIPS_HIGHER},
10244   {"%neg", BFD_RELOC_MIPS_SUB},
10245   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
10246   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
10247   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
10248   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
10249   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
10250   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
10251   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
10252 #endif
10253   {"%hi", BFD_RELOC_HI16_S}
10254 };
10255
10256 static const struct percent_op_match mips16_percent_op[] =
10257 {
10258   {"%lo", BFD_RELOC_MIPS16_LO16},
10259   {"%gprel", BFD_RELOC_MIPS16_GPREL},
10260   {"%hi", BFD_RELOC_MIPS16_HI16_S}
10261 };
10262
10263
10264 /* Return true if *STR points to a relocation operator.  When returning true,
10265    move *STR over the operator and store its relocation code in *RELOC.
10266    Leave both *STR and *RELOC alone when returning false.  */
10267
10268 static bfd_boolean
10269 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
10270 {
10271   const struct percent_op_match *percent_op;
10272   size_t limit, i;
10273
10274   if (mips_opts.mips16)
10275     {
10276       percent_op = mips16_percent_op;
10277       limit = ARRAY_SIZE (mips16_percent_op);
10278     }
10279   else
10280     {
10281       percent_op = mips_percent_op;
10282       limit = ARRAY_SIZE (mips_percent_op);
10283     }
10284
10285   for (i = 0; i < limit; i++)
10286     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
10287       {
10288         int len = strlen (percent_op[i].str);
10289
10290         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
10291           continue;
10292
10293         *str += strlen (percent_op[i].str);
10294         *reloc = percent_op[i].reloc;
10295
10296         /* Check whether the output BFD supports this relocation.
10297            If not, issue an error and fall back on something safe.  */
10298         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
10299           {
10300             as_bad ("relocation %s isn't supported by the current ABI",
10301                     percent_op[i].str);
10302             *reloc = BFD_RELOC_UNUSED;
10303           }
10304         return TRUE;
10305       }
10306   return FALSE;
10307 }
10308
10309
10310 /* Parse string STR as a 16-bit relocatable operand.  Store the
10311    expression in *EP and the relocations in the array starting
10312    at RELOC.  Return the number of relocation operators used.
10313
10314    On exit, EXPR_END points to the first character after the expression.  */
10315
10316 static size_t
10317 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
10318                        char *str)
10319 {
10320   bfd_reloc_code_real_type reversed_reloc[3];
10321   size_t reloc_index, i;
10322   int crux_depth, str_depth;
10323   char *crux;
10324
10325   /* Search for the start of the main expression, recoding relocations
10326      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
10327      of the main expression and with CRUX_DEPTH containing the number
10328      of open brackets at that point.  */
10329   reloc_index = -1;
10330   str_depth = 0;
10331   do
10332     {
10333       reloc_index++;
10334       crux = str;
10335       crux_depth = str_depth;
10336
10337       /* Skip over whitespace and brackets, keeping count of the number
10338          of brackets.  */
10339       while (*str == ' ' || *str == '\t' || *str == '(')
10340         if (*str++ == '(')
10341           str_depth++;
10342     }
10343   while (*str == '%'
10344          && reloc_index < (HAVE_NEWABI ? 3 : 1)
10345          && parse_relocation (&str, &reversed_reloc[reloc_index]));
10346
10347   my_getExpression (ep, crux);
10348   str = expr_end;
10349
10350   /* Match every open bracket.  */
10351   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
10352     if (*str++ == ')')
10353       crux_depth--;
10354
10355   if (crux_depth > 0)
10356     as_bad ("unclosed '('");
10357
10358   expr_end = str;
10359
10360   if (reloc_index != 0)
10361     {
10362       prev_reloc_op_frag = frag_now;
10363       for (i = 0; i < reloc_index; i++)
10364         reloc[i] = reversed_reloc[reloc_index - 1 - i];
10365     }
10366
10367   return reloc_index;
10368 }
10369
10370 static void
10371 my_getExpression (expressionS *ep, char *str)
10372 {
10373   char *save_in;
10374   valueT val;
10375
10376   save_in = input_line_pointer;
10377   input_line_pointer = str;
10378   expression (ep);
10379   expr_end = input_line_pointer;
10380   input_line_pointer = save_in;
10381
10382   /* If we are in mips16 mode, and this is an expression based on `.',
10383      then we bump the value of the symbol by 1 since that is how other
10384      text symbols are handled.  We don't bother to handle complex
10385      expressions, just `.' plus or minus a constant.  */
10386   if (mips_opts.mips16
10387       && ep->X_op == O_symbol
10388       && strcmp (S_GET_NAME (ep->X_add_symbol), FAKE_LABEL_NAME) == 0
10389       && S_GET_SEGMENT (ep->X_add_symbol) == now_seg
10390       && symbol_get_frag (ep->X_add_symbol) == frag_now
10391       && symbol_constant_p (ep->X_add_symbol)
10392       && (val = S_GET_VALUE (ep->X_add_symbol)) == frag_now_fix ())
10393     S_SET_VALUE (ep->X_add_symbol, val + 1);
10394 }
10395
10396 /* Turn a string in input_line_pointer into a floating point constant
10397    of type TYPE, and store the appropriate bytes in *LITP.  The number
10398    of LITTLENUMS emitted is stored in *SIZEP.  An error message is
10399    returned, or NULL on OK.  */
10400
10401 char *
10402 md_atof (int type, char *litP, int *sizeP)
10403 {
10404   int prec;
10405   LITTLENUM_TYPE words[4];
10406   char *t;
10407   int i;
10408
10409   switch (type)
10410     {
10411     case 'f':
10412       prec = 2;
10413       break;
10414
10415     case 'd':
10416       prec = 4;
10417       break;
10418
10419     default:
10420       *sizeP = 0;
10421       return _("bad call to md_atof");
10422     }
10423
10424   t = atof_ieee (input_line_pointer, type, words);
10425   if (t)
10426     input_line_pointer = t;
10427
10428   *sizeP = prec * 2;
10429
10430   if (! target_big_endian)
10431     {
10432       for (i = prec - 1; i >= 0; i--)
10433         {
10434           md_number_to_chars (litP, words[i], 2);
10435           litP += 2;
10436         }
10437     }
10438   else
10439     {
10440       for (i = 0; i < prec; i++)
10441         {
10442           md_number_to_chars (litP, words[i], 2);
10443           litP += 2;
10444         }
10445     }
10446
10447   return NULL;
10448 }
10449
10450 void
10451 md_number_to_chars (char *buf, valueT val, int n)
10452 {
10453   if (target_big_endian)
10454     number_to_chars_bigendian (buf, val, n);
10455   else
10456     number_to_chars_littleendian (buf, val, n);
10457 }
10458 \f
10459 #ifdef OBJ_ELF
10460 static int support_64bit_objects(void)
10461 {
10462   const char **list, **l;
10463   int yes;
10464
10465   list = bfd_target_list ();
10466   for (l = list; *l != NULL; l++)
10467 #ifdef TE_TMIPS
10468     /* This is traditional mips */
10469     if (strcmp (*l, "elf64-tradbigmips") == 0
10470         || strcmp (*l, "elf64-tradlittlemips") == 0)
10471 #else
10472     if (strcmp (*l, "elf64-bigmips") == 0
10473         || strcmp (*l, "elf64-littlemips") == 0)
10474 #endif
10475       break;
10476   yes = (*l != NULL);
10477   free (list);
10478   return yes;
10479 }
10480 #endif /* OBJ_ELF */
10481
10482 const char *md_shortopts = "O::g::G:";
10483
10484 struct option md_longopts[] =
10485 {
10486   /* Options which specify architecture.  */
10487 #define OPTION_ARCH_BASE    (OPTION_MD_BASE)
10488 #define OPTION_MARCH (OPTION_ARCH_BASE + 0)
10489   {"march", required_argument, NULL, OPTION_MARCH},
10490 #define OPTION_MTUNE (OPTION_ARCH_BASE + 1)
10491   {"mtune", required_argument, NULL, OPTION_MTUNE},
10492 #define OPTION_MIPS1 (OPTION_ARCH_BASE + 2)
10493   {"mips0", no_argument, NULL, OPTION_MIPS1},
10494   {"mips1", no_argument, NULL, OPTION_MIPS1},
10495 #define OPTION_MIPS2 (OPTION_ARCH_BASE + 3)
10496   {"mips2", no_argument, NULL, OPTION_MIPS2},
10497 #define OPTION_MIPS3 (OPTION_ARCH_BASE + 4)
10498   {"mips3", no_argument, NULL, OPTION_MIPS3},
10499 #define OPTION_MIPS4 (OPTION_ARCH_BASE + 5)
10500   {"mips4", no_argument, NULL, OPTION_MIPS4},
10501 #define OPTION_MIPS5 (OPTION_ARCH_BASE + 6)
10502   {"mips5", no_argument, NULL, OPTION_MIPS5},
10503 #define OPTION_MIPS32 (OPTION_ARCH_BASE + 7)
10504   {"mips32", no_argument, NULL, OPTION_MIPS32},
10505 #define OPTION_MIPS64 (OPTION_ARCH_BASE + 8)
10506   {"mips64", no_argument, NULL, OPTION_MIPS64},
10507 #define OPTION_MIPS32R2 (OPTION_ARCH_BASE + 9)
10508   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
10509 #define OPTION_MIPS64R2 (OPTION_ARCH_BASE + 10)
10510   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
10511
10512   /* Options which specify Application Specific Extensions (ASEs).  */
10513 #define OPTION_ASE_BASE (OPTION_ARCH_BASE + 11)
10514 #define OPTION_MIPS16 (OPTION_ASE_BASE + 0)
10515   {"mips16", no_argument, NULL, OPTION_MIPS16},
10516 #define OPTION_NO_MIPS16 (OPTION_ASE_BASE + 1)
10517   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
10518 #define OPTION_MIPS3D (OPTION_ASE_BASE + 2)
10519   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
10520 #define OPTION_NO_MIPS3D (OPTION_ASE_BASE + 3)
10521   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
10522 #define OPTION_MDMX (OPTION_ASE_BASE + 4)
10523   {"mdmx", no_argument, NULL, OPTION_MDMX},
10524 #define OPTION_NO_MDMX (OPTION_ASE_BASE + 5)
10525   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
10526 #define OPTION_DSP (OPTION_ASE_BASE + 6)
10527   {"mdsp", no_argument, NULL, OPTION_DSP},
10528 #define OPTION_NO_DSP (OPTION_ASE_BASE + 7)
10529   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
10530 #define OPTION_MT (OPTION_ASE_BASE + 8)
10531   {"mmt", no_argument, NULL, OPTION_MT},
10532 #define OPTION_NO_MT (OPTION_ASE_BASE + 9)
10533   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
10534
10535   /* Old-style architecture options.  Don't add more of these.  */
10536 #define OPTION_COMPAT_ARCH_BASE (OPTION_ASE_BASE + 10)
10537 #define OPTION_M4650 (OPTION_COMPAT_ARCH_BASE + 0)
10538   {"m4650", no_argument, NULL, OPTION_M4650},
10539 #define OPTION_NO_M4650 (OPTION_COMPAT_ARCH_BASE + 1)
10540   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
10541 #define OPTION_M4010 (OPTION_COMPAT_ARCH_BASE + 2)
10542   {"m4010", no_argument, NULL, OPTION_M4010},
10543 #define OPTION_NO_M4010 (OPTION_COMPAT_ARCH_BASE + 3)
10544   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
10545 #define OPTION_M4100 (OPTION_COMPAT_ARCH_BASE + 4)
10546   {"m4100", no_argument, NULL, OPTION_M4100},
10547 #define OPTION_NO_M4100 (OPTION_COMPAT_ARCH_BASE + 5)
10548   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
10549 #define OPTION_M3900 (OPTION_COMPAT_ARCH_BASE + 6)
10550   {"m3900", no_argument, NULL, OPTION_M3900},
10551 #define OPTION_NO_M3900 (OPTION_COMPAT_ARCH_BASE + 7)
10552   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
10553
10554   /* Options which enable bug fixes.  */
10555 #define OPTION_FIX_BASE    (OPTION_COMPAT_ARCH_BASE + 8)
10556 #define OPTION_M7000_HILO_FIX (OPTION_FIX_BASE + 0)
10557   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
10558 #define OPTION_MNO_7000_HILO_FIX (OPTION_FIX_BASE + 1)
10559   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
10560   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
10561 #define OPTION_FIX_VR4120 (OPTION_FIX_BASE + 2)
10562 #define OPTION_NO_FIX_VR4120 (OPTION_FIX_BASE + 3)
10563   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
10564   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
10565 #define OPTION_FIX_VR4130 (OPTION_FIX_BASE + 4)
10566 #define OPTION_NO_FIX_VR4130 (OPTION_FIX_BASE + 5)
10567   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
10568   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
10569
10570   /* Miscellaneous options.  */
10571 #define OPTION_MISC_BASE (OPTION_FIX_BASE + 6)
10572 #define OPTION_TRAP (OPTION_MISC_BASE + 0)
10573   {"trap", no_argument, NULL, OPTION_TRAP},
10574   {"no-break", no_argument, NULL, OPTION_TRAP},
10575 #define OPTION_BREAK (OPTION_MISC_BASE + 1)
10576   {"break", no_argument, NULL, OPTION_BREAK},
10577   {"no-trap", no_argument, NULL, OPTION_BREAK},
10578 #define OPTION_EB (OPTION_MISC_BASE + 2)
10579   {"EB", no_argument, NULL, OPTION_EB},
10580 #define OPTION_EL (OPTION_MISC_BASE + 3)
10581   {"EL", no_argument, NULL, OPTION_EL},
10582 #define OPTION_FP32 (OPTION_MISC_BASE + 4)
10583   {"mfp32", no_argument, NULL, OPTION_FP32},
10584 #define OPTION_GP32 (OPTION_MISC_BASE + 5)
10585   {"mgp32", no_argument, NULL, OPTION_GP32},
10586 #define OPTION_CONSTRUCT_FLOATS (OPTION_MISC_BASE + 6)
10587   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
10588 #define OPTION_NO_CONSTRUCT_FLOATS (OPTION_MISC_BASE + 7)
10589   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
10590 #define OPTION_FP64 (OPTION_MISC_BASE + 8)
10591   {"mfp64", no_argument, NULL, OPTION_FP64},
10592 #define OPTION_GP64 (OPTION_MISC_BASE + 9)
10593   {"mgp64", no_argument, NULL, OPTION_GP64},
10594 #define OPTION_RELAX_BRANCH (OPTION_MISC_BASE + 10)
10595 #define OPTION_NO_RELAX_BRANCH (OPTION_MISC_BASE + 11)
10596   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
10597   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
10598 #define OPTION_MSHARED (OPTION_MISC_BASE + 12)
10599 #define OPTION_MNO_SHARED (OPTION_MISC_BASE + 13)
10600   {"mshared", no_argument, NULL, OPTION_MSHARED},
10601   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
10602 #define OPTION_MSYM32 (OPTION_MISC_BASE + 14)
10603 #define OPTION_MNO_SYM32 (OPTION_MISC_BASE + 15)
10604   {"msym32", no_argument, NULL, OPTION_MSYM32},
10605   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
10606
10607   /* ELF-specific options.  */
10608 #ifdef OBJ_ELF
10609 #define OPTION_ELF_BASE    (OPTION_MISC_BASE + 16)
10610 #define OPTION_CALL_SHARED (OPTION_ELF_BASE + 0)
10611   {"KPIC",        no_argument, NULL, OPTION_CALL_SHARED},
10612   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
10613 #define OPTION_NON_SHARED  (OPTION_ELF_BASE + 1)
10614   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
10615 #define OPTION_XGOT        (OPTION_ELF_BASE + 2)
10616   {"xgot",        no_argument, NULL, OPTION_XGOT},
10617 #define OPTION_MABI        (OPTION_ELF_BASE + 3)
10618   {"mabi", required_argument, NULL, OPTION_MABI},
10619 #define OPTION_32          (OPTION_ELF_BASE + 4)
10620   {"32",          no_argument, NULL, OPTION_32},
10621 #define OPTION_N32         (OPTION_ELF_BASE + 5)
10622   {"n32",         no_argument, NULL, OPTION_N32},
10623 #define OPTION_64          (OPTION_ELF_BASE + 6)
10624   {"64",          no_argument, NULL, OPTION_64},
10625 #define OPTION_MDEBUG      (OPTION_ELF_BASE + 7)
10626   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
10627 #define OPTION_NO_MDEBUG   (OPTION_ELF_BASE + 8)
10628   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
10629 #define OPTION_PDR         (OPTION_ELF_BASE + 9)
10630   {"mpdr", no_argument, NULL, OPTION_PDR},
10631 #define OPTION_NO_PDR      (OPTION_ELF_BASE + 10)
10632   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
10633 #endif /* OBJ_ELF */
10634
10635   {NULL, no_argument, NULL, 0}
10636 };
10637 size_t md_longopts_size = sizeof (md_longopts);
10638
10639 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
10640    NEW_VALUE.  Warn if another value was already specified.  Note:
10641    we have to defer parsing the -march and -mtune arguments in order
10642    to handle 'from-abi' correctly, since the ABI might be specified
10643    in a later argument.  */
10644
10645 static void
10646 mips_set_option_string (const char **string_ptr, const char *new_value)
10647 {
10648   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
10649     as_warn (_("A different %s was already specified, is now %s"),
10650              string_ptr == &mips_arch_string ? "-march" : "-mtune",
10651              new_value);
10652
10653   *string_ptr = new_value;
10654 }
10655
10656 int
10657 md_parse_option (int c, char *arg)
10658 {
10659   switch (c)
10660     {
10661     case OPTION_CONSTRUCT_FLOATS:
10662       mips_disable_float_construction = 0;
10663       break;
10664
10665     case OPTION_NO_CONSTRUCT_FLOATS:
10666       mips_disable_float_construction = 1;
10667       break;
10668
10669     case OPTION_TRAP:
10670       mips_trap = 1;
10671       break;
10672
10673     case OPTION_BREAK:
10674       mips_trap = 0;
10675       break;
10676
10677     case OPTION_EB:
10678       target_big_endian = 1;
10679       break;
10680
10681     case OPTION_EL:
10682       target_big_endian = 0;
10683       break;
10684
10685     case 'O':
10686       if (arg && arg[1] == '0')
10687         mips_optimize = 1;
10688       else
10689         mips_optimize = 2;
10690       break;
10691
10692     case 'g':
10693       if (arg == NULL)
10694         mips_debug = 2;
10695       else
10696         mips_debug = atoi (arg);
10697       /* When the MIPS assembler sees -g or -g2, it does not do
10698          optimizations which limit full symbolic debugging.  We take
10699          that to be equivalent to -O0.  */
10700       if (mips_debug == 2)
10701         mips_optimize = 1;
10702       break;
10703
10704     case OPTION_MIPS1:
10705       file_mips_isa = ISA_MIPS1;
10706       break;
10707
10708     case OPTION_MIPS2:
10709       file_mips_isa = ISA_MIPS2;
10710       break;
10711
10712     case OPTION_MIPS3:
10713       file_mips_isa = ISA_MIPS3;
10714       break;
10715
10716     case OPTION_MIPS4:
10717       file_mips_isa = ISA_MIPS4;
10718       break;
10719
10720     case OPTION_MIPS5:
10721       file_mips_isa = ISA_MIPS5;
10722       break;
10723
10724     case OPTION_MIPS32:
10725       file_mips_isa = ISA_MIPS32;
10726       break;
10727
10728     case OPTION_MIPS32R2:
10729       file_mips_isa = ISA_MIPS32R2;
10730       break;
10731
10732     case OPTION_MIPS64R2:
10733       file_mips_isa = ISA_MIPS64R2;
10734       break;
10735
10736     case OPTION_MIPS64:
10737       file_mips_isa = ISA_MIPS64;
10738       break;
10739
10740     case OPTION_MTUNE:
10741       mips_set_option_string (&mips_tune_string, arg);
10742       break;
10743
10744     case OPTION_MARCH:
10745       mips_set_option_string (&mips_arch_string, arg);
10746       break;
10747
10748     case OPTION_M4650:
10749       mips_set_option_string (&mips_arch_string, "4650");
10750       mips_set_option_string (&mips_tune_string, "4650");
10751       break;
10752
10753     case OPTION_NO_M4650:
10754       break;
10755
10756     case OPTION_M4010:
10757       mips_set_option_string (&mips_arch_string, "4010");
10758       mips_set_option_string (&mips_tune_string, "4010");
10759       break;
10760
10761     case OPTION_NO_M4010:
10762       break;
10763
10764     case OPTION_M4100:
10765       mips_set_option_string (&mips_arch_string, "4100");
10766       mips_set_option_string (&mips_tune_string, "4100");
10767       break;
10768
10769     case OPTION_NO_M4100:
10770       break;
10771
10772     case OPTION_M3900:
10773       mips_set_option_string (&mips_arch_string, "3900");
10774       mips_set_option_string (&mips_tune_string, "3900");
10775       break;
10776
10777     case OPTION_NO_M3900:
10778       break;
10779
10780     case OPTION_MDMX:
10781       mips_opts.ase_mdmx = 1;
10782       break;
10783
10784     case OPTION_NO_MDMX:
10785       mips_opts.ase_mdmx = 0;
10786       break;
10787
10788     case OPTION_DSP:
10789       mips_opts.ase_dsp = 1;
10790       break;
10791
10792     case OPTION_NO_DSP:
10793       mips_opts.ase_dsp = 0;
10794       break;
10795
10796     case OPTION_MT:
10797       mips_opts.ase_mt = 1;
10798       break;
10799
10800     case OPTION_NO_MT:
10801       mips_opts.ase_mt = 0;
10802       break;
10803
10804     case OPTION_MIPS16:
10805       mips_opts.mips16 = 1;
10806       mips_no_prev_insn ();
10807       break;
10808
10809     case OPTION_NO_MIPS16:
10810       mips_opts.mips16 = 0;
10811       mips_no_prev_insn ();
10812       break;
10813
10814     case OPTION_MIPS3D:
10815       mips_opts.ase_mips3d = 1;
10816       break;
10817
10818     case OPTION_NO_MIPS3D:
10819       mips_opts.ase_mips3d = 0;
10820       break;
10821
10822     case OPTION_FIX_VR4120:
10823       mips_fix_vr4120 = 1;
10824       break;
10825
10826     case OPTION_NO_FIX_VR4120:
10827       mips_fix_vr4120 = 0;
10828       break;
10829
10830     case OPTION_FIX_VR4130:
10831       mips_fix_vr4130 = 1;
10832       break;
10833
10834     case OPTION_NO_FIX_VR4130:
10835       mips_fix_vr4130 = 0;
10836       break;
10837
10838     case OPTION_RELAX_BRANCH:
10839       mips_relax_branch = 1;
10840       break;
10841
10842     case OPTION_NO_RELAX_BRANCH:
10843       mips_relax_branch = 0;
10844       break;
10845
10846     case OPTION_MSHARED:
10847       mips_in_shared = TRUE;
10848       break;
10849
10850     case OPTION_MNO_SHARED:
10851       mips_in_shared = FALSE;
10852       break;
10853
10854     case OPTION_MSYM32:
10855       mips_opts.sym32 = TRUE;
10856       break;
10857
10858     case OPTION_MNO_SYM32:
10859       mips_opts.sym32 = FALSE;
10860       break;
10861
10862 #ifdef OBJ_ELF
10863       /* When generating ELF code, we permit -KPIC and -call_shared to
10864          select SVR4_PIC, and -non_shared to select no PIC.  This is
10865          intended to be compatible with Irix 5.  */
10866     case OPTION_CALL_SHARED:
10867       if (OUTPUT_FLAVOR != bfd_target_elf_flavour)
10868         {
10869           as_bad (_("-call_shared is supported only for ELF format"));
10870           return 0;
10871         }
10872       mips_pic = SVR4_PIC;
10873       mips_abicalls = TRUE;
10874       if (g_switch_seen && g_switch_value != 0)
10875         {
10876           as_bad (_("-G may not be used with SVR4 PIC code"));
10877           return 0;
10878         }
10879       g_switch_value = 0;
10880       break;
10881
10882     case OPTION_NON_SHARED:
10883       if (OUTPUT_FLAVOR != bfd_target_elf_flavour)
10884         {
10885           as_bad (_("-non_shared is supported only for ELF format"));
10886           return 0;
10887         }
10888       mips_pic = NO_PIC;
10889       mips_abicalls = FALSE;
10890       break;
10891
10892       /* The -xgot option tells the assembler to use 32 bit offsets
10893          when accessing the got in SVR4_PIC mode.  It is for Irix
10894          compatibility.  */
10895     case OPTION_XGOT:
10896       mips_big_got = 1;
10897       break;
10898 #endif /* OBJ_ELF */
10899
10900     case 'G':
10901       g_switch_value = atoi (arg);
10902       g_switch_seen = 1;
10903       if (mips_pic == SVR4_PIC && g_switch_value != 0)
10904         {
10905           as_bad (_("-G may not be used with SVR4 PIC code"));
10906           return 0;
10907         }
10908       break;
10909
10910 #ifdef OBJ_ELF
10911       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
10912          and -mabi=64.  */
10913     case OPTION_32:
10914       if (OUTPUT_FLAVOR != bfd_target_elf_flavour)
10915         {
10916           as_bad (_("-32 is supported for ELF format only"));
10917           return 0;
10918         }
10919       mips_abi = O32_ABI;
10920       break;
10921
10922     case OPTION_N32:
10923       if (OUTPUT_FLAVOR != bfd_target_elf_flavour)
10924         {
10925           as_bad (_("-n32 is supported for ELF format only"));
10926           return 0;
10927         }
10928       mips_abi = N32_ABI;
10929       break;
10930
10931     case OPTION_64:
10932       if (OUTPUT_FLAVOR != bfd_target_elf_flavour)
10933         {
10934           as_bad (_("-64 is supported for ELF format only"));
10935           return 0;
10936         }
10937       mips_abi = N64_ABI;
10938       if (! support_64bit_objects())
10939         as_fatal (_("No compiled in support for 64 bit object file format"));
10940       break;
10941 #endif /* OBJ_ELF */
10942
10943     case OPTION_GP32:
10944       file_mips_gp32 = 1;
10945       break;
10946
10947     case OPTION_GP64:
10948       file_mips_gp32 = 0;
10949       break;
10950
10951     case OPTION_FP32:
10952       file_mips_fp32 = 1;
10953       break;
10954
10955     case OPTION_FP64:
10956       file_mips_fp32 = 0;
10957       break;
10958
10959 #ifdef OBJ_ELF
10960     case OPTION_MABI:
10961       if (OUTPUT_FLAVOR != bfd_target_elf_flavour)
10962         {
10963           as_bad (_("-mabi is supported for ELF format only"));
10964           return 0;
10965         }
10966       if (strcmp (arg, "32") == 0)
10967         mips_abi = O32_ABI;
10968       else if (strcmp (arg, "o64") == 0)
10969         mips_abi = O64_ABI;
10970       else if (strcmp (arg, "n32") == 0)
10971         mips_abi = N32_ABI;
10972       else if (strcmp (arg, "64") == 0)
10973         {
10974           mips_abi = N64_ABI;
10975           if (! support_64bit_objects())
10976             as_fatal (_("No compiled in support for 64 bit object file "
10977                         "format"));
10978         }
10979       else if (strcmp (arg, "eabi") == 0)
10980         mips_abi = EABI_ABI;
10981       else
10982         {
10983           as_fatal (_("invalid abi -mabi=%s"), arg);
10984           return 0;
10985         }
10986       break;
10987 #endif /* OBJ_ELF */
10988
10989     case OPTION_M7000_HILO_FIX:
10990       mips_7000_hilo_fix = TRUE;
10991       break;
10992
10993     case OPTION_MNO_7000_HILO_FIX:
10994       mips_7000_hilo_fix = FALSE;
10995       break;
10996
10997 #ifdef OBJ_ELF
10998     case OPTION_MDEBUG:
10999       mips_flag_mdebug = TRUE;
11000       break;
11001
11002     case OPTION_NO_MDEBUG:
11003       mips_flag_mdebug = FALSE;
11004       break;
11005
11006     case OPTION_PDR:
11007       mips_flag_pdr = TRUE;
11008       break;
11009
11010     case OPTION_NO_PDR:
11011       mips_flag_pdr = FALSE;
11012       break;
11013 #endif /* OBJ_ELF */
11014
11015     default:
11016       return 0;
11017     }
11018
11019   return 1;
11020 }
11021 \f
11022 /* Set up globals to generate code for the ISA or processor
11023    described by INFO.  */
11024
11025 static void
11026 mips_set_architecture (const struct mips_cpu_info *info)
11027 {
11028   if (info != 0)
11029     {
11030       file_mips_arch = info->cpu;
11031       mips_opts.arch = info->cpu;
11032       mips_opts.isa = info->isa;
11033     }
11034 }
11035
11036
11037 /* Likewise for tuning.  */
11038
11039 static void
11040 mips_set_tune (const struct mips_cpu_info *info)
11041 {
11042   if (info != 0)
11043     mips_tune = info->cpu;
11044 }
11045
11046
11047 void
11048 mips_after_parse_args (void)
11049 {
11050   const struct mips_cpu_info *arch_info = 0;
11051   const struct mips_cpu_info *tune_info = 0;
11052
11053   /* GP relative stuff not working for PE */
11054   if (strncmp (TARGET_OS, "pe", 2) == 0)
11055     {
11056       if (g_switch_seen && g_switch_value != 0)
11057         as_bad (_("-G not supported in this configuration."));
11058       g_switch_value = 0;
11059     }
11060
11061   if (mips_abi == NO_ABI)
11062     mips_abi = MIPS_DEFAULT_ABI;
11063
11064   /* The following code determines the architecture and register size.
11065      Similar code was added to GCC 3.3 (see override_options() in
11066      config/mips/mips.c).  The GAS and GCC code should be kept in sync
11067      as much as possible.  */
11068
11069   if (mips_arch_string != 0)
11070     arch_info = mips_parse_cpu ("-march", mips_arch_string);
11071
11072   if (file_mips_isa != ISA_UNKNOWN)
11073     {
11074       /* Handle -mipsN.  At this point, file_mips_isa contains the
11075          ISA level specified by -mipsN, while arch_info->isa contains
11076          the -march selection (if any).  */
11077       if (arch_info != 0)
11078         {
11079           /* -march takes precedence over -mipsN, since it is more descriptive.
11080              There's no harm in specifying both as long as the ISA levels
11081              are the same.  */
11082           if (file_mips_isa != arch_info->isa)
11083             as_bad (_("-%s conflicts with the other architecture options, which imply -%s"),
11084                     mips_cpu_info_from_isa (file_mips_isa)->name,
11085                     mips_cpu_info_from_isa (arch_info->isa)->name);
11086         }
11087       else
11088         arch_info = mips_cpu_info_from_isa (file_mips_isa);
11089     }
11090
11091   if (arch_info == 0)
11092     arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
11093
11094   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
11095     as_bad ("-march=%s is not compatible with the selected ABI",
11096             arch_info->name);
11097
11098   mips_set_architecture (arch_info);
11099
11100   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
11101   if (mips_tune_string != 0)
11102     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
11103
11104   if (tune_info == 0)
11105     mips_set_tune (arch_info);
11106   else
11107     mips_set_tune (tune_info);
11108
11109   if (file_mips_gp32 >= 0)
11110     {
11111       /* The user specified the size of the integer registers.  Make sure
11112          it agrees with the ABI and ISA.  */
11113       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
11114         as_bad (_("-mgp64 used with a 32-bit processor"));
11115       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
11116         as_bad (_("-mgp32 used with a 64-bit ABI"));
11117       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
11118         as_bad (_("-mgp64 used with a 32-bit ABI"));
11119     }
11120   else
11121     {
11122       /* Infer the integer register size from the ABI and processor.
11123          Restrict ourselves to 32-bit registers if that's all the
11124          processor has, or if the ABI cannot handle 64-bit registers.  */
11125       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
11126                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
11127     }
11128
11129   /* ??? GAS treats single-float processors as though they had 64-bit
11130      float registers (although it complains when double-precision
11131      instructions are used).  As things stand, saying they have 32-bit
11132      registers would lead to spurious "register must be even" messages.
11133      So here we assume float registers are always the same size as
11134      integer ones, unless the user says otherwise.  */
11135   if (file_mips_fp32 < 0)
11136     file_mips_fp32 = file_mips_gp32;
11137
11138   /* End of GCC-shared inference code.  */
11139
11140   /* This flag is set when we have a 64-bit capable CPU but use only
11141      32-bit wide registers.  Note that EABI does not use it.  */
11142   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
11143       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
11144           || mips_abi == O32_ABI))
11145     mips_32bitmode = 1;
11146
11147   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
11148     as_bad (_("trap exception not supported at ISA 1"));
11149
11150   /* If the selected architecture includes support for ASEs, enable
11151      generation of code for them.  */
11152   if (mips_opts.mips16 == -1)
11153     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
11154   if (mips_opts.ase_mips3d == -1)
11155     mips_opts.ase_mips3d = (CPU_HAS_MIPS3D (file_mips_arch)) ? 1 : 0;
11156   if (mips_opts.ase_mdmx == -1)
11157     mips_opts.ase_mdmx = (CPU_HAS_MDMX (file_mips_arch)) ? 1 : 0;
11158   if (mips_opts.ase_dsp == -1)
11159     mips_opts.ase_dsp = (CPU_HAS_DSP (file_mips_arch)) ? 1 : 0;
11160   if (mips_opts.ase_mt == -1)
11161     mips_opts.ase_mt = (CPU_HAS_MT (file_mips_arch)) ? 1 : 0;
11162
11163   file_mips_isa = mips_opts.isa;
11164   file_ase_mips16 = mips_opts.mips16;
11165   file_ase_mips3d = mips_opts.ase_mips3d;
11166   file_ase_mdmx = mips_opts.ase_mdmx;
11167   file_ase_dsp = mips_opts.ase_dsp;
11168   file_ase_mt = mips_opts.ase_mt;
11169   mips_opts.gp32 = file_mips_gp32;
11170   mips_opts.fp32 = file_mips_fp32;
11171
11172   if (mips_flag_mdebug < 0)
11173     {
11174 #ifdef OBJ_MAYBE_ECOFF
11175       if (OUTPUT_FLAVOR == bfd_target_ecoff_flavour)
11176         mips_flag_mdebug = 1;
11177       else
11178 #endif /* OBJ_MAYBE_ECOFF */
11179         mips_flag_mdebug = 0;
11180     }
11181 }
11182 \f
11183 void
11184 mips_init_after_args (void)
11185 {
11186   /* initialize opcodes */
11187   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
11188   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
11189 }
11190
11191 long
11192 md_pcrel_from (fixS *fixP)
11193 {
11194   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
11195   switch (fixP->fx_r_type)
11196     {
11197     case BFD_RELOC_16_PCREL_S2:
11198     case BFD_RELOC_MIPS_JMP:
11199       /* Return the address of the delay slot.  */
11200       return addr + 4;
11201     default:
11202       return addr;
11203     }
11204 }
11205
11206 /* This is called before the symbol table is processed.  In order to
11207    work with gcc when using mips-tfile, we must keep all local labels.
11208    However, in other cases, we want to discard them.  If we were
11209    called with -g, but we didn't see any debugging information, it may
11210    mean that gcc is smuggling debugging information through to
11211    mips-tfile, in which case we must generate all local labels.  */
11212
11213 void
11214 mips_frob_file_before_adjust (void)
11215 {
11216 #ifndef NO_ECOFF_DEBUGGING
11217   if (ECOFF_DEBUGGING
11218       && mips_debug != 0
11219       && ! ecoff_debugging_seen)
11220     flag_keep_locals = 1;
11221 #endif
11222 }
11223
11224 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
11225    the corresponding LO16 reloc.  This is called before md_apply_fix and
11226    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
11227    relocation operators.
11228
11229    For our purposes, a %lo() expression matches a %got() or %hi()
11230    expression if:
11231
11232       (a) it refers to the same symbol; and
11233       (b) the offset applied in the %lo() expression is no lower than
11234           the offset applied in the %got() or %hi().
11235
11236    (b) allows us to cope with code like:
11237
11238         lui     $4,%hi(foo)
11239         lh      $4,%lo(foo+2)($4)
11240
11241    ...which is legal on RELA targets, and has a well-defined behaviour
11242    if the user knows that adding 2 to "foo" will not induce a carry to
11243    the high 16 bits.
11244
11245    When several %lo()s match a particular %got() or %hi(), we use the
11246    following rules to distinguish them:
11247
11248      (1) %lo()s with smaller offsets are a better match than %lo()s with
11249          higher offsets.
11250
11251      (2) %lo()s with no matching %got() or %hi() are better than those
11252          that already have a matching %got() or %hi().
11253
11254      (3) later %lo()s are better than earlier %lo()s.
11255
11256    These rules are applied in order.
11257
11258    (1) means, among other things, that %lo()s with identical offsets are
11259    chosen if they exist.
11260
11261    (2) means that we won't associate several high-part relocations with
11262    the same low-part relocation unless there's no alternative.  Having
11263    several high parts for the same low part is a GNU extension; this rule
11264    allows careful users to avoid it.
11265
11266    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
11267    with the last high-part relocation being at the front of the list.
11268    It therefore makes sense to choose the last matching low-part
11269    relocation, all other things being equal.  It's also easier
11270    to code that way.  */
11271
11272 void
11273 mips_frob_file (void)
11274 {
11275   struct mips_hi_fixup *l;
11276
11277   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
11278     {
11279       segment_info_type *seginfo;
11280       bfd_boolean matched_lo_p;
11281       fixS **hi_pos, **lo_pos, **pos;
11282
11283       assert (reloc_needs_lo_p (l->fixp->fx_r_type));
11284
11285       /* If a GOT16 relocation turns out to be against a global symbol,
11286          there isn't supposed to be a matching LO.  */
11287       if (l->fixp->fx_r_type == BFD_RELOC_MIPS_GOT16
11288           && !pic_need_relax (l->fixp->fx_addsy, l->seg))
11289         continue;
11290
11291       /* Check quickly whether the next fixup happens to be a matching %lo.  */
11292       if (fixup_has_matching_lo_p (l->fixp))
11293         continue;
11294
11295       seginfo = seg_info (l->seg);
11296
11297       /* Set HI_POS to the position of this relocation in the chain.
11298          Set LO_POS to the position of the chosen low-part relocation.
11299          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
11300          relocation that matches an immediately-preceding high-part
11301          relocation.  */
11302       hi_pos = NULL;
11303       lo_pos = NULL;
11304       matched_lo_p = FALSE;
11305       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
11306         {
11307           if (*pos == l->fixp)
11308             hi_pos = pos;
11309
11310           if (((*pos)->fx_r_type == BFD_RELOC_LO16
11311                || (*pos)->fx_r_type == BFD_RELOC_MIPS16_LO16)
11312               && (*pos)->fx_addsy == l->fixp->fx_addsy
11313               && (*pos)->fx_offset >= l->fixp->fx_offset
11314               && (lo_pos == NULL
11315                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
11316                   || (!matched_lo_p
11317                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
11318             lo_pos = pos;
11319
11320           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
11321                           && fixup_has_matching_lo_p (*pos));
11322         }
11323
11324       /* If we found a match, remove the high-part relocation from its
11325          current position and insert it before the low-part relocation.
11326          Make the offsets match so that fixup_has_matching_lo_p()
11327          will return true.
11328
11329          We don't warn about unmatched high-part relocations since some
11330          versions of gcc have been known to emit dead "lui ...%hi(...)"
11331          instructions.  */
11332       if (lo_pos != NULL)
11333         {
11334           l->fixp->fx_offset = (*lo_pos)->fx_offset;
11335           if (l->fixp->fx_next != *lo_pos)
11336             {
11337               *hi_pos = l->fixp->fx_next;
11338               l->fixp->fx_next = *lo_pos;
11339               *lo_pos = l->fixp;
11340             }
11341         }
11342     }
11343 }
11344
11345 /* We may have combined relocations without symbols in the N32/N64 ABI.
11346    We have to prevent gas from dropping them.  */
11347
11348 int
11349 mips_force_relocation (fixS *fixp)
11350 {
11351   if (generic_force_reloc (fixp))
11352     return 1;
11353
11354   if (HAVE_NEWABI
11355       && S_GET_SEGMENT (fixp->fx_addsy) == bfd_abs_section_ptr
11356       && (fixp->fx_r_type == BFD_RELOC_MIPS_SUB
11357           || fixp->fx_r_type == BFD_RELOC_HI16_S
11358           || fixp->fx_r_type == BFD_RELOC_LO16))
11359     return 1;
11360
11361   return 0;
11362 }
11363
11364 /* This hook is called before a fix is simplified.  We don't really
11365    decide whether to skip a fix here.  Rather, we turn global symbols
11366    used as branch targets into local symbols, such that they undergo
11367    simplification.  We can only do this if the symbol is defined and
11368    it is in the same section as the branch.  If this doesn't hold, we
11369    emit a better error message than just saying the relocation is not
11370    valid for the selected object format.
11371
11372    FIXP is the fix-up we're going to try to simplify, SEG is the
11373    segment in which the fix up occurs.  The return value should be
11374    non-zero to indicate the fix-up is valid for further
11375    simplifications.  */
11376
11377 int
11378 mips_validate_fix (struct fix *fixP, asection *seg)
11379 {
11380   /* There's a lot of discussion on whether it should be possible to
11381      use R_MIPS_PC16 to represent branch relocations.  The outcome
11382      seems to be that it can, but gas/bfd are very broken in creating
11383      RELA relocations for this, so for now we only accept branches to
11384      symbols in the same section.  Anything else is of dubious value,
11385      since there's no guarantee that at link time the symbol would be
11386      in range.  Even for branches to local symbols this is arguably
11387      wrong, since it we assume the symbol is not going to be
11388      overridden, which should be possible per ELF library semantics,
11389      but then, there isn't a dynamic relocation that could be used to
11390      this effect, and the target would likely be out of range as well.
11391
11392      Unfortunately, it seems that there is too much code out there
11393      that relies on branches to symbols that are global to be resolved
11394      as if they were local, like the IRIX tools do, so we do it as
11395      well, but with a warning so that people are reminded to fix their
11396      code.  If we ever get back to using R_MIPS_PC16 for branch
11397      targets, this entire block should go away (and probably the
11398      whole function).  */
11399
11400   if (fixP->fx_r_type == BFD_RELOC_16_PCREL_S2
11401       && ((OUTPUT_FLAVOR == bfd_target_ecoff_flavour
11402            || OUTPUT_FLAVOR == bfd_target_elf_flavour)
11403           || bfd_reloc_type_lookup (stdoutput, BFD_RELOC_16_PCREL_S2) == NULL)
11404       && fixP->fx_addsy)
11405     {
11406       if (! S_IS_DEFINED (fixP->fx_addsy))
11407         {
11408           as_bad_where (fixP->fx_file, fixP->fx_line,
11409                         _("Cannot branch to undefined symbol."));
11410           /* Avoid any further errors about this fixup.  */
11411           fixP->fx_done = 1;
11412         }
11413       else if (S_GET_SEGMENT (fixP->fx_addsy) != seg)
11414         {
11415           as_bad_where (fixP->fx_file, fixP->fx_line,
11416                         _("Cannot branch to symbol in another section."));
11417           fixP->fx_done = 1;
11418         }
11419       else if (S_IS_EXTERNAL (fixP->fx_addsy))
11420         {
11421           symbolS *sym = fixP->fx_addsy;
11422
11423           if (mips_pic == SVR4_PIC)
11424             as_warn_where (fixP->fx_file, fixP->fx_line,
11425                            _("Pretending global symbol used as branch target is local."));
11426
11427           fixP->fx_addsy = symbol_create (S_GET_NAME (sym),
11428                                           S_GET_SEGMENT (sym),
11429                                           S_GET_VALUE (sym),
11430                                           symbol_get_frag (sym));
11431           copy_symbol_attributes (fixP->fx_addsy, sym);
11432           S_CLEAR_EXTERNAL (fixP->fx_addsy);
11433           assert (symbol_resolved_p (sym));
11434           symbol_mark_resolved (fixP->fx_addsy);
11435         }
11436     }
11437
11438   return 1;
11439 }
11440
11441 /* Apply a fixup to the object file.  */
11442
11443 void
11444 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
11445 {
11446   bfd_byte *buf;
11447   long insn;
11448   reloc_howto_type *howto;
11449
11450   /* We ignore generic BFD relocations we don't know about.  */
11451   howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
11452   if (! howto)
11453     return;
11454
11455   assert (fixP->fx_size == 4
11456           || fixP->fx_r_type == BFD_RELOC_16
11457           || fixP->fx_r_type == BFD_RELOC_64
11458           || fixP->fx_r_type == BFD_RELOC_CTOR
11459           || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
11460           || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
11461           || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY);
11462
11463   buf = (bfd_byte *) (fixP->fx_frag->fr_literal + fixP->fx_where);
11464
11465   assert (! fixP->fx_pcrel);
11466
11467   /* Don't treat parts of a composite relocation as done.  There are two
11468      reasons for this:
11469
11470      (1) The second and third parts will be against 0 (RSS_UNDEF) but
11471          should nevertheless be emitted if the first part is.
11472
11473      (2) In normal usage, composite relocations are never assembly-time
11474          constants.  The easiest way of dealing with the pathological
11475          exceptions is to generate a relocation against STN_UNDEF and
11476          leave everything up to the linker.  */
11477   if (fixP->fx_addsy == NULL && fixP->fx_tcbit == 0)
11478     fixP->fx_done = 1;
11479
11480   switch (fixP->fx_r_type)
11481     {
11482     case BFD_RELOC_MIPS_TLS_GD:
11483     case BFD_RELOC_MIPS_TLS_LDM:
11484     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
11485     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
11486     case BFD_RELOC_MIPS_TLS_GOTTPREL:
11487     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
11488     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
11489       S_SET_THREAD_LOCAL (fixP->fx_addsy);
11490       /* fall through */
11491
11492     case BFD_RELOC_MIPS_JMP:
11493     case BFD_RELOC_MIPS_SHIFT5:
11494     case BFD_RELOC_MIPS_SHIFT6:
11495     case BFD_RELOC_MIPS_GOT_DISP:
11496     case BFD_RELOC_MIPS_GOT_PAGE:
11497     case BFD_RELOC_MIPS_GOT_OFST:
11498     case BFD_RELOC_MIPS_SUB:
11499     case BFD_RELOC_MIPS_INSERT_A:
11500     case BFD_RELOC_MIPS_INSERT_B:
11501     case BFD_RELOC_MIPS_DELETE:
11502     case BFD_RELOC_MIPS_HIGHEST:
11503     case BFD_RELOC_MIPS_HIGHER:
11504     case BFD_RELOC_MIPS_SCN_DISP:
11505     case BFD_RELOC_MIPS_REL16:
11506     case BFD_RELOC_MIPS_RELGOT:
11507     case BFD_RELOC_MIPS_JALR:
11508     case BFD_RELOC_HI16:
11509     case BFD_RELOC_HI16_S:
11510     case BFD_RELOC_GPREL16:
11511     case BFD_RELOC_MIPS_LITERAL:
11512     case BFD_RELOC_MIPS_CALL16:
11513     case BFD_RELOC_MIPS_GOT16:
11514     case BFD_RELOC_GPREL32:
11515     case BFD_RELOC_MIPS_GOT_HI16:
11516     case BFD_RELOC_MIPS_GOT_LO16:
11517     case BFD_RELOC_MIPS_CALL_HI16:
11518     case BFD_RELOC_MIPS_CALL_LO16:
11519     case BFD_RELOC_MIPS16_GPREL:
11520     case BFD_RELOC_MIPS16_HI16:
11521     case BFD_RELOC_MIPS16_HI16_S:
11522       assert (! fixP->fx_pcrel);
11523       /* Nothing needed to do. The value comes from the reloc entry */
11524       break;
11525
11526     case BFD_RELOC_MIPS16_JMP:
11527       /* We currently always generate a reloc against a symbol, which
11528          means that we don't want an addend even if the symbol is
11529          defined.  */
11530       *valP = 0;
11531       break;
11532
11533     case BFD_RELOC_64:
11534       /* This is handled like BFD_RELOC_32, but we output a sign
11535          extended value if we are only 32 bits.  */
11536       if (fixP->fx_done)
11537         {
11538           if (8 <= sizeof (valueT))
11539             md_number_to_chars ((char *) buf, *valP, 8);
11540           else
11541             {
11542               valueT hiv;
11543
11544               if ((*valP & 0x80000000) != 0)
11545                 hiv = 0xffffffff;
11546               else
11547                 hiv = 0;
11548               md_number_to_chars ((char *)(buf + (target_big_endian ? 4 : 0)),
11549                                   *valP, 4);
11550               md_number_to_chars ((char *)(buf + (target_big_endian ? 0 : 4)),
11551                                   hiv, 4);
11552             }
11553         }
11554       break;
11555
11556     case BFD_RELOC_RVA:
11557     case BFD_RELOC_32:
11558       /* If we are deleting this reloc entry, we must fill in the
11559          value now.  This can happen if we have a .word which is not
11560          resolved when it appears but is later defined.   */
11561       if (fixP->fx_done)
11562         md_number_to_chars ((char *) buf, *valP, 4);
11563       break;
11564
11565     case BFD_RELOC_16:
11566       /* If we are deleting this reloc entry, we must fill in the
11567          value now.  */
11568       if (fixP->fx_done)
11569         md_number_to_chars ((char *) buf, *valP, 2);
11570       break;
11571
11572     case BFD_RELOC_LO16:
11573     case BFD_RELOC_MIPS16_LO16:
11574       /* FIXME: Now that embedded-PIC is gone, some of this code/comment
11575          may be safe to remove, but if so it's not obvious.  */
11576       /* When handling an embedded PIC switch statement, we can wind
11577          up deleting a LO16 reloc.  See the 'o' case in mips_ip.  */
11578       if (fixP->fx_done)
11579         {
11580           if (*valP + 0x8000 > 0xffff)
11581             as_bad_where (fixP->fx_file, fixP->fx_line,
11582                           _("relocation overflow"));
11583           if (target_big_endian)
11584             buf += 2;
11585           md_number_to_chars ((char *) buf, *valP, 2);
11586         }
11587       break;
11588
11589     case BFD_RELOC_16_PCREL_S2:
11590       if ((*valP & 0x3) != 0)
11591         as_bad_where (fixP->fx_file, fixP->fx_line,
11592                       _("Branch to odd address (%lx)"), (long) *valP);
11593
11594       /*
11595        * We need to save the bits in the instruction since fixup_segment()
11596        * might be deleting the relocation entry (i.e., a branch within
11597        * the current segment).
11598        */
11599       if (! fixP->fx_done)
11600         break;
11601
11602       /* update old instruction data */
11603       if (target_big_endian)
11604         insn = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
11605       else
11606         insn = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf[0];
11607
11608       if (*valP + 0x20000 <= 0x3ffff)
11609         {
11610           insn |= (*valP >> 2) & 0xffff;
11611           md_number_to_chars ((char *) buf, insn, 4);
11612         }
11613       else if (mips_pic == NO_PIC
11614                && fixP->fx_done
11615                && fixP->fx_frag->fr_address >= text_section->vma
11616                && (fixP->fx_frag->fr_address
11617                    < text_section->vma + bfd_get_section_size (text_section))
11618                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
11619                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
11620                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
11621         {
11622           /* The branch offset is too large.  If this is an
11623              unconditional branch, and we are not generating PIC code,
11624              we can convert it to an absolute jump instruction.  */
11625           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
11626             insn = 0x0c000000;  /* jal */
11627           else
11628             insn = 0x08000000;  /* j */
11629           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
11630           fixP->fx_done = 0;
11631           fixP->fx_addsy = section_symbol (text_section);
11632           *valP += md_pcrel_from (fixP);
11633           md_number_to_chars ((char *) buf, insn, 4);
11634         }
11635       else
11636         {
11637           /* If we got here, we have branch-relaxation disabled,
11638              and there's nothing we can do to fix this instruction
11639              without turning it into a longer sequence.  */
11640           as_bad_where (fixP->fx_file, fixP->fx_line,
11641                         _("Branch out of range"));
11642         }
11643       break;
11644
11645     case BFD_RELOC_VTABLE_INHERIT:
11646       fixP->fx_done = 0;
11647       if (fixP->fx_addsy
11648           && !S_IS_DEFINED (fixP->fx_addsy)
11649           && !S_IS_WEAK (fixP->fx_addsy))
11650         S_SET_WEAK (fixP->fx_addsy);
11651       break;
11652
11653     case BFD_RELOC_VTABLE_ENTRY:
11654       fixP->fx_done = 0;
11655       break;
11656
11657     default:
11658       internalError ();
11659     }
11660
11661   /* Remember value for tc_gen_reloc.  */
11662   fixP->fx_addnumber = *valP;
11663 }
11664
11665 static symbolS *
11666 get_symbol (void)
11667 {
11668   int c;
11669   char *name;
11670   symbolS *p;
11671
11672   name = input_line_pointer;
11673   c = get_symbol_end ();
11674   p = (symbolS *) symbol_find_or_make (name);
11675   *input_line_pointer = c;
11676   return p;
11677 }
11678
11679 /* Align the current frag to a given power of two.  The MIPS assembler
11680    also automatically adjusts any preceding label.  */
11681
11682 static void
11683 mips_align (int to, int fill, symbolS *label)
11684 {
11685   mips_emit_delays ();
11686   frag_align (to, fill, 0);
11687   record_alignment (now_seg, to);
11688   if (label != NULL)
11689     {
11690       assert (S_GET_SEGMENT (label) == now_seg);
11691       symbol_set_frag (label, frag_now);
11692       S_SET_VALUE (label, (valueT) frag_now_fix ());
11693     }
11694 }
11695
11696 /* Align to a given power of two.  .align 0 turns off the automatic
11697    alignment used by the data creating pseudo-ops.  */
11698
11699 static void
11700 s_align (int x ATTRIBUTE_UNUSED)
11701 {
11702   register int temp;
11703   register long temp_fill;
11704   long max_alignment = 15;
11705
11706   /*
11707
11708     o  Note that the assembler pulls down any immediately preceding label
11709        to the aligned address.
11710     o  It's not documented but auto alignment is reinstated by
11711        a .align pseudo instruction.
11712     o  Note also that after auto alignment is turned off the mips assembler
11713        issues an error on attempt to assemble an improperly aligned data item.
11714        We don't.
11715
11716     */
11717
11718   temp = get_absolute_expression ();
11719   if (temp > max_alignment)
11720     as_bad (_("Alignment too large: %d. assumed."), temp = max_alignment);
11721   else if (temp < 0)
11722     {
11723       as_warn (_("Alignment negative: 0 assumed."));
11724       temp = 0;
11725     }
11726   if (*input_line_pointer == ',')
11727     {
11728       ++input_line_pointer;
11729       temp_fill = get_absolute_expression ();
11730     }
11731   else
11732     temp_fill = 0;
11733   if (temp)
11734     {
11735       auto_align = 1;
11736       mips_align (temp, (int) temp_fill,
11737                   insn_labels != NULL ? insn_labels->label : NULL);
11738     }
11739   else
11740     {
11741       auto_align = 0;
11742     }
11743
11744   demand_empty_rest_of_line ();
11745 }
11746
11747 static void
11748 s_change_sec (int sec)
11749 {
11750   segT seg;
11751
11752 #ifdef OBJ_ELF
11753   /* The ELF backend needs to know that we are changing sections, so
11754      that .previous works correctly.  We could do something like check
11755      for an obj_section_change_hook macro, but that might be confusing
11756      as it would not be appropriate to use it in the section changing
11757      functions in read.c, since obj-elf.c intercepts those.  FIXME:
11758      This should be cleaner, somehow.  */
11759   obj_elf_section_change_hook ();
11760 #endif
11761
11762   mips_emit_delays ();
11763   switch (sec)
11764     {
11765     case 't':
11766       s_text (0);
11767       break;
11768     case 'd':
11769       s_data (0);
11770       break;
11771     case 'b':
11772       subseg_set (bss_section, (subsegT) get_absolute_expression ());
11773       demand_empty_rest_of_line ();
11774       break;
11775
11776     case 'r':
11777       seg = subseg_new (RDATA_SECTION_NAME,
11778                         (subsegT) get_absolute_expression ());
11779       if (OUTPUT_FLAVOR == bfd_target_elf_flavour)
11780         {
11781           bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
11782                                                   | SEC_READONLY | SEC_RELOC
11783                                                   | SEC_DATA));
11784           if (strcmp (TARGET_OS, "elf") != 0)
11785             record_alignment (seg, 4);
11786         }
11787       demand_empty_rest_of_line ();
11788       break;
11789
11790     case 's':
11791       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
11792       if (OUTPUT_FLAVOR == bfd_target_elf_flavour)
11793         {
11794           bfd_set_section_flags (stdoutput, seg,
11795                                  SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
11796           if (strcmp (TARGET_OS, "elf") != 0)
11797             record_alignment (seg, 4);
11798         }
11799       demand_empty_rest_of_line ();
11800       break;
11801     }
11802
11803   auto_align = 1;
11804 }
11805
11806 void
11807 s_change_section (int ignore ATTRIBUTE_UNUSED)
11808 {
11809 #ifdef OBJ_ELF
11810   char *section_name;
11811   char c;
11812   char next_c = 0;
11813   int section_type;
11814   int section_flag;
11815   int section_entry_size;
11816   int section_alignment;
11817
11818   if (OUTPUT_FLAVOR != bfd_target_elf_flavour)
11819     return;
11820
11821   section_name = input_line_pointer;
11822   c = get_symbol_end ();
11823   if (c)
11824     next_c = *(input_line_pointer + 1);
11825
11826   /* Do we have .section Name<,"flags">?  */
11827   if (c != ',' || (c == ',' && next_c == '"'))
11828     {
11829       /* just after name is now '\0'.  */
11830       *input_line_pointer = c;
11831       input_line_pointer = section_name;
11832       obj_elf_section (ignore);
11833       return;
11834     }
11835   input_line_pointer++;
11836
11837   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
11838   if (c == ',')
11839     section_type = get_absolute_expression ();
11840   else
11841     section_type = 0;
11842   if (*input_line_pointer++ == ',')
11843     section_flag = get_absolute_expression ();
11844   else
11845     section_flag = 0;
11846   if (*input_line_pointer++ == ',')
11847     section_entry_size = get_absolute_expression ();
11848   else
11849     section_entry_size = 0;
11850   if (*input_line_pointer++ == ',')
11851     section_alignment = get_absolute_expression ();
11852   else
11853     section_alignment = 0;
11854
11855   section_name = xstrdup (section_name);
11856
11857   /* When using the generic form of .section (as implemented by obj-elf.c),
11858      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
11859      traditionally had to fall back on the more common @progbits instead.
11860
11861      There's nothing really harmful in this, since bfd will correct
11862      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
11863      means that, for backwards compatibiltiy, the special_section entries
11864      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
11865
11866      Even so, we shouldn't force users of the MIPS .section syntax to
11867      incorrectly label the sections as SHT_PROGBITS.  The best compromise
11868      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
11869      generic type-checking code.  */
11870   if (section_type == SHT_MIPS_DWARF)
11871     section_type = SHT_PROGBITS;
11872
11873   obj_elf_change_section (section_name, section_type, section_flag,
11874                           section_entry_size, 0, 0, 0);
11875
11876   if (now_seg->name != section_name)
11877     free (section_name);
11878 #endif /* OBJ_ELF */
11879 }
11880
11881 void
11882 mips_enable_auto_align (void)
11883 {
11884   auto_align = 1;
11885 }
11886
11887 static void
11888 s_cons (int log_size)
11889 {
11890   symbolS *label;
11891
11892   label = insn_labels != NULL ? insn_labels->label : NULL;
11893   mips_emit_delays ();
11894   if (log_size > 0 && auto_align)
11895     mips_align (log_size, 0, label);
11896   mips_clear_insn_labels ();
11897   cons (1 << log_size);
11898 }
11899
11900 static void
11901 s_float_cons (int type)
11902 {
11903   symbolS *label;
11904
11905   label = insn_labels != NULL ? insn_labels->label : NULL;
11906
11907   mips_emit_delays ();
11908
11909   if (auto_align)
11910     {
11911       if (type == 'd')
11912         mips_align (3, 0, label);
11913       else
11914         mips_align (2, 0, label);
11915     }
11916
11917   mips_clear_insn_labels ();
11918
11919   float_cons (type);
11920 }
11921
11922 /* Handle .globl.  We need to override it because on Irix 5 you are
11923    permitted to say
11924        .globl foo .text
11925    where foo is an undefined symbol, to mean that foo should be
11926    considered to be the address of a function.  */
11927
11928 static void
11929 s_mips_globl (int x ATTRIBUTE_UNUSED)
11930 {
11931   char *name;
11932   int c;
11933   symbolS *symbolP;
11934   flagword flag;
11935
11936   do
11937     {
11938       name = input_line_pointer;
11939       c = get_symbol_end ();
11940       symbolP = symbol_find_or_make (name);
11941       S_SET_EXTERNAL (symbolP);
11942
11943       *input_line_pointer = c;
11944       SKIP_WHITESPACE ();
11945
11946       /* On Irix 5, every global symbol that is not explicitly labelled as
11947          being a function is apparently labelled as being an object.  */
11948       flag = BSF_OBJECT;
11949
11950       if (!is_end_of_line[(unsigned char) *input_line_pointer]
11951           && (*input_line_pointer != ','))
11952         {
11953           char *secname;
11954           asection *sec;
11955
11956           secname = input_line_pointer;
11957           c = get_symbol_end ();
11958           sec = bfd_get_section_by_name (stdoutput, secname);
11959           if (sec == NULL)
11960             as_bad (_("%s: no such section"), secname);
11961           *input_line_pointer = c;
11962
11963           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
11964             flag = BSF_FUNCTION;
11965         }
11966
11967       symbol_get_bfdsym (symbolP)->flags |= flag;
11968
11969       c = *input_line_pointer;
11970       if (c == ',')
11971         {
11972           input_line_pointer++;
11973           SKIP_WHITESPACE ();
11974           if (is_end_of_line[(unsigned char) *input_line_pointer])
11975             c = '\n';
11976         }
11977     }
11978   while (c == ',');
11979
11980   demand_empty_rest_of_line ();
11981 }
11982
11983 static void
11984 s_option (int x ATTRIBUTE_UNUSED)
11985 {
11986   char *opt;
11987   char c;
11988
11989   opt = input_line_pointer;
11990   c = get_symbol_end ();
11991
11992   if (*opt == 'O')
11993     {
11994       /* FIXME: What does this mean?  */
11995     }
11996   else if (strncmp (opt, "pic", 3) == 0)
11997     {
11998       int i;
11999
12000       i = atoi (opt + 3);
12001       if (i == 0)
12002         mips_pic = NO_PIC;
12003       else if (i == 2)
12004         {
12005         mips_pic = SVR4_PIC;
12006           mips_abicalls = TRUE;
12007         }
12008       else
12009         as_bad (_(".option pic%d not supported"), i);
12010
12011       if (mips_pic == SVR4_PIC)
12012         {
12013           if (g_switch_seen && g_switch_value != 0)
12014             as_warn (_("-G may not be used with SVR4 PIC code"));
12015           g_switch_value = 0;
12016           bfd_set_gp_size (stdoutput, 0);
12017         }
12018     }
12019   else
12020     as_warn (_("Unrecognized option \"%s\""), opt);
12021
12022   *input_line_pointer = c;
12023   demand_empty_rest_of_line ();
12024 }
12025
12026 /* This structure is used to hold a stack of .set values.  */
12027
12028 struct mips_option_stack
12029 {
12030   struct mips_option_stack *next;
12031   struct mips_set_options options;
12032 };
12033
12034 static struct mips_option_stack *mips_opts_stack;
12035
12036 /* Handle the .set pseudo-op.  */
12037
12038 static void
12039 s_mipsset (int x ATTRIBUTE_UNUSED)
12040 {
12041   char *name = input_line_pointer, ch;
12042
12043   while (!is_end_of_line[(unsigned char) *input_line_pointer])
12044     ++input_line_pointer;
12045   ch = *input_line_pointer;
12046   *input_line_pointer = '\0';
12047
12048   if (strcmp (name, "reorder") == 0)
12049     {
12050       if (mips_opts.noreorder)
12051         end_noreorder ();
12052     }
12053   else if (strcmp (name, "noreorder") == 0)
12054     {
12055       if (!mips_opts.noreorder)
12056         start_noreorder ();
12057     }
12058   else if (strcmp (name, "at") == 0)
12059     {
12060       mips_opts.noat = 0;
12061     }
12062   else if (strcmp (name, "noat") == 0)
12063     {
12064       mips_opts.noat = 1;
12065     }
12066   else if (strcmp (name, "macro") == 0)
12067     {
12068       mips_opts.warn_about_macros = 0;
12069     }
12070   else if (strcmp (name, "nomacro") == 0)
12071     {
12072       if (mips_opts.noreorder == 0)
12073         as_bad (_("`noreorder' must be set before `nomacro'"));
12074       mips_opts.warn_about_macros = 1;
12075     }
12076   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
12077     {
12078       mips_opts.nomove = 0;
12079     }
12080   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
12081     {
12082       mips_opts.nomove = 1;
12083     }
12084   else if (strcmp (name, "bopt") == 0)
12085     {
12086       mips_opts.nobopt = 0;
12087     }
12088   else if (strcmp (name, "nobopt") == 0)
12089     {
12090       mips_opts.nobopt = 1;
12091     }
12092   else if (strcmp (name, "mips16") == 0
12093            || strcmp (name, "MIPS-16") == 0)
12094     mips_opts.mips16 = 1;
12095   else if (strcmp (name, "nomips16") == 0
12096            || strcmp (name, "noMIPS-16") == 0)
12097     mips_opts.mips16 = 0;
12098   else if (strcmp (name, "mips3d") == 0)
12099     mips_opts.ase_mips3d = 1;
12100   else if (strcmp (name, "nomips3d") == 0)
12101     mips_opts.ase_mips3d = 0;
12102   else if (strcmp (name, "mdmx") == 0)
12103     mips_opts.ase_mdmx = 1;
12104   else if (strcmp (name, "nomdmx") == 0)
12105     mips_opts.ase_mdmx = 0;
12106   else if (strcmp (name, "dsp") == 0)
12107     mips_opts.ase_dsp = 1;
12108   else if (strcmp (name, "nodsp") == 0)
12109     mips_opts.ase_dsp = 0;
12110   else if (strcmp (name, "mt") == 0)
12111     mips_opts.ase_mt = 1;
12112   else if (strcmp (name, "nomt") == 0)
12113     mips_opts.ase_mt = 0;
12114   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
12115     {
12116       int reset = 0;
12117
12118       /* Permit the user to change the ISA and architecture on the fly.
12119          Needless to say, misuse can cause serious problems.  */
12120       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
12121         {
12122           reset = 1;
12123           mips_opts.isa = file_mips_isa;
12124           mips_opts.arch = file_mips_arch;
12125         }
12126       else if (strncmp (name, "arch=", 5) == 0)
12127         {
12128           const struct mips_cpu_info *p;
12129
12130           p = mips_parse_cpu("internal use", name + 5);
12131           if (!p)
12132             as_bad (_("unknown architecture %s"), name + 5);
12133           else
12134             {
12135               mips_opts.arch = p->cpu;
12136               mips_opts.isa = p->isa;
12137             }
12138         }
12139       else if (strncmp (name, "mips", 4) == 0)
12140         {
12141           const struct mips_cpu_info *p;
12142
12143           p = mips_parse_cpu("internal use", name);
12144           if (!p)
12145             as_bad (_("unknown ISA level %s"), name + 4);
12146           else
12147             {
12148               mips_opts.arch = p->cpu;
12149               mips_opts.isa = p->isa;
12150             }
12151         }
12152       else
12153         as_bad (_("unknown ISA or architecture %s"), name);
12154
12155       switch (mips_opts.isa)
12156         {
12157         case  0:
12158           break;
12159         case ISA_MIPS1:
12160         case ISA_MIPS2:
12161         case ISA_MIPS32:
12162         case ISA_MIPS32R2:
12163           mips_opts.gp32 = 1;
12164           mips_opts.fp32 = 1;
12165           break;
12166         case ISA_MIPS3:
12167         case ISA_MIPS4:
12168         case ISA_MIPS5:
12169         case ISA_MIPS64:
12170         case ISA_MIPS64R2:
12171           mips_opts.gp32 = 0;
12172           mips_opts.fp32 = 0;
12173           break;
12174         default:
12175           as_bad (_("unknown ISA level %s"), name + 4);
12176           break;
12177         }
12178       if (reset)
12179         {
12180           mips_opts.gp32 = file_mips_gp32;
12181           mips_opts.fp32 = file_mips_fp32;
12182         }
12183     }
12184   else if (strcmp (name, "autoextend") == 0)
12185     mips_opts.noautoextend = 0;
12186   else if (strcmp (name, "noautoextend") == 0)
12187     mips_opts.noautoextend = 1;
12188   else if (strcmp (name, "push") == 0)
12189     {
12190       struct mips_option_stack *s;
12191
12192       s = (struct mips_option_stack *) xmalloc (sizeof *s);
12193       s->next = mips_opts_stack;
12194       s->options = mips_opts;
12195       mips_opts_stack = s;
12196     }
12197   else if (strcmp (name, "pop") == 0)
12198     {
12199       struct mips_option_stack *s;
12200
12201       s = mips_opts_stack;
12202       if (s == NULL)
12203         as_bad (_(".set pop with no .set push"));
12204       else
12205         {
12206           /* If we're changing the reorder mode we need to handle
12207              delay slots correctly.  */
12208           if (s->options.noreorder && ! mips_opts.noreorder)
12209             start_noreorder ();
12210           else if (! s->options.noreorder && mips_opts.noreorder)
12211             end_noreorder ();
12212
12213           mips_opts = s->options;
12214           mips_opts_stack = s->next;
12215           free (s);
12216         }
12217     }
12218   else if (strcmp (name, "sym32") == 0)
12219     mips_opts.sym32 = TRUE;
12220   else if (strcmp (name, "nosym32") == 0)
12221     mips_opts.sym32 = FALSE;
12222   else
12223     {
12224       as_warn (_("Tried to set unrecognized symbol: %s\n"), name);
12225     }
12226   *input_line_pointer = ch;
12227   demand_empty_rest_of_line ();
12228 }
12229
12230 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
12231    .option pic2.  It means to generate SVR4 PIC calls.  */
12232
12233 static void
12234 s_abicalls (int ignore ATTRIBUTE_UNUSED)
12235 {
12236   mips_pic = SVR4_PIC;
12237   mips_abicalls = TRUE;
12238
12239   if (g_switch_seen && g_switch_value != 0)
12240     as_warn (_("-G may not be used with SVR4 PIC code"));
12241   g_switch_value = 0;
12242
12243   bfd_set_gp_size (stdoutput, 0);
12244   demand_empty_rest_of_line ();
12245 }
12246
12247 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
12248    PIC code.  It sets the $gp register for the function based on the
12249    function address, which is in the register named in the argument.
12250    This uses a relocation against _gp_disp, which is handled specially
12251    by the linker.  The result is:
12252         lui     $gp,%hi(_gp_disp)
12253         addiu   $gp,$gp,%lo(_gp_disp)
12254         addu    $gp,$gp,.cpload argument
12255    The .cpload argument is normally $25 == $t9.
12256
12257    The -mno-shared option changes this to:
12258         lui     $gp,%hi(__gnu_local_gp)
12259         addiu   $gp,$gp,%lo(__gnu_local_gp)
12260    and the argument is ignored.  This saves an instruction, but the
12261    resulting code is not position independent; it uses an absolute
12262    address for __gnu_local_gp.  Thus code assembled with -mno-shared
12263    can go into an ordinary executable, but not into a shared library.  */
12264
12265 static void
12266 s_cpload (int ignore ATTRIBUTE_UNUSED)
12267 {
12268   expressionS ex;
12269   int reg;
12270   int in_shared;
12271
12272   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
12273      .cpload is ignored.  */
12274   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
12275     {
12276       s_ignore (0);
12277       return;
12278     }
12279
12280   /* .cpload should be in a .set noreorder section.  */
12281   if (mips_opts.noreorder == 0)
12282     as_warn (_(".cpload not in noreorder section"));
12283
12284   reg = tc_get_register (0);
12285
12286   /* If we need to produce a 64-bit address, we are better off using
12287      the default instruction sequence.  */
12288   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
12289
12290   ex.X_op = O_symbol;
12291   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
12292                                          "__gnu_local_gp");
12293   ex.X_op_symbol = NULL;
12294   ex.X_add_number = 0;
12295
12296   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
12297   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
12298
12299   macro_start ();
12300   macro_build_lui (&ex, mips_gp_register);
12301   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
12302                mips_gp_register, BFD_RELOC_LO16);
12303   if (in_shared)
12304     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
12305                  mips_gp_register, reg);
12306   macro_end ();
12307
12308   demand_empty_rest_of_line ();
12309 }
12310
12311 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
12312      .cpsetup $reg1, offset|$reg2, label
12313
12314    If offset is given, this results in:
12315      sd         $gp, offset($sp)
12316      lui        $gp, %hi(%neg(%gp_rel(label)))
12317      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
12318      daddu      $gp, $gp, $reg1
12319
12320    If $reg2 is given, this results in:
12321      daddu      $reg2, $gp, $0
12322      lui        $gp, %hi(%neg(%gp_rel(label)))
12323      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
12324      daddu      $gp, $gp, $reg1
12325    $reg1 is normally $25 == $t9.
12326
12327    The -mno-shared option replaces the last three instructions with
12328         lui     $gp,%hi(_gp)
12329         addiu   $gp,$gp,%lo(_gp)
12330    */
12331
12332 static void
12333 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
12334 {
12335   expressionS ex_off;
12336   expressionS ex_sym;
12337   int reg1;
12338
12339   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
12340      We also need NewABI support.  */
12341   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
12342     {
12343       s_ignore (0);
12344       return;
12345     }
12346
12347   reg1 = tc_get_register (0);
12348   SKIP_WHITESPACE ();
12349   if (*input_line_pointer != ',')
12350     {
12351       as_bad (_("missing argument separator ',' for .cpsetup"));
12352       return;
12353     }
12354   else
12355     ++input_line_pointer;
12356   SKIP_WHITESPACE ();
12357   if (*input_line_pointer == '$')
12358     {
12359       mips_cpreturn_register = tc_get_register (0);
12360       mips_cpreturn_offset = -1;
12361     }
12362   else
12363     {
12364       mips_cpreturn_offset = get_absolute_expression ();
12365       mips_cpreturn_register = -1;
12366     }
12367   SKIP_WHITESPACE ();
12368   if (*input_line_pointer != ',')
12369     {
12370       as_bad (_("missing argument separator ',' for .cpsetup"));
12371       return;
12372     }
12373   else
12374     ++input_line_pointer;
12375   SKIP_WHITESPACE ();
12376   expression (&ex_sym);
12377
12378   macro_start ();
12379   if (mips_cpreturn_register == -1)
12380     {
12381       ex_off.X_op = O_constant;
12382       ex_off.X_add_symbol = NULL;
12383       ex_off.X_op_symbol = NULL;
12384       ex_off.X_add_number = mips_cpreturn_offset;
12385
12386       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
12387                    BFD_RELOC_LO16, SP);
12388     }
12389   else
12390     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
12391                  mips_gp_register, 0);
12392
12393   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
12394     {
12395       macro_build (&ex_sym, "lui", "t,u", mips_gp_register,
12396                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
12397                    BFD_RELOC_HI16_S);
12398
12399       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
12400                    mips_gp_register, -1, BFD_RELOC_GPREL16,
12401                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
12402
12403       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
12404                    mips_gp_register, reg1);
12405     }
12406   else
12407     {
12408       expressionS ex;
12409
12410       ex.X_op = O_symbol;
12411       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
12412       ex.X_op_symbol = NULL;
12413       ex.X_add_number = 0;
12414
12415       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
12416       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
12417
12418       macro_build_lui (&ex, mips_gp_register);
12419       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
12420                    mips_gp_register, BFD_RELOC_LO16);
12421     }
12422
12423   macro_end ();
12424
12425   demand_empty_rest_of_line ();
12426 }
12427
12428 static void
12429 s_cplocal (int ignore ATTRIBUTE_UNUSED)
12430 {
12431   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
12432    .cplocal is ignored.  */
12433   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
12434     {
12435       s_ignore (0);
12436       return;
12437     }
12438
12439   mips_gp_register = tc_get_register (0);
12440   demand_empty_rest_of_line ();
12441 }
12442
12443 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
12444    offset from $sp.  The offset is remembered, and after making a PIC
12445    call $gp is restored from that location.  */
12446
12447 static void
12448 s_cprestore (int ignore ATTRIBUTE_UNUSED)
12449 {
12450   expressionS ex;
12451
12452   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
12453      .cprestore is ignored.  */
12454   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
12455     {
12456       s_ignore (0);
12457       return;
12458     }
12459
12460   mips_cprestore_offset = get_absolute_expression ();
12461   mips_cprestore_valid = 1;
12462
12463   ex.X_op = O_constant;
12464   ex.X_add_symbol = NULL;
12465   ex.X_op_symbol = NULL;
12466   ex.X_add_number = mips_cprestore_offset;
12467
12468   macro_start ();
12469   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
12470                                 SP, HAVE_64BIT_ADDRESSES);
12471   macro_end ();
12472
12473   demand_empty_rest_of_line ();
12474 }
12475
12476 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
12477    was given in the preceding .cpsetup, it results in:
12478      ld         $gp, offset($sp)
12479
12480    If a register $reg2 was given there, it results in:
12481      daddu      $gp, $reg2, $0
12482  */
12483 static void
12484 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
12485 {
12486   expressionS ex;
12487
12488   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
12489      We also need NewABI support.  */
12490   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
12491     {
12492       s_ignore (0);
12493       return;
12494     }
12495
12496   macro_start ();
12497   if (mips_cpreturn_register == -1)
12498     {
12499       ex.X_op = O_constant;
12500       ex.X_add_symbol = NULL;
12501       ex.X_op_symbol = NULL;
12502       ex.X_add_number = mips_cpreturn_offset;
12503
12504       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
12505     }
12506   else
12507     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
12508                  mips_cpreturn_register, 0);
12509   macro_end ();
12510
12511   demand_empty_rest_of_line ();
12512 }
12513
12514 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
12515    code.  It sets the offset to use in gp_rel relocations.  */
12516
12517 static void
12518 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
12519 {
12520   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
12521      We also need NewABI support.  */
12522   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
12523     {
12524       s_ignore (0);
12525       return;
12526     }
12527
12528   mips_gprel_offset = get_absolute_expression ();
12529
12530   demand_empty_rest_of_line ();
12531 }
12532
12533 /* Handle the .gpword pseudo-op.  This is used when generating PIC
12534    code.  It generates a 32 bit GP relative reloc.  */
12535
12536 static void
12537 s_gpword (int ignore ATTRIBUTE_UNUSED)
12538 {
12539   symbolS *label;
12540   expressionS ex;
12541   char *p;
12542
12543   /* When not generating PIC code, this is treated as .word.  */
12544   if (mips_pic != SVR4_PIC)
12545     {
12546       s_cons (2);
12547       return;
12548     }
12549
12550   label = insn_labels != NULL ? insn_labels->label : NULL;
12551   mips_emit_delays ();
12552   if (auto_align)
12553     mips_align (2, 0, label);
12554   mips_clear_insn_labels ();
12555
12556   expression (&ex);
12557
12558   if (ex.X_op != O_symbol || ex.X_add_number != 0)
12559     {
12560       as_bad (_("Unsupported use of .gpword"));
12561       ignore_rest_of_line ();
12562     }
12563
12564   p = frag_more (4);
12565   md_number_to_chars (p, 0, 4);
12566   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
12567                BFD_RELOC_GPREL32);
12568
12569   demand_empty_rest_of_line ();
12570 }
12571
12572 static void
12573 s_gpdword (int ignore ATTRIBUTE_UNUSED)
12574 {
12575   symbolS *label;
12576   expressionS ex;
12577   char *p;
12578
12579   /* When not generating PIC code, this is treated as .dword.  */
12580   if (mips_pic != SVR4_PIC)
12581     {
12582       s_cons (3);
12583       return;
12584     }
12585
12586   label = insn_labels != NULL ? insn_labels->label : NULL;
12587   mips_emit_delays ();
12588   if (auto_align)
12589     mips_align (3, 0, label);
12590   mips_clear_insn_labels ();
12591
12592   expression (&ex);
12593
12594   if (ex.X_op != O_symbol || ex.X_add_number != 0)
12595     {
12596       as_bad (_("Unsupported use of .gpdword"));
12597       ignore_rest_of_line ();
12598     }
12599
12600   p = frag_more (8);
12601   md_number_to_chars (p, 0, 8);
12602   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
12603                BFD_RELOC_GPREL32)->fx_tcbit = 1;
12604
12605   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
12606   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
12607            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
12608
12609   demand_empty_rest_of_line ();
12610 }
12611
12612 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
12613    tables in SVR4 PIC code.  */
12614
12615 static void
12616 s_cpadd (int ignore ATTRIBUTE_UNUSED)
12617 {
12618   int reg;
12619
12620   /* This is ignored when not generating SVR4 PIC code.  */
12621   if (mips_pic != SVR4_PIC)
12622     {
12623       s_ignore (0);
12624       return;
12625     }
12626
12627   /* Add $gp to the register named as an argument.  */
12628   macro_start ();
12629   reg = tc_get_register (0);
12630   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
12631   macro_end ();
12632
12633   demand_empty_rest_of_line ();
12634 }
12635
12636 /* Handle the .insn pseudo-op.  This marks instruction labels in
12637    mips16 mode.  This permits the linker to handle them specially,
12638    such as generating jalx instructions when needed.  We also make
12639    them odd for the duration of the assembly, in order to generate the
12640    right sort of code.  We will make them even in the adjust_symtab
12641    routine, while leaving them marked.  This is convenient for the
12642    debugger and the disassembler.  The linker knows to make them odd
12643    again.  */
12644
12645 static void
12646 s_insn (int ignore ATTRIBUTE_UNUSED)
12647 {
12648   mips16_mark_labels ();
12649
12650   demand_empty_rest_of_line ();
12651 }
12652
12653 /* Handle a .stabn directive.  We need these in order to mark a label
12654    as being a mips16 text label correctly.  Sometimes the compiler
12655    will emit a label, followed by a .stabn, and then switch sections.
12656    If the label and .stabn are in mips16 mode, then the label is
12657    really a mips16 text label.  */
12658
12659 static void
12660 s_mips_stab (int type)
12661 {
12662   if (type == 'n')
12663     mips16_mark_labels ();
12664
12665   s_stab (type);
12666 }
12667
12668 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.
12669  */
12670
12671 static void
12672 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
12673 {
12674   char *name;
12675   int c;
12676   symbolS *symbolP;
12677   expressionS exp;
12678
12679   name = input_line_pointer;
12680   c = get_symbol_end ();
12681   symbolP = symbol_find_or_make (name);
12682   S_SET_WEAK (symbolP);
12683   *input_line_pointer = c;
12684
12685   SKIP_WHITESPACE ();
12686
12687   if (! is_end_of_line[(unsigned char) *input_line_pointer])
12688     {
12689       if (S_IS_DEFINED (symbolP))
12690         {
12691           as_bad ("ignoring attempt to redefine symbol %s",
12692                   S_GET_NAME (symbolP));
12693           ignore_rest_of_line ();
12694           return;
12695         }
12696
12697       if (*input_line_pointer == ',')
12698         {
12699           ++input_line_pointer;
12700           SKIP_WHITESPACE ();
12701         }
12702
12703       expression (&exp);
12704       if (exp.X_op != O_symbol)
12705         {
12706           as_bad ("bad .weakext directive");
12707           ignore_rest_of_line ();
12708           return;
12709         }
12710       symbol_set_value_expression (symbolP, &exp);
12711     }
12712
12713   demand_empty_rest_of_line ();
12714 }
12715
12716 /* Parse a register string into a number.  Called from the ECOFF code
12717    to parse .frame.  The argument is non-zero if this is the frame
12718    register, so that we can record it in mips_frame_reg.  */
12719
12720 int
12721 tc_get_register (int frame)
12722 {
12723   int reg;
12724
12725   SKIP_WHITESPACE ();
12726   if (*input_line_pointer++ != '$')
12727     {
12728       as_warn (_("expected `$'"));
12729       reg = ZERO;
12730     }
12731   else if (ISDIGIT (*input_line_pointer))
12732     {
12733       reg = get_absolute_expression ();
12734       if (reg < 0 || reg >= 32)
12735         {
12736           as_warn (_("Bad register number"));
12737           reg = ZERO;
12738         }
12739     }
12740   else
12741     {
12742       if (strncmp (input_line_pointer, "ra", 2) == 0)
12743         {
12744           reg = RA;
12745           input_line_pointer += 2;
12746         }
12747       else if (strncmp (input_line_pointer, "fp", 2) == 0)
12748         {
12749           reg = FP;
12750           input_line_pointer += 2;
12751         }
12752       else if (strncmp (input_line_pointer, "sp", 2) == 0)
12753         {
12754           reg = SP;
12755           input_line_pointer += 2;
12756         }
12757       else if (strncmp (input_line_pointer, "gp", 2) == 0)
12758         {
12759           reg = GP;
12760           input_line_pointer += 2;
12761         }
12762       else if (strncmp (input_line_pointer, "at", 2) == 0)
12763         {
12764           reg = AT;
12765           input_line_pointer += 2;
12766         }
12767       else if (strncmp (input_line_pointer, "kt0", 3) == 0)
12768         {
12769           reg = KT0;
12770           input_line_pointer += 3;
12771         }
12772       else if (strncmp (input_line_pointer, "kt1", 3) == 0)
12773         {
12774           reg = KT1;
12775           input_line_pointer += 3;
12776         }
12777       else if (strncmp (input_line_pointer, "zero", 4) == 0)
12778         {
12779           reg = ZERO;
12780           input_line_pointer += 4;
12781         }
12782       else
12783         {
12784           as_warn (_("Unrecognized register name"));
12785           reg = ZERO;
12786           while (ISALNUM(*input_line_pointer))
12787            input_line_pointer++;
12788         }
12789     }
12790   if (frame)
12791     {
12792       mips_frame_reg = reg != 0 ? reg : SP;
12793       mips_frame_reg_valid = 1;
12794       mips_cprestore_valid = 0;
12795     }
12796   return reg;
12797 }
12798
12799 valueT
12800 md_section_align (asection *seg, valueT addr)
12801 {
12802   int align = bfd_get_section_alignment (stdoutput, seg);
12803
12804 #ifdef OBJ_ELF
12805   /* We don't need to align ELF sections to the full alignment.
12806      However, Irix 5 may prefer that we align them at least to a 16
12807      byte boundary.  We don't bother to align the sections if we are
12808      targeted for an embedded system.  */
12809   if (strcmp (TARGET_OS, "elf") == 0)
12810     return addr;
12811   if (align > 4)
12812     align = 4;
12813 #endif
12814
12815   return ((addr + (1 << align) - 1) & (-1 << align));
12816 }
12817
12818 /* Utility routine, called from above as well.  If called while the
12819    input file is still being read, it's only an approximation.  (For
12820    example, a symbol may later become defined which appeared to be
12821    undefined earlier.)  */
12822
12823 static int
12824 nopic_need_relax (symbolS *sym, int before_relaxing)
12825 {
12826   if (sym == 0)
12827     return 0;
12828
12829   if (g_switch_value > 0)
12830     {
12831       const char *symname;
12832       int change;
12833
12834       /* Find out whether this symbol can be referenced off the $gp
12835          register.  It can be if it is smaller than the -G size or if
12836          it is in the .sdata or .sbss section.  Certain symbols can
12837          not be referenced off the $gp, although it appears as though
12838          they can.  */
12839       symname = S_GET_NAME (sym);
12840       if (symname != (const char *) NULL
12841           && (strcmp (symname, "eprol") == 0
12842               || strcmp (symname, "etext") == 0
12843               || strcmp (symname, "_gp") == 0
12844               || strcmp (symname, "edata") == 0
12845               || strcmp (symname, "_fbss") == 0
12846               || strcmp (symname, "_fdata") == 0
12847               || strcmp (symname, "_ftext") == 0
12848               || strcmp (symname, "end") == 0
12849               || strcmp (symname, "_gp_disp") == 0))
12850         change = 1;
12851       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
12852                && (0
12853 #ifndef NO_ECOFF_DEBUGGING
12854                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
12855                        && (symbol_get_obj (sym)->ecoff_extern_size
12856                            <= g_switch_value))
12857 #endif
12858                    /* We must defer this decision until after the whole
12859                       file has been read, since there might be a .extern
12860                       after the first use of this symbol.  */
12861                    || (before_relaxing
12862 #ifndef NO_ECOFF_DEBUGGING
12863                        && symbol_get_obj (sym)->ecoff_extern_size == 0
12864 #endif
12865                        && S_GET_VALUE (sym) == 0)
12866                    || (S_GET_VALUE (sym) != 0
12867                        && S_GET_VALUE (sym) <= g_switch_value)))
12868         change = 0;
12869       else
12870         {
12871           const char *segname;
12872
12873           segname = segment_name (S_GET_SEGMENT (sym));
12874           assert (strcmp (segname, ".lit8") != 0
12875                   && strcmp (segname, ".lit4") != 0);
12876           change = (strcmp (segname, ".sdata") != 0
12877                     && strcmp (segname, ".sbss") != 0
12878                     && strncmp (segname, ".sdata.", 7) != 0
12879                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
12880         }
12881       return change;
12882     }
12883   else
12884     /* We are not optimizing for the $gp register.  */
12885     return 1;
12886 }
12887
12888
12889 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
12890
12891 static bfd_boolean
12892 pic_need_relax (symbolS *sym, asection *segtype)
12893 {
12894   asection *symsec;
12895   bfd_boolean linkonce;
12896
12897   /* Handle the case of a symbol equated to another symbol.  */
12898   while (symbol_equated_reloc_p (sym))
12899     {
12900       symbolS *n;
12901
12902       /* It's possible to get a loop here in a badly written
12903          program.  */
12904       n = symbol_get_value_expression (sym)->X_add_symbol;
12905       if (n == sym)
12906         break;
12907       sym = n;
12908     }
12909
12910   symsec = S_GET_SEGMENT (sym);
12911
12912   /* duplicate the test for LINK_ONCE sections as in adjust_reloc_syms */
12913   linkonce = FALSE;
12914   if (symsec != segtype && ! S_IS_LOCAL (sym))
12915     {
12916       if ((bfd_get_section_flags (stdoutput, symsec) & SEC_LINK_ONCE)
12917           != 0)
12918         linkonce = TRUE;
12919
12920       /* The GNU toolchain uses an extension for ELF: a section
12921          beginning with the magic string .gnu.linkonce is a linkonce
12922          section.  */
12923       if (strncmp (segment_name (symsec), ".gnu.linkonce",
12924                    sizeof ".gnu.linkonce" - 1) == 0)
12925         linkonce = TRUE;
12926     }
12927
12928   /* This must duplicate the test in adjust_reloc_syms.  */
12929   return (symsec != &bfd_und_section
12930           && symsec != &bfd_abs_section
12931           && ! bfd_is_com_section (symsec)
12932           && !linkonce
12933 #ifdef OBJ_ELF
12934           /* A global or weak symbol is treated as external.  */
12935           && (OUTPUT_FLAVOR != bfd_target_elf_flavour
12936               || (! S_IS_WEAK (sym) && ! S_IS_EXTERNAL (sym)))
12937 #endif
12938           );
12939 }
12940
12941
12942 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
12943    extended opcode.  SEC is the section the frag is in.  */
12944
12945 static int
12946 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
12947 {
12948   int type;
12949   register const struct mips16_immed_operand *op;
12950   offsetT val;
12951   int mintiny, maxtiny;
12952   segT symsec;
12953   fragS *sym_frag;
12954
12955   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
12956     return 0;
12957   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
12958     return 1;
12959
12960   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
12961   op = mips16_immed_operands;
12962   while (op->type != type)
12963     {
12964       ++op;
12965       assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
12966     }
12967
12968   if (op->unsp)
12969     {
12970       if (type == '<' || type == '>' || type == '[' || type == ']')
12971         {
12972           mintiny = 1;
12973           maxtiny = 1 << op->nbits;
12974         }
12975       else
12976         {
12977           mintiny = 0;
12978           maxtiny = (1 << op->nbits) - 1;
12979         }
12980     }
12981   else
12982     {
12983       mintiny = - (1 << (op->nbits - 1));
12984       maxtiny = (1 << (op->nbits - 1)) - 1;
12985     }
12986
12987   sym_frag = symbol_get_frag (fragp->fr_symbol);
12988   val = S_GET_VALUE (fragp->fr_symbol);
12989   symsec = S_GET_SEGMENT (fragp->fr_symbol);
12990
12991   if (op->pcrel)
12992     {
12993       addressT addr;
12994
12995       /* We won't have the section when we are called from
12996          mips_relax_frag.  However, we will always have been called
12997          from md_estimate_size_before_relax first.  If this is a
12998          branch to a different section, we mark it as such.  If SEC is
12999          NULL, and the frag is not marked, then it must be a branch to
13000          the same section.  */
13001       if (sec == NULL)
13002         {
13003           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
13004             return 1;
13005         }
13006       else
13007         {
13008           /* Must have been called from md_estimate_size_before_relax.  */
13009           if (symsec != sec)
13010             {
13011               fragp->fr_subtype =
13012                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
13013
13014               /* FIXME: We should support this, and let the linker
13015                  catch branches and loads that are out of range.  */
13016               as_bad_where (fragp->fr_file, fragp->fr_line,
13017                             _("unsupported PC relative reference to different section"));
13018
13019               return 1;
13020             }
13021           if (fragp != sym_frag && sym_frag->fr_address == 0)
13022             /* Assume non-extended on the first relaxation pass.
13023                The address we have calculated will be bogus if this is
13024                a forward branch to another frag, as the forward frag
13025                will have fr_address == 0.  */
13026             return 0;
13027         }
13028
13029       /* In this case, we know for sure that the symbol fragment is in
13030          the same section.  If the relax_marker of the symbol fragment
13031          differs from the relax_marker of this fragment, we have not
13032          yet adjusted the symbol fragment fr_address.  We want to add
13033          in STRETCH in order to get a better estimate of the address.
13034          This particularly matters because of the shift bits.  */
13035       if (stretch != 0
13036           && sym_frag->relax_marker != fragp->relax_marker)
13037         {
13038           fragS *f;
13039
13040           /* Adjust stretch for any alignment frag.  Note that if have
13041              been expanding the earlier code, the symbol may be
13042              defined in what appears to be an earlier frag.  FIXME:
13043              This doesn't handle the fr_subtype field, which specifies
13044              a maximum number of bytes to skip when doing an
13045              alignment.  */
13046           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
13047             {
13048               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
13049                 {
13050                   if (stretch < 0)
13051                     stretch = - ((- stretch)
13052                                  & ~ ((1 << (int) f->fr_offset) - 1));
13053                   else
13054                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
13055                   if (stretch == 0)
13056                     break;
13057                 }
13058             }
13059           if (f != NULL)
13060             val += stretch;
13061         }
13062
13063       addr = fragp->fr_address + fragp->fr_fix;
13064
13065       /* The base address rules are complicated.  The base address of
13066          a branch is the following instruction.  The base address of a
13067          PC relative load or add is the instruction itself, but if it
13068          is in a delay slot (in which case it can not be extended) use
13069          the address of the instruction whose delay slot it is in.  */
13070       if (type == 'p' || type == 'q')
13071         {
13072           addr += 2;
13073
13074           /* If we are currently assuming that this frag should be
13075              extended, then, the current address is two bytes
13076              higher.  */
13077           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
13078             addr += 2;
13079
13080           /* Ignore the low bit in the target, since it will be set
13081              for a text label.  */
13082           if ((val & 1) != 0)
13083             --val;
13084         }
13085       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
13086         addr -= 4;
13087       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
13088         addr -= 2;
13089
13090       val -= addr & ~ ((1 << op->shift) - 1);
13091
13092       /* Branch offsets have an implicit 0 in the lowest bit.  */
13093       if (type == 'p' || type == 'q')
13094         val /= 2;
13095
13096       /* If any of the shifted bits are set, we must use an extended
13097          opcode.  If the address depends on the size of this
13098          instruction, this can lead to a loop, so we arrange to always
13099          use an extended opcode.  We only check this when we are in
13100          the main relaxation loop, when SEC is NULL.  */
13101       if ((val & ((1 << op->shift) - 1)) != 0 && sec == NULL)
13102         {
13103           fragp->fr_subtype =
13104             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
13105           return 1;
13106         }
13107
13108       /* If we are about to mark a frag as extended because the value
13109          is precisely maxtiny + 1, then there is a chance of an
13110          infinite loop as in the following code:
13111              la $4,foo
13112              .skip      1020
13113              .align     2
13114            foo:
13115          In this case when the la is extended, foo is 0x3fc bytes
13116          away, so the la can be shrunk, but then foo is 0x400 away, so
13117          the la must be extended.  To avoid this loop, we mark the
13118          frag as extended if it was small, and is about to become
13119          extended with a value of maxtiny + 1.  */
13120       if (val == ((maxtiny + 1) << op->shift)
13121           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
13122           && sec == NULL)
13123         {
13124           fragp->fr_subtype =
13125             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
13126           return 1;
13127         }
13128     }
13129   else if (symsec != absolute_section && sec != NULL)
13130     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
13131
13132   if ((val & ((1 << op->shift) - 1)) != 0
13133       || val < (mintiny << op->shift)
13134       || val > (maxtiny << op->shift))
13135     return 1;
13136   else
13137     return 0;
13138 }
13139
13140 /* Compute the length of a branch sequence, and adjust the
13141    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
13142    worst-case length is computed, with UPDATE being used to indicate
13143    whether an unconditional (-1), branch-likely (+1) or regular (0)
13144    branch is to be computed.  */
13145 static int
13146 relaxed_branch_length (fragS *fragp, asection *sec, int update)
13147 {
13148   bfd_boolean toofar;
13149   int length;
13150
13151   if (fragp
13152       && S_IS_DEFINED (fragp->fr_symbol)
13153       && sec == S_GET_SEGMENT (fragp->fr_symbol))
13154     {
13155       addressT addr;
13156       offsetT val;
13157
13158       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
13159
13160       addr = fragp->fr_address + fragp->fr_fix + 4;
13161
13162       val -= addr;
13163
13164       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
13165     }
13166   else if (fragp)
13167     /* If the symbol is not defined or it's in a different segment,
13168        assume the user knows what's going on and emit a short
13169        branch.  */
13170     toofar = FALSE;
13171   else
13172     toofar = TRUE;
13173
13174   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
13175     fragp->fr_subtype
13176       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_UNCOND (fragp->fr_subtype),
13177                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
13178                              RELAX_BRANCH_LINK (fragp->fr_subtype),
13179                              toofar);
13180
13181   length = 4;
13182   if (toofar)
13183     {
13184       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
13185         length += 8;
13186
13187       if (mips_pic != NO_PIC)
13188         {
13189           /* Additional space for PIC loading of target address.  */
13190           length += 8;
13191           if (mips_opts.isa == ISA_MIPS1)
13192             /* Additional space for $at-stabilizing nop.  */
13193             length += 4;
13194         }
13195
13196       /* If branch is conditional.  */
13197       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
13198         length += 8;
13199     }
13200
13201   return length;
13202 }
13203
13204 /* Estimate the size of a frag before relaxing.  Unless this is the
13205    mips16, we are not really relaxing here, and the final size is
13206    encoded in the subtype information.  For the mips16, we have to
13207    decide whether we are using an extended opcode or not.  */
13208
13209 int
13210 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
13211 {
13212   int change;
13213
13214   if (RELAX_BRANCH_P (fragp->fr_subtype))
13215     {
13216
13217       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
13218
13219       return fragp->fr_var;
13220     }
13221
13222   if (RELAX_MIPS16_P (fragp->fr_subtype))
13223     /* We don't want to modify the EXTENDED bit here; it might get us
13224        into infinite loops.  We change it only in mips_relax_frag().  */
13225     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
13226
13227   if (mips_pic == NO_PIC)
13228     change = nopic_need_relax (fragp->fr_symbol, 0);
13229   else if (mips_pic == SVR4_PIC)
13230     change = pic_need_relax (fragp->fr_symbol, segtype);
13231   else
13232     abort ();
13233
13234   if (change)
13235     {
13236       fragp->fr_subtype |= RELAX_USE_SECOND;
13237       return -RELAX_FIRST (fragp->fr_subtype);
13238     }
13239   else
13240     return -RELAX_SECOND (fragp->fr_subtype);
13241 }
13242
13243 /* This is called to see whether a reloc against a defined symbol
13244    should be converted into a reloc against a section.  */
13245
13246 int
13247 mips_fix_adjustable (fixS *fixp)
13248 {
13249   /* Don't adjust MIPS16 jump relocations, so we don't have to worry
13250      about the format of the offset in the .o file. */
13251   if (fixp->fx_r_type == BFD_RELOC_MIPS16_JMP)
13252     return 0;
13253
13254   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
13255       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
13256     return 0;
13257
13258   if (fixp->fx_addsy == NULL)
13259     return 1;
13260
13261   /* If symbol SYM is in a mergeable section, relocations of the form
13262      SYM + 0 can usually be made section-relative.  The mergeable data
13263      is then identified by the section offset rather than by the symbol.
13264
13265      However, if we're generating REL LO16 relocations, the offset is split
13266      between the LO16 and parterning high part relocation.  The linker will
13267      need to recalculate the complete offset in order to correctly identify
13268      the merge data.
13269
13270      The linker has traditionally not looked for the parterning high part
13271      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
13272      placed anywhere.  Rather than break backwards compatibility by changing
13273      this, it seems better not to force the issue, and instead keep the
13274      original symbol.  This will work with either linker behavior.  */
13275   if ((fixp->fx_r_type == BFD_RELOC_LO16
13276        || fixp->fx_r_type == BFD_RELOC_MIPS16_LO16
13277        || reloc_needs_lo_p (fixp->fx_r_type))
13278       && HAVE_IN_PLACE_ADDENDS
13279       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
13280     return 0;
13281
13282 #ifdef OBJ_ELF
13283   /* Don't adjust relocations against mips16 symbols, so that the linker
13284      can find them if it needs to set up a stub.  */
13285   if (OUTPUT_FLAVOR == bfd_target_elf_flavour
13286       && S_GET_OTHER (fixp->fx_addsy) == STO_MIPS16
13287       && fixp->fx_subsy == NULL)
13288     return 0;
13289 #endif
13290
13291   return 1;
13292 }
13293
13294 /* Translate internal representation of relocation info to BFD target
13295    format.  */
13296
13297 arelent **
13298 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
13299 {
13300   static arelent *retval[4];
13301   arelent *reloc;
13302   bfd_reloc_code_real_type code;
13303
13304   memset (retval, 0, sizeof(retval));
13305   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
13306   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
13307   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
13308   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
13309
13310   assert (! fixp->fx_pcrel);
13311   reloc->addend = fixp->fx_addnumber;
13312
13313   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
13314      entry to be used in the relocation's section offset.  */
13315   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
13316     {
13317       reloc->address = reloc->addend;
13318       reloc->addend = 0;
13319     }
13320
13321   code = fixp->fx_r_type;
13322
13323   /* To support a PC relative reloc, we used a Cygnus extension.
13324      We check for that here to make sure that we don't let such a
13325      reloc escape normally.  (FIXME: This was formerly used by
13326      embedded-PIC support, but is now used by branch handling in
13327      general.  That probably should be fixed.)  */
13328   if ((OUTPUT_FLAVOR == bfd_target_ecoff_flavour
13329        || OUTPUT_FLAVOR == bfd_target_elf_flavour)
13330       && code == BFD_RELOC_16_PCREL_S2)
13331     reloc->howto = NULL;
13332   else
13333     reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
13334
13335   if (reloc->howto == NULL)
13336     {
13337       as_bad_where (fixp->fx_file, fixp->fx_line,
13338                     _("Can not represent %s relocation in this object file format"),
13339                     bfd_get_reloc_code_name (code));
13340       retval[0] = NULL;
13341     }
13342
13343   return retval;
13344 }
13345
13346 /* Relax a machine dependent frag.  This returns the amount by which
13347    the current size of the frag should change.  */
13348
13349 int
13350 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
13351 {
13352   if (RELAX_BRANCH_P (fragp->fr_subtype))
13353     {
13354       offsetT old_var = fragp->fr_var;
13355
13356       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
13357
13358       return fragp->fr_var - old_var;
13359     }
13360
13361   if (! RELAX_MIPS16_P (fragp->fr_subtype))
13362     return 0;
13363
13364   if (mips16_extended_frag (fragp, NULL, stretch))
13365     {
13366       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
13367         return 0;
13368       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
13369       return 2;
13370     }
13371   else
13372     {
13373       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
13374         return 0;
13375       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
13376       return -2;
13377     }
13378
13379   return 0;
13380 }
13381
13382 /* Convert a machine dependent frag.  */
13383
13384 void
13385 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
13386 {
13387   if (RELAX_BRANCH_P (fragp->fr_subtype))
13388     {
13389       bfd_byte *buf;
13390       unsigned long insn;
13391       expressionS exp;
13392       fixS *fixp;
13393
13394       buf = (bfd_byte *)fragp->fr_literal + fragp->fr_fix;
13395
13396       if (target_big_endian)
13397         insn = bfd_getb32 (buf);
13398       else
13399         insn = bfd_getl32 (buf);
13400
13401       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
13402         {
13403           /* We generate a fixup instead of applying it right now
13404              because, if there are linker relaxations, we're going to
13405              need the relocations.  */
13406           exp.X_op = O_symbol;
13407           exp.X_add_symbol = fragp->fr_symbol;
13408           exp.X_add_number = fragp->fr_offset;
13409
13410           fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
13411                               4, &exp, 1,
13412                               BFD_RELOC_16_PCREL_S2);
13413           fixp->fx_file = fragp->fr_file;
13414           fixp->fx_line = fragp->fr_line;
13415
13416           md_number_to_chars ((char *) buf, insn, 4);
13417           buf += 4;
13418         }
13419       else
13420         {
13421           int i;
13422
13423           as_warn_where (fragp->fr_file, fragp->fr_line,
13424                          _("relaxed out-of-range branch into a jump"));
13425
13426           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
13427             goto uncond;
13428
13429           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
13430             {
13431               /* Reverse the branch.  */
13432               switch ((insn >> 28) & 0xf)
13433                 {
13434                 case 4:
13435                   /* bc[0-3][tf]l? and bc1any[24][ft] instructions can
13436                      have the condition reversed by tweaking a single
13437                      bit, and their opcodes all have 0x4???????.  */
13438                   assert ((insn & 0xf1000000) == 0x41000000);
13439                   insn ^= 0x00010000;
13440                   break;
13441
13442                 case 0:
13443                   /* bltz       0x04000000      bgez    0x04010000
13444                      bltzal     0x04100000      bgezal  0x04110000 */
13445                   assert ((insn & 0xfc0e0000) == 0x04000000);
13446                   insn ^= 0x00010000;
13447                   break;
13448
13449                 case 1:
13450                   /* beq        0x10000000      bne     0x14000000
13451                      blez       0x18000000      bgtz    0x1c000000 */
13452                   insn ^= 0x04000000;
13453                   break;
13454
13455                 default:
13456                   abort ();
13457                 }
13458             }
13459
13460           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
13461             {
13462               /* Clear the and-link bit.  */
13463               assert ((insn & 0xfc1c0000) == 0x04100000);
13464
13465               /* bltzal 0x04100000      bgezal  0x04110000
13466                 bltzall 0x04120000     bgezall  0x04130000 */
13467               insn &= ~0x00100000;
13468             }
13469
13470           /* Branch over the branch (if the branch was likely) or the
13471              full jump (not likely case).  Compute the offset from the
13472              current instruction to branch to.  */
13473           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
13474             i = 16;
13475           else
13476             {
13477               /* How many bytes in instructions we've already emitted?  */
13478               i = buf - (bfd_byte *)fragp->fr_literal - fragp->fr_fix;
13479               /* How many bytes in instructions from here to the end?  */
13480               i = fragp->fr_var - i;
13481             }
13482           /* Convert to instruction count.  */
13483           i >>= 2;
13484           /* Branch counts from the next instruction.  */
13485           i--;
13486           insn |= i;
13487           /* Branch over the jump.  */
13488           md_number_to_chars ((char *) buf, insn, 4);
13489           buf += 4;
13490
13491           /* Nop */
13492           md_number_to_chars ((char *) buf, 0, 4);
13493           buf += 4;
13494
13495           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
13496             {
13497               /* beql $0, $0, 2f */
13498               insn = 0x50000000;
13499               /* Compute the PC offset from the current instruction to
13500                  the end of the variable frag.  */
13501               /* How many bytes in instructions we've already emitted?  */
13502               i = buf - (bfd_byte *)fragp->fr_literal - fragp->fr_fix;
13503               /* How many bytes in instructions from here to the end?  */
13504               i = fragp->fr_var - i;
13505               /* Convert to instruction count.  */
13506               i >>= 2;
13507               /* Don't decrement i, because we want to branch over the
13508                  delay slot.  */
13509
13510               insn |= i;
13511               md_number_to_chars ((char *) buf, insn, 4);
13512               buf += 4;
13513
13514               md_number_to_chars ((char *) buf, 0, 4);
13515               buf += 4;
13516             }
13517
13518         uncond:
13519           if (mips_pic == NO_PIC)
13520             {
13521               /* j or jal.  */
13522               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
13523                       ? 0x0c000000 : 0x08000000);
13524               exp.X_op = O_symbol;
13525               exp.X_add_symbol = fragp->fr_symbol;
13526               exp.X_add_number = fragp->fr_offset;
13527
13528               fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
13529                                   4, &exp, 0, BFD_RELOC_MIPS_JMP);
13530               fixp->fx_file = fragp->fr_file;
13531               fixp->fx_line = fragp->fr_line;
13532
13533               md_number_to_chars ((char *) buf, insn, 4);
13534               buf += 4;
13535             }
13536           else
13537             {
13538               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
13539               insn = HAVE_64BIT_ADDRESSES ? 0xdf810000 : 0x8f810000;
13540               exp.X_op = O_symbol;
13541               exp.X_add_symbol = fragp->fr_symbol;
13542               exp.X_add_number = fragp->fr_offset;
13543
13544               if (fragp->fr_offset)
13545                 {
13546                   exp.X_add_symbol = make_expr_symbol (&exp);
13547                   exp.X_add_number = 0;
13548                 }
13549
13550               fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
13551                                   4, &exp, 0, BFD_RELOC_MIPS_GOT16);
13552               fixp->fx_file = fragp->fr_file;
13553               fixp->fx_line = fragp->fr_line;
13554
13555               md_number_to_chars ((char *) buf, insn, 4);
13556               buf += 4;
13557
13558               if (mips_opts.isa == ISA_MIPS1)
13559                 {
13560                   /* nop */
13561                   md_number_to_chars ((char *) buf, 0, 4);
13562                   buf += 4;
13563                 }
13564
13565               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
13566               insn = HAVE_64BIT_ADDRESSES ? 0x64210000 : 0x24210000;
13567
13568               fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
13569                                   4, &exp, 0, BFD_RELOC_LO16);
13570               fixp->fx_file = fragp->fr_file;
13571               fixp->fx_line = fragp->fr_line;
13572
13573               md_number_to_chars ((char *) buf, insn, 4);
13574               buf += 4;
13575
13576               /* j(al)r $at.  */
13577               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
13578                 insn = 0x0020f809;
13579               else
13580                 insn = 0x00200008;
13581
13582               md_number_to_chars ((char *) buf, insn, 4);
13583               buf += 4;
13584             }
13585         }
13586
13587       assert (buf == (bfd_byte *)fragp->fr_literal
13588               + fragp->fr_fix + fragp->fr_var);
13589
13590       fragp->fr_fix += fragp->fr_var;
13591
13592       return;
13593     }
13594
13595   if (RELAX_MIPS16_P (fragp->fr_subtype))
13596     {
13597       int type;
13598       register const struct mips16_immed_operand *op;
13599       bfd_boolean small, ext;
13600       offsetT val;
13601       bfd_byte *buf;
13602       unsigned long insn;
13603       bfd_boolean use_extend;
13604       unsigned short extend;
13605
13606       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
13607       op = mips16_immed_operands;
13608       while (op->type != type)
13609         ++op;
13610
13611       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
13612         {
13613           small = FALSE;
13614           ext = TRUE;
13615         }
13616       else
13617         {
13618           small = TRUE;
13619           ext = FALSE;
13620         }
13621
13622       resolve_symbol_value (fragp->fr_symbol);
13623       val = S_GET_VALUE (fragp->fr_symbol);
13624       if (op->pcrel)
13625         {
13626           addressT addr;
13627
13628           addr = fragp->fr_address + fragp->fr_fix;
13629
13630           /* The rules for the base address of a PC relative reloc are
13631              complicated; see mips16_extended_frag.  */
13632           if (type == 'p' || type == 'q')
13633             {
13634               addr += 2;
13635               if (ext)
13636                 addr += 2;
13637               /* Ignore the low bit in the target, since it will be
13638                  set for a text label.  */
13639               if ((val & 1) != 0)
13640                 --val;
13641             }
13642           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
13643             addr -= 4;
13644           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
13645             addr -= 2;
13646
13647           addr &= ~ (addressT) ((1 << op->shift) - 1);
13648           val -= addr;
13649
13650           /* Make sure the section winds up with the alignment we have
13651              assumed.  */
13652           if (op->shift > 0)
13653             record_alignment (asec, op->shift);
13654         }
13655
13656       if (ext
13657           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
13658               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
13659         as_warn_where (fragp->fr_file, fragp->fr_line,
13660                        _("extended instruction in delay slot"));
13661
13662       buf = (bfd_byte *) (fragp->fr_literal + fragp->fr_fix);
13663
13664       if (target_big_endian)
13665         insn = bfd_getb16 (buf);
13666       else
13667         insn = bfd_getl16 (buf);
13668
13669       mips16_immed (fragp->fr_file, fragp->fr_line, type, val,
13670                     RELAX_MIPS16_USER_EXT (fragp->fr_subtype),
13671                     small, ext, &insn, &use_extend, &extend);
13672
13673       if (use_extend)
13674         {
13675           md_number_to_chars ((char *) buf, 0xf000 | extend, 2);
13676           fragp->fr_fix += 2;
13677           buf += 2;
13678         }
13679
13680       md_number_to_chars ((char *) buf, insn, 2);
13681       fragp->fr_fix += 2;
13682       buf += 2;
13683     }
13684   else
13685     {
13686       int first, second;
13687       fixS *fixp;
13688
13689       first = RELAX_FIRST (fragp->fr_subtype);
13690       second = RELAX_SECOND (fragp->fr_subtype);
13691       fixp = (fixS *) fragp->fr_opcode;
13692
13693       /* Possibly emit a warning if we've chosen the longer option.  */
13694       if (((fragp->fr_subtype & RELAX_USE_SECOND) != 0)
13695           == ((fragp->fr_subtype & RELAX_SECOND_LONGER) != 0))
13696         {
13697           const char *msg = macro_warning (fragp->fr_subtype);
13698           if (msg != 0)
13699             as_warn_where (fragp->fr_file, fragp->fr_line, msg);
13700         }
13701
13702       /* Go through all the fixups for the first sequence.  Disable them
13703          (by marking them as done) if we're going to use the second
13704          sequence instead.  */
13705       while (fixp
13706              && fixp->fx_frag == fragp
13707              && fixp->fx_where < fragp->fr_fix - second)
13708         {
13709           if (fragp->fr_subtype & RELAX_USE_SECOND)
13710             fixp->fx_done = 1;
13711           fixp = fixp->fx_next;
13712         }
13713
13714       /* Go through the fixups for the second sequence.  Disable them if
13715          we're going to use the first sequence, otherwise adjust their
13716          addresses to account for the relaxation.  */
13717       while (fixp && fixp->fx_frag == fragp)
13718         {
13719           if (fragp->fr_subtype & RELAX_USE_SECOND)
13720             fixp->fx_where -= first;
13721           else
13722             fixp->fx_done = 1;
13723           fixp = fixp->fx_next;
13724         }
13725
13726       /* Now modify the frag contents.  */
13727       if (fragp->fr_subtype & RELAX_USE_SECOND)
13728         {
13729           char *start;
13730
13731           start = fragp->fr_literal + fragp->fr_fix - first - second;
13732           memmove (start, start + first, second);
13733           fragp->fr_fix -= first;
13734         }
13735       else
13736         fragp->fr_fix -= second;
13737     }
13738 }
13739
13740 #ifdef OBJ_ELF
13741
13742 /* This function is called after the relocs have been generated.
13743    We've been storing mips16 text labels as odd.  Here we convert them
13744    back to even for the convenience of the debugger.  */
13745
13746 void
13747 mips_frob_file_after_relocs (void)
13748 {
13749   asymbol **syms;
13750   unsigned int count, i;
13751
13752   if (OUTPUT_FLAVOR != bfd_target_elf_flavour)
13753     return;
13754
13755   syms = bfd_get_outsymbols (stdoutput);
13756   count = bfd_get_symcount (stdoutput);
13757   for (i = 0; i < count; i++, syms++)
13758     {
13759       if (elf_symbol (*syms)->internal_elf_sym.st_other == STO_MIPS16
13760           && ((*syms)->value & 1) != 0)
13761         {
13762           (*syms)->value &= ~1;
13763           /* If the symbol has an odd size, it was probably computed
13764              incorrectly, so adjust that as well.  */
13765           if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
13766             ++elf_symbol (*syms)->internal_elf_sym.st_size;
13767         }
13768     }
13769 }
13770
13771 #endif
13772
13773 /* This function is called whenever a label is defined.  It is used
13774    when handling branch delays; if a branch has a label, we assume we
13775    can not move it.  */
13776
13777 void
13778 mips_define_label (symbolS *sym)
13779 {
13780   struct insn_label_list *l;
13781
13782   if (free_insn_labels == NULL)
13783     l = (struct insn_label_list *) xmalloc (sizeof *l);
13784   else
13785     {
13786       l = free_insn_labels;
13787       free_insn_labels = l->next;
13788     }
13789
13790   l->label = sym;
13791   l->next = insn_labels;
13792   insn_labels = l;
13793
13794 #ifdef OBJ_ELF
13795   dwarf2_emit_label (sym);
13796 #endif
13797 }
13798 \f
13799 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
13800
13801 /* Some special processing for a MIPS ELF file.  */
13802
13803 void
13804 mips_elf_final_processing (void)
13805 {
13806   /* Write out the register information.  */
13807   if (mips_abi != N64_ABI)
13808     {
13809       Elf32_RegInfo s;
13810
13811       s.ri_gprmask = mips_gprmask;
13812       s.ri_cprmask[0] = mips_cprmask[0];
13813       s.ri_cprmask[1] = mips_cprmask[1];
13814       s.ri_cprmask[2] = mips_cprmask[2];
13815       s.ri_cprmask[3] = mips_cprmask[3];
13816       /* The gp_value field is set by the MIPS ELF backend.  */
13817
13818       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
13819                                        ((Elf32_External_RegInfo *)
13820                                         mips_regmask_frag));
13821     }
13822   else
13823     {
13824       Elf64_Internal_RegInfo s;
13825
13826       s.ri_gprmask = mips_gprmask;
13827       s.ri_pad = 0;
13828       s.ri_cprmask[0] = mips_cprmask[0];
13829       s.ri_cprmask[1] = mips_cprmask[1];
13830       s.ri_cprmask[2] = mips_cprmask[2];
13831       s.ri_cprmask[3] = mips_cprmask[3];
13832       /* The gp_value field is set by the MIPS ELF backend.  */
13833
13834       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
13835                                        ((Elf64_External_RegInfo *)
13836                                         mips_regmask_frag));
13837     }
13838
13839   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
13840      sort of BFD interface for this.  */
13841   if (mips_any_noreorder)
13842     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
13843   if (mips_pic != NO_PIC)
13844     {
13845     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
13846       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
13847     }
13848   if (mips_abicalls)
13849     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
13850
13851   /* Set MIPS ELF flags for ASEs.  */
13852   /* We may need to define a new flag for DSP ASE, and set this flag when
13853      file_ase_dsp is true.  */
13854   /* We may need to define a new flag for MT ASE, and set this flag when
13855      file_ase_mt is true.  */
13856   if (file_ase_mips16)
13857     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
13858 #if 0 /* XXX FIXME */
13859   if (file_ase_mips3d)
13860     elf_elfheader (stdoutput)->e_flags |= ???;
13861 #endif
13862   if (file_ase_mdmx)
13863     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
13864
13865   /* Set the MIPS ELF ABI flags.  */
13866   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
13867     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
13868   else if (mips_abi == O64_ABI)
13869     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
13870   else if (mips_abi == EABI_ABI)
13871     {
13872       if (!file_mips_gp32)
13873         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
13874       else
13875         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
13876     }
13877   else if (mips_abi == N32_ABI)
13878     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
13879
13880   /* Nothing to do for N64_ABI.  */
13881
13882   if (mips_32bitmode)
13883     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
13884 }
13885
13886 #endif /* OBJ_ELF || OBJ_MAYBE_ELF */
13887 \f
13888 typedef struct proc {
13889   symbolS *func_sym;
13890   symbolS *func_end_sym;
13891   unsigned long reg_mask;
13892   unsigned long reg_offset;
13893   unsigned long fpreg_mask;
13894   unsigned long fpreg_offset;
13895   unsigned long frame_offset;
13896   unsigned long frame_reg;
13897   unsigned long pc_reg;
13898 } procS;
13899
13900 static procS cur_proc;
13901 static procS *cur_proc_ptr;
13902 static int numprocs;
13903
13904 /* Fill in an rs_align_code fragment.  */
13905
13906 void
13907 mips_handle_align (fragS *fragp)
13908 {
13909   if (fragp->fr_type != rs_align_code)
13910     return;
13911
13912   if (mips_opts.mips16)
13913     {
13914       static const unsigned char be_nop[] = { 0x65, 0x00 };
13915       static const unsigned char le_nop[] = { 0x00, 0x65 };
13916
13917       int bytes;
13918       char *p;
13919
13920       bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
13921       p = fragp->fr_literal + fragp->fr_fix;
13922
13923       if (bytes & 1)
13924         {
13925           *p++ = 0;
13926           fragp->fr_fix++;
13927         }
13928
13929       memcpy (p, (target_big_endian ? be_nop : le_nop), 2);
13930       fragp->fr_var = 2;
13931     }
13932
13933   /* For mips32, a nop is a zero, which we trivially get by doing nothing.  */
13934 }
13935
13936 static void
13937 md_obj_begin (void)
13938 {
13939 }
13940
13941 static void
13942 md_obj_end (void)
13943 {
13944   /* check for premature end, nesting errors, etc */
13945   if (cur_proc_ptr)
13946     as_warn (_("missing .end at end of assembly"));
13947 }
13948
13949 static long
13950 get_number (void)
13951 {
13952   int negative = 0;
13953   long val = 0;
13954
13955   if (*input_line_pointer == '-')
13956     {
13957       ++input_line_pointer;
13958       negative = 1;
13959     }
13960   if (!ISDIGIT (*input_line_pointer))
13961     as_bad (_("expected simple number"));
13962   if (input_line_pointer[0] == '0')
13963     {
13964       if (input_line_pointer[1] == 'x')
13965         {
13966           input_line_pointer += 2;
13967           while (ISXDIGIT (*input_line_pointer))
13968             {
13969               val <<= 4;
13970               val |= hex_value (*input_line_pointer++);
13971             }
13972           return negative ? -val : val;
13973         }
13974       else
13975         {
13976           ++input_line_pointer;
13977           while (ISDIGIT (*input_line_pointer))
13978             {
13979               val <<= 3;
13980               val |= *input_line_pointer++ - '0';
13981             }
13982           return negative ? -val : val;
13983         }
13984     }
13985   if (!ISDIGIT (*input_line_pointer))
13986     {
13987       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
13988               *input_line_pointer, *input_line_pointer);
13989       as_warn (_("invalid number"));
13990       return -1;
13991     }
13992   while (ISDIGIT (*input_line_pointer))
13993     {
13994       val *= 10;
13995       val += *input_line_pointer++ - '0';
13996     }
13997   return negative ? -val : val;
13998 }
13999
14000 /* The .file directive; just like the usual .file directive, but there
14001    is an initial number which is the ECOFF file index.  In the non-ECOFF
14002    case .file implies DWARF-2.  */
14003
14004 static void
14005 s_mips_file (int x ATTRIBUTE_UNUSED)
14006 {
14007   static int first_file_directive = 0;
14008
14009   if (ECOFF_DEBUGGING)
14010     {
14011       get_number ();
14012       s_app_file (0);
14013     }
14014   else
14015     {
14016       char *filename;
14017
14018       filename = dwarf2_directive_file (0);
14019
14020       /* Versions of GCC up to 3.1 start files with a ".file"
14021          directive even for stabs output.  Make sure that this
14022          ".file" is handled.  Note that you need a version of GCC
14023          after 3.1 in order to support DWARF-2 on MIPS.  */
14024       if (filename != NULL && ! first_file_directive)
14025         {
14026           (void) new_logical_line (filename, -1);
14027           s_app_file_string (filename, 0);
14028         }
14029       first_file_directive = 1;
14030     }
14031 }
14032
14033 /* The .loc directive, implying DWARF-2.  */
14034
14035 static void
14036 s_mips_loc (int x ATTRIBUTE_UNUSED)
14037 {
14038   if (!ECOFF_DEBUGGING)
14039     dwarf2_directive_loc (0);
14040 }
14041
14042 /* The .end directive.  */
14043
14044 static void
14045 s_mips_end (int x ATTRIBUTE_UNUSED)
14046 {
14047   symbolS *p;
14048
14049   /* Following functions need their own .frame and .cprestore directives.  */
14050   mips_frame_reg_valid = 0;
14051   mips_cprestore_valid = 0;
14052
14053   if (!is_end_of_line[(unsigned char) *input_line_pointer])
14054     {
14055       p = get_symbol ();
14056       demand_empty_rest_of_line ();
14057     }
14058   else
14059     p = NULL;
14060
14061   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
14062     as_warn (_(".end not in text section"));
14063
14064   if (!cur_proc_ptr)
14065     {
14066       as_warn (_(".end directive without a preceding .ent directive."));
14067       demand_empty_rest_of_line ();
14068       return;
14069     }
14070
14071   if (p != NULL)
14072     {
14073       assert (S_GET_NAME (p));
14074       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
14075         as_warn (_(".end symbol does not match .ent symbol."));
14076
14077       if (debug_type == DEBUG_STABS)
14078         stabs_generate_asm_endfunc (S_GET_NAME (p),
14079                                     S_GET_NAME (p));
14080     }
14081   else
14082     as_warn (_(".end directive missing or unknown symbol"));
14083
14084 #ifdef OBJ_ELF
14085   /* Create an expression to calculate the size of the function.  */
14086   if (p && cur_proc_ptr)
14087     {
14088       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
14089       expressionS *exp = xmalloc (sizeof (expressionS));
14090
14091       obj->size = exp;
14092       exp->X_op = O_subtract;
14093       exp->X_add_symbol = symbol_temp_new_now ();
14094       exp->X_op_symbol = p;
14095       exp->X_add_number = 0;
14096
14097       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
14098     }
14099
14100   /* Generate a .pdr section.  */
14101   if (OUTPUT_FLAVOR == bfd_target_elf_flavour && ! ECOFF_DEBUGGING
14102       && mips_flag_pdr)
14103     {
14104       segT saved_seg = now_seg;
14105       subsegT saved_subseg = now_subseg;
14106       valueT dot;
14107       expressionS exp;
14108       char *fragp;
14109
14110       dot = frag_now_fix ();
14111
14112 #ifdef md_flush_pending_output
14113       md_flush_pending_output ();
14114 #endif
14115
14116       assert (pdr_seg);
14117       subseg_set (pdr_seg, 0);
14118
14119       /* Write the symbol.  */
14120       exp.X_op = O_symbol;
14121       exp.X_add_symbol = p;
14122       exp.X_add_number = 0;
14123       emit_expr (&exp, 4);
14124
14125       fragp = frag_more (7 * 4);
14126
14127       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
14128       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
14129       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
14130       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
14131       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
14132       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
14133       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
14134
14135       subseg_set (saved_seg, saved_subseg);
14136     }
14137 #endif /* OBJ_ELF */
14138
14139   cur_proc_ptr = NULL;
14140 }
14141
14142 /* The .aent and .ent directives.  */
14143
14144 static void
14145 s_mips_ent (int aent)
14146 {
14147   symbolS *symbolP;
14148
14149   symbolP = get_symbol ();
14150   if (*input_line_pointer == ',')
14151     ++input_line_pointer;
14152   SKIP_WHITESPACE ();
14153   if (ISDIGIT (*input_line_pointer)
14154       || *input_line_pointer == '-')
14155     get_number ();
14156
14157   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
14158     as_warn (_(".ent or .aent not in text section."));
14159
14160   if (!aent && cur_proc_ptr)
14161     as_warn (_("missing .end"));
14162
14163   if (!aent)
14164     {
14165       /* This function needs its own .frame and .cprestore directives.  */
14166       mips_frame_reg_valid = 0;
14167       mips_cprestore_valid = 0;
14168
14169       cur_proc_ptr = &cur_proc;
14170       memset (cur_proc_ptr, '\0', sizeof (procS));
14171
14172       cur_proc_ptr->func_sym = symbolP;
14173
14174       symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
14175
14176       ++numprocs;
14177
14178       if (debug_type == DEBUG_STABS)
14179         stabs_generate_asm_func (S_GET_NAME (symbolP),
14180                                  S_GET_NAME (symbolP));
14181     }
14182
14183   demand_empty_rest_of_line ();
14184 }
14185
14186 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
14187    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
14188    s_mips_frame is used so that we can set the PDR information correctly.
14189    We can't use the ecoff routines because they make reference to the ecoff
14190    symbol table (in the mdebug section).  */
14191
14192 static void
14193 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
14194 {
14195 #ifdef OBJ_ELF
14196   if (OUTPUT_FLAVOR == bfd_target_elf_flavour && ! ECOFF_DEBUGGING)
14197     {
14198       long val;
14199
14200       if (cur_proc_ptr == (procS *) NULL)
14201         {
14202           as_warn (_(".frame outside of .ent"));
14203           demand_empty_rest_of_line ();
14204           return;
14205         }
14206
14207       cur_proc_ptr->frame_reg = tc_get_register (1);
14208
14209       SKIP_WHITESPACE ();
14210       if (*input_line_pointer++ != ','
14211           || get_absolute_expression_and_terminator (&val) != ',')
14212         {
14213           as_warn (_("Bad .frame directive"));
14214           --input_line_pointer;
14215           demand_empty_rest_of_line ();
14216           return;
14217         }
14218
14219       cur_proc_ptr->frame_offset = val;
14220       cur_proc_ptr->pc_reg = tc_get_register (0);
14221
14222       demand_empty_rest_of_line ();
14223     }
14224   else
14225 #endif /* OBJ_ELF */
14226     s_ignore (ignore);
14227 }
14228
14229 /* The .fmask and .mask directives. If the mdebug section is present
14230    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
14231    embedded targets, s_mips_mask is used so that we can set the PDR
14232    information correctly. We can't use the ecoff routines because they
14233    make reference to the ecoff symbol table (in the mdebug section).  */
14234
14235 static void
14236 s_mips_mask (int reg_type)
14237 {
14238 #ifdef OBJ_ELF
14239   if (OUTPUT_FLAVOR == bfd_target_elf_flavour && ! ECOFF_DEBUGGING)
14240     {
14241       long mask, off;
14242
14243       if (cur_proc_ptr == (procS *) NULL)
14244         {
14245           as_warn (_(".mask/.fmask outside of .ent"));
14246           demand_empty_rest_of_line ();
14247           return;
14248         }
14249
14250       if (get_absolute_expression_and_terminator (&mask) != ',')
14251         {
14252           as_warn (_("Bad .mask/.fmask directive"));
14253           --input_line_pointer;
14254           demand_empty_rest_of_line ();
14255           return;
14256         }
14257
14258       off = get_absolute_expression ();
14259
14260       if (reg_type == 'F')
14261         {
14262           cur_proc_ptr->fpreg_mask = mask;
14263           cur_proc_ptr->fpreg_offset = off;
14264         }
14265       else
14266         {
14267           cur_proc_ptr->reg_mask = mask;
14268           cur_proc_ptr->reg_offset = off;
14269         }
14270
14271       demand_empty_rest_of_line ();
14272     }
14273   else
14274 #endif /* OBJ_ELF */
14275     s_ignore (reg_type);
14276 }
14277
14278 /* A table describing all the processors gas knows about.  Names are
14279    matched in the order listed.
14280
14281    To ease comparison, please keep this table in the same order as
14282    gcc's mips_cpu_info_table[].  */
14283 static const struct mips_cpu_info mips_cpu_info_table[] =
14284 {
14285   /* Entries for generic ISAs */
14286   { "mips1",          1,      ISA_MIPS1,      CPU_R3000 },
14287   { "mips2",          1,      ISA_MIPS2,      CPU_R6000 },
14288   { "mips3",          1,      ISA_MIPS3,      CPU_R4000 },
14289   { "mips4",          1,      ISA_MIPS4,      CPU_R8000 },
14290   { "mips5",          1,      ISA_MIPS5,      CPU_MIPS5 },
14291   { "mips32",         1,      ISA_MIPS32,     CPU_MIPS32 },
14292   { "mips32r2",       1,      ISA_MIPS32R2,   CPU_MIPS32R2 },
14293   { "mips64",         1,      ISA_MIPS64,     CPU_MIPS64 },
14294   { "mips64r2",       1,      ISA_MIPS64R2,   CPU_MIPS64R2 },
14295
14296   /* MIPS I */
14297   { "r3000",          0,      ISA_MIPS1,      CPU_R3000 },
14298   { "r2000",          0,      ISA_MIPS1,      CPU_R3000 },
14299   { "r3900",          0,      ISA_MIPS1,      CPU_R3900 },
14300
14301   /* MIPS II */
14302   { "r6000",          0,      ISA_MIPS2,      CPU_R6000 },
14303
14304   /* MIPS III */
14305   { "r4000",          0,      ISA_MIPS3,      CPU_R4000 },
14306   { "r4010",          0,      ISA_MIPS2,      CPU_R4010 },
14307   { "vr4100",         0,      ISA_MIPS3,      CPU_VR4100 },
14308   { "vr4111",         0,      ISA_MIPS3,      CPU_R4111 },
14309   { "vr4120",         0,      ISA_MIPS3,      CPU_VR4120 },
14310   { "vr4130",         0,      ISA_MIPS3,      CPU_VR4120 },
14311   { "vr4181",         0,      ISA_MIPS3,      CPU_R4111 },
14312   { "vr4300",         0,      ISA_MIPS3,      CPU_R4300 },
14313   { "r4400",          0,      ISA_MIPS3,      CPU_R4400 },
14314   { "r4600",          0,      ISA_MIPS3,      CPU_R4600 },
14315   { "orion",          0,      ISA_MIPS3,      CPU_R4600 },
14316   { "r4650",          0,      ISA_MIPS3,      CPU_R4650 },
14317
14318   /* MIPS IV */
14319   { "r8000",          0,      ISA_MIPS4,      CPU_R8000 },
14320   { "r10000",         0,      ISA_MIPS4,      CPU_R10000 },
14321   { "r12000",         0,      ISA_MIPS4,      CPU_R12000 },
14322   { "vr5000",         0,      ISA_MIPS4,      CPU_R5000 },
14323   { "vr5400",         0,      ISA_MIPS4,      CPU_VR5400 },
14324   { "vr5500",         0,      ISA_MIPS4,      CPU_VR5500 },
14325   { "rm5200",         0,      ISA_MIPS4,      CPU_R5000 },
14326   { "rm5230",         0,      ISA_MIPS4,      CPU_R5000 },
14327   { "rm5231",         0,      ISA_MIPS4,      CPU_R5000 },
14328   { "rm5261",         0,      ISA_MIPS4,      CPU_R5000 },
14329   { "rm5721",         0,      ISA_MIPS4,      CPU_R5000 },
14330   { "rm7000",         0,      ISA_MIPS4,      CPU_RM7000 },
14331   { "rm9000",         0,      ISA_MIPS4,      CPU_RM9000 },
14332
14333   /* MIPS 32 */
14334   { "4kc",            0,      ISA_MIPS32,     CPU_MIPS32 },
14335   { "4km",            0,      ISA_MIPS32,     CPU_MIPS32 },
14336   { "4kp",            0,      ISA_MIPS32,     CPU_MIPS32 },
14337
14338   /* MIPS32 Release 2 */
14339   { "m4k",            0,      ISA_MIPS32R2,   CPU_MIPS32R2 },
14340   { "24k",            0,      ISA_MIPS32R2,   CPU_MIPS32R2 },
14341   { "24kc",           0,      ISA_MIPS32R2,   CPU_MIPS32R2 },
14342   { "24kf",           0,      ISA_MIPS32R2,   CPU_MIPS32R2 },
14343   { "24kx",           0,      ISA_MIPS32R2,   CPU_MIPS32R2 },
14344
14345   /* MIPS 64 */
14346   { "5kc",            0,      ISA_MIPS64,     CPU_MIPS64 },
14347   { "5kf",            0,      ISA_MIPS64,     CPU_MIPS64 },
14348   { "20kc",           0,      ISA_MIPS64,     CPU_MIPS64 },
14349
14350   /* Broadcom SB-1 CPU core */
14351   { "sb1",            0,      ISA_MIPS64,     CPU_SB1 },
14352
14353   /* End marker */
14354   { NULL, 0, 0, 0 }
14355 };
14356
14357
14358 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
14359    with a final "000" replaced by "k".  Ignore case.
14360
14361    Note: this function is shared between GCC and GAS.  */
14362
14363 static bfd_boolean
14364 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
14365 {
14366   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
14367     given++, canonical++;
14368
14369   return ((*given == 0 && *canonical == 0)
14370           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
14371 }
14372
14373
14374 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
14375    CPU name.  We've traditionally allowed a lot of variation here.
14376
14377    Note: this function is shared between GCC and GAS.  */
14378
14379 static bfd_boolean
14380 mips_matching_cpu_name_p (const char *canonical, const char *given)
14381 {
14382   /* First see if the name matches exactly, or with a final "000"
14383      turned into "k".  */
14384   if (mips_strict_matching_cpu_name_p (canonical, given))
14385     return TRUE;
14386
14387   /* If not, try comparing based on numerical designation alone.
14388      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
14389   if (TOLOWER (*given) == 'r')
14390     given++;
14391   if (!ISDIGIT (*given))
14392     return FALSE;
14393
14394   /* Skip over some well-known prefixes in the canonical name,
14395      hoping to find a number there too.  */
14396   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
14397     canonical += 2;
14398   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
14399     canonical += 2;
14400   else if (TOLOWER (canonical[0]) == 'r')
14401     canonical += 1;
14402
14403   return mips_strict_matching_cpu_name_p (canonical, given);
14404 }
14405
14406
14407 /* Parse an option that takes the name of a processor as its argument.
14408    OPTION is the name of the option and CPU_STRING is the argument.
14409    Return the corresponding processor enumeration if the CPU_STRING is
14410    recognized, otherwise report an error and return null.
14411
14412    A similar function exists in GCC.  */
14413
14414 static const struct mips_cpu_info *
14415 mips_parse_cpu (const char *option, const char *cpu_string)
14416 {
14417   const struct mips_cpu_info *p;
14418
14419   /* 'from-abi' selects the most compatible architecture for the given
14420      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
14421      EABIs, we have to decide whether we're using the 32-bit or 64-bit
14422      version.  Look first at the -mgp options, if given, otherwise base
14423      the choice on MIPS_DEFAULT_64BIT.
14424
14425      Treat NO_ABI like the EABIs.  One reason to do this is that the
14426      plain 'mips' and 'mips64' configs have 'from-abi' as their default
14427      architecture.  This code picks MIPS I for 'mips' and MIPS III for
14428      'mips64', just as we did in the days before 'from-abi'.  */
14429   if (strcasecmp (cpu_string, "from-abi") == 0)
14430     {
14431       if (ABI_NEEDS_32BIT_REGS (mips_abi))
14432         return mips_cpu_info_from_isa (ISA_MIPS1);
14433
14434       if (ABI_NEEDS_64BIT_REGS (mips_abi))
14435         return mips_cpu_info_from_isa (ISA_MIPS3);
14436
14437       if (file_mips_gp32 >= 0)
14438         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
14439
14440       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
14441                                      ? ISA_MIPS3
14442                                      : ISA_MIPS1);
14443     }
14444
14445   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
14446   if (strcasecmp (cpu_string, "default") == 0)
14447     return 0;
14448
14449   for (p = mips_cpu_info_table; p->name != 0; p++)
14450     if (mips_matching_cpu_name_p (p->name, cpu_string))
14451       return p;
14452
14453   as_bad ("Bad value (%s) for %s", cpu_string, option);
14454   return 0;
14455 }
14456
14457 /* Return the canonical processor information for ISA (a member of the
14458    ISA_MIPS* enumeration).  */
14459
14460 static const struct mips_cpu_info *
14461 mips_cpu_info_from_isa (int isa)
14462 {
14463   int i;
14464
14465   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
14466     if (mips_cpu_info_table[i].is_isa
14467         && isa == mips_cpu_info_table[i].isa)
14468       return (&mips_cpu_info_table[i]);
14469
14470   return NULL;
14471 }
14472
14473 static const struct mips_cpu_info *
14474 mips_cpu_info_from_arch (int arch)
14475 {
14476   int i;
14477
14478   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
14479     if (arch == mips_cpu_info_table[i].cpu)
14480       return (&mips_cpu_info_table[i]);
14481
14482   return NULL;
14483 }
14484 \f
14485 static void
14486 show (FILE *stream, const char *string, int *col_p, int *first_p)
14487 {
14488   if (*first_p)
14489     {
14490       fprintf (stream, "%24s", "");
14491       *col_p = 24;
14492     }
14493   else
14494     {
14495       fprintf (stream, ", ");
14496       *col_p += 2;
14497     }
14498
14499   if (*col_p + strlen (string) > 72)
14500     {
14501       fprintf (stream, "\n%24s", "");
14502       *col_p = 24;
14503     }
14504
14505   fprintf (stream, "%s", string);
14506   *col_p += strlen (string);
14507
14508   *first_p = 0;
14509 }
14510
14511 void
14512 md_show_usage (FILE *stream)
14513 {
14514   int column, first;
14515   size_t i;
14516
14517   fprintf (stream, _("\
14518 MIPS options:\n\
14519 -EB                     generate big endian output\n\
14520 -EL                     generate little endian output\n\
14521 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
14522 -G NUM                  allow referencing objects up to NUM bytes\n\
14523                         implicitly with the gp register [default 8]\n"));
14524   fprintf (stream, _("\
14525 -mips1                  generate MIPS ISA I instructions\n\
14526 -mips2                  generate MIPS ISA II instructions\n\
14527 -mips3                  generate MIPS ISA III instructions\n\
14528 -mips4                  generate MIPS ISA IV instructions\n\
14529 -mips5                  generate MIPS ISA V instructions\n\
14530 -mips32                 generate MIPS32 ISA instructions\n\
14531 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
14532 -mips64                 generate MIPS64 ISA instructions\n\
14533 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
14534 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
14535
14536   first = 1;
14537
14538   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
14539     show (stream, mips_cpu_info_table[i].name, &column, &first);
14540   show (stream, "from-abi", &column, &first);
14541   fputc ('\n', stream);
14542
14543   fprintf (stream, _("\
14544 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
14545 -no-mCPU                don't generate code specific to CPU.\n\
14546                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
14547
14548   first = 1;
14549
14550   show (stream, "3900", &column, &first);
14551   show (stream, "4010", &column, &first);
14552   show (stream, "4100", &column, &first);
14553   show (stream, "4650", &column, &first);
14554   fputc ('\n', stream);
14555
14556   fprintf (stream, _("\
14557 -mips16                 generate mips16 instructions\n\
14558 -no-mips16              do not generate mips16 instructions\n"));
14559   fprintf (stream, _("\
14560 -mdsp                   generate DSP instructions\n\
14561 -mno-dsp                do not generate DSP instructions\n"));
14562   fprintf (stream, _("\
14563 -mmt                    generate MT instructions\n\
14564 -mno-mt                 do not generate MT instructions\n"));
14565   fprintf (stream, _("\
14566 -mfix-vr4120            work around certain VR4120 errata\n\
14567 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
14568 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
14569 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
14570 -mno-shared             optimize output for executables\n\
14571 -msym32                 assume all symbols have 32-bit values\n\
14572 -O0                     remove unneeded NOPs, do not swap branches\n\
14573 -O                      remove unneeded NOPs and swap branches\n\
14574 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
14575 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
14576 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
14577 #ifdef OBJ_ELF
14578   fprintf (stream, _("\
14579 -KPIC, -call_shared     generate SVR4 position independent code\n\
14580 -non_shared             do not generate position independent code\n\
14581 -xgot                   assume a 32 bit GOT\n\
14582 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
14583 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
14584                         non-shared code\n\
14585 -mabi=ABI               create ABI conformant object file for:\n"));
14586
14587   first = 1;
14588
14589   show (stream, "32", &column, &first);
14590   show (stream, "o64", &column, &first);
14591   show (stream, "n32", &column, &first);
14592   show (stream, "64", &column, &first);
14593   show (stream, "eabi", &column, &first);
14594
14595   fputc ('\n', stream);
14596
14597   fprintf (stream, _("\
14598 -32                     create o32 ABI object file (default)\n\
14599 -n32                    create n32 ABI object file\n\
14600 -64                     create 64 ABI object file\n"));
14601 #endif
14602 }
14603
14604 enum dwarf2_format
14605 mips_dwarf2_format (void)
14606 {
14607   if (mips_abi == N64_ABI)
14608     {
14609 #ifdef TE_IRIX
14610       return dwarf2_format_64bit_irix;
14611 #else
14612       return dwarf2_format_64bit;
14613 #endif
14614     }
14615   else
14616     return dwarf2_format_32bit;
14617 }
14618
14619 int
14620 mips_dwarf2_addr_size (void)
14621 {
14622   if (mips_abi == N64_ABI)
14623     return 8;
14624   else
14625     return 4;
14626 }
14627
14628 /* Standard calling conventions leave the CFA at SP on entry.  */
14629 void
14630 mips_cfi_frame_initial_instructions (void)
14631 {
14632   cfi_add_CFA_def_cfa_register (SP);
14633 }
14634