MIPS: Keep the ISA bit in compressed code addresses
[external/binutils.git] / gdb / mips-tdep.c
1 /* Target-dependent code for the MIPS architecture, for GDB, the GNU Debugger.
2
3    Copyright (C) 1988-2014 Free Software Foundation, Inc.
4
5    Contributed by Alessandro Forin(af@cs.cmu.edu) at CMU
6    and by Per Bothner(bothner@cs.wisc.edu) at U.Wisconsin.
7
8    This file is part of GDB.
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
22
23 #include "defs.h"
24 #include "frame.h"
25 #include "inferior.h"
26 #include "symtab.h"
27 #include "value.h"
28 #include "gdbcmd.h"
29 #include "language.h"
30 #include "gdbcore.h"
31 #include "symfile.h"
32 #include "objfiles.h"
33 #include "gdbtypes.h"
34 #include "target.h"
35 #include "arch-utils.h"
36 #include "regcache.h"
37 #include "osabi.h"
38 #include "mips-tdep.h"
39 #include "block.h"
40 #include "reggroups.h"
41 #include "opcode/mips.h"
42 #include "elf/mips.h"
43 #include "elf-bfd.h"
44 #include "symcat.h"
45 #include "sim-regno.h"
46 #include "dis-asm.h"
47 #include "frame-unwind.h"
48 #include "frame-base.h"
49 #include "trad-frame.h"
50 #include "infcall.h"
51 #include "floatformat.h"
52 #include "remote.h"
53 #include "target-descriptions.h"
54 #include "dwarf2-frame.h"
55 #include "user-regs.h"
56 #include "valprint.h"
57 #include "ax.h"
58
59 static const struct objfile_data *mips_pdr_data;
60
61 static struct type *mips_register_type (struct gdbarch *gdbarch, int regnum);
62
63 static int mips32_instruction_has_delay_slot (struct gdbarch *gdbarch,
64                                               ULONGEST inst);
65 static int micromips_instruction_has_delay_slot (ULONGEST insn, int mustbe32);
66 static int mips16_instruction_has_delay_slot (unsigned short inst,
67                                               int mustbe32);
68
69 static int mips32_insn_at_pc_has_delay_slot (struct gdbarch *gdbarch,
70                                              CORE_ADDR addr);
71 static int micromips_insn_at_pc_has_delay_slot (struct gdbarch *gdbarch,
72                                                 CORE_ADDR addr, int mustbe32);
73 static int mips16_insn_at_pc_has_delay_slot (struct gdbarch *gdbarch,
74                                              CORE_ADDR addr, int mustbe32);
75
76 /* A useful bit in the CP0 status register (MIPS_PS_REGNUM).  */
77 /* This bit is set if we are emulating 32-bit FPRs on a 64-bit chip.  */
78 #define ST0_FR (1 << 26)
79
80 /* The sizes of floating point registers.  */
81
82 enum
83 {
84   MIPS_FPU_SINGLE_REGSIZE = 4,
85   MIPS_FPU_DOUBLE_REGSIZE = 8
86 };
87
88 enum
89 {
90   MIPS32_REGSIZE = 4,
91   MIPS64_REGSIZE = 8
92 };
93
94 static const char *mips_abi_string;
95
96 static const char *const mips_abi_strings[] = {
97   "auto",
98   "n32",
99   "o32",
100   "n64",
101   "o64",
102   "eabi32",
103   "eabi64",
104   NULL
105 };
106
107 /* For backwards compatibility we default to MIPS16.  This flag is
108    overridden as soon as unambiguous ELF file flags tell us the
109    compressed ISA encoding used.  */
110 static const char mips_compression_mips16[] = "mips16";
111 static const char mips_compression_micromips[] = "micromips";
112 static const char *const mips_compression_strings[] =
113 {
114   mips_compression_mips16,
115   mips_compression_micromips,
116   NULL
117 };
118
119 static const char *mips_compression_string = mips_compression_mips16;
120
121 /* The standard register names, and all the valid aliases for them.  */
122 struct register_alias
123 {
124   const char *name;
125   int regnum;
126 };
127
128 /* Aliases for o32 and most other ABIs.  */
129 const struct register_alias mips_o32_aliases[] = {
130   { "ta0", 12 },
131   { "ta1", 13 },
132   { "ta2", 14 },
133   { "ta3", 15 }
134 };
135
136 /* Aliases for n32 and n64.  */
137 const struct register_alias mips_n32_n64_aliases[] = {
138   { "ta0", 8 },
139   { "ta1", 9 },
140   { "ta2", 10 },
141   { "ta3", 11 }
142 };
143
144 /* Aliases for ABI-independent registers.  */
145 const struct register_alias mips_register_aliases[] = {
146   /* The architecture manuals specify these ABI-independent names for
147      the GPRs.  */
148 #define R(n) { "r" #n, n }
149   R(0), R(1), R(2), R(3), R(4), R(5), R(6), R(7),
150   R(8), R(9), R(10), R(11), R(12), R(13), R(14), R(15),
151   R(16), R(17), R(18), R(19), R(20), R(21), R(22), R(23),
152   R(24), R(25), R(26), R(27), R(28), R(29), R(30), R(31),
153 #undef R
154
155   /* k0 and k1 are sometimes called these instead (for "kernel
156      temp").  */
157   { "kt0", 26 },
158   { "kt1", 27 },
159
160   /* This is the traditional GDB name for the CP0 status register.  */
161   { "sr", MIPS_PS_REGNUM },
162
163   /* This is the traditional GDB name for the CP0 BadVAddr register.  */
164   { "bad", MIPS_EMBED_BADVADDR_REGNUM },
165
166   /* This is the traditional GDB name for the FCSR.  */
167   { "fsr", MIPS_EMBED_FP0_REGNUM + 32 }
168 };
169
170 const struct register_alias mips_numeric_register_aliases[] = {
171 #define R(n) { #n, n }
172   R(0), R(1), R(2), R(3), R(4), R(5), R(6), R(7),
173   R(8), R(9), R(10), R(11), R(12), R(13), R(14), R(15),
174   R(16), R(17), R(18), R(19), R(20), R(21), R(22), R(23),
175   R(24), R(25), R(26), R(27), R(28), R(29), R(30), R(31),
176 #undef R
177 };
178
179 #ifndef MIPS_DEFAULT_FPU_TYPE
180 #define MIPS_DEFAULT_FPU_TYPE MIPS_FPU_DOUBLE
181 #endif
182 static int mips_fpu_type_auto = 1;
183 static enum mips_fpu_type mips_fpu_type = MIPS_DEFAULT_FPU_TYPE;
184
185 static unsigned int mips_debug = 0;
186
187 /* Properties (for struct target_desc) describing the g/G packet
188    layout.  */
189 #define PROPERTY_GP32 "internal: transfers-32bit-registers"
190 #define PROPERTY_GP64 "internal: transfers-64bit-registers"
191
192 struct target_desc *mips_tdesc_gp32;
193 struct target_desc *mips_tdesc_gp64;
194
195 const struct mips_regnum *
196 mips_regnum (struct gdbarch *gdbarch)
197 {
198   return gdbarch_tdep (gdbarch)->regnum;
199 }
200
201 static int
202 mips_fpa0_regnum (struct gdbarch *gdbarch)
203 {
204   return mips_regnum (gdbarch)->fp0 + 12;
205 }
206
207 /* Return 1 if REGNUM refers to a floating-point general register, raw
208    or cooked.  Otherwise return 0.  */
209
210 static int
211 mips_float_register_p (struct gdbarch *gdbarch, int regnum)
212 {
213   int rawnum = regnum % gdbarch_num_regs (gdbarch);
214
215   return (rawnum >= mips_regnum (gdbarch)->fp0
216           && rawnum < mips_regnum (gdbarch)->fp0 + 32);
217 }
218
219 #define MIPS_EABI(gdbarch) (gdbarch_tdep (gdbarch)->mips_abi \
220                      == MIPS_ABI_EABI32 \
221                    || gdbarch_tdep (gdbarch)->mips_abi == MIPS_ABI_EABI64)
222
223 #define MIPS_LAST_FP_ARG_REGNUM(gdbarch) \
224   (gdbarch_tdep (gdbarch)->mips_last_fp_arg_regnum)
225
226 #define MIPS_LAST_ARG_REGNUM(gdbarch) \
227   (gdbarch_tdep (gdbarch)->mips_last_arg_regnum)
228
229 #define MIPS_FPU_TYPE(gdbarch) (gdbarch_tdep (gdbarch)->mips_fpu_type)
230
231 /* Return the MIPS ABI associated with GDBARCH.  */
232 enum mips_abi
233 mips_abi (struct gdbarch *gdbarch)
234 {
235   return gdbarch_tdep (gdbarch)->mips_abi;
236 }
237
238 int
239 mips_isa_regsize (struct gdbarch *gdbarch)
240 {
241   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
242
243   /* If we know how big the registers are, use that size.  */
244   if (tdep->register_size_valid_p)
245     return tdep->register_size;
246
247   /* Fall back to the previous behavior.  */
248   return (gdbarch_bfd_arch_info (gdbarch)->bits_per_word
249           / gdbarch_bfd_arch_info (gdbarch)->bits_per_byte);
250 }
251
252 /* Return the currently configured (or set) saved register size.  */
253
254 unsigned int
255 mips_abi_regsize (struct gdbarch *gdbarch)
256 {
257   switch (mips_abi (gdbarch))
258     {
259     case MIPS_ABI_EABI32:
260     case MIPS_ABI_O32:
261       return 4;
262     case MIPS_ABI_N32:
263     case MIPS_ABI_N64:
264     case MIPS_ABI_O64:
265     case MIPS_ABI_EABI64:
266       return 8;
267     case MIPS_ABI_UNKNOWN:
268     case MIPS_ABI_LAST:
269     default:
270       internal_error (__FILE__, __LINE__, _("bad switch"));
271     }
272 }
273
274 /* MIPS16/microMIPS function addresses are odd (bit 0 is set).  Here
275    are some functions to handle addresses associated with compressed
276    code including but not limited to testing, setting, or clearing
277    bit 0 of such addresses.  */
278
279 /* Return one iff compressed code is the MIPS16 instruction set.  */
280
281 static int
282 is_mips16_isa (struct gdbarch *gdbarch)
283 {
284   return gdbarch_tdep (gdbarch)->mips_isa == ISA_MIPS16;
285 }
286
287 /* Return one iff compressed code is the microMIPS instruction set.  */
288
289 static int
290 is_micromips_isa (struct gdbarch *gdbarch)
291 {
292   return gdbarch_tdep (gdbarch)->mips_isa == ISA_MICROMIPS;
293 }
294
295 /* Return one iff ADDR denotes compressed code.  */
296
297 static int
298 is_compact_addr (CORE_ADDR addr)
299 {
300   return ((addr) & 1);
301 }
302
303 /* Return one iff ADDR denotes standard ISA code.  */
304
305 static int
306 is_mips_addr (CORE_ADDR addr)
307 {
308   return !is_compact_addr (addr);
309 }
310
311 /* Return one iff ADDR denotes MIPS16 code.  */
312
313 static int
314 is_mips16_addr (struct gdbarch *gdbarch, CORE_ADDR addr)
315 {
316   return is_compact_addr (addr) && is_mips16_isa (gdbarch);
317 }
318
319 /* Return one iff ADDR denotes microMIPS code.  */
320
321 static int
322 is_micromips_addr (struct gdbarch *gdbarch, CORE_ADDR addr)
323 {
324   return is_compact_addr (addr) && is_micromips_isa (gdbarch);
325 }
326
327 /* Strip the ISA (compression) bit off from ADDR.  */
328
329 static CORE_ADDR
330 unmake_compact_addr (CORE_ADDR addr)
331 {
332   return ((addr) & ~(CORE_ADDR) 1);
333 }
334
335 /* Add the ISA (compression) bit to ADDR.  */
336
337 static CORE_ADDR
338 make_compact_addr (CORE_ADDR addr)
339 {
340   return ((addr) | (CORE_ADDR) 1);
341 }
342
343 /* Extern version of unmake_compact_addr; we use a separate function
344    so that unmake_compact_addr can be inlined throughout this file.  */
345
346 CORE_ADDR
347 mips_unmake_compact_addr (CORE_ADDR addr)
348 {
349   return unmake_compact_addr (addr);
350 }
351
352 /* Functions for setting and testing a bit in a minimal symbol that
353    marks it as MIPS16 or microMIPS function.  The MSB of the minimal
354    symbol's "info" field is used for this purpose.
355
356    gdbarch_elf_make_msymbol_special tests whether an ELF symbol is
357    "special", i.e. refers to a MIPS16 or microMIPS function, and sets
358    one of the "special" bits in a minimal symbol to mark it accordingly.
359    The test checks an ELF-private flag that is valid for true function
360    symbols only; for synthetic symbols such as for PLT stubs that have
361    no ELF-private part at all the MIPS BFD backend arranges for this
362    information to be carried in the asymbol's udata field instead.
363
364    msymbol_is_mips16 and msymbol_is_micromips test the "special" bit
365    in a minimal symbol.  */
366
367 static void
368 mips_elf_make_msymbol_special (asymbol * sym, struct minimal_symbol *msym)
369 {
370   elf_symbol_type *elfsym = (elf_symbol_type *) sym;
371   unsigned char st_other;
372
373   if ((sym->flags & BSF_SYNTHETIC) == 0)
374     st_other = elfsym->internal_elf_sym.st_other;
375   else if ((sym->flags & BSF_FUNCTION) != 0)
376     st_other = sym->udata.i;
377   else
378     return;
379
380   if (ELF_ST_IS_MICROMIPS (st_other))
381     {
382       MSYMBOL_TARGET_FLAG_2 (msym) = 1;
383       SET_MSYMBOL_VALUE_ADDRESS (msym, MSYMBOL_VALUE_RAW_ADDRESS (msym) | 1);
384     }
385   else if (ELF_ST_IS_MIPS16 (st_other))
386     {
387       MSYMBOL_TARGET_FLAG_1 (msym) = 1;
388       SET_MSYMBOL_VALUE_ADDRESS (msym, MSYMBOL_VALUE_RAW_ADDRESS (msym) | 1);
389     }
390 }
391
392 /* Return one iff MSYM refers to standard ISA code.  */
393
394 static int
395 msymbol_is_mips (struct minimal_symbol *msym)
396 {
397   return !(MSYMBOL_TARGET_FLAG_1 (msym) | MSYMBOL_TARGET_FLAG_2 (msym));
398 }
399
400 /* Return one iff MSYM refers to MIPS16 code.  */
401
402 static int
403 msymbol_is_mips16 (struct minimal_symbol *msym)
404 {
405   return MSYMBOL_TARGET_FLAG_1 (msym);
406 }
407
408 /* Return one iff MSYM refers to microMIPS code.  */
409
410 static int
411 msymbol_is_micromips (struct minimal_symbol *msym)
412 {
413   return MSYMBOL_TARGET_FLAG_2 (msym);
414 }
415
416 /* Set the ISA bit in the main symbol too, complementing the corresponding
417    minimal symbol setting and reflecting the run-time value of the symbol.
418    The need for comes from the ISA bit having been cleared as code in
419    `_bfd_mips_elf_symbol_processing' separated it into the ELF symbol's
420    `st_other' STO_MIPS16 or STO_MICROMIPS annotation, making the values
421    of symbols referring to compressed code different in GDB to the values
422    used by actual code.  That in turn makes them evaluate incorrectly in
423    expressions, producing results different to what the same expressions
424    yield when compiled into the program being debugged.  */
425
426 static void
427 mips_make_symbol_special (struct symbol *sym, struct objfile *objfile)
428 {
429   if (SYMBOL_CLASS (sym) == LOC_BLOCK)
430     {
431       /* We are in symbol reading so it is OK to cast away constness.  */
432       struct block *block = (struct block *) SYMBOL_BLOCK_VALUE (sym);
433       CORE_ADDR compact_block_start;
434       struct bound_minimal_symbol msym;
435
436       compact_block_start = BLOCK_START (block) | 1;
437       msym = lookup_minimal_symbol_by_pc (compact_block_start);
438       if (msym.minsym && !msymbol_is_mips (msym.minsym))
439         {
440           BLOCK_START (block) = compact_block_start;
441         }
442     }
443 }
444
445 /* XFER a value from the big/little/left end of the register.
446    Depending on the size of the value it might occupy the entire
447    register or just part of it.  Make an allowance for this, aligning
448    things accordingly.  */
449
450 static void
451 mips_xfer_register (struct gdbarch *gdbarch, struct regcache *regcache,
452                     int reg_num, int length,
453                     enum bfd_endian endian, gdb_byte *in,
454                     const gdb_byte *out, int buf_offset)
455 {
456   int reg_offset = 0;
457
458   gdb_assert (reg_num >= gdbarch_num_regs (gdbarch));
459   /* Need to transfer the left or right part of the register, based on
460      the targets byte order.  */
461   switch (endian)
462     {
463     case BFD_ENDIAN_BIG:
464       reg_offset = register_size (gdbarch, reg_num) - length;
465       break;
466     case BFD_ENDIAN_LITTLE:
467       reg_offset = 0;
468       break;
469     case BFD_ENDIAN_UNKNOWN:    /* Indicates no alignment.  */
470       reg_offset = 0;
471       break;
472     default:
473       internal_error (__FILE__, __LINE__, _("bad switch"));
474     }
475   if (mips_debug)
476     fprintf_unfiltered (gdb_stderr,
477                         "xfer $%d, reg offset %d, buf offset %d, length %d, ",
478                         reg_num, reg_offset, buf_offset, length);
479   if (mips_debug && out != NULL)
480     {
481       int i;
482       fprintf_unfiltered (gdb_stdlog, "out ");
483       for (i = 0; i < length; i++)
484         fprintf_unfiltered (gdb_stdlog, "%02x", out[buf_offset + i]);
485     }
486   if (in != NULL)
487     regcache_cooked_read_part (regcache, reg_num, reg_offset, length,
488                                in + buf_offset);
489   if (out != NULL)
490     regcache_cooked_write_part (regcache, reg_num, reg_offset, length,
491                                 out + buf_offset);
492   if (mips_debug && in != NULL)
493     {
494       int i;
495       fprintf_unfiltered (gdb_stdlog, "in ");
496       for (i = 0; i < length; i++)
497         fprintf_unfiltered (gdb_stdlog, "%02x", in[buf_offset + i]);
498     }
499   if (mips_debug)
500     fprintf_unfiltered (gdb_stdlog, "\n");
501 }
502
503 /* Determine if a MIPS3 or later cpu is operating in MIPS{1,2} FPU
504    compatiblity mode.  A return value of 1 means that we have
505    physical 64-bit registers, but should treat them as 32-bit registers.  */
506
507 static int
508 mips2_fp_compat (struct frame_info *frame)
509 {
510   struct gdbarch *gdbarch = get_frame_arch (frame);
511   /* MIPS1 and MIPS2 have only 32 bit FPRs, and the FR bit is not
512      meaningful.  */
513   if (register_size (gdbarch, mips_regnum (gdbarch)->fp0) == 4)
514     return 0;
515
516 #if 0
517   /* FIXME drow 2002-03-10: This is disabled until we can do it consistently,
518      in all the places we deal with FP registers.  PR gdb/413.  */
519   /* Otherwise check the FR bit in the status register - it controls
520      the FP compatiblity mode.  If it is clear we are in compatibility
521      mode.  */
522   if ((get_frame_register_unsigned (frame, MIPS_PS_REGNUM) & ST0_FR) == 0)
523     return 1;
524 #endif
525
526   return 0;
527 }
528
529 #define VM_MIN_ADDRESS (CORE_ADDR)0x400000
530
531 static CORE_ADDR heuristic_proc_start (struct gdbarch *, CORE_ADDR);
532
533 static void reinit_frame_cache_sfunc (char *, int, struct cmd_list_element *);
534
535 /* The list of available "set mips " and "show mips " commands.  */
536
537 static struct cmd_list_element *setmipscmdlist = NULL;
538 static struct cmd_list_element *showmipscmdlist = NULL;
539
540 /* Integer registers 0 thru 31 are handled explicitly by
541    mips_register_name().  Processor specific registers 32 and above
542    are listed in the following tables.  */
543
544 enum
545 { NUM_MIPS_PROCESSOR_REGS = (90 - 32) };
546
547 /* Generic MIPS.  */
548
549 static const char *mips_generic_reg_names[NUM_MIPS_PROCESSOR_REGS] = {
550   "sr", "lo", "hi", "bad", "cause", "pc",
551   "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7",
552   "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15",
553   "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23",
554   "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31",
555   "fsr", "fir",
556 };
557
558 /* Names of IDT R3041 registers.  */
559
560 static const char *mips_r3041_reg_names[] = {
561   "sr", "lo", "hi", "bad", "cause", "pc",
562   "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7",
563   "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15",
564   "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23",
565   "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31",
566   "fsr", "fir", "", /*"fp" */ "",
567   "", "", "bus", "ccfg", "", "", "", "",
568   "", "", "port", "cmp", "", "", "epc", "prid",
569 };
570
571 /* Names of tx39 registers.  */
572
573 static const char *mips_tx39_reg_names[NUM_MIPS_PROCESSOR_REGS] = {
574   "sr", "lo", "hi", "bad", "cause", "pc",
575   "", "", "", "", "", "", "", "",
576   "", "", "", "", "", "", "", "",
577   "", "", "", "", "", "", "", "",
578   "", "", "", "", "", "", "", "",
579   "", "", "", "",
580   "", "", "", "", "", "", "", "",
581   "", "", "config", "cache", "debug", "depc", "epc",
582 };
583
584 /* Names of IRIX registers.  */
585 static const char *mips_irix_reg_names[NUM_MIPS_PROCESSOR_REGS] = {
586   "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7",
587   "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15",
588   "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23",
589   "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31",
590   "pc", "cause", "bad", "hi", "lo", "fsr", "fir"
591 };
592
593 /* Names of registers with Linux kernels.  */
594 static const char *mips_linux_reg_names[NUM_MIPS_PROCESSOR_REGS] = {
595   "sr", "lo", "hi", "bad", "cause", "pc",
596   "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7",
597   "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15",
598   "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23",
599   "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31",
600   "fsr", "fir"
601 };
602
603
604 /* Return the name of the register corresponding to REGNO.  */
605 static const char *
606 mips_register_name (struct gdbarch *gdbarch, int regno)
607 {
608   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
609   /* GPR names for all ABIs other than n32/n64.  */
610   static char *mips_gpr_names[] = {
611     "zero", "at", "v0", "v1", "a0", "a1", "a2", "a3",
612     "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7",
613     "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7",
614     "t8", "t9", "k0", "k1", "gp", "sp", "s8", "ra",
615   };
616
617   /* GPR names for n32 and n64 ABIs.  */
618   static char *mips_n32_n64_gpr_names[] = {
619     "zero", "at", "v0", "v1", "a0", "a1", "a2", "a3",
620     "a4", "a5", "a6", "a7", "t0", "t1", "t2", "t3",
621     "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7",
622     "t8", "t9", "k0", "k1", "gp", "sp", "s8", "ra"
623   };
624
625   enum mips_abi abi = mips_abi (gdbarch);
626
627   /* Map [gdbarch_num_regs .. 2*gdbarch_num_regs) onto the raw registers, 
628      but then don't make the raw register names visible.  This (upper)
629      range of user visible register numbers are the pseudo-registers.
630
631      This approach was adopted accommodate the following scenario:
632      It is possible to debug a 64-bit device using a 32-bit
633      programming model.  In such instances, the raw registers are
634      configured to be 64-bits wide, while the pseudo registers are
635      configured to be 32-bits wide.  The registers that the user
636      sees - the pseudo registers - match the users expectations
637      given the programming model being used.  */
638   int rawnum = regno % gdbarch_num_regs (gdbarch);
639   if (regno < gdbarch_num_regs (gdbarch))
640     return "";
641
642   /* The MIPS integer registers are always mapped from 0 to 31.  The
643      names of the registers (which reflects the conventions regarding
644      register use) vary depending on the ABI.  */
645   if (0 <= rawnum && rawnum < 32)
646     {
647       if (abi == MIPS_ABI_N32 || abi == MIPS_ABI_N64)
648         return mips_n32_n64_gpr_names[rawnum];
649       else
650         return mips_gpr_names[rawnum];
651     }
652   else if (tdesc_has_registers (gdbarch_target_desc (gdbarch)))
653     return tdesc_register_name (gdbarch, rawnum);
654   else if (32 <= rawnum && rawnum < gdbarch_num_regs (gdbarch))
655     {
656       gdb_assert (rawnum - 32 < NUM_MIPS_PROCESSOR_REGS);
657       if (tdep->mips_processor_reg_names[rawnum - 32])
658         return tdep->mips_processor_reg_names[rawnum - 32];
659       return "";
660     }
661   else
662     internal_error (__FILE__, __LINE__,
663                     _("mips_register_name: bad register number %d"), rawnum);
664 }
665
666 /* Return the groups that a MIPS register can be categorised into.  */
667
668 static int
669 mips_register_reggroup_p (struct gdbarch *gdbarch, int regnum,
670                           struct reggroup *reggroup)
671 {
672   int vector_p;
673   int float_p;
674   int raw_p;
675   int rawnum = regnum % gdbarch_num_regs (gdbarch);
676   int pseudo = regnum / gdbarch_num_regs (gdbarch);
677   if (reggroup == all_reggroup)
678     return pseudo;
679   vector_p = TYPE_VECTOR (register_type (gdbarch, regnum));
680   float_p = TYPE_CODE (register_type (gdbarch, regnum)) == TYPE_CODE_FLT;
681   /* FIXME: cagney/2003-04-13: Can't yet use gdbarch_num_regs
682      (gdbarch), as not all architectures are multi-arch.  */
683   raw_p = rawnum < gdbarch_num_regs (gdbarch);
684   if (gdbarch_register_name (gdbarch, regnum) == NULL
685       || gdbarch_register_name (gdbarch, regnum)[0] == '\0')
686     return 0;
687   if (reggroup == float_reggroup)
688     return float_p && pseudo;
689   if (reggroup == vector_reggroup)
690     return vector_p && pseudo;
691   if (reggroup == general_reggroup)
692     return (!vector_p && !float_p) && pseudo;
693   /* Save the pseudo registers.  Need to make certain that any code
694      extracting register values from a saved register cache also uses
695      pseudo registers.  */
696   if (reggroup == save_reggroup)
697     return raw_p && pseudo;
698   /* Restore the same pseudo register.  */
699   if (reggroup == restore_reggroup)
700     return raw_p && pseudo;
701   return 0;
702 }
703
704 /* Return the groups that a MIPS register can be categorised into.
705    This version is only used if we have a target description which
706    describes real registers (and their groups).  */
707
708 static int
709 mips_tdesc_register_reggroup_p (struct gdbarch *gdbarch, int regnum,
710                                 struct reggroup *reggroup)
711 {
712   int rawnum = regnum % gdbarch_num_regs (gdbarch);
713   int pseudo = regnum / gdbarch_num_regs (gdbarch);
714   int ret;
715
716   /* Only save, restore, and display the pseudo registers.  Need to
717      make certain that any code extracting register values from a
718      saved register cache also uses pseudo registers.
719
720      Note: saving and restoring the pseudo registers is slightly
721      strange; if we have 64 bits, we should save and restore all
722      64 bits.  But this is hard and has little benefit.  */
723   if (!pseudo)
724     return 0;
725
726   ret = tdesc_register_in_reggroup_p (gdbarch, rawnum, reggroup);
727   if (ret != -1)
728     return ret;
729
730   return mips_register_reggroup_p (gdbarch, regnum, reggroup);
731 }
732
733 /* Map the symbol table registers which live in the range [1 *
734    gdbarch_num_regs .. 2 * gdbarch_num_regs) back onto the corresponding raw
735    registers.  Take care of alignment and size problems.  */
736
737 static enum register_status
738 mips_pseudo_register_read (struct gdbarch *gdbarch, struct regcache *regcache,
739                            int cookednum, gdb_byte *buf)
740 {
741   int rawnum = cookednum % gdbarch_num_regs (gdbarch);
742   gdb_assert (cookednum >= gdbarch_num_regs (gdbarch)
743               && cookednum < 2 * gdbarch_num_regs (gdbarch));
744   if (register_size (gdbarch, rawnum) == register_size (gdbarch, cookednum))
745     return regcache_raw_read (regcache, rawnum, buf);
746   else if (register_size (gdbarch, rawnum) >
747            register_size (gdbarch, cookednum))
748     {
749       if (gdbarch_tdep (gdbarch)->mips64_transfers_32bit_regs_p)
750         return regcache_raw_read_part (regcache, rawnum, 0, 4, buf);
751       else
752         {
753           enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
754           LONGEST regval;
755           enum register_status status;
756
757           status = regcache_raw_read_signed (regcache, rawnum, &regval);
758           if (status == REG_VALID)
759             store_signed_integer (buf, 4, byte_order, regval);
760           return status;
761         }
762     }
763   else
764     internal_error (__FILE__, __LINE__, _("bad register size"));
765 }
766
767 static void
768 mips_pseudo_register_write (struct gdbarch *gdbarch,
769                             struct regcache *regcache, int cookednum,
770                             const gdb_byte *buf)
771 {
772   int rawnum = cookednum % gdbarch_num_regs (gdbarch);
773   gdb_assert (cookednum >= gdbarch_num_regs (gdbarch)
774               && cookednum < 2 * gdbarch_num_regs (gdbarch));
775   if (register_size (gdbarch, rawnum) == register_size (gdbarch, cookednum))
776     regcache_raw_write (regcache, rawnum, buf);
777   else if (register_size (gdbarch, rawnum) >
778            register_size (gdbarch, cookednum))
779     {
780       if (gdbarch_tdep (gdbarch)->mips64_transfers_32bit_regs_p)
781         regcache_raw_write_part (regcache, rawnum, 0, 4, buf);
782       else
783         {
784           /* Sign extend the shortened version of the register prior
785              to placing it in the raw register.  This is required for
786              some mips64 parts in order to avoid unpredictable behavior.  */
787           enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
788           LONGEST regval = extract_signed_integer (buf, 4, byte_order);
789           regcache_raw_write_signed (regcache, rawnum, regval);
790         }
791     }
792   else
793     internal_error (__FILE__, __LINE__, _("bad register size"));
794 }
795
796 static int
797 mips_ax_pseudo_register_collect (struct gdbarch *gdbarch,
798                                  struct agent_expr *ax, int reg)
799 {
800   int rawnum = reg % gdbarch_num_regs (gdbarch);
801   gdb_assert (reg >= gdbarch_num_regs (gdbarch)
802               && reg < 2 * gdbarch_num_regs (gdbarch));
803
804   ax_reg_mask (ax, rawnum);
805
806   return 0;
807 }
808
809 static int
810 mips_ax_pseudo_register_push_stack (struct gdbarch *gdbarch,
811                                     struct agent_expr *ax, int reg)
812 {
813   int rawnum = reg % gdbarch_num_regs (gdbarch);
814   gdb_assert (reg >= gdbarch_num_regs (gdbarch)
815               && reg < 2 * gdbarch_num_regs (gdbarch));
816   if (register_size (gdbarch, rawnum) >= register_size (gdbarch, reg))
817     {
818       ax_reg (ax, rawnum);
819
820       if (register_size (gdbarch, rawnum) > register_size (gdbarch, reg))
821         {
822           if (!gdbarch_tdep (gdbarch)->mips64_transfers_32bit_regs_p
823               || gdbarch_byte_order (gdbarch) != BFD_ENDIAN_BIG)
824             {
825               ax_const_l (ax, 32);
826               ax_simple (ax, aop_lsh);
827             }
828           ax_const_l (ax, 32);
829           ax_simple (ax, aop_rsh_signed);
830         }
831     }
832   else
833     internal_error (__FILE__, __LINE__, _("bad register size"));
834
835   return 0;
836 }
837
838 /* Table to translate 3-bit register field to actual register number.  */
839 static const signed char mips_reg3_to_reg[8] = { 16, 17, 2, 3, 4, 5, 6, 7 };
840
841 /* Heuristic_proc_start may hunt through the text section for a long
842    time across a 2400 baud serial line.  Allows the user to limit this
843    search.  */
844
845 static int heuristic_fence_post = 0;
846
847 /* Number of bytes of storage in the actual machine representation for
848    register N.  NOTE: This defines the pseudo register type so need to
849    rebuild the architecture vector.  */
850
851 static int mips64_transfers_32bit_regs_p = 0;
852
853 static void
854 set_mips64_transfers_32bit_regs (char *args, int from_tty,
855                                  struct cmd_list_element *c)
856 {
857   struct gdbarch_info info;
858   gdbarch_info_init (&info);
859   /* FIXME: cagney/2003-11-15: Should be setting a field in "info"
860      instead of relying on globals.  Doing that would let generic code
861      handle the search for this specific architecture.  */
862   if (!gdbarch_update_p (info))
863     {
864       mips64_transfers_32bit_regs_p = 0;
865       error (_("32-bit compatibility mode not supported"));
866     }
867 }
868
869 /* Convert to/from a register and the corresponding memory value.  */
870
871 /* This predicate tests for the case of an 8 byte floating point
872    value that is being transferred to or from a pair of floating point
873    registers each of which are (or are considered to be) only 4 bytes
874    wide.  */
875 static int
876 mips_convert_register_float_case_p (struct gdbarch *gdbarch, int regnum,
877                                     struct type *type)
878 {
879   return (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG
880           && register_size (gdbarch, regnum) == 4
881           && mips_float_register_p (gdbarch, regnum)
882           && TYPE_CODE (type) == TYPE_CODE_FLT && TYPE_LENGTH (type) == 8);
883 }
884
885 /* This predicate tests for the case of a value of less than 8
886    bytes in width that is being transfered to or from an 8 byte
887    general purpose register.  */
888 static int
889 mips_convert_register_gpreg_case_p (struct gdbarch *gdbarch, int regnum,
890                                     struct type *type)
891 {
892   int num_regs = gdbarch_num_regs (gdbarch);
893
894   return (register_size (gdbarch, regnum) == 8
895           && regnum % num_regs > 0 && regnum % num_regs < 32
896           && TYPE_LENGTH (type) < 8);
897 }
898
899 static int
900 mips_convert_register_p (struct gdbarch *gdbarch,
901                          int regnum, struct type *type)
902 {
903   return (mips_convert_register_float_case_p (gdbarch, regnum, type)
904           || mips_convert_register_gpreg_case_p (gdbarch, regnum, type));
905 }
906
907 static int
908 mips_register_to_value (struct frame_info *frame, int regnum,
909                         struct type *type, gdb_byte *to,
910                         int *optimizedp, int *unavailablep)
911 {
912   struct gdbarch *gdbarch = get_frame_arch (frame);
913
914   if (mips_convert_register_float_case_p (gdbarch, regnum, type))
915     {
916       get_frame_register (frame, regnum + 0, to + 4);
917       get_frame_register (frame, regnum + 1, to + 0);
918
919       if (!get_frame_register_bytes (frame, regnum + 0, 0, 4, to + 4,
920                                      optimizedp, unavailablep))
921         return 0;
922
923       if (!get_frame_register_bytes (frame, regnum + 1, 0, 4, to + 0,
924                                      optimizedp, unavailablep))
925         return 0;
926       *optimizedp = *unavailablep = 0;
927       return 1;
928     }
929   else if (mips_convert_register_gpreg_case_p (gdbarch, regnum, type))
930     {
931       int len = TYPE_LENGTH (type);
932       CORE_ADDR offset;
933
934       offset = gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG ? 8 - len : 0;
935       if (!get_frame_register_bytes (frame, regnum, offset, len, to,
936                                      optimizedp, unavailablep))
937         return 0;
938
939       *optimizedp = *unavailablep = 0;
940       return 1;
941     }
942   else
943     {
944       internal_error (__FILE__, __LINE__,
945                       _("mips_register_to_value: unrecognized case"));
946     }
947 }
948
949 static void
950 mips_value_to_register (struct frame_info *frame, int regnum,
951                         struct type *type, const gdb_byte *from)
952 {
953   struct gdbarch *gdbarch = get_frame_arch (frame);
954
955   if (mips_convert_register_float_case_p (gdbarch, regnum, type))
956     {
957       put_frame_register (frame, regnum + 0, from + 4);
958       put_frame_register (frame, regnum + 1, from + 0);
959     }
960   else if (mips_convert_register_gpreg_case_p (gdbarch, regnum, type))
961     {
962       gdb_byte fill[8];
963       int len = TYPE_LENGTH (type);
964       
965       /* Sign extend values, irrespective of type, that are stored to 
966          a 64-bit general purpose register.  (32-bit unsigned values
967          are stored as signed quantities within a 64-bit register.
968          When performing an operation, in compiled code, that combines
969          a 32-bit unsigned value with a signed 64-bit value, a type
970          conversion is first performed that zeroes out the high 32 bits.)  */
971       if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
972         {
973           if (from[0] & 0x80)
974             store_signed_integer (fill, 8, BFD_ENDIAN_BIG, -1);
975           else
976             store_signed_integer (fill, 8, BFD_ENDIAN_BIG, 0);
977           put_frame_register_bytes (frame, regnum, 0, 8 - len, fill);
978           put_frame_register_bytes (frame, regnum, 8 - len, len, from);
979         }
980       else
981         {
982           if (from[len-1] & 0x80)
983             store_signed_integer (fill, 8, BFD_ENDIAN_LITTLE, -1);
984           else
985             store_signed_integer (fill, 8, BFD_ENDIAN_LITTLE, 0);
986           put_frame_register_bytes (frame, regnum, 0, len, from);
987           put_frame_register_bytes (frame, regnum, len, 8 - len, fill);
988         }
989     }
990   else
991     {
992       internal_error (__FILE__, __LINE__,
993                       _("mips_value_to_register: unrecognized case"));
994     }
995 }
996
997 /* Return the GDB type object for the "standard" data type of data in
998    register REG.  */
999
1000 static struct type *
1001 mips_register_type (struct gdbarch *gdbarch, int regnum)
1002 {
1003   gdb_assert (regnum >= 0 && regnum < 2 * gdbarch_num_regs (gdbarch));
1004   if (mips_float_register_p (gdbarch, regnum))
1005     {
1006       /* The floating-point registers raw, or cooked, always match
1007          mips_isa_regsize(), and also map 1:1, byte for byte.  */
1008       if (mips_isa_regsize (gdbarch) == 4)
1009         return builtin_type (gdbarch)->builtin_float;
1010       else
1011         return builtin_type (gdbarch)->builtin_double;
1012     }
1013   else if (regnum < gdbarch_num_regs (gdbarch))
1014     {
1015       /* The raw or ISA registers.  These are all sized according to
1016          the ISA regsize.  */
1017       if (mips_isa_regsize (gdbarch) == 4)
1018         return builtin_type (gdbarch)->builtin_int32;
1019       else
1020         return builtin_type (gdbarch)->builtin_int64;
1021     }
1022   else
1023     {
1024       int rawnum = regnum - gdbarch_num_regs (gdbarch);
1025
1026       /* The cooked or ABI registers.  These are sized according to
1027          the ABI (with a few complications).  */
1028       if (rawnum == mips_regnum (gdbarch)->fp_control_status
1029           || rawnum == mips_regnum (gdbarch)->fp_implementation_revision)
1030         return builtin_type (gdbarch)->builtin_int32;
1031       else if (gdbarch_osabi (gdbarch) != GDB_OSABI_IRIX
1032                && gdbarch_osabi (gdbarch) != GDB_OSABI_LINUX
1033                && rawnum >= MIPS_FIRST_EMBED_REGNUM
1034                && rawnum <= MIPS_LAST_EMBED_REGNUM)
1035         /* The pseudo/cooked view of the embedded registers is always
1036            32-bit.  The raw view is handled below.  */
1037         return builtin_type (gdbarch)->builtin_int32;
1038       else if (gdbarch_tdep (gdbarch)->mips64_transfers_32bit_regs_p)
1039         /* The target, while possibly using a 64-bit register buffer,
1040            is only transfering 32-bits of each integer register.
1041            Reflect this in the cooked/pseudo (ABI) register value.  */
1042         return builtin_type (gdbarch)->builtin_int32;
1043       else if (mips_abi_regsize (gdbarch) == 4)
1044         /* The ABI is restricted to 32-bit registers (the ISA could be
1045            32- or 64-bit).  */
1046         return builtin_type (gdbarch)->builtin_int32;
1047       else
1048         /* 64-bit ABI.  */
1049         return builtin_type (gdbarch)->builtin_int64;
1050     }
1051 }
1052
1053 /* Return the GDB type for the pseudo register REGNUM, which is the
1054    ABI-level view.  This function is only called if there is a target
1055    description which includes registers, so we know precisely the
1056    types of hardware registers.  */
1057
1058 static struct type *
1059 mips_pseudo_register_type (struct gdbarch *gdbarch, int regnum)
1060 {
1061   const int num_regs = gdbarch_num_regs (gdbarch);
1062   int rawnum = regnum % num_regs;
1063   struct type *rawtype;
1064
1065   gdb_assert (regnum >= num_regs && regnum < 2 * num_regs);
1066
1067   /* Absent registers are still absent.  */
1068   rawtype = gdbarch_register_type (gdbarch, rawnum);
1069   if (TYPE_LENGTH (rawtype) == 0)
1070     return rawtype;
1071
1072   if (mips_float_register_p (gdbarch, rawnum))
1073     /* Present the floating point registers however the hardware did;
1074        do not try to convert between FPU layouts.  */
1075     return rawtype;
1076
1077   /* Use pointer types for registers if we can.  For n32 we can not,
1078      since we do not have a 64-bit pointer type.  */
1079   if (mips_abi_regsize (gdbarch)
1080       == TYPE_LENGTH (builtin_type (gdbarch)->builtin_data_ptr))
1081     {
1082       if (rawnum == MIPS_SP_REGNUM
1083           || rawnum == mips_regnum (gdbarch)->badvaddr)
1084         return builtin_type (gdbarch)->builtin_data_ptr;
1085       else if (rawnum == mips_regnum (gdbarch)->pc)
1086         return builtin_type (gdbarch)->builtin_func_ptr;
1087     }
1088
1089   if (mips_abi_regsize (gdbarch) == 4 && TYPE_LENGTH (rawtype) == 8
1090       && ((rawnum >= MIPS_ZERO_REGNUM && rawnum <= MIPS_PS_REGNUM)
1091           || rawnum == mips_regnum (gdbarch)->lo
1092           || rawnum == mips_regnum (gdbarch)->hi
1093           || rawnum == mips_regnum (gdbarch)->badvaddr
1094           || rawnum == mips_regnum (gdbarch)->cause
1095           || rawnum == mips_regnum (gdbarch)->pc
1096           || (mips_regnum (gdbarch)->dspacc != -1
1097               && rawnum >= mips_regnum (gdbarch)->dspacc
1098               && rawnum < mips_regnum (gdbarch)->dspacc + 6)))
1099     return builtin_type (gdbarch)->builtin_int32;
1100
1101   if (gdbarch_osabi (gdbarch) != GDB_OSABI_IRIX
1102       && gdbarch_osabi (gdbarch) != GDB_OSABI_LINUX
1103       && rawnum >= MIPS_EMBED_FP0_REGNUM + 32
1104       && rawnum <= MIPS_LAST_EMBED_REGNUM)
1105     {
1106       /* The pseudo/cooked view of embedded registers is always
1107          32-bit, even if the target transfers 64-bit values for them.
1108          New targets relying on XML descriptions should only transfer
1109          the necessary 32 bits, but older versions of GDB expected 64,
1110          so allow the target to provide 64 bits without interfering
1111          with the displayed type.  */
1112       return builtin_type (gdbarch)->builtin_int32;
1113     }
1114
1115   /* For all other registers, pass through the hardware type.  */
1116   return rawtype;
1117 }
1118
1119 /* Should the upper word of 64-bit addresses be zeroed?  */
1120 enum auto_boolean mask_address_var = AUTO_BOOLEAN_AUTO;
1121
1122 static int
1123 mips_mask_address_p (struct gdbarch_tdep *tdep)
1124 {
1125   switch (mask_address_var)
1126     {
1127     case AUTO_BOOLEAN_TRUE:
1128       return 1;
1129     case AUTO_BOOLEAN_FALSE:
1130       return 0;
1131       break;
1132     case AUTO_BOOLEAN_AUTO:
1133       return tdep->default_mask_address_p;
1134     default:
1135       internal_error (__FILE__, __LINE__,
1136                       _("mips_mask_address_p: bad switch"));
1137       return -1;
1138     }
1139 }
1140
1141 static void
1142 show_mask_address (struct ui_file *file, int from_tty,
1143                    struct cmd_list_element *c, const char *value)
1144 {
1145   struct gdbarch_tdep *tdep = gdbarch_tdep (target_gdbarch ());
1146
1147   deprecated_show_value_hack (file, from_tty, c, value);
1148   switch (mask_address_var)
1149     {
1150     case AUTO_BOOLEAN_TRUE:
1151       printf_filtered ("The 32 bit mips address mask is enabled\n");
1152       break;
1153     case AUTO_BOOLEAN_FALSE:
1154       printf_filtered ("The 32 bit mips address mask is disabled\n");
1155       break;
1156     case AUTO_BOOLEAN_AUTO:
1157       printf_filtered
1158         ("The 32 bit address mask is set automatically.  Currently %s\n",
1159          mips_mask_address_p (tdep) ? "enabled" : "disabled");
1160       break;
1161     default:
1162       internal_error (__FILE__, __LINE__, _("show_mask_address: bad switch"));
1163       break;
1164     }
1165 }
1166
1167 /* Tell if the program counter value in MEMADDR is in a standard ISA
1168    function.  */
1169
1170 int
1171 mips_pc_is_mips (CORE_ADDR memaddr)
1172 {
1173   struct bound_minimal_symbol sym;
1174
1175   /* Flags indicating that this is a MIPS16 or microMIPS function is
1176      stored by elfread.c in the high bit of the info field.  Use this
1177      to decide if the function is standard MIPS.  Otherwise if bit 0
1178      of the address is clear, then this is a standard MIPS function.  */
1179   sym = lookup_minimal_symbol_by_pc (make_compact_addr (memaddr));
1180   if (sym.minsym)
1181     return msymbol_is_mips (sym.minsym);
1182   else
1183     return is_mips_addr (memaddr);
1184 }
1185
1186 /* Tell if the program counter value in MEMADDR is in a MIPS16 function.  */
1187
1188 int
1189 mips_pc_is_mips16 (struct gdbarch *gdbarch, CORE_ADDR memaddr)
1190 {
1191   struct bound_minimal_symbol sym;
1192
1193   /* A flag indicating that this is a MIPS16 function is stored by
1194      elfread.c in the high bit of the info field.  Use this to decide
1195      if the function is MIPS16.  Otherwise if bit 0 of the address is
1196      set, then ELF file flags will tell if this is a MIPS16 function.  */
1197   sym = lookup_minimal_symbol_by_pc (make_compact_addr (memaddr));
1198   if (sym.minsym)
1199     return msymbol_is_mips16 (sym.minsym);
1200   else
1201     return is_mips16_addr (gdbarch, memaddr);
1202 }
1203
1204 /* Tell if the program counter value in MEMADDR is in a microMIPS function.  */
1205
1206 int
1207 mips_pc_is_micromips (struct gdbarch *gdbarch, CORE_ADDR memaddr)
1208 {
1209   struct bound_minimal_symbol sym;
1210
1211   /* A flag indicating that this is a microMIPS function is stored by
1212      elfread.c in the high bit of the info field.  Use this to decide
1213      if the function is microMIPS.  Otherwise if bit 0 of the address
1214      is set, then ELF file flags will tell if this is a microMIPS
1215      function.  */
1216   sym = lookup_minimal_symbol_by_pc (make_compact_addr (memaddr));
1217   if (sym.minsym)
1218     return msymbol_is_micromips (sym.minsym);
1219   else
1220     return is_micromips_addr (gdbarch, memaddr);
1221 }
1222
1223 /* Tell the ISA type of the function the program counter value in MEMADDR
1224    is in.  */
1225
1226 static enum mips_isa
1227 mips_pc_isa (struct gdbarch *gdbarch, CORE_ADDR memaddr)
1228 {
1229   struct bound_minimal_symbol sym;
1230
1231   /* A flag indicating that this is a MIPS16 or a microMIPS function
1232      is stored by elfread.c in the high bit of the info field.  Use
1233      this to decide if the function is MIPS16 or microMIPS or normal
1234      MIPS.  Otherwise if bit 0 of the address is set, then ELF file
1235      flags will tell if this is a MIPS16 or a microMIPS function.  */
1236   sym = lookup_minimal_symbol_by_pc (make_compact_addr (memaddr));
1237   if (sym.minsym)
1238     {
1239       if (msymbol_is_micromips (sym.minsym))
1240         return ISA_MICROMIPS;
1241       else if (msymbol_is_mips16 (sym.minsym))
1242         return ISA_MIPS16;
1243       else
1244         return ISA_MIPS;
1245     }
1246   else
1247     {
1248       if (is_mips_addr (memaddr))
1249         return ISA_MIPS;
1250       else if (is_micromips_addr (gdbarch, memaddr))
1251         return ISA_MICROMIPS;
1252       else
1253         return ISA_MIPS16;
1254     }
1255 }
1256
1257 /* Set the ISA bit correctly in the PC, used by DWARF-2 machinery.
1258    The need for comes from the ISA bit having been cleared, making
1259    addresses in FDE, range records, etc. referring to compressed code
1260    different to those in line information, the symbol table and finally
1261    the PC register.  That in turn confuses many operations.  */
1262
1263 static CORE_ADDR
1264 mips_adjust_dwarf2_addr (CORE_ADDR pc)
1265 {
1266   pc = unmake_compact_addr (pc);
1267   return mips_pc_is_mips (pc) ? pc : make_compact_addr (pc);
1268 }
1269
1270 /* Recalculate the line record requested so that the resulting PC has
1271    the ISA bit set correctly, used by DWARF-2 machinery.  The need for
1272    this adjustment comes from some records associated with compressed
1273    code having the ISA bit cleared, most notably at function prologue
1274    ends.  The ISA bit is in this context retrieved from the minimal
1275    symbol covering the address requested, which in turn has been
1276    constructed from the binary's symbol table rather than DWARF-2
1277    information.  The correct setting of the ISA bit is required for
1278    breakpoint addresses to correctly match against the stop PC.
1279
1280    As line entries can specify relative address adjustments we need to
1281    keep track of the absolute value of the last line address recorded
1282    in line information, so that we can calculate the actual address to
1283    apply the ISA bit adjustment to.  We use PC for this tracking and
1284    keep the original address there.
1285
1286    As such relative address adjustments can be odd within compressed
1287    code we need to keep track of the last line address with the ISA
1288    bit adjustment applied too, as the original address may or may not
1289    have had the ISA bit set.  We use ADJ_PC for this tracking and keep
1290    the adjusted address there.
1291
1292    For relative address adjustments we then use these variables to
1293    calculate the address intended by line information, which will be
1294    PC-relative, and return an updated adjustment carrying ISA bit
1295    information, which will be ADJ_PC-relative.  For absolute address
1296    adjustments we just return the same address that we store in ADJ_PC
1297    too.
1298
1299    As the first line entry can be relative to an implied address value
1300    of 0 we need to have the initial address set up that we store in PC
1301    and ADJ_PC.  This is arranged with a call from `dwarf_decode_lines_1'
1302    that sets PC to 0 and ADJ_PC accordingly, usually 0 as well.  */
1303
1304 static CORE_ADDR
1305 mips_adjust_dwarf2_line (CORE_ADDR addr, int rel)
1306 {
1307   static CORE_ADDR adj_pc;
1308   static CORE_ADDR pc;
1309   CORE_ADDR isa_pc;
1310
1311   pc = rel ? pc + addr : addr;
1312   isa_pc = mips_adjust_dwarf2_addr (pc);
1313   addr = rel ? isa_pc - adj_pc : isa_pc;
1314   adj_pc = isa_pc;
1315   return addr;
1316 }
1317
1318 /* Various MIPS16 thunk (aka stub or trampoline) names.  */
1319
1320 static const char mips_str_mips16_call_stub[] = "__mips16_call_stub_";
1321 static const char mips_str_mips16_ret_stub[] = "__mips16_ret_";
1322 static const char mips_str_call_fp_stub[] = "__call_stub_fp_";
1323 static const char mips_str_call_stub[] = "__call_stub_";
1324 static const char mips_str_fn_stub[] = "__fn_stub_";
1325
1326 /* This is used as a PIC thunk prefix.  */
1327
1328 static const char mips_str_pic[] = ".pic.";
1329
1330 /* Return non-zero if the PC is inside a call thunk (aka stub or
1331    trampoline) that should be treated as a temporary frame.  */
1332
1333 static int
1334 mips_in_frame_stub (CORE_ADDR pc)
1335 {
1336   CORE_ADDR start_addr;
1337   const char *name;
1338
1339   /* Find the starting address of the function containing the PC.  */
1340   if (find_pc_partial_function (pc, &name, &start_addr, NULL) == 0)
1341     return 0;
1342
1343   /* If the PC is in __mips16_call_stub_*, this is a call/return stub.  */
1344   if (strncmp (name, mips_str_mips16_call_stub,
1345                strlen (mips_str_mips16_call_stub)) == 0)
1346     return 1;
1347   /* If the PC is in __call_stub_*, this is a call/return or a call stub.  */
1348   if (strncmp (name, mips_str_call_stub, strlen (mips_str_call_stub)) == 0)
1349     return 1;
1350   /* If the PC is in __fn_stub_*, this is a call stub.  */
1351   if (strncmp (name, mips_str_fn_stub, strlen (mips_str_fn_stub)) == 0)
1352     return 1;
1353
1354   return 0;                     /* Not a stub.  */
1355 }
1356
1357 /* MIPS believes that the PC has a sign extended value.  Perhaps the
1358    all registers should be sign extended for simplicity?  */
1359
1360 static CORE_ADDR
1361 mips_read_pc (struct regcache *regcache)
1362 {
1363   int regnum = gdbarch_pc_regnum (get_regcache_arch (regcache));
1364   LONGEST pc;
1365
1366   regcache_cooked_read_signed (regcache, regnum, &pc);
1367   return pc;
1368 }
1369
1370 static CORE_ADDR
1371 mips_unwind_pc (struct gdbarch *gdbarch, struct frame_info *next_frame)
1372 {
1373   CORE_ADDR pc;
1374
1375   pc = frame_unwind_register_signed (next_frame, gdbarch_pc_regnum (gdbarch));
1376   /* macro/2012-04-20: This hack skips over MIPS16 call thunks as
1377      intermediate frames.  In this case we can get the caller's address
1378      from $ra, or if $ra contains an address within a thunk as well, then
1379      it must be in the return path of __mips16_call_stub_{s,d}{f,c}_{0..10}
1380      and thus the caller's address is in $s2.  */
1381   if (frame_relative_level (next_frame) >= 0 && mips_in_frame_stub (pc))
1382     {
1383       pc = frame_unwind_register_signed
1384              (next_frame, gdbarch_num_regs (gdbarch) + MIPS_RA_REGNUM);
1385       if (mips_in_frame_stub (pc))
1386         pc = frame_unwind_register_signed
1387                (next_frame, gdbarch_num_regs (gdbarch) + MIPS_S2_REGNUM);
1388     }
1389   return pc;
1390 }
1391
1392 static CORE_ADDR
1393 mips_unwind_sp (struct gdbarch *gdbarch, struct frame_info *next_frame)
1394 {
1395   return frame_unwind_register_signed
1396            (next_frame, gdbarch_num_regs (gdbarch) + MIPS_SP_REGNUM);
1397 }
1398
1399 /* Assuming THIS_FRAME is a dummy, return the frame ID of that
1400    dummy frame.  The frame ID's base needs to match the TOS value
1401    saved by save_dummy_frame_tos(), and the PC match the dummy frame's
1402    breakpoint.  */
1403
1404 static struct frame_id
1405 mips_dummy_id (struct gdbarch *gdbarch, struct frame_info *this_frame)
1406 {
1407   return frame_id_build
1408            (get_frame_register_signed (this_frame,
1409                                        gdbarch_num_regs (gdbarch)
1410                                        + MIPS_SP_REGNUM),
1411             get_frame_pc (this_frame));
1412 }
1413
1414 /* Implement the "write_pc" gdbarch method.  */
1415
1416 void
1417 mips_write_pc (struct regcache *regcache, CORE_ADDR pc)
1418 {
1419   int regnum = gdbarch_pc_regnum (get_regcache_arch (regcache));
1420
1421   regcache_cooked_write_unsigned (regcache, regnum, pc);
1422 }
1423
1424 /* Fetch and return instruction from the specified location.  Handle
1425    MIPS16/microMIPS as appropriate.  */
1426
1427 static ULONGEST
1428 mips_fetch_instruction (struct gdbarch *gdbarch,
1429                         enum mips_isa isa, CORE_ADDR addr, int *statusp)
1430 {
1431   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1432   gdb_byte buf[MIPS_INSN32_SIZE];
1433   int instlen;
1434   int status;
1435
1436   switch (isa)
1437     {
1438     case ISA_MICROMIPS:
1439     case ISA_MIPS16:
1440       instlen = MIPS_INSN16_SIZE;
1441       addr = unmake_compact_addr (addr);
1442       break;
1443     case ISA_MIPS:
1444       instlen = MIPS_INSN32_SIZE;
1445       break;
1446     default:
1447       internal_error (__FILE__, __LINE__, _("invalid ISA"));
1448       break;
1449     }
1450   status = target_read_memory (addr, buf, instlen);
1451   if (statusp != NULL)
1452     *statusp = status;
1453   if (status)
1454     {
1455       if (statusp == NULL)
1456         memory_error (status, addr);
1457       return 0;
1458     }
1459   return extract_unsigned_integer (buf, instlen, byte_order);
1460 }
1461
1462 /* These are the fields of 32 bit mips instructions.  */
1463 #define mips32_op(x) (x >> 26)
1464 #define itype_op(x) (x >> 26)
1465 #define itype_rs(x) ((x >> 21) & 0x1f)
1466 #define itype_rt(x) ((x >> 16) & 0x1f)
1467 #define itype_immediate(x) (x & 0xffff)
1468
1469 #define jtype_op(x) (x >> 26)
1470 #define jtype_target(x) (x & 0x03ffffff)
1471
1472 #define rtype_op(x) (x >> 26)
1473 #define rtype_rs(x) ((x >> 21) & 0x1f)
1474 #define rtype_rt(x) ((x >> 16) & 0x1f)
1475 #define rtype_rd(x) ((x >> 11) & 0x1f)
1476 #define rtype_shamt(x) ((x >> 6) & 0x1f)
1477 #define rtype_funct(x) (x & 0x3f)
1478
1479 /* MicroMIPS instruction fields.  */
1480 #define micromips_op(x) ((x) >> 10)
1481
1482 /* 16-bit/32-bit-high-part instruction formats, B and S refer to the lowest
1483    bit and the size respectively of the field extracted.  */
1484 #define b0s4_imm(x) ((x) & 0xf)
1485 #define b0s5_imm(x) ((x) & 0x1f)
1486 #define b0s5_reg(x) ((x) & 0x1f)
1487 #define b0s7_imm(x) ((x) & 0x7f)
1488 #define b0s10_imm(x) ((x) & 0x3ff)
1489 #define b1s4_imm(x) (((x) >> 1) & 0xf)
1490 #define b1s9_imm(x) (((x) >> 1) & 0x1ff)
1491 #define b2s3_cc(x) (((x) >> 2) & 0x7)
1492 #define b4s2_regl(x) (((x) >> 4) & 0x3)
1493 #define b5s5_op(x) (((x) >> 5) & 0x1f)
1494 #define b5s5_reg(x) (((x) >> 5) & 0x1f)
1495 #define b6s4_op(x) (((x) >> 6) & 0xf)
1496 #define b7s3_reg(x) (((x) >> 7) & 0x7)
1497
1498 /* 32-bit instruction formats, B and S refer to the lowest bit and the size
1499    respectively of the field extracted.  */
1500 #define b0s6_op(x) ((x) & 0x3f)
1501 #define b0s11_op(x) ((x) & 0x7ff)
1502 #define b0s12_imm(x) ((x) & 0xfff)
1503 #define b0s16_imm(x) ((x) & 0xffff)
1504 #define b0s26_imm(x) ((x) & 0x3ffffff)
1505 #define b6s10_ext(x) (((x) >> 6) & 0x3ff)
1506 #define b11s5_reg(x) (((x) >> 11) & 0x1f)
1507 #define b12s4_op(x) (((x) >> 12) & 0xf)
1508
1509 /* Return the size in bytes of the instruction INSN encoded in the ISA
1510    instruction set.  */
1511
1512 static int
1513 mips_insn_size (enum mips_isa isa, ULONGEST insn)
1514 {
1515   switch (isa)
1516     {
1517     case ISA_MICROMIPS:
1518       if (micromips_op (insn) == 0x1f)
1519         return 3 * MIPS_INSN16_SIZE;
1520       else if (((micromips_op (insn) & 0x4) == 0x4)
1521                || ((micromips_op (insn) & 0x7) == 0x0))
1522         return 2 * MIPS_INSN16_SIZE;
1523       else
1524         return MIPS_INSN16_SIZE;
1525     case ISA_MIPS16:
1526       if ((insn & 0xf800) == 0xf000)
1527         return 2 * MIPS_INSN16_SIZE;
1528       else
1529         return MIPS_INSN16_SIZE;
1530     case ISA_MIPS:
1531         return MIPS_INSN32_SIZE;
1532     }
1533   internal_error (__FILE__, __LINE__, _("invalid ISA"));
1534 }
1535
1536 static LONGEST
1537 mips32_relative_offset (ULONGEST inst)
1538 {
1539   return ((itype_immediate (inst) ^ 0x8000) - 0x8000) << 2;
1540 }
1541
1542 /* Determine the address of the next instruction executed after the INST
1543    floating condition branch instruction at PC.  COUNT specifies the
1544    number of the floating condition bits tested by the branch.  */
1545
1546 static CORE_ADDR
1547 mips32_bc1_pc (struct gdbarch *gdbarch, struct frame_info *frame,
1548                ULONGEST inst, CORE_ADDR pc, int count)
1549 {
1550   int fcsr = mips_regnum (gdbarch)->fp_control_status;
1551   int cnum = (itype_rt (inst) >> 2) & (count - 1);
1552   int tf = itype_rt (inst) & 1;
1553   int mask = (1 << count) - 1;
1554   ULONGEST fcs;
1555   int cond;
1556
1557   if (fcsr == -1)
1558     /* No way to handle; it'll most likely trap anyway.  */
1559     return pc;
1560
1561   fcs = get_frame_register_unsigned (frame, fcsr);
1562   cond = ((fcs >> 24) & 0xfe) | ((fcs >> 23) & 0x01);
1563
1564   if (((cond >> cnum) & mask) != mask * !tf)
1565     pc += mips32_relative_offset (inst);
1566   else
1567     pc += 4;
1568
1569   return pc;
1570 }
1571
1572 /* Return nonzero if the gdbarch is an Octeon series.  */
1573
1574 static int
1575 is_octeon (struct gdbarch *gdbarch)
1576 {
1577   const struct bfd_arch_info *info = gdbarch_bfd_arch_info (gdbarch);
1578
1579   return (info->mach == bfd_mach_mips_octeon
1580          || info->mach == bfd_mach_mips_octeonp
1581          || info->mach == bfd_mach_mips_octeon2);
1582 }
1583
1584 /* Return true if the OP represents the Octeon's BBIT instruction.  */
1585
1586 static int
1587 is_octeon_bbit_op (int op, struct gdbarch *gdbarch)
1588 {
1589   if (!is_octeon (gdbarch))
1590     return 0;
1591   /* BBIT0 is encoded as LWC2: 110 010.  */
1592   /* BBIT032 is encoded as LDC2: 110 110.  */
1593   /* BBIT1 is encoded as SWC2: 111 010.  */
1594   /* BBIT132 is encoded as SDC2: 111 110.  */
1595   if (op == 50 || op == 54 || op == 58 || op == 62)
1596     return 1;
1597   return 0;
1598 }
1599
1600
1601 /* Determine where to set a single step breakpoint while considering
1602    branch prediction.  */
1603
1604 static CORE_ADDR
1605 mips32_next_pc (struct frame_info *frame, CORE_ADDR pc)
1606 {
1607   struct gdbarch *gdbarch = get_frame_arch (frame);
1608   unsigned long inst;
1609   int op;
1610   inst = mips_fetch_instruction (gdbarch, ISA_MIPS, pc, NULL);
1611   op = itype_op (inst);
1612   if ((inst & 0xe0000000) != 0)         /* Not a special, jump or branch
1613                                            instruction.  */
1614     {
1615       if (op >> 2 == 5)
1616         /* BEQL, BNEL, BLEZL, BGTZL: bits 0101xx */
1617         {
1618           switch (op & 0x03)
1619             {
1620             case 0:             /* BEQL */
1621               goto equal_branch;
1622             case 1:             /* BNEL */
1623               goto neq_branch;
1624             case 2:             /* BLEZL */
1625               goto less_branch;
1626             case 3:             /* BGTZL */
1627               goto greater_branch;
1628             default:
1629               pc += 4;
1630             }
1631         }
1632       else if (op == 17 && itype_rs (inst) == 8)
1633         /* BC1F, BC1FL, BC1T, BC1TL: 010001 01000 */
1634         pc = mips32_bc1_pc (gdbarch, frame, inst, pc + 4, 1);
1635       else if (op == 17 && itype_rs (inst) == 9
1636                && (itype_rt (inst) & 2) == 0)
1637         /* BC1ANY2F, BC1ANY2T: 010001 01001 xxx0x */
1638         pc = mips32_bc1_pc (gdbarch, frame, inst, pc + 4, 2);
1639       else if (op == 17 && itype_rs (inst) == 10
1640                && (itype_rt (inst) & 2) == 0)
1641         /* BC1ANY4F, BC1ANY4T: 010001 01010 xxx0x */
1642         pc = mips32_bc1_pc (gdbarch, frame, inst, pc + 4, 4);
1643       else if (op == 29)
1644         /* JALX: 011101 */
1645         /* The new PC will be alternate mode.  */
1646         {
1647           unsigned long reg;
1648
1649           reg = jtype_target (inst) << 2;
1650           /* Add 1 to indicate 16-bit mode -- invert ISA mode.  */
1651           pc = ((pc + 4) & ~(CORE_ADDR) 0x0fffffff) + reg + 1;
1652         }
1653       else if (is_octeon_bbit_op (op, gdbarch))
1654         {
1655           int bit, branch_if;
1656
1657           branch_if = op == 58 || op == 62;
1658           bit = itype_rt (inst);
1659
1660           /* Take into account the *32 instructions.  */
1661           if (op == 54 || op == 62)
1662             bit += 32;
1663
1664           if (((get_frame_register_signed (frame,
1665                                            itype_rs (inst)) >> bit) & 1)
1666               == branch_if)
1667             pc += mips32_relative_offset (inst) + 4;
1668           else
1669             pc += 8;        /* After the delay slot.  */
1670         }
1671
1672       else
1673         pc += 4;                /* Not a branch, next instruction is easy.  */
1674     }
1675   else
1676     {                           /* This gets way messy.  */
1677
1678       /* Further subdivide into SPECIAL, REGIMM and other.  */
1679       switch (op & 0x07)        /* Extract bits 28,27,26.  */
1680         {
1681         case 0:         /* SPECIAL */
1682           op = rtype_funct (inst);
1683           switch (op)
1684             {
1685             case 8:             /* JR */
1686             case 9:             /* JALR */
1687               /* Set PC to that address.  */
1688               pc = get_frame_register_signed (frame, rtype_rs (inst));
1689               break;
1690             case 12:            /* SYSCALL */
1691               {
1692                 struct gdbarch_tdep *tdep;
1693
1694                 tdep = gdbarch_tdep (get_frame_arch (frame));
1695                 if (tdep->syscall_next_pc != NULL)
1696                   pc = tdep->syscall_next_pc (frame);
1697                 else
1698                   pc += 4;
1699               }
1700               break;
1701             default:
1702               pc += 4;
1703             }
1704
1705           break;                /* end SPECIAL */
1706         case 1:                 /* REGIMM */
1707           {
1708             op = itype_rt (inst);       /* branch condition */
1709             switch (op)
1710               {
1711               case 0:           /* BLTZ */
1712               case 2:           /* BLTZL */
1713               case 16:          /* BLTZAL */
1714               case 18:          /* BLTZALL */
1715               less_branch:
1716                 if (get_frame_register_signed (frame, itype_rs (inst)) < 0)
1717                   pc += mips32_relative_offset (inst) + 4;
1718                 else
1719                   pc += 8;      /* after the delay slot */
1720                 break;
1721               case 1:           /* BGEZ */
1722               case 3:           /* BGEZL */
1723               case 17:          /* BGEZAL */
1724               case 19:          /* BGEZALL */
1725                 if (get_frame_register_signed (frame, itype_rs (inst)) >= 0)
1726                   pc += mips32_relative_offset (inst) + 4;
1727                 else
1728                   pc += 8;      /* after the delay slot */
1729                 break;
1730               case 0x1c:        /* BPOSGE32 */
1731               case 0x1e:        /* BPOSGE64 */
1732                 pc += 4;
1733                 if (itype_rs (inst) == 0)
1734                   {
1735                     unsigned int pos = (op & 2) ? 64 : 32;
1736                     int dspctl = mips_regnum (gdbarch)->dspctl;
1737
1738                     if (dspctl == -1)
1739                       /* No way to handle; it'll most likely trap anyway.  */
1740                       break;
1741
1742                     if ((get_frame_register_unsigned (frame,
1743                                                       dspctl) & 0x7f) >= pos)
1744                       pc += mips32_relative_offset (inst);
1745                     else
1746                       pc += 4;
1747                   }
1748                 break;
1749                 /* All of the other instructions in the REGIMM category */
1750               default:
1751                 pc += 4;
1752               }
1753           }
1754           break;                /* end REGIMM */
1755         case 2:         /* J */
1756         case 3:         /* JAL */
1757           {
1758             unsigned long reg;
1759             reg = jtype_target (inst) << 2;
1760             /* Upper four bits get never changed...  */
1761             pc = reg + ((pc + 4) & ~(CORE_ADDR) 0x0fffffff);
1762           }
1763           break;
1764         case 4:         /* BEQ, BEQL */
1765         equal_branch:
1766           if (get_frame_register_signed (frame, itype_rs (inst)) ==
1767               get_frame_register_signed (frame, itype_rt (inst)))
1768             pc += mips32_relative_offset (inst) + 4;
1769           else
1770             pc += 8;
1771           break;
1772         case 5:         /* BNE, BNEL */
1773         neq_branch:
1774           if (get_frame_register_signed (frame, itype_rs (inst)) !=
1775               get_frame_register_signed (frame, itype_rt (inst)))
1776             pc += mips32_relative_offset (inst) + 4;
1777           else
1778             pc += 8;
1779           break;
1780         case 6:         /* BLEZ, BLEZL */
1781           if (get_frame_register_signed (frame, itype_rs (inst)) <= 0)
1782             pc += mips32_relative_offset (inst) + 4;
1783           else
1784             pc += 8;
1785           break;
1786         case 7:
1787         default:
1788         greater_branch: /* BGTZ, BGTZL */
1789           if (get_frame_register_signed (frame, itype_rs (inst)) > 0)
1790             pc += mips32_relative_offset (inst) + 4;
1791           else
1792             pc += 8;
1793           break;
1794         }                       /* switch */
1795     }                           /* else */
1796   return pc;
1797 }                               /* mips32_next_pc */
1798
1799 /* Extract the 7-bit signed immediate offset from the microMIPS instruction
1800    INSN.  */
1801
1802 static LONGEST
1803 micromips_relative_offset7 (ULONGEST insn)
1804 {
1805   return ((b0s7_imm (insn) ^ 0x40) - 0x40) << 1;
1806 }
1807
1808 /* Extract the 10-bit signed immediate offset from the microMIPS instruction
1809    INSN.  */
1810
1811 static LONGEST
1812 micromips_relative_offset10 (ULONGEST insn)
1813 {
1814   return ((b0s10_imm (insn) ^ 0x200) - 0x200) << 1;
1815 }
1816
1817 /* Extract the 16-bit signed immediate offset from the microMIPS instruction
1818    INSN.  */
1819
1820 static LONGEST
1821 micromips_relative_offset16 (ULONGEST insn)
1822 {
1823   return ((b0s16_imm (insn) ^ 0x8000) - 0x8000) << 1;
1824 }
1825
1826 /* Return the size in bytes of the microMIPS instruction at the address PC.  */
1827
1828 static int
1829 micromips_pc_insn_size (struct gdbarch *gdbarch, CORE_ADDR pc)
1830 {
1831   ULONGEST insn;
1832
1833   insn = mips_fetch_instruction (gdbarch, ISA_MICROMIPS, pc, NULL);
1834   return mips_insn_size (ISA_MICROMIPS, insn);
1835 }
1836
1837 /* Calculate the address of the next microMIPS instruction to execute
1838    after the INSN coprocessor 1 conditional branch instruction at the
1839    address PC.  COUNT denotes the number of coprocessor condition bits
1840    examined by the branch.  */
1841
1842 static CORE_ADDR
1843 micromips_bc1_pc (struct gdbarch *gdbarch, struct frame_info *frame,
1844                   ULONGEST insn, CORE_ADDR pc, int count)
1845 {
1846   int fcsr = mips_regnum (gdbarch)->fp_control_status;
1847   int cnum = b2s3_cc (insn >> 16) & (count - 1);
1848   int tf = b5s5_op (insn >> 16) & 1;
1849   int mask = (1 << count) - 1;
1850   ULONGEST fcs;
1851   int cond;
1852
1853   if (fcsr == -1)
1854     /* No way to handle; it'll most likely trap anyway.  */
1855     return pc;
1856
1857   fcs = get_frame_register_unsigned (frame, fcsr);
1858   cond = ((fcs >> 24) & 0xfe) | ((fcs >> 23) & 0x01);
1859
1860   if (((cond >> cnum) & mask) != mask * !tf)
1861     pc += micromips_relative_offset16 (insn);
1862   else
1863     pc += micromips_pc_insn_size (gdbarch, pc);
1864
1865   return pc;
1866 }
1867
1868 /* Calculate the address of the next microMIPS instruction to execute
1869    after the instruction at the address PC.  */
1870
1871 static CORE_ADDR
1872 micromips_next_pc (struct frame_info *frame, CORE_ADDR pc)
1873 {
1874   struct gdbarch *gdbarch = get_frame_arch (frame);
1875   ULONGEST insn;
1876
1877   insn = mips_fetch_instruction (gdbarch, ISA_MICROMIPS, pc, NULL);
1878   pc += MIPS_INSN16_SIZE;
1879   switch (mips_insn_size (ISA_MICROMIPS, insn))
1880     {
1881     /* 48-bit instructions.  */
1882     case 3 * MIPS_INSN16_SIZE: /* POOL48A: bits 011111 */
1883       /* No branch or jump instructions in this category.  */
1884       pc += 2 * MIPS_INSN16_SIZE;
1885       break;
1886
1887     /* 32-bit instructions.  */
1888     case 2 * MIPS_INSN16_SIZE:
1889       insn <<= 16;
1890       insn |= mips_fetch_instruction (gdbarch, ISA_MICROMIPS, pc, NULL);
1891       pc += MIPS_INSN16_SIZE;
1892       switch (micromips_op (insn >> 16))
1893         {
1894         case 0x00: /* POOL32A: bits 000000 */
1895           if (b0s6_op (insn) == 0x3c
1896                                 /* POOL32Axf: bits 000000 ... 111100 */
1897               && (b6s10_ext (insn) & 0x2bf) == 0x3c)
1898                                 /* JALR, JALR.HB: 000000 000x111100 111100 */
1899                                 /* JALRS, JALRS.HB: 000000 010x111100 111100 */
1900             pc = get_frame_register_signed (frame, b0s5_reg (insn >> 16));
1901           break;
1902
1903         case 0x10: /* POOL32I: bits 010000 */
1904           switch (b5s5_op (insn >> 16))
1905             {
1906             case 0x00: /* BLTZ: bits 010000 00000 */
1907             case 0x01: /* BLTZAL: bits 010000 00001 */
1908             case 0x11: /* BLTZALS: bits 010000 10001 */
1909               if (get_frame_register_signed (frame,
1910                                              b0s5_reg (insn >> 16)) < 0)
1911                 pc += micromips_relative_offset16 (insn);
1912               else
1913                 pc += micromips_pc_insn_size (gdbarch, pc);
1914               break;
1915
1916             case 0x02: /* BGEZ: bits 010000 00010 */
1917             case 0x03: /* BGEZAL: bits 010000 00011 */
1918             case 0x13: /* BGEZALS: bits 010000 10011 */
1919               if (get_frame_register_signed (frame,
1920                                              b0s5_reg (insn >> 16)) >= 0)
1921                 pc += micromips_relative_offset16 (insn);
1922               else
1923                 pc += micromips_pc_insn_size (gdbarch, pc);
1924               break;
1925
1926             case 0x04: /* BLEZ: bits 010000 00100 */
1927               if (get_frame_register_signed (frame,
1928                                              b0s5_reg (insn >> 16)) <= 0)
1929                 pc += micromips_relative_offset16 (insn);
1930               else
1931                 pc += micromips_pc_insn_size (gdbarch, pc);
1932               break;
1933
1934             case 0x05: /* BNEZC: bits 010000 00101 */
1935               if (get_frame_register_signed (frame,
1936                                              b0s5_reg (insn >> 16)) != 0)
1937                 pc += micromips_relative_offset16 (insn);
1938               break;
1939
1940             case 0x06: /* BGTZ: bits 010000 00110 */
1941               if (get_frame_register_signed (frame,
1942                                              b0s5_reg (insn >> 16)) > 0)
1943                 pc += micromips_relative_offset16 (insn);
1944               else
1945                 pc += micromips_pc_insn_size (gdbarch, pc);
1946               break;
1947
1948             case 0x07: /* BEQZC: bits 010000 00111 */
1949               if (get_frame_register_signed (frame,
1950                                              b0s5_reg (insn >> 16)) == 0)
1951                 pc += micromips_relative_offset16 (insn);
1952               break;
1953
1954             case 0x14: /* BC2F: bits 010000 10100 xxx00 */
1955             case 0x15: /* BC2T: bits 010000 10101 xxx00 */
1956               if (((insn >> 16) & 0x3) == 0x0)
1957                 /* BC2F, BC2T: don't know how to handle these.  */
1958                 break;
1959               break;
1960
1961             case 0x1a: /* BPOSGE64: bits 010000 11010 */
1962             case 0x1b: /* BPOSGE32: bits 010000 11011 */
1963               {
1964                 unsigned int pos = (b5s5_op (insn >> 16) & 1) ? 32 : 64;
1965                 int dspctl = mips_regnum (gdbarch)->dspctl;
1966
1967                 if (dspctl == -1)
1968                   /* No way to handle; it'll most likely trap anyway.  */
1969                   break;
1970
1971                 if ((get_frame_register_unsigned (frame,
1972                                                   dspctl) & 0x7f) >= pos)
1973                   pc += micromips_relative_offset16 (insn);
1974                 else
1975                   pc += micromips_pc_insn_size (gdbarch, pc);
1976               }
1977               break;
1978
1979             case 0x1c: /* BC1F: bits 010000 11100 xxx00 */
1980                        /* BC1ANY2F: bits 010000 11100 xxx01 */
1981             case 0x1d: /* BC1T: bits 010000 11101 xxx00 */
1982                        /* BC1ANY2T: bits 010000 11101 xxx01 */
1983               if (((insn >> 16) & 0x2) == 0x0)
1984                 pc = micromips_bc1_pc (gdbarch, frame, insn, pc,
1985                                        ((insn >> 16) & 0x1) + 1);
1986               break;
1987
1988             case 0x1e: /* BC1ANY4F: bits 010000 11110 xxx01 */
1989             case 0x1f: /* BC1ANY4T: bits 010000 11111 xxx01 */
1990               if (((insn >> 16) & 0x3) == 0x1)
1991                 pc = micromips_bc1_pc (gdbarch, frame, insn, pc, 4);
1992               break;
1993             }
1994           break;
1995
1996         case 0x1d: /* JALS: bits 011101 */
1997         case 0x35: /* J: bits 110101 */
1998         case 0x3d: /* JAL: bits 111101 */
1999             pc = ((pc | 0x7fffffe) ^ 0x7fffffe) | (b0s26_imm (insn) << 1);
2000           break;
2001
2002         case 0x25: /* BEQ: bits 100101 */
2003             if (get_frame_register_signed (frame, b0s5_reg (insn >> 16))
2004                 == get_frame_register_signed (frame, b5s5_reg (insn >> 16)))
2005               pc += micromips_relative_offset16 (insn);
2006             else
2007               pc += micromips_pc_insn_size (gdbarch, pc);
2008           break;
2009
2010         case 0x2d: /* BNE: bits 101101 */
2011             if (get_frame_register_signed (frame, b0s5_reg (insn >> 16))
2012                 != get_frame_register_signed (frame, b5s5_reg (insn >> 16)))
2013               pc += micromips_relative_offset16 (insn);
2014             else
2015               pc += micromips_pc_insn_size (gdbarch, pc);
2016           break;
2017
2018         case 0x3c: /* JALX: bits 111100 */
2019             pc = ((pc | 0xfffffff) ^ 0xfffffff) | (b0s26_imm (insn) << 2);
2020           break;
2021         }
2022       break;
2023
2024     /* 16-bit instructions.  */
2025     case MIPS_INSN16_SIZE:
2026       switch (micromips_op (insn))
2027         {
2028         case 0x11: /* POOL16C: bits 010001 */
2029           if ((b5s5_op (insn) & 0x1c) == 0xc)
2030             /* JR16, JRC, JALR16, JALRS16: 010001 011xx */
2031             pc = get_frame_register_signed (frame, b0s5_reg (insn));
2032           else if (b5s5_op (insn) == 0x18)
2033             /* JRADDIUSP: bits 010001 11000 */
2034             pc = get_frame_register_signed (frame, MIPS_RA_REGNUM);
2035           break;
2036
2037         case 0x23: /* BEQZ16: bits 100011 */
2038           {
2039             int rs = mips_reg3_to_reg[b7s3_reg (insn)];
2040
2041             if (get_frame_register_signed (frame, rs) == 0)
2042               pc += micromips_relative_offset7 (insn);
2043             else
2044               pc += micromips_pc_insn_size (gdbarch, pc);
2045           }
2046           break;
2047
2048         case 0x2b: /* BNEZ16: bits 101011 */
2049           {
2050             int rs = mips_reg3_to_reg[b7s3_reg (insn)];
2051
2052             if (get_frame_register_signed (frame, rs) != 0)
2053               pc += micromips_relative_offset7 (insn);
2054             else
2055               pc += micromips_pc_insn_size (gdbarch, pc);
2056           }
2057           break;
2058
2059         case 0x33: /* B16: bits 110011 */
2060           pc += micromips_relative_offset10 (insn);
2061           break;
2062         }
2063       break;
2064     }
2065
2066   return pc;
2067 }
2068
2069 /* Decoding the next place to set a breakpoint is irregular for the
2070    mips 16 variant, but fortunately, there fewer instructions.  We have
2071    to cope ith extensions for 16 bit instructions and a pair of actual
2072    32 bit instructions.  We dont want to set a single step instruction
2073    on the extend instruction either.  */
2074
2075 /* Lots of mips16 instruction formats */
2076 /* Predicting jumps requires itype,ritype,i8type
2077    and their extensions      extItype,extritype,extI8type.  */
2078 enum mips16_inst_fmts
2079 {
2080   itype,                        /* 0  immediate 5,10 */
2081   ritype,                       /* 1   5,3,8 */
2082   rrtype,                       /* 2   5,3,3,5 */
2083   rritype,                      /* 3   5,3,3,5 */
2084   rrrtype,                      /* 4   5,3,3,3,2 */
2085   rriatype,                     /* 5   5,3,3,1,4 */
2086   shifttype,                    /* 6   5,3,3,3,2 */
2087   i8type,                       /* 7   5,3,8 */
2088   i8movtype,                    /* 8   5,3,3,5 */
2089   i8mov32rtype,                 /* 9   5,3,5,3 */
2090   i64type,                      /* 10  5,3,8 */
2091   ri64type,                     /* 11  5,3,3,5 */
2092   jalxtype,                     /* 12  5,1,5,5,16 - a 32 bit instruction */
2093   exiItype,                     /* 13  5,6,5,5,1,1,1,1,1,1,5 */
2094   extRitype,                    /* 14  5,6,5,5,3,1,1,1,5 */
2095   extRRItype,                   /* 15  5,5,5,5,3,3,5 */
2096   extRRIAtype,                  /* 16  5,7,4,5,3,3,1,4 */
2097   EXTshifttype,                 /* 17  5,5,1,1,1,1,1,1,5,3,3,1,1,1,2 */
2098   extI8type,                    /* 18  5,6,5,5,3,1,1,1,5 */
2099   extI64type,                   /* 19  5,6,5,5,3,1,1,1,5 */
2100   extRi64type,                  /* 20  5,6,5,5,3,3,5 */
2101   extshift64type                /* 21  5,5,1,1,1,1,1,1,5,1,1,1,3,5 */
2102 };
2103 /* I am heaping all the fields of the formats into one structure and
2104    then, only the fields which are involved in instruction extension.  */
2105 struct upk_mips16
2106 {
2107   CORE_ADDR offset;
2108   unsigned int regx;            /* Function in i8 type.  */
2109   unsigned int regy;
2110 };
2111
2112
2113 /* The EXT-I, EXT-ri nad EXT-I8 instructions all have the same format
2114    for the bits which make up the immediate extension.  */
2115
2116 static CORE_ADDR
2117 extended_offset (unsigned int extension)
2118 {
2119   CORE_ADDR value;
2120
2121   value = (extension >> 16) & 0x1f;     /* Extract 15:11.  */
2122   value = value << 6;
2123   value |= (extension >> 21) & 0x3f;    /* Extract 10:5.  */
2124   value = value << 5;
2125   value |= extension & 0x1f;            /* Extract 4:0.  */
2126
2127   return value;
2128 }
2129
2130 /* Only call this function if you know that this is an extendable
2131    instruction.  It won't malfunction, but why make excess remote memory
2132    references?  If the immediate operands get sign extended or something,
2133    do it after the extension is performed.  */
2134 /* FIXME: Every one of these cases needs to worry about sign extension
2135    when the offset is to be used in relative addressing.  */
2136
2137 static unsigned int
2138 fetch_mips_16 (struct gdbarch *gdbarch, CORE_ADDR pc)
2139 {
2140   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2141   gdb_byte buf[8];
2142
2143   pc = unmake_compact_addr (pc);        /* Clear the low order bit.  */
2144   target_read_memory (pc, buf, 2);
2145   return extract_unsigned_integer (buf, 2, byte_order);
2146 }
2147
2148 static void
2149 unpack_mips16 (struct gdbarch *gdbarch, CORE_ADDR pc,
2150                unsigned int extension,
2151                unsigned int inst,
2152                enum mips16_inst_fmts insn_format, struct upk_mips16 *upk)
2153 {
2154   CORE_ADDR offset;
2155   int regx;
2156   int regy;
2157   switch (insn_format)
2158     {
2159     case itype:
2160       {
2161         CORE_ADDR value;
2162         if (extension)
2163           {
2164             value = extended_offset ((extension << 16) | inst);
2165             value = (value ^ 0x8000) - 0x8000;          /* Sign-extend.  */
2166           }
2167         else
2168           {
2169             value = inst & 0x7ff;
2170             value = (value ^ 0x400) - 0x400;            /* Sign-extend.  */
2171           }
2172         offset = value;
2173         regx = -1;
2174         regy = -1;
2175       }
2176       break;
2177     case ritype:
2178     case i8type:
2179       {                         /* A register identifier and an offset.  */
2180         /* Most of the fields are the same as I type but the
2181            immediate value is of a different length.  */
2182         CORE_ADDR value;
2183         if (extension)
2184           {
2185             value = extended_offset ((extension << 16) | inst);
2186             value = (value ^ 0x8000) - 0x8000;          /* Sign-extend.  */
2187           }
2188         else
2189           {
2190             value = inst & 0xff;                        /* 8 bits */
2191             value = (value ^ 0x80) - 0x80;              /* Sign-extend.  */
2192           }
2193         offset = value;
2194         regx = (inst >> 8) & 0x07;                      /* i8 funct */
2195         regy = -1;
2196         break;
2197       }
2198     case jalxtype:
2199       {
2200         unsigned long value;
2201         unsigned int nexthalf;
2202         value = ((inst & 0x1f) << 5) | ((inst >> 5) & 0x1f);
2203         value = value << 16;
2204         nexthalf = mips_fetch_instruction (gdbarch, ISA_MIPS16, pc + 2, NULL);
2205                                                 /* Low bit still set.  */
2206         value |= nexthalf;
2207         offset = value;
2208         regx = -1;
2209         regy = -1;
2210         break;
2211       }
2212     default:
2213       internal_error (__FILE__, __LINE__, _("bad switch"));
2214     }
2215   upk->offset = offset;
2216   upk->regx = regx;
2217   upk->regy = regy;
2218 }
2219
2220
2221 /* Calculate the destination of a branch whose 16-bit opcode word is at PC,
2222    and having a signed 16-bit OFFSET.  */
2223
2224 static CORE_ADDR
2225 add_offset_16 (CORE_ADDR pc, int offset)
2226 {
2227   return pc + (offset << 1) + 2;
2228 }
2229
2230 static CORE_ADDR
2231 extended_mips16_next_pc (struct frame_info *frame, CORE_ADDR pc,
2232                          unsigned int extension, unsigned int insn)
2233 {
2234   struct gdbarch *gdbarch = get_frame_arch (frame);
2235   int op = (insn >> 11);
2236   switch (op)
2237     {
2238     case 2:                     /* Branch */
2239       {
2240         struct upk_mips16 upk;
2241         unpack_mips16 (gdbarch, pc, extension, insn, itype, &upk);
2242         pc = add_offset_16 (pc, upk.offset);
2243         break;
2244       }
2245     case 3:                     /* JAL , JALX - Watch out, these are 32 bit
2246                                    instructions.  */
2247       {
2248         struct upk_mips16 upk;
2249         unpack_mips16 (gdbarch, pc, extension, insn, jalxtype, &upk);
2250         pc = ((pc + 2) & (~(CORE_ADDR) 0x0fffffff)) | (upk.offset << 2);
2251         if ((insn >> 10) & 0x01)        /* Exchange mode */
2252           pc = pc & ~0x01;      /* Clear low bit, indicate 32 bit mode.  */
2253         else
2254           pc |= 0x01;
2255         break;
2256       }
2257     case 4:                     /* beqz */
2258       {
2259         struct upk_mips16 upk;
2260         int reg;
2261         unpack_mips16 (gdbarch, pc, extension, insn, ritype, &upk);
2262         reg = get_frame_register_signed (frame, mips_reg3_to_reg[upk.regx]);
2263         if (reg == 0)
2264           pc = add_offset_16 (pc, upk.offset);
2265         else
2266           pc += 2;
2267         break;
2268       }
2269     case 5:                     /* bnez */
2270       {
2271         struct upk_mips16 upk;
2272         int reg;
2273         unpack_mips16 (gdbarch, pc, extension, insn, ritype, &upk);
2274         reg = get_frame_register_signed (frame, mips_reg3_to_reg[upk.regx]);
2275         if (reg != 0)
2276           pc = add_offset_16 (pc, upk.offset);
2277         else
2278           pc += 2;
2279         break;
2280       }
2281     case 12:                    /* I8 Formats btez btnez */
2282       {
2283         struct upk_mips16 upk;
2284         int reg;
2285         unpack_mips16 (gdbarch, pc, extension, insn, i8type, &upk);
2286         /* upk.regx contains the opcode */
2287         reg = get_frame_register_signed (frame, 24);  /* Test register is 24 */
2288         if (((upk.regx == 0) && (reg == 0))     /* BTEZ */
2289             || ((upk.regx == 1) && (reg != 0))) /* BTNEZ */
2290           pc = add_offset_16 (pc, upk.offset);
2291         else
2292           pc += 2;
2293         break;
2294       }
2295     case 29:                    /* RR Formats JR, JALR, JALR-RA */
2296       {
2297         struct upk_mips16 upk;
2298         /* upk.fmt = rrtype; */
2299         op = insn & 0x1f;
2300         if (op == 0)
2301           {
2302             int reg;
2303             upk.regx = (insn >> 8) & 0x07;
2304             upk.regy = (insn >> 5) & 0x07;
2305             if ((upk.regy & 1) == 0)
2306               reg = mips_reg3_to_reg[upk.regx];
2307             else
2308               reg = 31;         /* Function return instruction.  */
2309             pc = get_frame_register_signed (frame, reg);
2310           }
2311         else
2312           pc += 2;
2313         break;
2314       }
2315     case 30:
2316       /* This is an instruction extension.  Fetch the real instruction
2317          (which follows the extension) and decode things based on
2318          that.  */
2319       {
2320         pc += 2;
2321         pc = extended_mips16_next_pc (frame, pc, insn,
2322                                       fetch_mips_16 (gdbarch, pc));
2323         break;
2324       }
2325     default:
2326       {
2327         pc += 2;
2328         break;
2329       }
2330     }
2331   return pc;
2332 }
2333
2334 static CORE_ADDR
2335 mips16_next_pc (struct frame_info *frame, CORE_ADDR pc)
2336 {
2337   struct gdbarch *gdbarch = get_frame_arch (frame);
2338   unsigned int insn = fetch_mips_16 (gdbarch, pc);
2339   return extended_mips16_next_pc (frame, pc, 0, insn);
2340 }
2341
2342 /* The mips_next_pc function supports single_step when the remote
2343    target monitor or stub is not developed enough to do a single_step.
2344    It works by decoding the current instruction and predicting where a
2345    branch will go.  This isn't hard because all the data is available.
2346    The MIPS32, MIPS16 and microMIPS variants are quite different.  */
2347 static CORE_ADDR
2348 mips_next_pc (struct frame_info *frame, CORE_ADDR pc)
2349 {
2350   struct gdbarch *gdbarch = get_frame_arch (frame);
2351
2352   if (mips_pc_is_mips16 (gdbarch, pc))
2353     return mips16_next_pc (frame, pc);
2354   else if (mips_pc_is_micromips (gdbarch, pc))
2355     return micromips_next_pc (frame, pc);
2356   else
2357     return mips32_next_pc (frame, pc);
2358 }
2359
2360 /* Return non-zero if the MIPS16 instruction INSN is a compact branch
2361    or jump.  */
2362
2363 static int
2364 mips16_instruction_is_compact_branch (unsigned short insn)
2365 {
2366   switch (insn & 0xf800)
2367     {
2368     case 0xe800:
2369       return (insn & 0x009f) == 0x80;   /* JALRC/JRC */
2370     case 0x6000:
2371       return (insn & 0x0600) == 0;      /* BTNEZ/BTEQZ */
2372     case 0x2800:                        /* BNEZ */
2373     case 0x2000:                        /* BEQZ */
2374     case 0x1000:                        /* B */
2375       return 1;
2376     default:
2377       return 0;
2378     }
2379 }
2380
2381 /* Return non-zero if the microMIPS instruction INSN is a compact branch
2382    or jump.  */
2383
2384 static int
2385 micromips_instruction_is_compact_branch (unsigned short insn)
2386 {
2387   switch (micromips_op (insn))
2388     {
2389     case 0x11:                  /* POOL16C: bits 010001 */
2390       return (b5s5_op (insn) == 0x18
2391                                 /* JRADDIUSP: bits 010001 11000 */
2392               || b5s5_op (insn) == 0xd);
2393                                 /* JRC: bits 010011 01101 */
2394     case 0x10:                  /* POOL32I: bits 010000 */
2395       return (b5s5_op (insn) & 0x1d) == 0x5;
2396                                 /* BEQZC/BNEZC: bits 010000 001x1 */
2397     default:
2398       return 0;
2399     }
2400 }
2401
2402 struct mips_frame_cache
2403 {
2404   CORE_ADDR base;
2405   struct trad_frame_saved_reg *saved_regs;
2406 };
2407
2408 /* Set a register's saved stack address in temp_saved_regs.  If an
2409    address has already been set for this register, do nothing; this
2410    way we will only recognize the first save of a given register in a
2411    function prologue.
2412
2413    For simplicity, save the address in both [0 .. gdbarch_num_regs) and
2414    [gdbarch_num_regs .. 2*gdbarch_num_regs).
2415    Strictly speaking, only the second range is used as it is only second
2416    range (the ABI instead of ISA registers) that comes into play when finding
2417    saved registers in a frame.  */
2418
2419 static void
2420 set_reg_offset (struct gdbarch *gdbarch, struct mips_frame_cache *this_cache,
2421                 int regnum, CORE_ADDR offset)
2422 {
2423   if (this_cache != NULL
2424       && this_cache->saved_regs[regnum].addr == -1)
2425     {
2426       this_cache->saved_regs[regnum + 0 * gdbarch_num_regs (gdbarch)].addr
2427         = offset;
2428       this_cache->saved_regs[regnum + 1 * gdbarch_num_regs (gdbarch)].addr
2429         = offset;
2430     }
2431 }
2432
2433
2434 /* Fetch the immediate value from a MIPS16 instruction.
2435    If the previous instruction was an EXTEND, use it to extend
2436    the upper bits of the immediate value.  This is a helper function
2437    for mips16_scan_prologue.  */
2438
2439 static int
2440 mips16_get_imm (unsigned short prev_inst,       /* previous instruction */
2441                 unsigned short inst,    /* current instruction */
2442                 int nbits,      /* number of bits in imm field */
2443                 int scale,      /* scale factor to be applied to imm */
2444                 int is_signed)  /* is the imm field signed?  */
2445 {
2446   int offset;
2447
2448   if ((prev_inst & 0xf800) == 0xf000)   /* prev instruction was EXTEND? */
2449     {
2450       offset = ((prev_inst & 0x1f) << 11) | (prev_inst & 0x7e0);
2451       if (offset & 0x8000)      /* check for negative extend */
2452         offset = 0 - (0x10000 - (offset & 0xffff));
2453       return offset | (inst & 0x1f);
2454     }
2455   else
2456     {
2457       int max_imm = 1 << nbits;
2458       int mask = max_imm - 1;
2459       int sign_bit = max_imm >> 1;
2460
2461       offset = inst & mask;
2462       if (is_signed && (offset & sign_bit))
2463         offset = 0 - (max_imm - offset);
2464       return offset * scale;
2465     }
2466 }
2467
2468
2469 /* Analyze the function prologue from START_PC to LIMIT_PC. Builds
2470    the associated FRAME_CACHE if not null.
2471    Return the address of the first instruction past the prologue.  */
2472
2473 static CORE_ADDR
2474 mips16_scan_prologue (struct gdbarch *gdbarch,
2475                       CORE_ADDR start_pc, CORE_ADDR limit_pc,
2476                       struct frame_info *this_frame,
2477                       struct mips_frame_cache *this_cache)
2478 {
2479   int prev_non_prologue_insn = 0;
2480   int this_non_prologue_insn;
2481   int non_prologue_insns = 0;
2482   CORE_ADDR prev_pc;
2483   CORE_ADDR cur_pc;
2484   CORE_ADDR frame_addr = 0;     /* Value of $r17, used as frame pointer.  */
2485   CORE_ADDR sp;
2486   long frame_offset = 0;        /* Size of stack frame.  */
2487   long frame_adjust = 0;        /* Offset of FP from SP.  */
2488   int frame_reg = MIPS_SP_REGNUM;
2489   unsigned short prev_inst = 0; /* saved copy of previous instruction.  */
2490   unsigned inst = 0;            /* current instruction */
2491   unsigned entry_inst = 0;      /* the entry instruction */
2492   unsigned save_inst = 0;       /* the save instruction */
2493   int prev_delay_slot = 0;
2494   int in_delay_slot;
2495   int reg, offset;
2496
2497   int extend_bytes = 0;
2498   int prev_extend_bytes = 0;
2499   CORE_ADDR end_prologue_addr;
2500
2501   /* Can be called when there's no process, and hence when there's no
2502      THIS_FRAME.  */
2503   if (this_frame != NULL)
2504     sp = get_frame_register_signed (this_frame,
2505                                     gdbarch_num_regs (gdbarch)
2506                                     + MIPS_SP_REGNUM);
2507   else
2508     sp = 0;
2509
2510   if (limit_pc > start_pc + 200)
2511     limit_pc = start_pc + 200;
2512   prev_pc = start_pc;
2513
2514   /* Permit at most one non-prologue non-control-transfer instruction
2515      in the middle which may have been reordered by the compiler for
2516      optimisation.  */
2517   for (cur_pc = start_pc; cur_pc < limit_pc; cur_pc += MIPS_INSN16_SIZE)
2518     {
2519       this_non_prologue_insn = 0;
2520       in_delay_slot = 0;
2521
2522       /* Save the previous instruction.  If it's an EXTEND, we'll extract
2523          the immediate offset extension from it in mips16_get_imm.  */
2524       prev_inst = inst;
2525
2526       /* Fetch and decode the instruction.  */
2527       inst = (unsigned short) mips_fetch_instruction (gdbarch, ISA_MIPS16,
2528                                                       cur_pc, NULL);
2529
2530       /* Normally we ignore extend instructions.  However, if it is
2531          not followed by a valid prologue instruction, then this
2532          instruction is not part of the prologue either.  We must
2533          remember in this case to adjust the end_prologue_addr back
2534          over the extend.  */
2535       if ((inst & 0xf800) == 0xf000)    /* extend */
2536         {
2537           extend_bytes = MIPS_INSN16_SIZE;
2538           continue;
2539         }
2540
2541       prev_extend_bytes = extend_bytes;
2542       extend_bytes = 0;
2543
2544       if ((inst & 0xff00) == 0x6300     /* addiu sp */
2545           || (inst & 0xff00) == 0xfb00) /* daddiu sp */
2546         {
2547           offset = mips16_get_imm (prev_inst, inst, 8, 8, 1);
2548           if (offset < 0)       /* Negative stack adjustment?  */
2549             frame_offset -= offset;
2550           else
2551             /* Exit loop if a positive stack adjustment is found, which
2552                usually means that the stack cleanup code in the function
2553                epilogue is reached.  */
2554             break;
2555         }
2556       else if ((inst & 0xf800) == 0xd000)       /* sw reg,n($sp) */
2557         {
2558           offset = mips16_get_imm (prev_inst, inst, 8, 4, 0);
2559           reg = mips_reg3_to_reg[(inst & 0x700) >> 8];
2560           set_reg_offset (gdbarch, this_cache, reg, sp + offset);
2561         }
2562       else if ((inst & 0xff00) == 0xf900)       /* sd reg,n($sp) */
2563         {
2564           offset = mips16_get_imm (prev_inst, inst, 5, 8, 0);
2565           reg = mips_reg3_to_reg[(inst & 0xe0) >> 5];
2566           set_reg_offset (gdbarch, this_cache, reg, sp + offset);
2567         }
2568       else if ((inst & 0xff00) == 0x6200)       /* sw $ra,n($sp) */
2569         {
2570           offset = mips16_get_imm (prev_inst, inst, 8, 4, 0);
2571           set_reg_offset (gdbarch, this_cache, MIPS_RA_REGNUM, sp + offset);
2572         }
2573       else if ((inst & 0xff00) == 0xfa00)       /* sd $ra,n($sp) */
2574         {
2575           offset = mips16_get_imm (prev_inst, inst, 8, 8, 0);
2576           set_reg_offset (gdbarch, this_cache, MIPS_RA_REGNUM, sp + offset);
2577         }
2578       else if (inst == 0x673d)  /* move $s1, $sp */
2579         {
2580           frame_addr = sp;
2581           frame_reg = 17;
2582         }
2583       else if ((inst & 0xff00) == 0x0100)       /* addiu $s1,sp,n */
2584         {
2585           offset = mips16_get_imm (prev_inst, inst, 8, 4, 0);
2586           frame_addr = sp + offset;
2587           frame_reg = 17;
2588           frame_adjust = offset;
2589         }
2590       else if ((inst & 0xFF00) == 0xd900)       /* sw reg,offset($s1) */
2591         {
2592           offset = mips16_get_imm (prev_inst, inst, 5, 4, 0);
2593           reg = mips_reg3_to_reg[(inst & 0xe0) >> 5];
2594           set_reg_offset (gdbarch, this_cache, reg, frame_addr + offset);
2595         }
2596       else if ((inst & 0xFF00) == 0x7900)       /* sd reg,offset($s1) */
2597         {
2598           offset = mips16_get_imm (prev_inst, inst, 5, 8, 0);
2599           reg = mips_reg3_to_reg[(inst & 0xe0) >> 5];
2600           set_reg_offset (gdbarch, this_cache, reg, frame_addr + offset);
2601         }
2602       else if ((inst & 0xf81f) == 0xe809
2603                && (inst & 0x700) != 0x700)      /* entry */
2604         entry_inst = inst;      /* Save for later processing.  */
2605       else if ((inst & 0xff80) == 0x6480)       /* save */
2606         {
2607           save_inst = inst;     /* Save for later processing.  */
2608           if (prev_extend_bytes)                /* extend */
2609             save_inst |= prev_inst << 16;
2610         }
2611       else if ((inst & 0xff1c) == 0x6704)       /* move reg,$a0-$a3 */
2612         {
2613           /* This instruction is part of the prologue, but we don't
2614              need to do anything special to handle it.  */
2615         }
2616       else if (mips16_instruction_has_delay_slot (inst, 0))
2617                                                 /* JAL/JALR/JALX/JR */
2618         {
2619           /* The instruction in the delay slot can be a part
2620              of the prologue, so move forward once more.  */
2621           in_delay_slot = 1;
2622           if (mips16_instruction_has_delay_slot (inst, 1))
2623                                                 /* JAL/JALX */
2624             {
2625               prev_extend_bytes = MIPS_INSN16_SIZE;
2626               cur_pc += MIPS_INSN16_SIZE;       /* 32-bit instruction */
2627             }
2628         }
2629       else
2630         {
2631           this_non_prologue_insn = 1;
2632         }
2633
2634       non_prologue_insns += this_non_prologue_insn;
2635
2636       /* A jump or branch, or enough non-prologue insns seen?  If so,
2637          then we must have reached the end of the prologue by now.  */
2638       if (prev_delay_slot || non_prologue_insns > 1
2639           || mips16_instruction_is_compact_branch (inst))
2640         break;
2641
2642       prev_non_prologue_insn = this_non_prologue_insn;
2643       prev_delay_slot = in_delay_slot;
2644       prev_pc = cur_pc - prev_extend_bytes;
2645     }
2646
2647   /* The entry instruction is typically the first instruction in a function,
2648      and it stores registers at offsets relative to the value of the old SP
2649      (before the prologue).  But the value of the sp parameter to this
2650      function is the new SP (after the prologue has been executed).  So we
2651      can't calculate those offsets until we've seen the entire prologue,
2652      and can calculate what the old SP must have been.  */
2653   if (entry_inst != 0)
2654     {
2655       int areg_count = (entry_inst >> 8) & 7;
2656       int sreg_count = (entry_inst >> 6) & 3;
2657
2658       /* The entry instruction always subtracts 32 from the SP.  */
2659       frame_offset += 32;
2660
2661       /* Now we can calculate what the SP must have been at the
2662          start of the function prologue.  */
2663       sp += frame_offset;
2664
2665       /* Check if a0-a3 were saved in the caller's argument save area.  */
2666       for (reg = 4, offset = 0; reg < areg_count + 4; reg++)
2667         {
2668           set_reg_offset (gdbarch, this_cache, reg, sp + offset);
2669           offset += mips_abi_regsize (gdbarch);
2670         }
2671
2672       /* Check if the ra register was pushed on the stack.  */
2673       offset = -4;
2674       if (entry_inst & 0x20)
2675         {
2676           set_reg_offset (gdbarch, this_cache, MIPS_RA_REGNUM, sp + offset);
2677           offset -= mips_abi_regsize (gdbarch);
2678         }
2679
2680       /* Check if the s0 and s1 registers were pushed on the stack.  */
2681       for (reg = 16; reg < sreg_count + 16; reg++)
2682         {
2683           set_reg_offset (gdbarch, this_cache, reg, sp + offset);
2684           offset -= mips_abi_regsize (gdbarch);
2685         }
2686     }
2687
2688   /* The SAVE instruction is similar to ENTRY, except that defined by the
2689      MIPS16e ASE of the MIPS Architecture.  Unlike with ENTRY though, the
2690      size of the frame is specified as an immediate field of instruction
2691      and an extended variation exists which lets additional registers and
2692      frame space to be specified.  The instruction always treats registers
2693      as 32-bit so its usefulness for 64-bit ABIs is questionable.  */
2694   if (save_inst != 0 && mips_abi_regsize (gdbarch) == 4)
2695     {
2696       static int args_table[16] = {
2697         0, 0, 0, 0, 1, 1, 1, 1,
2698         2, 2, 2, 0, 3, 3, 4, -1,
2699       };
2700       static int astatic_table[16] = {
2701         0, 1, 2, 3, 0, 1, 2, 3,
2702         0, 1, 2, 4, 0, 1, 0, -1,
2703       };
2704       int aregs = (save_inst >> 16) & 0xf;
2705       int xsregs = (save_inst >> 24) & 0x7;
2706       int args = args_table[aregs];
2707       int astatic = astatic_table[aregs];
2708       long frame_size;
2709
2710       if (args < 0)
2711         {
2712           warning (_("Invalid number of argument registers encoded in SAVE."));
2713           args = 0;
2714         }
2715       if (astatic < 0)
2716         {
2717           warning (_("Invalid number of static registers encoded in SAVE."));
2718           astatic = 0;
2719         }
2720
2721       /* For standard SAVE the frame size of 0 means 128.  */
2722       frame_size = ((save_inst >> 16) & 0xf0) | (save_inst & 0xf);
2723       if (frame_size == 0 && (save_inst >> 16) == 0)
2724         frame_size = 16;
2725       frame_size *= 8;
2726       frame_offset += frame_size;
2727
2728       /* Now we can calculate what the SP must have been at the
2729          start of the function prologue.  */
2730       sp += frame_offset;
2731
2732       /* Check if A0-A3 were saved in the caller's argument save area.  */
2733       for (reg = MIPS_A0_REGNUM, offset = 0; reg < args + 4; reg++)
2734         {
2735           set_reg_offset (gdbarch, this_cache, reg, sp + offset);
2736           offset += mips_abi_regsize (gdbarch);
2737         }
2738
2739       offset = -4;
2740
2741       /* Check if the RA register was pushed on the stack.  */
2742       if (save_inst & 0x40)
2743         {
2744           set_reg_offset (gdbarch, this_cache, MIPS_RA_REGNUM, sp + offset);
2745           offset -= mips_abi_regsize (gdbarch);
2746         }
2747
2748       /* Check if the S8 register was pushed on the stack.  */
2749       if (xsregs > 6)
2750         {
2751           set_reg_offset (gdbarch, this_cache, 30, sp + offset);
2752           offset -= mips_abi_regsize (gdbarch);
2753           xsregs--;
2754         }
2755       /* Check if S2-S7 were pushed on the stack.  */
2756       for (reg = 18 + xsregs - 1; reg > 18 - 1; reg--)
2757         {
2758           set_reg_offset (gdbarch, this_cache, reg, sp + offset);
2759           offset -= mips_abi_regsize (gdbarch);
2760         }
2761
2762       /* Check if the S1 register was pushed on the stack.  */
2763       if (save_inst & 0x10)
2764         {
2765           set_reg_offset (gdbarch, this_cache, 17, sp + offset);
2766           offset -= mips_abi_regsize (gdbarch);
2767         }
2768       /* Check if the S0 register was pushed on the stack.  */
2769       if (save_inst & 0x20)
2770         {
2771           set_reg_offset (gdbarch, this_cache, 16, sp + offset);
2772           offset -= mips_abi_regsize (gdbarch);
2773         }
2774
2775       /* Check if A0-A3 were pushed on the stack.  */
2776       for (reg = MIPS_A0_REGNUM + 3; reg > MIPS_A0_REGNUM + 3 - astatic; reg--)
2777         {
2778           set_reg_offset (gdbarch, this_cache, reg, sp + offset);
2779           offset -= mips_abi_regsize (gdbarch);
2780         }
2781     }
2782
2783   if (this_cache != NULL)
2784     {
2785       this_cache->base =
2786         (get_frame_register_signed (this_frame,
2787                                     gdbarch_num_regs (gdbarch) + frame_reg)
2788          + frame_offset - frame_adjust);
2789       /* FIXME: brobecker/2004-10-10: Just as in the mips32 case, we should
2790          be able to get rid of the assignment below, evetually.  But it's
2791          still needed for now.  */
2792       this_cache->saved_regs[gdbarch_num_regs (gdbarch)
2793                              + mips_regnum (gdbarch)->pc]
2794         = this_cache->saved_regs[gdbarch_num_regs (gdbarch) + MIPS_RA_REGNUM];
2795     }
2796
2797   /* Set end_prologue_addr to the address of the instruction immediately
2798      after the last one we scanned.  Unless the last one looked like a
2799      non-prologue instruction (and we looked ahead), in which case use
2800      its address instead.  */
2801   end_prologue_addr = (prev_non_prologue_insn || prev_delay_slot
2802                        ? prev_pc : cur_pc - prev_extend_bytes);
2803
2804   return end_prologue_addr;
2805 }
2806
2807 /* Heuristic unwinder for 16-bit MIPS instruction set (aka MIPS16).
2808    Procedures that use the 32-bit instruction set are handled by the
2809    mips_insn32 unwinder.  */
2810
2811 static struct mips_frame_cache *
2812 mips_insn16_frame_cache (struct frame_info *this_frame, void **this_cache)
2813 {
2814   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2815   struct mips_frame_cache *cache;
2816
2817   if ((*this_cache) != NULL)
2818     return (*this_cache);
2819   cache = FRAME_OBSTACK_ZALLOC (struct mips_frame_cache);
2820   (*this_cache) = cache;
2821   cache->saved_regs = trad_frame_alloc_saved_regs (this_frame);
2822
2823   /* Analyze the function prologue.  */
2824   {
2825     const CORE_ADDR pc = get_frame_address_in_block (this_frame);
2826     CORE_ADDR start_addr;
2827
2828     find_pc_partial_function (pc, NULL, &start_addr, NULL);
2829     if (start_addr == 0)
2830       start_addr = heuristic_proc_start (gdbarch, pc);
2831     /* We can't analyze the prologue if we couldn't find the begining
2832        of the function.  */
2833     if (start_addr == 0)
2834       return cache;
2835
2836     mips16_scan_prologue (gdbarch, start_addr, pc, this_frame, *this_cache);
2837   }
2838   
2839   /* gdbarch_sp_regnum contains the value and not the address.  */
2840   trad_frame_set_value (cache->saved_regs,
2841                         gdbarch_num_regs (gdbarch) + MIPS_SP_REGNUM,
2842                         cache->base);
2843
2844   return (*this_cache);
2845 }
2846
2847 static void
2848 mips_insn16_frame_this_id (struct frame_info *this_frame, void **this_cache,
2849                            struct frame_id *this_id)
2850 {
2851   struct mips_frame_cache *info = mips_insn16_frame_cache (this_frame,
2852                                                            this_cache);
2853   /* This marks the outermost frame.  */
2854   if (info->base == 0)
2855     return;
2856   (*this_id) = frame_id_build (info->base, get_frame_func (this_frame));
2857 }
2858
2859 static struct value *
2860 mips_insn16_frame_prev_register (struct frame_info *this_frame,
2861                                  void **this_cache, int regnum)
2862 {
2863   struct mips_frame_cache *info = mips_insn16_frame_cache (this_frame,
2864                                                            this_cache);
2865   return trad_frame_get_prev_register (this_frame, info->saved_regs, regnum);
2866 }
2867
2868 static int
2869 mips_insn16_frame_sniffer (const struct frame_unwind *self,
2870                            struct frame_info *this_frame, void **this_cache)
2871 {
2872   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2873   CORE_ADDR pc = get_frame_pc (this_frame);
2874   if (mips_pc_is_mips16 (gdbarch, pc))
2875     return 1;
2876   return 0;
2877 }
2878
2879 static const struct frame_unwind mips_insn16_frame_unwind =
2880 {
2881   NORMAL_FRAME,
2882   default_frame_unwind_stop_reason,
2883   mips_insn16_frame_this_id,
2884   mips_insn16_frame_prev_register,
2885   NULL,
2886   mips_insn16_frame_sniffer
2887 };
2888
2889 static CORE_ADDR
2890 mips_insn16_frame_base_address (struct frame_info *this_frame,
2891                                 void **this_cache)
2892 {
2893   struct mips_frame_cache *info = mips_insn16_frame_cache (this_frame,
2894                                                            this_cache);
2895   return info->base;
2896 }
2897
2898 static const struct frame_base mips_insn16_frame_base =
2899 {
2900   &mips_insn16_frame_unwind,
2901   mips_insn16_frame_base_address,
2902   mips_insn16_frame_base_address,
2903   mips_insn16_frame_base_address
2904 };
2905
2906 static const struct frame_base *
2907 mips_insn16_frame_base_sniffer (struct frame_info *this_frame)
2908 {
2909   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2910   CORE_ADDR pc = get_frame_pc (this_frame);
2911   if (mips_pc_is_mips16 (gdbarch, pc))
2912     return &mips_insn16_frame_base;
2913   else
2914     return NULL;
2915 }
2916
2917 /* Decode a 9-bit signed immediate argument of ADDIUSP -- -2 is mapped
2918    to -258, -1 -- to -257, 0 -- to 256, 1 -- to 257 and other values are
2919    interpreted directly, and then multiplied by 4.  */
2920
2921 static int
2922 micromips_decode_imm9 (int imm)
2923 {
2924   imm = (imm ^ 0x100) - 0x100;
2925   if (imm > -3 && imm < 2)
2926     imm ^= 0x100;
2927   return imm << 2;
2928 }
2929
2930 /* Analyze the function prologue from START_PC to LIMIT_PC.  Return
2931    the address of the first instruction past the prologue.  */
2932
2933 static CORE_ADDR
2934 micromips_scan_prologue (struct gdbarch *gdbarch,
2935                          CORE_ADDR start_pc, CORE_ADDR limit_pc,
2936                          struct frame_info *this_frame,
2937                          struct mips_frame_cache *this_cache)
2938 {
2939   CORE_ADDR end_prologue_addr;
2940   int prev_non_prologue_insn = 0;
2941   int frame_reg = MIPS_SP_REGNUM;
2942   int this_non_prologue_insn;
2943   int non_prologue_insns = 0;
2944   long frame_offset = 0;        /* Size of stack frame.  */
2945   long frame_adjust = 0;        /* Offset of FP from SP.  */
2946   CORE_ADDR frame_addr = 0;     /* Value of $30, used as frame pointer.  */
2947   int prev_delay_slot = 0;
2948   int in_delay_slot;
2949   CORE_ADDR prev_pc;
2950   CORE_ADDR cur_pc;
2951   ULONGEST insn;                /* current instruction */
2952   CORE_ADDR sp;
2953   long offset;
2954   long sp_adj;
2955   long v1_off = 0;              /* The assumption is LUI will replace it.  */
2956   int reglist;
2957   int breg;
2958   int dreg;
2959   int sreg;
2960   int treg;
2961   int loc;
2962   int op;
2963   int s;
2964   int i;
2965
2966   /* Can be called when there's no process, and hence when there's no
2967      THIS_FRAME.  */
2968   if (this_frame != NULL)
2969     sp = get_frame_register_signed (this_frame,
2970                                     gdbarch_num_regs (gdbarch)
2971                                     + MIPS_SP_REGNUM);
2972   else
2973     sp = 0;
2974
2975   if (limit_pc > start_pc + 200)
2976     limit_pc = start_pc + 200;
2977   prev_pc = start_pc;
2978
2979   /* Permit at most one non-prologue non-control-transfer instruction
2980      in the middle which may have been reordered by the compiler for
2981      optimisation.  */
2982   for (cur_pc = start_pc; cur_pc < limit_pc; cur_pc += loc)
2983     {
2984       this_non_prologue_insn = 0;
2985       in_delay_slot = 0;
2986       sp_adj = 0;
2987       loc = 0;
2988       insn = mips_fetch_instruction (gdbarch, ISA_MICROMIPS, cur_pc, NULL);
2989       loc += MIPS_INSN16_SIZE;
2990       switch (mips_insn_size (ISA_MICROMIPS, insn))
2991         {
2992         /* 48-bit instructions.  */
2993         case 3 * MIPS_INSN16_SIZE:
2994           /* No prologue instructions in this category.  */
2995           this_non_prologue_insn = 1;
2996           loc += 2 * MIPS_INSN16_SIZE;
2997           break;
2998
2999         /* 32-bit instructions.  */
3000         case 2 * MIPS_INSN16_SIZE:
3001           insn <<= 16;
3002           insn |= mips_fetch_instruction (gdbarch,
3003                                           ISA_MICROMIPS, cur_pc + loc, NULL);
3004           loc += MIPS_INSN16_SIZE;
3005           switch (micromips_op (insn >> 16))
3006             {
3007             /* Record $sp/$fp adjustment.  */
3008             /* Discard (D)ADDU $gp,$jp used for PIC code.  */
3009             case 0x0: /* POOL32A: bits 000000 */
3010             case 0x16: /* POOL32S: bits 010110 */
3011               op = b0s11_op (insn);
3012               sreg = b0s5_reg (insn >> 16);
3013               treg = b5s5_reg (insn >> 16);
3014               dreg = b11s5_reg (insn);
3015               if (op == 0x1d0
3016                                 /* SUBU: bits 000000 00111010000 */
3017                                 /* DSUBU: bits 010110 00111010000 */
3018                   && dreg == MIPS_SP_REGNUM && sreg == MIPS_SP_REGNUM
3019                   && treg == 3)
3020                                 /* (D)SUBU $sp, $v1 */
3021                     sp_adj = v1_off;
3022               else if (op != 0x150
3023                                 /* ADDU: bits 000000 00101010000 */
3024                                 /* DADDU: bits 010110 00101010000 */
3025                        || dreg != 28 || sreg != 28 || treg != MIPS_T9_REGNUM)
3026                 this_non_prologue_insn = 1;
3027               break;
3028
3029             case 0x8: /* POOL32B: bits 001000 */
3030               op = b12s4_op (insn);
3031               breg = b0s5_reg (insn >> 16);
3032               reglist = sreg = b5s5_reg (insn >> 16);
3033               offset = (b0s12_imm (insn) ^ 0x800) - 0x800;
3034               if ((op == 0x9 || op == 0xc)
3035                                 /* SWP: bits 001000 1001 */
3036                                 /* SDP: bits 001000 1100 */
3037                   && breg == MIPS_SP_REGNUM && sreg < MIPS_RA_REGNUM)
3038                                 /* S[DW]P reg,offset($sp) */
3039                 {
3040                   s = 4 << ((b12s4_op (insn) & 0x4) == 0x4);
3041                   set_reg_offset (gdbarch, this_cache,
3042                                   sreg, sp + offset);
3043                   set_reg_offset (gdbarch, this_cache,
3044                                   sreg + 1, sp + offset + s);
3045                 }
3046               else if ((op == 0xd || op == 0xf)
3047                                 /* SWM: bits 001000 1101 */
3048                                 /* SDM: bits 001000 1111 */
3049                        && breg == MIPS_SP_REGNUM
3050                                 /* SWM reglist,offset($sp) */
3051                        && ((reglist >= 1 && reglist <= 9)
3052                            || (reglist >= 16 && reglist <= 25)))
3053                 {
3054                   int sreglist = min(reglist & 0xf, 8);
3055
3056                   s = 4 << ((b12s4_op (insn) & 0x2) == 0x2);
3057                   for (i = 0; i < sreglist; i++)
3058                     set_reg_offset (gdbarch, this_cache, 16 + i, sp + s * i);
3059                   if ((reglist & 0xf) > 8)
3060                     set_reg_offset (gdbarch, this_cache, 30, sp + s * i++);
3061                   if ((reglist & 0x10) == 0x10)
3062                     set_reg_offset (gdbarch, this_cache,
3063                                     MIPS_RA_REGNUM, sp + s * i++);
3064                 }
3065               else
3066                 this_non_prologue_insn = 1;
3067               break;
3068
3069             /* Record $sp/$fp adjustment.  */
3070             /* Discard (D)ADDIU $gp used for PIC code.  */
3071             case 0xc: /* ADDIU: bits 001100 */
3072             case 0x17: /* DADDIU: bits 010111 */
3073               sreg = b0s5_reg (insn >> 16);
3074               dreg = b5s5_reg (insn >> 16);
3075               offset = (b0s16_imm (insn) ^ 0x8000) - 0x8000;
3076               if (sreg == MIPS_SP_REGNUM && dreg == MIPS_SP_REGNUM)
3077                                 /* (D)ADDIU $sp, imm */
3078                 sp_adj = offset;
3079               else if (sreg == MIPS_SP_REGNUM && dreg == 30)
3080                                 /* (D)ADDIU $fp, $sp, imm */
3081                 {
3082                   frame_addr = sp + offset;
3083                   frame_adjust = offset;
3084                   frame_reg = 30;
3085                 }
3086               else if (sreg != 28 || dreg != 28)
3087                                 /* (D)ADDIU $gp, imm */
3088                 this_non_prologue_insn = 1;
3089               break;
3090
3091             /* LUI $v1 is used for larger $sp adjustments.  */
3092             /* Discard LUI $gp used for PIC code.  */
3093             case 0x10: /* POOL32I: bits 010000 */
3094               if (b5s5_op (insn >> 16) == 0xd
3095                                 /* LUI: bits 010000 001101 */
3096                   && b0s5_reg (insn >> 16) == 3)
3097                                 /* LUI $v1, imm */
3098                 v1_off = ((b0s16_imm (insn) << 16) ^ 0x80000000) - 0x80000000;
3099               else if (b5s5_op (insn >> 16) != 0xd
3100                                 /* LUI: bits 010000 001101 */
3101                        || b0s5_reg (insn >> 16) != 28)
3102                                 /* LUI $gp, imm */
3103                 this_non_prologue_insn = 1;
3104               break;
3105
3106             /* ORI $v1 is used for larger $sp adjustments.  */
3107             case 0x14: /* ORI: bits 010100 */
3108               sreg = b0s5_reg (insn >> 16);
3109               dreg = b5s5_reg (insn >> 16);
3110               if (sreg == 3 && dreg == 3)
3111                                 /* ORI $v1, imm */
3112                 v1_off |= b0s16_imm (insn);
3113               else
3114                 this_non_prologue_insn = 1;
3115               break;
3116
3117             case 0x26: /* SWC1: bits 100110 */
3118             case 0x2e: /* SDC1: bits 101110 */
3119               breg = b0s5_reg (insn >> 16);
3120               if (breg != MIPS_SP_REGNUM)
3121                                 /* S[DW]C1 reg,offset($sp) */
3122                 this_non_prologue_insn = 1;
3123               break;
3124
3125             case 0x36: /* SD: bits 110110 */
3126             case 0x3e: /* SW: bits 111110 */
3127               breg = b0s5_reg (insn >> 16);
3128               sreg = b5s5_reg (insn >> 16);
3129               offset = (b0s16_imm (insn) ^ 0x8000) - 0x8000;
3130               if (breg == MIPS_SP_REGNUM)
3131                                 /* S[DW] reg,offset($sp) */
3132                 set_reg_offset (gdbarch, this_cache, sreg, sp + offset);
3133               else
3134                 this_non_prologue_insn = 1;
3135               break;
3136
3137             default:
3138               /* The instruction in the delay slot can be a part
3139                  of the prologue, so move forward once more.  */
3140               if (micromips_instruction_has_delay_slot (insn, 0))
3141                 in_delay_slot = 1;
3142               else
3143                 this_non_prologue_insn = 1;
3144               break;
3145             }
3146           insn >>= 16;
3147           break;
3148
3149         /* 16-bit instructions.  */
3150         case MIPS_INSN16_SIZE:
3151           switch (micromips_op (insn))
3152             {
3153             case 0x3: /* MOVE: bits 000011 */
3154               sreg = b0s5_reg (insn);
3155               dreg = b5s5_reg (insn);
3156               if (sreg == MIPS_SP_REGNUM && dreg == 30)
3157                                 /* MOVE  $fp, $sp */
3158                 {
3159                   frame_addr = sp;
3160                   frame_reg = 30;
3161                 }
3162               else if ((sreg & 0x1c) != 0x4)
3163                                 /* MOVE  reg, $a0-$a3 */
3164                 this_non_prologue_insn = 1;
3165               break;
3166
3167             case 0x11: /* POOL16C: bits 010001 */
3168               if (b6s4_op (insn) == 0x5)
3169                                 /* SWM: bits 010001 0101 */
3170                 {
3171                   offset = ((b0s4_imm (insn) << 2) ^ 0x20) - 0x20;
3172                   reglist = b4s2_regl (insn);
3173                   for (i = 0; i <= reglist; i++)
3174                     set_reg_offset (gdbarch, this_cache, 16 + i, sp + 4 * i);
3175                   set_reg_offset (gdbarch, this_cache,
3176                                   MIPS_RA_REGNUM, sp + 4 * i++);
3177                 }
3178               else
3179                 this_non_prologue_insn = 1;
3180               break;
3181
3182             case 0x13: /* POOL16D: bits 010011 */
3183               if ((insn & 0x1) == 0x1)
3184                                 /* ADDIUSP: bits 010011 1 */
3185                 sp_adj = micromips_decode_imm9 (b1s9_imm (insn));
3186               else if (b5s5_reg (insn) == MIPS_SP_REGNUM)
3187                                 /* ADDIUS5: bits 010011 0 */
3188                                 /* ADDIUS5 $sp, imm */
3189                 sp_adj = (b1s4_imm (insn) ^ 8) - 8;
3190               else
3191                 this_non_prologue_insn = 1;
3192               break;
3193
3194             case 0x32: /* SWSP: bits 110010 */
3195               offset = b0s5_imm (insn) << 2;
3196               sreg = b5s5_reg (insn);
3197               set_reg_offset (gdbarch, this_cache, sreg, sp + offset);
3198               break;
3199
3200             default:
3201               /* The instruction in the delay slot can be a part
3202                  of the prologue, so move forward once more.  */
3203               if (micromips_instruction_has_delay_slot (insn << 16, 0))
3204                 in_delay_slot = 1;
3205               else
3206                 this_non_prologue_insn = 1;
3207               break;
3208             }
3209           break;
3210         }
3211       if (sp_adj < 0)
3212         frame_offset -= sp_adj;
3213
3214       non_prologue_insns += this_non_prologue_insn;
3215
3216       /* A jump or branch, enough non-prologue insns seen or positive
3217          stack adjustment?  If so, then we must have reached the end
3218          of the prologue by now.  */
3219       if (prev_delay_slot || non_prologue_insns > 1 || sp_adj > 0
3220           || micromips_instruction_is_compact_branch (insn))
3221         break;
3222
3223       prev_non_prologue_insn = this_non_prologue_insn;
3224       prev_delay_slot = in_delay_slot;
3225       prev_pc = cur_pc;
3226     }
3227
3228   if (this_cache != NULL)
3229     {
3230       this_cache->base =
3231         (get_frame_register_signed (this_frame,
3232                                     gdbarch_num_regs (gdbarch) + frame_reg)
3233          + frame_offset - frame_adjust);
3234       /* FIXME: brobecker/2004-10-10: Just as in the mips32 case, we should
3235          be able to get rid of the assignment below, evetually. But it's
3236          still needed for now.  */
3237       this_cache->saved_regs[gdbarch_num_regs (gdbarch)
3238                              + mips_regnum (gdbarch)->pc]
3239         = this_cache->saved_regs[gdbarch_num_regs (gdbarch) + MIPS_RA_REGNUM];
3240     }
3241
3242   /* Set end_prologue_addr to the address of the instruction immediately
3243      after the last one we scanned.  Unless the last one looked like a
3244      non-prologue instruction (and we looked ahead), in which case use
3245      its address instead.  */
3246   end_prologue_addr
3247     = prev_non_prologue_insn || prev_delay_slot ? prev_pc : cur_pc;
3248
3249   return end_prologue_addr;
3250 }
3251
3252 /* Heuristic unwinder for procedures using microMIPS instructions.
3253    Procedures that use the 32-bit instruction set are handled by the
3254    mips_insn32 unwinder.  Likewise MIPS16 and the mips_insn16 unwinder. */
3255
3256 static struct mips_frame_cache *
3257 mips_micro_frame_cache (struct frame_info *this_frame, void **this_cache)
3258 {
3259   struct gdbarch *gdbarch = get_frame_arch (this_frame);
3260   struct mips_frame_cache *cache;
3261
3262   if ((*this_cache) != NULL)
3263     return (*this_cache);
3264
3265   cache = FRAME_OBSTACK_ZALLOC (struct mips_frame_cache);
3266   (*this_cache) = cache;
3267   cache->saved_regs = trad_frame_alloc_saved_regs (this_frame);
3268
3269   /* Analyze the function prologue.  */
3270   {
3271     const CORE_ADDR pc = get_frame_address_in_block (this_frame);
3272     CORE_ADDR start_addr;
3273
3274     find_pc_partial_function (pc, NULL, &start_addr, NULL);
3275     if (start_addr == 0)
3276       start_addr = heuristic_proc_start (get_frame_arch (this_frame), pc);
3277     /* We can't analyze the prologue if we couldn't find the begining
3278        of the function.  */
3279     if (start_addr == 0)
3280       return cache;
3281
3282     micromips_scan_prologue (gdbarch, start_addr, pc, this_frame, *this_cache);
3283   }
3284
3285   /* gdbarch_sp_regnum contains the value and not the address.  */
3286   trad_frame_set_value (cache->saved_regs,
3287                         gdbarch_num_regs (gdbarch) + MIPS_SP_REGNUM,
3288                         cache->base);
3289
3290   return (*this_cache);
3291 }
3292
3293 static void
3294 mips_micro_frame_this_id (struct frame_info *this_frame, void **this_cache,
3295                           struct frame_id *this_id)
3296 {
3297   struct mips_frame_cache *info = mips_micro_frame_cache (this_frame,
3298                                                           this_cache);
3299   /* This marks the outermost frame.  */
3300   if (info->base == 0)
3301     return;
3302   (*this_id) = frame_id_build (info->base, get_frame_func (this_frame));
3303 }
3304
3305 static struct value *
3306 mips_micro_frame_prev_register (struct frame_info *this_frame,
3307                                 void **this_cache, int regnum)
3308 {
3309   struct mips_frame_cache *info = mips_micro_frame_cache (this_frame,
3310                                                           this_cache);
3311   return trad_frame_get_prev_register (this_frame, info->saved_regs, regnum);
3312 }
3313
3314 static int
3315 mips_micro_frame_sniffer (const struct frame_unwind *self,
3316                           struct frame_info *this_frame, void **this_cache)
3317 {
3318   struct gdbarch *gdbarch = get_frame_arch (this_frame);
3319   CORE_ADDR pc = get_frame_pc (this_frame);
3320
3321   if (mips_pc_is_micromips (gdbarch, pc))
3322     return 1;
3323   return 0;
3324 }
3325
3326 static const struct frame_unwind mips_micro_frame_unwind =
3327 {
3328   NORMAL_FRAME,
3329   default_frame_unwind_stop_reason,
3330   mips_micro_frame_this_id,
3331   mips_micro_frame_prev_register,
3332   NULL,
3333   mips_micro_frame_sniffer
3334 };
3335
3336 static CORE_ADDR
3337 mips_micro_frame_base_address (struct frame_info *this_frame,
3338                                void **this_cache)
3339 {
3340   struct mips_frame_cache *info = mips_micro_frame_cache (this_frame,
3341                                                           this_cache);
3342   return info->base;
3343 }
3344
3345 static const struct frame_base mips_micro_frame_base =
3346 {
3347   &mips_micro_frame_unwind,
3348   mips_micro_frame_base_address,
3349   mips_micro_frame_base_address,
3350   mips_micro_frame_base_address
3351 };
3352
3353 static const struct frame_base *
3354 mips_micro_frame_base_sniffer (struct frame_info *this_frame)
3355 {
3356   struct gdbarch *gdbarch = get_frame_arch (this_frame);
3357   CORE_ADDR pc = get_frame_pc (this_frame);
3358
3359   if (mips_pc_is_micromips (gdbarch, pc))
3360     return &mips_micro_frame_base;
3361   else
3362     return NULL;
3363 }
3364
3365 /* Mark all the registers as unset in the saved_regs array
3366    of THIS_CACHE.  Do nothing if THIS_CACHE is null.  */
3367
3368 static void
3369 reset_saved_regs (struct gdbarch *gdbarch, struct mips_frame_cache *this_cache)
3370 {
3371   if (this_cache == NULL || this_cache->saved_regs == NULL)
3372     return;
3373
3374   {
3375     const int num_regs = gdbarch_num_regs (gdbarch);
3376     int i;
3377
3378     for (i = 0; i < num_regs; i++)
3379       {
3380         this_cache->saved_regs[i].addr = -1;
3381       }
3382   }
3383 }
3384
3385 /* Analyze the function prologue from START_PC to LIMIT_PC.  Builds
3386    the associated FRAME_CACHE if not null.  
3387    Return the address of the first instruction past the prologue.  */
3388
3389 static CORE_ADDR
3390 mips32_scan_prologue (struct gdbarch *gdbarch,
3391                       CORE_ADDR start_pc, CORE_ADDR limit_pc,
3392                       struct frame_info *this_frame,
3393                       struct mips_frame_cache *this_cache)
3394 {
3395   int prev_non_prologue_insn;
3396   int this_non_prologue_insn;
3397   int non_prologue_insns;
3398   CORE_ADDR frame_addr = 0; /* Value of $r30. Used by gcc for
3399                                frame-pointer.  */
3400   int prev_delay_slot;
3401   CORE_ADDR prev_pc;
3402   CORE_ADDR cur_pc;
3403   CORE_ADDR sp;
3404   long frame_offset;
3405   int  frame_reg = MIPS_SP_REGNUM;
3406
3407   CORE_ADDR end_prologue_addr;
3408   int seen_sp_adjust = 0;
3409   int load_immediate_bytes = 0;
3410   int in_delay_slot;
3411   int regsize_is_64_bits = (mips_abi_regsize (gdbarch) == 8);
3412
3413   /* Can be called when there's no process, and hence when there's no
3414      THIS_FRAME.  */
3415   if (this_frame != NULL)
3416     sp = get_frame_register_signed (this_frame,
3417                                     gdbarch_num_regs (gdbarch)
3418                                     + MIPS_SP_REGNUM);
3419   else
3420     sp = 0;
3421
3422   if (limit_pc > start_pc + 200)
3423     limit_pc = start_pc + 200;
3424
3425 restart:
3426   prev_non_prologue_insn = 0;
3427   non_prologue_insns = 0;
3428   prev_delay_slot = 0;
3429   prev_pc = start_pc;
3430
3431   /* Permit at most one non-prologue non-control-transfer instruction
3432      in the middle which may have been reordered by the compiler for
3433      optimisation.  */
3434   frame_offset = 0;
3435   for (cur_pc = start_pc; cur_pc < limit_pc; cur_pc += MIPS_INSN32_SIZE)
3436     {
3437       unsigned long inst, high_word, low_word;
3438       int reg;
3439
3440       this_non_prologue_insn = 0;
3441       in_delay_slot = 0;
3442
3443       /* Fetch the instruction.  */
3444       inst = (unsigned long) mips_fetch_instruction (gdbarch, ISA_MIPS,
3445                                                      cur_pc, NULL);
3446
3447       /* Save some code by pre-extracting some useful fields.  */
3448       high_word = (inst >> 16) & 0xffff;
3449       low_word = inst & 0xffff;
3450       reg = high_word & 0x1f;
3451
3452       if (high_word == 0x27bd           /* addiu $sp,$sp,-i */
3453           || high_word == 0x23bd        /* addi $sp,$sp,-i */
3454           || high_word == 0x67bd)       /* daddiu $sp,$sp,-i */
3455         {
3456           if (low_word & 0x8000)        /* Negative stack adjustment?  */
3457             frame_offset += 0x10000 - low_word;
3458           else
3459             /* Exit loop if a positive stack adjustment is found, which
3460                usually means that the stack cleanup code in the function
3461                epilogue is reached.  */
3462             break;
3463           seen_sp_adjust = 1;
3464         }
3465       else if (((high_word & 0xFFE0) == 0xafa0) /* sw reg,offset($sp) */
3466                && !regsize_is_64_bits)
3467         {
3468           set_reg_offset (gdbarch, this_cache, reg, sp + low_word);
3469         }
3470       else if (((high_word & 0xFFE0) == 0xffa0) /* sd reg,offset($sp) */
3471                && regsize_is_64_bits)
3472         {
3473           /* Irix 6.2 N32 ABI uses sd instructions for saving $gp and $ra.  */
3474           set_reg_offset (gdbarch, this_cache, reg, sp + low_word);
3475         }
3476       else if (high_word == 0x27be)     /* addiu $30,$sp,size */
3477         {
3478           /* Old gcc frame, r30 is virtual frame pointer.  */
3479           if ((long) low_word != frame_offset)
3480             frame_addr = sp + low_word;
3481           else if (this_frame && frame_reg == MIPS_SP_REGNUM)
3482             {
3483               unsigned alloca_adjust;
3484
3485               frame_reg = 30;
3486               frame_addr = get_frame_register_signed
3487                 (this_frame, gdbarch_num_regs (gdbarch) + 30);
3488               frame_offset = 0;
3489
3490               alloca_adjust = (unsigned) (frame_addr - (sp + low_word));
3491               if (alloca_adjust > 0)
3492                 {
3493                   /* FP > SP + frame_size.  This may be because of
3494                      an alloca or somethings similar.  Fix sp to
3495                      "pre-alloca" value, and try again.  */
3496                   sp += alloca_adjust;
3497                   /* Need to reset the status of all registers.  Otherwise,
3498                      we will hit a guard that prevents the new address
3499                      for each register to be recomputed during the second
3500                      pass.  */
3501                   reset_saved_regs (gdbarch, this_cache);
3502                   goto restart;
3503                 }
3504             }
3505         }
3506       /* move $30,$sp.  With different versions of gas this will be either
3507          `addu $30,$sp,$zero' or `or $30,$sp,$zero' or `daddu 30,sp,$0'.
3508          Accept any one of these.  */
3509       else if (inst == 0x03A0F021 || inst == 0x03a0f025 || inst == 0x03a0f02d)
3510         {
3511           /* New gcc frame, virtual frame pointer is at r30 + frame_size.  */
3512           if (this_frame && frame_reg == MIPS_SP_REGNUM)
3513             {
3514               unsigned alloca_adjust;
3515
3516               frame_reg = 30;
3517               frame_addr = get_frame_register_signed
3518                 (this_frame, gdbarch_num_regs (gdbarch) + 30);
3519
3520               alloca_adjust = (unsigned) (frame_addr - sp);
3521               if (alloca_adjust > 0)
3522                 {
3523                   /* FP > SP + frame_size.  This may be because of
3524                      an alloca or somethings similar.  Fix sp to
3525                      "pre-alloca" value, and try again.  */
3526                   sp = frame_addr;
3527                   /* Need to reset the status of all registers.  Otherwise,
3528                      we will hit a guard that prevents the new address
3529                      for each register to be recomputed during the second
3530                      pass.  */
3531                   reset_saved_regs (gdbarch, this_cache);
3532                   goto restart;
3533                 }
3534             }
3535         }
3536       else if ((high_word & 0xFFE0) == 0xafc0   /* sw reg,offset($30) */
3537                && !regsize_is_64_bits)
3538         {
3539           set_reg_offset (gdbarch, this_cache, reg, frame_addr + low_word);
3540         }
3541       else if ((high_word & 0xFFE0) == 0xE7A0 /* swc1 freg,n($sp) */
3542                || (high_word & 0xF3E0) == 0xA3C0 /* sx reg,n($s8) */
3543                || (inst & 0xFF9F07FF) == 0x00800021 /* move reg,$a0-$a3 */
3544                || high_word == 0x3c1c /* lui $gp,n */
3545                || high_word == 0x279c /* addiu $gp,$gp,n */
3546                || inst == 0x0399e021 /* addu $gp,$gp,$t9 */
3547                || inst == 0x033ce021 /* addu $gp,$t9,$gp */
3548               )
3549         {
3550           /* These instructions are part of the prologue, but we don't
3551              need to do anything special to handle them.  */
3552         }
3553       /* The instructions below load $at or $t0 with an immediate
3554          value in preparation for a stack adjustment via
3555          subu $sp,$sp,[$at,$t0].  These instructions could also
3556          initialize a local variable, so we accept them only before
3557          a stack adjustment instruction was seen.  */
3558       else if (!seen_sp_adjust
3559                && !prev_delay_slot
3560                && (high_word == 0x3c01 /* lui $at,n */
3561                    || high_word == 0x3c08 /* lui $t0,n */
3562                    || high_word == 0x3421 /* ori $at,$at,n */
3563                    || high_word == 0x3508 /* ori $t0,$t0,n */
3564                    || high_word == 0x3401 /* ori $at,$zero,n */
3565                    || high_word == 0x3408 /* ori $t0,$zero,n */
3566                   ))
3567         {
3568           load_immediate_bytes += MIPS_INSN32_SIZE;             /* FIXME!  */
3569         }
3570       /* Check for branches and jumps.  The instruction in the delay
3571          slot can be a part of the prologue, so move forward once more.  */
3572       else if (mips32_instruction_has_delay_slot (gdbarch, inst))
3573         {
3574           in_delay_slot = 1;
3575         }
3576       /* This instruction is not an instruction typically found
3577          in a prologue, so we must have reached the end of the
3578          prologue.  */
3579       else
3580         {
3581           this_non_prologue_insn = 1;
3582         }
3583
3584       non_prologue_insns += this_non_prologue_insn;
3585
3586       /* A jump or branch, or enough non-prologue insns seen?  If so,
3587          then we must have reached the end of the prologue by now.  */
3588       if (prev_delay_slot || non_prologue_insns > 1)
3589         break;
3590
3591       prev_non_prologue_insn = this_non_prologue_insn;
3592       prev_delay_slot = in_delay_slot;
3593       prev_pc = cur_pc;
3594     }
3595
3596   if (this_cache != NULL)
3597     {
3598       this_cache->base = 
3599         (get_frame_register_signed (this_frame,
3600                                     gdbarch_num_regs (gdbarch) + frame_reg)
3601          + frame_offset);
3602       /* FIXME: brobecker/2004-09-15: We should be able to get rid of
3603          this assignment below, eventually.  But it's still needed
3604          for now.  */
3605       this_cache->saved_regs[gdbarch_num_regs (gdbarch)
3606                              + mips_regnum (gdbarch)->pc]
3607         = this_cache->saved_regs[gdbarch_num_regs (gdbarch)
3608                                  + MIPS_RA_REGNUM];
3609     }
3610
3611   /* Set end_prologue_addr to the address of the instruction immediately
3612      after the last one we scanned.  Unless the last one looked like a
3613      non-prologue instruction (and we looked ahead), in which case use
3614      its address instead.  */
3615   end_prologue_addr
3616     = prev_non_prologue_insn || prev_delay_slot ? prev_pc : cur_pc;
3617      
3618   /* In a frameless function, we might have incorrectly
3619      skipped some load immediate instructions.  Undo the skipping
3620      if the load immediate was not followed by a stack adjustment.  */
3621   if (load_immediate_bytes && !seen_sp_adjust)
3622     end_prologue_addr -= load_immediate_bytes;
3623
3624   return end_prologue_addr;
3625 }
3626
3627 /* Heuristic unwinder for procedures using 32-bit instructions (covers
3628    both 32-bit and 64-bit MIPS ISAs).  Procedures using 16-bit
3629    instructions (a.k.a. MIPS16) are handled by the mips_insn16
3630    unwinder.  Likewise microMIPS and the mips_micro unwinder. */
3631
3632 static struct mips_frame_cache *
3633 mips_insn32_frame_cache (struct frame_info *this_frame, void **this_cache)
3634 {
3635   struct gdbarch *gdbarch = get_frame_arch (this_frame);
3636   struct mips_frame_cache *cache;
3637
3638   if ((*this_cache) != NULL)
3639     return (*this_cache);
3640
3641   cache = FRAME_OBSTACK_ZALLOC (struct mips_frame_cache);
3642   (*this_cache) = cache;
3643   cache->saved_regs = trad_frame_alloc_saved_regs (this_frame);
3644
3645   /* Analyze the function prologue.  */
3646   {
3647     const CORE_ADDR pc = get_frame_address_in_block (this_frame);
3648     CORE_ADDR start_addr;
3649
3650     find_pc_partial_function (pc, NULL, &start_addr, NULL);
3651     if (start_addr == 0)
3652       start_addr = heuristic_proc_start (gdbarch, pc);
3653     /* We can't analyze the prologue if we couldn't find the begining
3654        of the function.  */
3655     if (start_addr == 0)
3656       return cache;
3657
3658     mips32_scan_prologue (gdbarch, start_addr, pc, this_frame, *this_cache);
3659   }
3660   
3661   /* gdbarch_sp_regnum contains the value and not the address.  */
3662   trad_frame_set_value (cache->saved_regs,
3663                         gdbarch_num_regs (gdbarch) + MIPS_SP_REGNUM,
3664                         cache->base);
3665
3666   return (*this_cache);
3667 }
3668
3669 static void
3670 mips_insn32_frame_this_id (struct frame_info *this_frame, void **this_cache,
3671                            struct frame_id *this_id)
3672 {
3673   struct mips_frame_cache *info = mips_insn32_frame_cache (this_frame,
3674                                                            this_cache);
3675   /* This marks the outermost frame.  */
3676   if (info->base == 0)
3677     return;
3678   (*this_id) = frame_id_build (info->base, get_frame_func (this_frame));
3679 }
3680
3681 static struct value *
3682 mips_insn32_frame_prev_register (struct frame_info *this_frame,
3683                                  void **this_cache, int regnum)
3684 {
3685   struct mips_frame_cache *info = mips_insn32_frame_cache (this_frame,
3686                                                            this_cache);
3687   return trad_frame_get_prev_register (this_frame, info->saved_regs, regnum);
3688 }
3689
3690 static int
3691 mips_insn32_frame_sniffer (const struct frame_unwind *self,
3692                            struct frame_info *this_frame, void **this_cache)
3693 {
3694   CORE_ADDR pc = get_frame_pc (this_frame);
3695   if (mips_pc_is_mips (pc))
3696     return 1;
3697   return 0;
3698 }
3699
3700 static const struct frame_unwind mips_insn32_frame_unwind =
3701 {
3702   NORMAL_FRAME,
3703   default_frame_unwind_stop_reason,
3704   mips_insn32_frame_this_id,
3705   mips_insn32_frame_prev_register,
3706   NULL,
3707   mips_insn32_frame_sniffer
3708 };
3709
3710 static CORE_ADDR
3711 mips_insn32_frame_base_address (struct frame_info *this_frame,
3712                                 void **this_cache)
3713 {
3714   struct mips_frame_cache *info = mips_insn32_frame_cache (this_frame,
3715                                                            this_cache);
3716   return info->base;
3717 }
3718
3719 static const struct frame_base mips_insn32_frame_base =
3720 {
3721   &mips_insn32_frame_unwind,
3722   mips_insn32_frame_base_address,
3723   mips_insn32_frame_base_address,
3724   mips_insn32_frame_base_address
3725 };
3726
3727 static const struct frame_base *
3728 mips_insn32_frame_base_sniffer (struct frame_info *this_frame)
3729 {
3730   CORE_ADDR pc = get_frame_pc (this_frame);
3731   if (mips_pc_is_mips (pc))
3732     return &mips_insn32_frame_base;
3733   else
3734     return NULL;
3735 }
3736
3737 static struct trad_frame_cache *
3738 mips_stub_frame_cache (struct frame_info *this_frame, void **this_cache)
3739 {
3740   CORE_ADDR pc;
3741   CORE_ADDR start_addr;
3742   CORE_ADDR stack_addr;
3743   struct trad_frame_cache *this_trad_cache;
3744   struct gdbarch *gdbarch = get_frame_arch (this_frame);
3745   int num_regs = gdbarch_num_regs (gdbarch);
3746
3747   if ((*this_cache) != NULL)
3748     return (*this_cache);
3749   this_trad_cache = trad_frame_cache_zalloc (this_frame);
3750   (*this_cache) = this_trad_cache;
3751
3752   /* The return address is in the link register.  */
3753   trad_frame_set_reg_realreg (this_trad_cache,
3754                               gdbarch_pc_regnum (gdbarch),
3755                               num_regs + MIPS_RA_REGNUM);
3756
3757   /* Frame ID, since it's a frameless / stackless function, no stack
3758      space is allocated and SP on entry is the current SP.  */
3759   pc = get_frame_pc (this_frame);
3760   find_pc_partial_function (pc, NULL, &start_addr, NULL);
3761   stack_addr = get_frame_register_signed (this_frame,
3762                                           num_regs + MIPS_SP_REGNUM);
3763   trad_frame_set_id (this_trad_cache, frame_id_build (stack_addr, start_addr));
3764
3765   /* Assume that the frame's base is the same as the
3766      stack-pointer.  */
3767   trad_frame_set_this_base (this_trad_cache, stack_addr);
3768
3769   return this_trad_cache;
3770 }
3771
3772 static void
3773 mips_stub_frame_this_id (struct frame_info *this_frame, void **this_cache,
3774                          struct frame_id *this_id)
3775 {
3776   struct trad_frame_cache *this_trad_cache
3777     = mips_stub_frame_cache (this_frame, this_cache);
3778   trad_frame_get_id (this_trad_cache, this_id);
3779 }
3780
3781 static struct value *
3782 mips_stub_frame_prev_register (struct frame_info *this_frame,
3783                                void **this_cache, int regnum)
3784 {
3785   struct trad_frame_cache *this_trad_cache
3786     = mips_stub_frame_cache (this_frame, this_cache);
3787   return trad_frame_get_register (this_trad_cache, this_frame, regnum);
3788 }
3789
3790 static int
3791 mips_stub_frame_sniffer (const struct frame_unwind *self,
3792                          struct frame_info *this_frame, void **this_cache)
3793 {
3794   gdb_byte dummy[4];
3795   struct obj_section *s;
3796   CORE_ADDR pc = get_frame_address_in_block (this_frame);
3797   struct bound_minimal_symbol msym;
3798
3799   /* Use the stub unwinder for unreadable code.  */
3800   if (target_read_memory (get_frame_pc (this_frame), dummy, 4) != 0)
3801     return 1;
3802
3803   if (in_plt_section (pc) || in_mips_stubs_section (pc))
3804     return 1;
3805
3806   /* Calling a PIC function from a non-PIC function passes through a
3807      stub.  The stub for foo is named ".pic.foo".  */
3808   msym = lookup_minimal_symbol_by_pc (pc);
3809   if (msym.minsym != NULL
3810       && MSYMBOL_LINKAGE_NAME (msym.minsym) != NULL
3811       && strncmp (MSYMBOL_LINKAGE_NAME (msym.minsym), ".pic.", 5) == 0)
3812     return 1;
3813
3814   return 0;
3815 }
3816
3817 static const struct frame_unwind mips_stub_frame_unwind =
3818 {
3819   NORMAL_FRAME,
3820   default_frame_unwind_stop_reason,
3821   mips_stub_frame_this_id,
3822   mips_stub_frame_prev_register,
3823   NULL,
3824   mips_stub_frame_sniffer
3825 };
3826
3827 static CORE_ADDR
3828 mips_stub_frame_base_address (struct frame_info *this_frame,
3829                               void **this_cache)
3830 {
3831   struct trad_frame_cache *this_trad_cache
3832     = mips_stub_frame_cache (this_frame, this_cache);
3833   return trad_frame_get_this_base (this_trad_cache);
3834 }
3835
3836 static const struct frame_base mips_stub_frame_base =
3837 {
3838   &mips_stub_frame_unwind,
3839   mips_stub_frame_base_address,
3840   mips_stub_frame_base_address,
3841   mips_stub_frame_base_address
3842 };
3843
3844 static const struct frame_base *
3845 mips_stub_frame_base_sniffer (struct frame_info *this_frame)
3846 {
3847   if (mips_stub_frame_sniffer (&mips_stub_frame_unwind, this_frame, NULL))
3848     return &mips_stub_frame_base;
3849   else
3850     return NULL;
3851 }
3852
3853 /* mips_addr_bits_remove - remove useless address bits  */
3854
3855 static CORE_ADDR
3856 mips_addr_bits_remove (struct gdbarch *gdbarch, CORE_ADDR addr)
3857 {
3858   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
3859
3860   if (mips_mask_address_p (tdep) && (((ULONGEST) addr) >> 32 == 0xffffffffUL))
3861     /* This hack is a work-around for existing boards using PMON, the
3862        simulator, and any other 64-bit targets that doesn't have true
3863        64-bit addressing.  On these targets, the upper 32 bits of
3864        addresses are ignored by the hardware.  Thus, the PC or SP are
3865        likely to have been sign extended to all 1s by instruction
3866        sequences that load 32-bit addresses.  For example, a typical
3867        piece of code that loads an address is this:
3868
3869        lui $r2, <upper 16 bits>
3870        ori $r2, <lower 16 bits>
3871
3872        But the lui sign-extends the value such that the upper 32 bits
3873        may be all 1s.  The workaround is simply to mask off these
3874        bits.  In the future, gcc may be changed to support true 64-bit
3875        addressing, and this masking will have to be disabled.  */
3876     return addr &= 0xffffffffUL;
3877   else
3878     return addr;
3879 }
3880
3881
3882 /* Checks for an atomic sequence of instructions beginning with a LL/LLD
3883    instruction and ending with a SC/SCD instruction.  If such a sequence
3884    is found, attempt to step through it.  A breakpoint is placed at the end of 
3885    the sequence.  */
3886
3887 /* Instructions used during single-stepping of atomic sequences, standard
3888    ISA version.  */
3889 #define LL_OPCODE 0x30
3890 #define LLD_OPCODE 0x34
3891 #define SC_OPCODE 0x38
3892 #define SCD_OPCODE 0x3c
3893
3894 static int
3895 mips_deal_with_atomic_sequence (struct gdbarch *gdbarch,
3896                                 struct address_space *aspace, CORE_ADDR pc)
3897 {
3898   CORE_ADDR breaks[2] = {-1, -1};
3899   CORE_ADDR loc = pc;
3900   CORE_ADDR branch_bp; /* Breakpoint at branch instruction's destination.  */
3901   ULONGEST insn;
3902   int insn_count;
3903   int index;
3904   int last_breakpoint = 0; /* Defaults to 0 (no breakpoints placed).  */  
3905   const int atomic_sequence_length = 16; /* Instruction sequence length.  */
3906
3907   insn = mips_fetch_instruction (gdbarch, ISA_MIPS, loc, NULL);
3908   /* Assume all atomic sequences start with a ll/lld instruction.  */
3909   if (itype_op (insn) != LL_OPCODE && itype_op (insn) != LLD_OPCODE)
3910     return 0;
3911
3912   /* Assume that no atomic sequence is longer than "atomic_sequence_length" 
3913      instructions.  */
3914   for (insn_count = 0; insn_count < atomic_sequence_length; ++insn_count)
3915     {
3916       int is_branch = 0;
3917       loc += MIPS_INSN32_SIZE;
3918       insn = mips_fetch_instruction (gdbarch, ISA_MIPS, loc, NULL);
3919
3920       /* Assume that there is at most one branch in the atomic
3921          sequence.  If a branch is found, put a breakpoint in its
3922          destination address.  */
3923       switch (itype_op (insn))
3924         {
3925         case 0: /* SPECIAL */
3926           if (rtype_funct (insn) >> 1 == 4) /* JR, JALR */
3927             return 0; /* fallback to the standard single-step code.  */
3928           break;
3929         case 1: /* REGIMM */
3930           is_branch = ((itype_rt (insn) & 0xc) == 0 /* B{LT,GE}Z* */
3931                        || ((itype_rt (insn) & 0x1e) == 0
3932                            && itype_rs (insn) == 0)); /* BPOSGE* */
3933           break;
3934         case 2: /* J */
3935         case 3: /* JAL */
3936           return 0; /* fallback to the standard single-step code.  */
3937         case 4: /* BEQ */
3938         case 5: /* BNE */
3939         case 6: /* BLEZ */
3940         case 7: /* BGTZ */
3941         case 20: /* BEQL */
3942         case 21: /* BNEL */
3943         case 22: /* BLEZL */
3944         case 23: /* BGTTL */
3945           is_branch = 1;
3946           break;
3947         case 17: /* COP1 */
3948           is_branch = ((itype_rs (insn) == 9 || itype_rs (insn) == 10)
3949                        && (itype_rt (insn) & 0x2) == 0);
3950           if (is_branch) /* BC1ANY2F, BC1ANY2T, BC1ANY4F, BC1ANY4T */
3951             break;
3952         /* Fall through.  */
3953         case 18: /* COP2 */
3954         case 19: /* COP3 */
3955           is_branch = (itype_rs (insn) == 8); /* BCzF, BCzFL, BCzT, BCzTL */
3956           break;
3957         }
3958       if (is_branch)
3959         {
3960           branch_bp = loc + mips32_relative_offset (insn) + 4;
3961           if (last_breakpoint >= 1)
3962             return 0; /* More than one branch found, fallback to the
3963                          standard single-step code.  */
3964           breaks[1] = branch_bp;
3965           last_breakpoint++;
3966         }
3967
3968       if (itype_op (insn) == SC_OPCODE || itype_op (insn) == SCD_OPCODE)
3969         break;
3970     }
3971
3972   /* Assume that the atomic sequence ends with a sc/scd instruction.  */
3973   if (itype_op (insn) != SC_OPCODE && itype_op (insn) != SCD_OPCODE)
3974     return 0;
3975
3976   loc += MIPS_INSN32_SIZE;
3977
3978   /* Insert a breakpoint right after the end of the atomic sequence.  */
3979   breaks[0] = loc;
3980
3981   /* Check for duplicated breakpoints.  Check also for a breakpoint
3982      placed (branch instruction's destination) in the atomic sequence.  */
3983   if (last_breakpoint && pc <= breaks[1] && breaks[1] <= breaks[0])
3984     last_breakpoint = 0;
3985
3986   /* Effectively inserts the breakpoints.  */
3987   for (index = 0; index <= last_breakpoint; index++)
3988     insert_single_step_breakpoint (gdbarch, aspace, breaks[index]);
3989
3990   return 1;
3991 }
3992
3993 static int
3994 micromips_deal_with_atomic_sequence (struct gdbarch *gdbarch,
3995                                      struct address_space *aspace,
3996                                      CORE_ADDR pc)
3997 {
3998   const int atomic_sequence_length = 16; /* Instruction sequence length.  */
3999   int last_breakpoint = 0; /* Defaults to 0 (no breakpoints placed).  */
4000   CORE_ADDR breaks[2] = {-1, -1};
4001   CORE_ADDR branch_bp = 0; /* Breakpoint at branch instruction's
4002                               destination.  */
4003   CORE_ADDR loc = pc;
4004   int sc_found = 0;
4005   ULONGEST insn;
4006   int insn_count;
4007   int index;
4008
4009   /* Assume all atomic sequences start with a ll/lld instruction.  */
4010   insn = mips_fetch_instruction (gdbarch, ISA_MICROMIPS, loc, NULL);
4011   if (micromips_op (insn) != 0x18)      /* POOL32C: bits 011000 */
4012     return 0;
4013   loc += MIPS_INSN16_SIZE;
4014   insn <<= 16;
4015   insn |= mips_fetch_instruction (gdbarch, ISA_MICROMIPS, loc, NULL);
4016   if ((b12s4_op (insn) & 0xb) != 0x3)   /* LL, LLD: bits 011000 0x11 */
4017     return 0;
4018   loc += MIPS_INSN16_SIZE;
4019
4020   /* Assume all atomic sequences end with an sc/scd instruction.  Assume
4021      that no atomic sequence is longer than "atomic_sequence_length"
4022      instructions.  */
4023   for (insn_count = 0;
4024        !sc_found && insn_count < atomic_sequence_length;
4025        ++insn_count)
4026     {
4027       int is_branch = 0;
4028
4029       insn = mips_fetch_instruction (gdbarch, ISA_MICROMIPS, loc, NULL);
4030       loc += MIPS_INSN16_SIZE;
4031
4032       /* Assume that there is at most one conditional branch in the
4033          atomic sequence.  If a branch is found, put a breakpoint in
4034          its destination address.  */
4035       switch (mips_insn_size (ISA_MICROMIPS, insn))
4036         {
4037         /* 48-bit instructions.  */
4038         case 3 * MIPS_INSN16_SIZE: /* POOL48A: bits 011111 */
4039           loc += 2 * MIPS_INSN16_SIZE;
4040           break;
4041
4042         /* 32-bit instructions.  */
4043         case 2 * MIPS_INSN16_SIZE:
4044           switch (micromips_op (insn))
4045             {
4046             case 0x10: /* POOL32I: bits 010000 */
4047               if ((b5s5_op (insn) & 0x18) != 0x0
4048                                 /* BLTZ, BLTZAL, BGEZ, BGEZAL: 010000 000xx */
4049                                 /* BLEZ, BNEZC, BGTZ, BEQZC: 010000 001xx */
4050                   && (b5s5_op (insn) & 0x1d) != 0x11
4051                                 /* BLTZALS, BGEZALS: bits 010000 100x1 */
4052                   && ((b5s5_op (insn) & 0x1e) != 0x14
4053                       || (insn & 0x3) != 0x0)
4054                                 /* BC2F, BC2T: bits 010000 1010x xxx00 */
4055                   && (b5s5_op (insn) & 0x1e) != 0x1a
4056                                 /* BPOSGE64, BPOSGE32: bits 010000 1101x */
4057                   && ((b5s5_op (insn) & 0x1e) != 0x1c
4058                       || (insn & 0x3) != 0x0)
4059                                 /* BC1F, BC1T: bits 010000 1110x xxx00 */
4060                   && ((b5s5_op (insn) & 0x1c) != 0x1c
4061                       || (insn & 0x3) != 0x1))
4062                                 /* BC1ANY*: bits 010000 111xx xxx01 */
4063                 break;
4064               /* Fall through.  */
4065
4066             case 0x25: /* BEQ: bits 100101 */
4067             case 0x2d: /* BNE: bits 101101 */
4068               insn <<= 16;
4069               insn |= mips_fetch_instruction (gdbarch,
4070                                               ISA_MICROMIPS, loc, NULL);
4071               branch_bp = (loc + MIPS_INSN16_SIZE
4072                            + micromips_relative_offset16 (insn));
4073               is_branch = 1;
4074               break;
4075
4076             case 0x00: /* POOL32A: bits 000000 */
4077               insn <<= 16;
4078               insn |= mips_fetch_instruction (gdbarch,
4079                                               ISA_MICROMIPS, loc, NULL);
4080               if (b0s6_op (insn) != 0x3c
4081                                 /* POOL32Axf: bits 000000 ... 111100 */
4082                   || (b6s10_ext (insn) & 0x2bf) != 0x3c)
4083                                 /* JALR, JALR.HB: 000000 000x111100 111100 */
4084                                 /* JALRS, JALRS.HB: 000000 010x111100 111100 */
4085                 break;
4086               /* Fall through.  */
4087
4088             case 0x1d: /* JALS: bits 011101 */
4089             case 0x35: /* J: bits 110101 */
4090             case 0x3d: /* JAL: bits 111101 */
4091             case 0x3c: /* JALX: bits 111100 */
4092               return 0; /* Fall back to the standard single-step code. */
4093
4094             case 0x18: /* POOL32C: bits 011000 */
4095               if ((b12s4_op (insn) & 0xb) == 0xb)
4096                                 /* SC, SCD: bits 011000 1x11 */
4097                 sc_found = 1;
4098               break;
4099             }
4100           loc += MIPS_INSN16_SIZE;
4101           break;
4102
4103         /* 16-bit instructions.  */
4104         case MIPS_INSN16_SIZE:
4105           switch (micromips_op (insn))
4106             {
4107             case 0x23: /* BEQZ16: bits 100011 */
4108             case 0x2b: /* BNEZ16: bits 101011 */
4109               branch_bp = loc + micromips_relative_offset7 (insn);
4110               is_branch = 1;
4111               break;
4112
4113             case 0x11: /* POOL16C: bits 010001 */
4114               if ((b5s5_op (insn) & 0x1c) != 0xc
4115                                 /* JR16, JRC, JALR16, JALRS16: 010001 011xx */
4116                   && b5s5_op (insn) != 0x18)
4117                                 /* JRADDIUSP: bits 010001 11000 */
4118                 break;
4119               return 0; /* Fall back to the standard single-step code. */
4120
4121             case 0x33: /* B16: bits 110011 */
4122               return 0; /* Fall back to the standard single-step code. */
4123             }
4124           break;
4125         }
4126       if (is_branch)
4127         {
4128           if (last_breakpoint >= 1)
4129             return 0; /* More than one branch found, fallback to the
4130                          standard single-step code.  */
4131           breaks[1] = branch_bp;
4132           last_breakpoint++;
4133         }
4134     }
4135   if (!sc_found)
4136     return 0;
4137
4138   /* Insert a breakpoint right after the end of the atomic sequence.  */
4139   breaks[0] = loc;
4140
4141   /* Check for duplicated breakpoints.  Check also for a breakpoint
4142      placed (branch instruction's destination) in the atomic sequence */
4143   if (last_breakpoint && pc <= breaks[1] && breaks[1] <= breaks[0])
4144     last_breakpoint = 0;
4145
4146   /* Effectively inserts the breakpoints.  */
4147   for (index = 0; index <= last_breakpoint; index++)
4148     insert_single_step_breakpoint (gdbarch, aspace, breaks[index]);
4149
4150   return 1;
4151 }
4152
4153 static int
4154 deal_with_atomic_sequence (struct gdbarch *gdbarch,
4155                            struct address_space *aspace, CORE_ADDR pc)
4156 {
4157   if (mips_pc_is_mips (pc))
4158     return mips_deal_with_atomic_sequence (gdbarch, aspace, pc);
4159   else if (mips_pc_is_micromips (gdbarch, pc))
4160     return micromips_deal_with_atomic_sequence (gdbarch, aspace, pc);
4161   else
4162     return 0;
4163 }
4164
4165 /* mips_software_single_step() is called just before we want to resume
4166    the inferior, if we want to single-step it but there is no hardware
4167    or kernel single-step support (MIPS on GNU/Linux for example).  We find
4168    the target of the coming instruction and breakpoint it.  */
4169
4170 int
4171 mips_software_single_step (struct frame_info *frame)
4172 {
4173   struct gdbarch *gdbarch = get_frame_arch (frame);
4174   struct address_space *aspace = get_frame_address_space (frame);
4175   CORE_ADDR pc, next_pc;
4176
4177   pc = get_frame_pc (frame);
4178   if (deal_with_atomic_sequence (gdbarch, aspace, pc))
4179     return 1;
4180
4181   next_pc = mips_next_pc (frame, pc);
4182
4183   insert_single_step_breakpoint (gdbarch, aspace, next_pc);
4184   return 1;
4185 }
4186
4187 /* Test whether the PC points to the return instruction at the
4188    end of a function.  */
4189
4190 static int
4191 mips_about_to_return (struct gdbarch *gdbarch, CORE_ADDR pc)
4192 {
4193   ULONGEST insn;
4194   ULONGEST hint;
4195
4196   /* This used to check for MIPS16, but this piece of code is never
4197      called for MIPS16 functions.  And likewise microMIPS ones.  */
4198   gdb_assert (mips_pc_is_mips (pc));
4199
4200   insn = mips_fetch_instruction (gdbarch, ISA_MIPS, pc, NULL);
4201   hint = 0x7c0;
4202   return (insn & ~hint) == 0x3e00008;                   /* jr(.hb) $ra */
4203 }
4204
4205
4206 /* This fencepost looks highly suspicious to me.  Removing it also
4207    seems suspicious as it could affect remote debugging across serial
4208    lines.  */
4209
4210 static CORE_ADDR
4211 heuristic_proc_start (struct gdbarch *gdbarch, CORE_ADDR pc)
4212 {
4213   CORE_ADDR start_pc;
4214   CORE_ADDR fence;
4215   int instlen;
4216   int seen_adjsp = 0;
4217   struct inferior *inf;
4218
4219   pc = gdbarch_addr_bits_remove (gdbarch, pc);
4220   start_pc = pc;
4221   fence = start_pc - heuristic_fence_post;
4222   if (start_pc == 0)
4223     return 0;
4224
4225   if (heuristic_fence_post == -1 || fence < VM_MIN_ADDRESS)
4226     fence = VM_MIN_ADDRESS;
4227
4228   instlen = mips_pc_is_mips (pc) ? MIPS_INSN32_SIZE : MIPS_INSN16_SIZE;
4229
4230   inf = current_inferior ();
4231
4232   /* Search back for previous return.  */
4233   for (start_pc -= instlen;; start_pc -= instlen)
4234     if (start_pc < fence)
4235       {
4236         /* It's not clear to me why we reach this point when
4237            stop_soon, but with this test, at least we
4238            don't print out warnings for every child forked (eg, on
4239            decstation).  22apr93 rich@cygnus.com.  */
4240         if (inf->control.stop_soon == NO_STOP_QUIETLY)
4241           {
4242             static int blurb_printed = 0;
4243
4244             warning (_("GDB can't find the start of the function at %s."),
4245                      paddress (gdbarch, pc));
4246
4247             if (!blurb_printed)
4248               {
4249                 /* This actually happens frequently in embedded
4250                    development, when you first connect to a board
4251                    and your stack pointer and pc are nowhere in
4252                    particular.  This message needs to give people
4253                    in that situation enough information to
4254                    determine that it's no big deal.  */
4255                 printf_filtered ("\n\
4256     GDB is unable to find the start of the function at %s\n\
4257 and thus can't determine the size of that function's stack frame.\n\
4258 This means that GDB may be unable to access that stack frame, or\n\
4259 the frames below it.\n\
4260     This problem is most likely caused by an invalid program counter or\n\
4261 stack pointer.\n\
4262     However, if you think GDB should simply search farther back\n\
4263 from %s for code which looks like the beginning of a\n\
4264 function, you can increase the range of the search using the `set\n\
4265 heuristic-fence-post' command.\n",
4266                         paddress (gdbarch, pc), paddress (gdbarch, pc));
4267                 blurb_printed = 1;
4268               }
4269           }
4270
4271         return 0;
4272       }
4273     else if (mips_pc_is_mips16 (gdbarch, start_pc))
4274       {
4275         unsigned short inst;
4276
4277         /* On MIPS16, any one of the following is likely to be the
4278            start of a function:
4279            extend save
4280            save
4281            entry
4282            addiu sp,-n
4283            daddiu sp,-n
4284            extend -n followed by 'addiu sp,+n' or 'daddiu sp,+n'.  */
4285         inst = mips_fetch_instruction (gdbarch, ISA_MIPS16, start_pc, NULL);
4286         if ((inst & 0xff80) == 0x6480)          /* save */
4287           {
4288             if (start_pc - instlen >= fence)
4289               {
4290                 inst = mips_fetch_instruction (gdbarch, ISA_MIPS16,
4291                                                start_pc - instlen, NULL);
4292                 if ((inst & 0xf800) == 0xf000)  /* extend */
4293                   start_pc -= instlen;
4294               }
4295             break;
4296           }
4297         else if (((inst & 0xf81f) == 0xe809
4298                   && (inst & 0x700) != 0x700)   /* entry */
4299                  || (inst & 0xff80) == 0x6380   /* addiu sp,-n */
4300                  || (inst & 0xff80) == 0xfb80   /* daddiu sp,-n */
4301                  || ((inst & 0xf810) == 0xf010 && seen_adjsp))  /* extend -n */
4302           break;
4303         else if ((inst & 0xff00) == 0x6300      /* addiu sp */
4304                  || (inst & 0xff00) == 0xfb00)  /* daddiu sp */
4305           seen_adjsp = 1;
4306         else
4307           seen_adjsp = 0;
4308       }
4309     else if (mips_pc_is_micromips (gdbarch, start_pc))
4310       {
4311         ULONGEST insn;
4312         int stop = 0;
4313         long offset;
4314         int dreg;
4315         int sreg;
4316
4317         /* On microMIPS, any one of the following is likely to be the
4318            start of a function:
4319            ADDIUSP -imm
4320            (D)ADDIU $sp, -imm
4321            LUI $gp, imm  */
4322         insn = mips_fetch_instruction (gdbarch, ISA_MICROMIPS, pc, NULL);
4323         switch (micromips_op (insn))
4324           {
4325           case 0xc: /* ADDIU: bits 001100 */
4326           case 0x17: /* DADDIU: bits 010111 */
4327             sreg = b0s5_reg (insn);
4328             dreg = b5s5_reg (insn);
4329             insn <<= 16;
4330             insn |= mips_fetch_instruction (gdbarch, ISA_MICROMIPS,
4331                                             pc + MIPS_INSN16_SIZE, NULL);
4332             offset = (b0s16_imm (insn) ^ 0x8000) - 0x8000;
4333             if (sreg == MIPS_SP_REGNUM && dreg == MIPS_SP_REGNUM
4334                                 /* (D)ADDIU $sp, imm */
4335                 && offset < 0)
4336               stop = 1;
4337             break;
4338
4339           case 0x10: /* POOL32I: bits 010000 */
4340             if (b5s5_op (insn) == 0xd
4341                                 /* LUI: bits 010000 001101 */
4342                 && b0s5_reg (insn >> 16) == 28)
4343                                 /* LUI $gp, imm */
4344               stop = 1;
4345             break;
4346
4347           case 0x13: /* POOL16D: bits 010011 */
4348             if ((insn & 0x1) == 0x1)
4349                                 /* ADDIUSP: bits 010011 1 */
4350               {
4351                 offset = micromips_decode_imm9 (b1s9_imm (insn));
4352                 if (offset < 0)
4353                                 /* ADDIUSP -imm */
4354                   stop = 1;
4355               }
4356             else
4357                                 /* ADDIUS5: bits 010011 0 */
4358               {
4359                 dreg = b5s5_reg (insn);
4360                 offset = (b1s4_imm (insn) ^ 8) - 8;
4361                 if (dreg == MIPS_SP_REGNUM && offset < 0)
4362                                 /* ADDIUS5  $sp, -imm */
4363                   stop = 1;
4364               }
4365             break;
4366           }
4367         if (stop)
4368           break;
4369       }
4370     else if (mips_about_to_return (gdbarch, start_pc))
4371       {
4372         /* Skip return and its delay slot.  */
4373         start_pc += 2 * MIPS_INSN32_SIZE;
4374         break;
4375       }
4376
4377   return start_pc;
4378 }
4379
4380 struct mips_objfile_private
4381 {
4382   bfd_size_type size;
4383   char *contents;
4384 };
4385
4386 /* According to the current ABI, should the type be passed in a
4387    floating-point register (assuming that there is space)?  When there
4388    is no FPU, FP are not even considered as possible candidates for
4389    FP registers and, consequently this returns false - forces FP
4390    arguments into integer registers.  */
4391
4392 static int
4393 fp_register_arg_p (struct gdbarch *gdbarch, enum type_code typecode,
4394                    struct type *arg_type)
4395 {
4396   return ((typecode == TYPE_CODE_FLT
4397            || (MIPS_EABI (gdbarch)
4398                && (typecode == TYPE_CODE_STRUCT
4399                    || typecode == TYPE_CODE_UNION)
4400                && TYPE_NFIELDS (arg_type) == 1
4401                && TYPE_CODE (check_typedef (TYPE_FIELD_TYPE (arg_type, 0))) 
4402                == TYPE_CODE_FLT))
4403           && MIPS_FPU_TYPE(gdbarch) != MIPS_FPU_NONE);
4404 }
4405
4406 /* On o32, argument passing in GPRs depends on the alignment of the type being
4407    passed.  Return 1 if this type must be aligned to a doubleword boundary.  */
4408
4409 static int
4410 mips_type_needs_double_align (struct type *type)
4411 {
4412   enum type_code typecode = TYPE_CODE (type);
4413
4414   if (typecode == TYPE_CODE_FLT && TYPE_LENGTH (type) == 8)
4415     return 1;
4416   else if (typecode == TYPE_CODE_STRUCT)
4417     {
4418       if (TYPE_NFIELDS (type) < 1)
4419         return 0;
4420       return mips_type_needs_double_align (TYPE_FIELD_TYPE (type, 0));
4421     }
4422   else if (typecode == TYPE_CODE_UNION)
4423     {
4424       int i, n;
4425
4426       n = TYPE_NFIELDS (type);
4427       for (i = 0; i < n; i++)
4428         if (mips_type_needs_double_align (TYPE_FIELD_TYPE (type, i)))
4429           return 1;
4430       return 0;
4431     }
4432   return 0;
4433 }
4434
4435 /* Adjust the address downward (direction of stack growth) so that it
4436    is correctly aligned for a new stack frame.  */
4437 static CORE_ADDR
4438 mips_frame_align (struct gdbarch *gdbarch, CORE_ADDR addr)
4439 {
4440   return align_down (addr, 16);
4441 }
4442
4443 /* Implement the "push_dummy_code" gdbarch method.  */
4444
4445 static CORE_ADDR
4446 mips_push_dummy_code (struct gdbarch *gdbarch, CORE_ADDR sp,
4447                       CORE_ADDR funaddr, struct value **args,
4448                       int nargs, struct type *value_type,
4449                       CORE_ADDR *real_pc, CORE_ADDR *bp_addr,
4450                       struct regcache *regcache)
4451 {
4452   static gdb_byte nop_insn[] = { 0, 0, 0, 0 };
4453   CORE_ADDR nop_addr;
4454   CORE_ADDR bp_slot;
4455
4456   /* Reserve enough room on the stack for our breakpoint instruction.  */
4457   bp_slot = sp - sizeof (nop_insn);
4458
4459   /* Return to microMIPS mode if calling microMIPS code to avoid
4460      triggering an address error exception on processors that only
4461      support microMIPS execution.  */
4462   *bp_addr = (mips_pc_is_micromips (gdbarch, funaddr)
4463               ? make_compact_addr (bp_slot) : bp_slot);
4464
4465   /* The breakpoint layer automatically adjusts the address of
4466      breakpoints inserted in a branch delay slot.  With enough
4467      bad luck, the 4 bytes located just before our breakpoint
4468      instruction could look like a branch instruction, and thus
4469      trigger the adjustement, and break the function call entirely.
4470      So, we reserve those 4 bytes and write a nop instruction
4471      to prevent that from happening.  */
4472   nop_addr = bp_slot - sizeof (nop_insn);
4473   write_memory (nop_addr, nop_insn, sizeof (nop_insn));
4474   sp = mips_frame_align (gdbarch, nop_addr);
4475
4476   /* Inferior resumes at the function entry point.  */
4477   *real_pc = funaddr;
4478
4479   return sp;
4480 }
4481
4482 static CORE_ADDR
4483 mips_eabi_push_dummy_call (struct gdbarch *gdbarch, struct value *function,
4484                            struct regcache *regcache, CORE_ADDR bp_addr,
4485                            int nargs, struct value **args, CORE_ADDR sp,
4486                            int struct_return, CORE_ADDR struct_addr)
4487 {
4488   int argreg;
4489   int float_argreg;
4490   int argnum;
4491   int len = 0;
4492   int stack_offset = 0;
4493   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
4494   CORE_ADDR func_addr = find_function_addr (function, NULL);
4495   int regsize = mips_abi_regsize (gdbarch);
4496
4497   /* For shared libraries, "t9" needs to point at the function
4498      address.  */
4499   regcache_cooked_write_signed (regcache, MIPS_T9_REGNUM, func_addr);
4500
4501   /* Set the return address register to point to the entry point of
4502      the program, where a breakpoint lies in wait.  */
4503   regcache_cooked_write_signed (regcache, MIPS_RA_REGNUM, bp_addr);
4504
4505   /* First ensure that the stack and structure return address (if any)
4506      are properly aligned.  The stack has to be at least 64-bit
4507      aligned even on 32-bit machines, because doubles must be 64-bit
4508      aligned.  For n32 and n64, stack frames need to be 128-bit
4509      aligned, so we round to this widest known alignment.  */
4510
4511   sp = align_down (sp, 16);
4512   struct_addr = align_down (struct_addr, 16);
4513
4514   /* Now make space on the stack for the args.  We allocate more
4515      than necessary for EABI, because the first few arguments are
4516      passed in registers, but that's OK.  */
4517   for (argnum = 0; argnum < nargs; argnum++)
4518     len += align_up (TYPE_LENGTH (value_type (args[argnum])), regsize);
4519   sp -= align_up (len, 16);
4520
4521   if (mips_debug)
4522     fprintf_unfiltered (gdb_stdlog,
4523                         "mips_eabi_push_dummy_call: sp=%s allocated %ld\n",
4524                         paddress (gdbarch, sp), (long) align_up (len, 16));
4525
4526   /* Initialize the integer and float register pointers.  */
4527   argreg = MIPS_A0_REGNUM;
4528   float_argreg = mips_fpa0_regnum (gdbarch);
4529
4530   /* The struct_return pointer occupies the first parameter-passing reg.  */
4531   if (struct_return)
4532     {
4533       if (mips_debug)
4534         fprintf_unfiltered (gdb_stdlog,
4535                             "mips_eabi_push_dummy_call: "
4536                             "struct_return reg=%d %s\n",
4537                             argreg, paddress (gdbarch, struct_addr));
4538       regcache_cooked_write_unsigned (regcache, argreg++, struct_addr);
4539     }
4540
4541   /* Now load as many as possible of the first arguments into
4542      registers, and push the rest onto the stack.  Loop thru args
4543      from first to last.  */
4544   for (argnum = 0; argnum < nargs; argnum++)
4545     {
4546       const gdb_byte *val;
4547       gdb_byte valbuf[MAX_REGISTER_SIZE];
4548       struct value *arg = args[argnum];
4549       struct type *arg_type = check_typedef (value_type (arg));
4550       int len = TYPE_LENGTH (arg_type);
4551       enum type_code typecode = TYPE_CODE (arg_type);
4552
4553       if (mips_debug)
4554         fprintf_unfiltered (gdb_stdlog,
4555                             "mips_eabi_push_dummy_call: %d len=%d type=%d",
4556                             argnum + 1, len, (int) typecode);
4557
4558       /* The EABI passes structures that do not fit in a register by
4559          reference.  */
4560       if (len > regsize
4561           && (typecode == TYPE_CODE_STRUCT || typecode == TYPE_CODE_UNION))
4562         {
4563           store_unsigned_integer (valbuf, regsize, byte_order,
4564                                   value_address (arg));
4565           typecode = TYPE_CODE_PTR;
4566           len = regsize;
4567           val = valbuf;
4568           if (mips_debug)
4569             fprintf_unfiltered (gdb_stdlog, " push");
4570         }
4571       else
4572         val = value_contents (arg);
4573
4574       /* 32-bit ABIs always start floating point arguments in an
4575          even-numbered floating point register.  Round the FP register
4576          up before the check to see if there are any FP registers
4577          left.  Non MIPS_EABI targets also pass the FP in the integer
4578          registers so also round up normal registers.  */
4579       if (regsize < 8 && fp_register_arg_p (gdbarch, typecode, arg_type))
4580         {
4581           if ((float_argreg & 1))
4582             float_argreg++;
4583         }
4584
4585       /* Floating point arguments passed in registers have to be
4586          treated specially.  On 32-bit architectures, doubles
4587          are passed in register pairs; the even register gets
4588          the low word, and the odd register gets the high word.
4589          On non-EABI processors, the first two floating point arguments are
4590          also copied to general registers, because MIPS16 functions
4591          don't use float registers for arguments.  This duplication of
4592          arguments in general registers can't hurt non-MIPS16 functions
4593          because those registers are normally skipped.  */
4594       /* MIPS_EABI squeezes a struct that contains a single floating
4595          point value into an FP register instead of pushing it onto the
4596          stack.  */
4597       if (fp_register_arg_p (gdbarch, typecode, arg_type)
4598           && float_argreg <= MIPS_LAST_FP_ARG_REGNUM (gdbarch))
4599         {
4600           /* EABI32 will pass doubles in consecutive registers, even on
4601              64-bit cores.  At one time, we used to check the size of
4602              `float_argreg' to determine whether or not to pass doubles
4603              in consecutive registers, but this is not sufficient for
4604              making the ABI determination.  */
4605           if (len == 8 && mips_abi (gdbarch) == MIPS_ABI_EABI32)
4606             {
4607               int low_offset = gdbarch_byte_order (gdbarch)
4608                                == BFD_ENDIAN_BIG ? 4 : 0;
4609               long regval;
4610
4611               /* Write the low word of the double to the even register(s).  */
4612               regval = extract_signed_integer (val + low_offset,
4613                                                4, byte_order);
4614               if (mips_debug)
4615                 fprintf_unfiltered (gdb_stdlog, " - fpreg=%d val=%s",
4616                                     float_argreg, phex (regval, 4));
4617               regcache_cooked_write_signed (regcache, float_argreg++, regval);
4618
4619               /* Write the high word of the double to the odd register(s).  */
4620               regval = extract_signed_integer (val + 4 - low_offset,
4621                                                4, byte_order);
4622               if (mips_debug)
4623                 fprintf_unfiltered (gdb_stdlog, " - fpreg=%d val=%s",
4624                                     float_argreg, phex (regval, 4));
4625               regcache_cooked_write_signed (regcache, float_argreg++, regval);
4626             }
4627           else
4628             {
4629               /* This is a floating point value that fits entirely
4630                  in a single register.  */
4631               /* On 32 bit ABI's the float_argreg is further adjusted
4632                  above to ensure that it is even register aligned.  */
4633               LONGEST regval = extract_signed_integer (val, len, byte_order);
4634               if (mips_debug)
4635                 fprintf_unfiltered (gdb_stdlog, " - fpreg=%d val=%s",
4636                                     float_argreg, phex (regval, len));
4637               regcache_cooked_write_signed (regcache, float_argreg++, regval);
4638             }
4639         }
4640       else
4641         {
4642           /* Copy the argument to general registers or the stack in
4643              register-sized pieces.  Large arguments are split between
4644              registers and stack.  */
4645           /* Note: structs whose size is not a multiple of regsize
4646              are treated specially: Irix cc passes
4647              them in registers where gcc sometimes puts them on the
4648              stack.  For maximum compatibility, we will put them in
4649              both places.  */
4650           int odd_sized_struct = (len > regsize && len % regsize != 0);
4651
4652           /* Note: Floating-point values that didn't fit into an FP
4653              register are only written to memory.  */
4654           while (len > 0)
4655             {
4656               /* Remember if the argument was written to the stack.  */
4657               int stack_used_p = 0;
4658               int partial_len = (len < regsize ? len : regsize);
4659
4660               if (mips_debug)
4661                 fprintf_unfiltered (gdb_stdlog, " -- partial=%d",
4662                                     partial_len);
4663
4664               /* Write this portion of the argument to the stack.  */
4665               if (argreg > MIPS_LAST_ARG_REGNUM (gdbarch)
4666                   || odd_sized_struct
4667                   || fp_register_arg_p (gdbarch, typecode, arg_type))
4668                 {
4669                   /* Should shorter than int integer values be
4670                      promoted to int before being stored?  */
4671                   int longword_offset = 0;
4672                   CORE_ADDR addr;
4673                   stack_used_p = 1;
4674                   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
4675                     {
4676                       if (regsize == 8
4677                           && (typecode == TYPE_CODE_INT
4678                               || typecode == TYPE_CODE_PTR
4679                               || typecode == TYPE_CODE_FLT) && len <= 4)
4680                         longword_offset = regsize - len;
4681                       else if ((typecode == TYPE_CODE_STRUCT
4682                                 || typecode == TYPE_CODE_UNION)
4683                                && TYPE_LENGTH (arg_type) < regsize)
4684                         longword_offset = regsize - len;
4685                     }
4686
4687                   if (mips_debug)
4688                     {
4689                       fprintf_unfiltered (gdb_stdlog, " - stack_offset=%s",
4690                                           paddress (gdbarch, stack_offset));
4691                       fprintf_unfiltered (gdb_stdlog, " longword_offset=%s",
4692                                           paddress (gdbarch, longword_offset));
4693                     }
4694
4695                   addr = sp + stack_offset + longword_offset;
4696
4697                   if (mips_debug)
4698                     {
4699                       int i;
4700                       fprintf_unfiltered (gdb_stdlog, " @%s ",
4701                                           paddress (gdbarch, addr));
4702                       for (i = 0; i < partial_len; i++)
4703                         {
4704                           fprintf_unfiltered (gdb_stdlog, "%02x",
4705                                               val[i] & 0xff);
4706                         }
4707                     }
4708                   write_memory (addr, val, partial_len);
4709                 }
4710
4711               /* Note!!! This is NOT an else clause.  Odd sized
4712                  structs may go thru BOTH paths.  Floating point
4713                  arguments will not.  */
4714               /* Write this portion of the argument to a general
4715                  purpose register.  */
4716               if (argreg <= MIPS_LAST_ARG_REGNUM (gdbarch)
4717                   && !fp_register_arg_p (gdbarch, typecode, arg_type))
4718                 {
4719                   LONGEST regval =
4720                     extract_signed_integer (val, partial_len, byte_order);
4721
4722                   if (mips_debug)
4723                     fprintf_filtered (gdb_stdlog, " - reg=%d val=%s",
4724                                       argreg,
4725                                       phex (regval, regsize));
4726                   regcache_cooked_write_signed (regcache, argreg, regval);
4727                   argreg++;
4728                 }
4729
4730               len -= partial_len;
4731               val += partial_len;
4732
4733               /* Compute the offset into the stack at which we will
4734                  copy the next parameter.
4735
4736                  In the new EABI (and the NABI32), the stack_offset
4737                  only needs to be adjusted when it has been used.  */
4738
4739               if (stack_used_p)
4740                 stack_offset += align_up (partial_len, regsize);
4741             }
4742         }
4743       if (mips_debug)
4744         fprintf_unfiltered (gdb_stdlog, "\n");
4745     }
4746
4747   regcache_cooked_write_signed (regcache, MIPS_SP_REGNUM, sp);
4748
4749   /* Return adjusted stack pointer.  */
4750   return sp;
4751 }
4752
4753 /* Determine the return value convention being used.  */
4754
4755 static enum return_value_convention
4756 mips_eabi_return_value (struct gdbarch *gdbarch, struct value *function,
4757                         struct type *type, struct regcache *regcache,
4758                         gdb_byte *readbuf, const gdb_byte *writebuf)
4759 {
4760   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
4761   int fp_return_type = 0;
4762   int offset, regnum, xfer;
4763
4764   if (TYPE_LENGTH (type) > 2 * mips_abi_regsize (gdbarch))
4765     return RETURN_VALUE_STRUCT_CONVENTION;
4766
4767   /* Floating point type?  */
4768   if (tdep->mips_fpu_type != MIPS_FPU_NONE)
4769     {
4770       if (TYPE_CODE (type) == TYPE_CODE_FLT)
4771         fp_return_type = 1;
4772       /* Structs with a single field of float type 
4773          are returned in a floating point register.  */
4774       if ((TYPE_CODE (type) == TYPE_CODE_STRUCT
4775            || TYPE_CODE (type) == TYPE_CODE_UNION)
4776           && TYPE_NFIELDS (type) == 1)
4777         {
4778           struct type *fieldtype = TYPE_FIELD_TYPE (type, 0);
4779
4780           if (TYPE_CODE (check_typedef (fieldtype)) == TYPE_CODE_FLT)
4781             fp_return_type = 1;
4782         }
4783     }
4784
4785   if (fp_return_type)      
4786     {
4787       /* A floating-point value belongs in the least significant part
4788          of FP0/FP1.  */
4789       if (mips_debug)
4790         fprintf_unfiltered (gdb_stderr, "Return float in $fp0\n");
4791       regnum = mips_regnum (gdbarch)->fp0;
4792     }
4793   else 
4794     {
4795       /* An integer value goes in V0/V1.  */
4796       if (mips_debug)
4797         fprintf_unfiltered (gdb_stderr, "Return scalar in $v0\n");
4798       regnum = MIPS_V0_REGNUM;
4799     }
4800   for (offset = 0;
4801        offset < TYPE_LENGTH (type);
4802        offset += mips_abi_regsize (gdbarch), regnum++)
4803     {
4804       xfer = mips_abi_regsize (gdbarch);
4805       if (offset + xfer > TYPE_LENGTH (type))
4806         xfer = TYPE_LENGTH (type) - offset;
4807       mips_xfer_register (gdbarch, regcache,
4808                           gdbarch_num_regs (gdbarch) + regnum, xfer,
4809                           gdbarch_byte_order (gdbarch), readbuf, writebuf,
4810                           offset);
4811     }
4812
4813   return RETURN_VALUE_REGISTER_CONVENTION;
4814 }
4815
4816
4817 /* N32/N64 ABI stuff.  */
4818
4819 /* Search for a naturally aligned double at OFFSET inside a struct
4820    ARG_TYPE.  The N32 / N64 ABIs pass these in floating point
4821    registers.  */
4822
4823 static int
4824 mips_n32n64_fp_arg_chunk_p (struct gdbarch *gdbarch, struct type *arg_type,
4825                             int offset)
4826 {
4827   int i;
4828
4829   if (TYPE_CODE (arg_type) != TYPE_CODE_STRUCT)
4830     return 0;
4831
4832   if (MIPS_FPU_TYPE (gdbarch) != MIPS_FPU_DOUBLE)
4833     return 0;
4834
4835   if (TYPE_LENGTH (arg_type) < offset + MIPS64_REGSIZE)
4836     return 0;
4837
4838   for (i = 0; i < TYPE_NFIELDS (arg_type); i++)
4839     {
4840       int pos;
4841       struct type *field_type;
4842
4843       /* We're only looking at normal fields.  */
4844       if (field_is_static (&TYPE_FIELD (arg_type, i))
4845           || (TYPE_FIELD_BITPOS (arg_type, i) % 8) != 0)
4846         continue;
4847
4848       /* If we have gone past the offset, there is no double to pass.  */
4849       pos = TYPE_FIELD_BITPOS (arg_type, i) / 8;
4850       if (pos > offset)
4851         return 0;
4852
4853       field_type = check_typedef (TYPE_FIELD_TYPE (arg_type, i));
4854
4855       /* If this field is entirely before the requested offset, go
4856          on to the next one.  */
4857       if (pos + TYPE_LENGTH (field_type) <= offset)
4858         continue;
4859
4860       /* If this is our special aligned double, we can stop.  */
4861       if (TYPE_CODE (field_type) == TYPE_CODE_FLT
4862           && TYPE_LENGTH (field_type) == MIPS64_REGSIZE)
4863         return 1;
4864
4865       /* This field starts at or before the requested offset, and
4866          overlaps it.  If it is a structure, recurse inwards.  */
4867       return mips_n32n64_fp_arg_chunk_p (gdbarch, field_type, offset - pos);
4868     }
4869
4870   return 0;
4871 }
4872
4873 static CORE_ADDR
4874 mips_n32n64_push_dummy_call (struct gdbarch *gdbarch, struct value *function,
4875                              struct regcache *regcache, CORE_ADDR bp_addr,
4876                              int nargs, struct value **args, CORE_ADDR sp,
4877                              int struct_return, CORE_ADDR struct_addr)
4878 {
4879   int argreg;
4880   int float_argreg;
4881   int argnum;
4882   int len = 0;
4883   int stack_offset = 0;
4884   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
4885   CORE_ADDR func_addr = find_function_addr (function, NULL);
4886
4887   /* For shared libraries, "t9" needs to point at the function
4888      address.  */
4889   regcache_cooked_write_signed (regcache, MIPS_T9_REGNUM, func_addr);
4890
4891   /* Set the return address register to point to the entry point of
4892      the program, where a breakpoint lies in wait.  */
4893   regcache_cooked_write_signed (regcache, MIPS_RA_REGNUM, bp_addr);
4894
4895   /* First ensure that the stack and structure return address (if any)
4896      are properly aligned.  The stack has to be at least 64-bit
4897      aligned even on 32-bit machines, because doubles must be 64-bit
4898      aligned.  For n32 and n64, stack frames need to be 128-bit
4899      aligned, so we round to this widest known alignment.  */
4900
4901   sp = align_down (sp, 16);
4902   struct_addr = align_down (struct_addr, 16);
4903
4904   /* Now make space on the stack for the args.  */
4905   for (argnum = 0; argnum < nargs; argnum++)
4906     len += align_up (TYPE_LENGTH (value_type (args[argnum])), MIPS64_REGSIZE);
4907   sp -= align_up (len, 16);
4908
4909   if (mips_debug)
4910     fprintf_unfiltered (gdb_stdlog,
4911                         "mips_n32n64_push_dummy_call: sp=%s allocated %ld\n",
4912                         paddress (gdbarch, sp), (long) align_up (len, 16));
4913
4914   /* Initialize the integer and float register pointers.  */
4915   argreg = MIPS_A0_REGNUM;
4916   float_argreg = mips_fpa0_regnum (gdbarch);
4917
4918   /* The struct_return pointer occupies the first parameter-passing reg.  */
4919   if (struct_return)
4920     {
4921       if (mips_debug)
4922         fprintf_unfiltered (gdb_stdlog,
4923                             "mips_n32n64_push_dummy_call: "
4924                             "struct_return reg=%d %s\n",
4925                             argreg, paddress (gdbarch, struct_addr));
4926       regcache_cooked_write_unsigned (regcache, argreg++, struct_addr);
4927     }
4928
4929   /* Now load as many as possible of the first arguments into
4930      registers, and push the rest onto the stack.  Loop thru args
4931      from first to last.  */
4932   for (argnum = 0; argnum < nargs; argnum++)
4933     {
4934       const gdb_byte *val;
4935       struct value *arg = args[argnum];
4936       struct type *arg_type = check_typedef (value_type (arg));
4937       int len = TYPE_LENGTH (arg_type);
4938       enum type_code typecode = TYPE_CODE (arg_type);
4939
4940       if (mips_debug)
4941         fprintf_unfiltered (gdb_stdlog,
4942                             "mips_n32n64_push_dummy_call: %d len=%d type=%d",
4943                             argnum + 1, len, (int) typecode);
4944
4945       val = value_contents (arg);
4946
4947       /* A 128-bit long double value requires an even-odd pair of
4948          floating-point registers.  */
4949       if (len == 16
4950           && fp_register_arg_p (gdbarch, typecode, arg_type)
4951           && (float_argreg & 1))
4952         {
4953           float_argreg++;
4954           argreg++;
4955         }
4956
4957       if (fp_register_arg_p (gdbarch, typecode, arg_type)
4958           && argreg <= MIPS_LAST_ARG_REGNUM (gdbarch))
4959         {
4960           /* This is a floating point value that fits entirely
4961              in a single register or a pair of registers.  */
4962           int reglen = (len <= MIPS64_REGSIZE ? len : MIPS64_REGSIZE);
4963           LONGEST regval = extract_unsigned_integer (val, reglen, byte_order);
4964           if (mips_debug)
4965             fprintf_unfiltered (gdb_stdlog, " - fpreg=%d val=%s",
4966                                 float_argreg, phex (regval, reglen));
4967           regcache_cooked_write_unsigned (regcache, float_argreg, regval);
4968
4969           if (mips_debug)
4970             fprintf_unfiltered (gdb_stdlog, " - reg=%d val=%s",
4971                                 argreg, phex (regval, reglen));
4972           regcache_cooked_write_unsigned (regcache, argreg, regval);
4973           float_argreg++;
4974           argreg++;
4975           if (len == 16)
4976             {
4977               regval = extract_unsigned_integer (val + reglen,
4978                                                  reglen, byte_order);
4979               if (mips_debug)
4980                 fprintf_unfiltered (gdb_stdlog, " - fpreg=%d val=%s",
4981                                     float_argreg, phex (regval, reglen));
4982               regcache_cooked_write_unsigned (regcache, float_argreg, regval);
4983
4984               if (mips_debug)
4985                 fprintf_unfiltered (gdb_stdlog, " - reg=%d val=%s",
4986                                     argreg, phex (regval, reglen));
4987               regcache_cooked_write_unsigned (regcache, argreg, regval);
4988               float_argreg++;
4989               argreg++;
4990             }
4991         }
4992       else
4993         {
4994           /* Copy the argument to general registers or the stack in
4995              register-sized pieces.  Large arguments are split between
4996              registers and stack.  */
4997           /* For N32/N64, structs, unions, or other composite types are
4998              treated as a sequence of doublewords, and are passed in integer
4999              or floating point registers as though they were simple scalar
5000              parameters to the extent that they fit, with any excess on the
5001              stack packed according to the normal memory layout of the
5002              object.
5003              The caller does not reserve space for the register arguments;
5004              the callee is responsible for reserving it if required.  */
5005           /* Note: Floating-point values that didn't fit into an FP
5006              register are only written to memory.  */
5007           while (len > 0)
5008             {
5009               /* Remember if the argument was written to the stack.  */
5010               int stack_used_p = 0;
5011               int partial_len = (len < MIPS64_REGSIZE ? len : MIPS64_REGSIZE);
5012
5013               if (mips_debug)
5014                 fprintf_unfiltered (gdb_stdlog, " -- partial=%d",
5015                                     partial_len);
5016
5017               if (fp_register_arg_p (gdbarch, typecode, arg_type))
5018                 gdb_assert (argreg > MIPS_LAST_ARG_REGNUM (gdbarch));
5019
5020               /* Write this portion of the argument to the stack.  */
5021               if (argreg > MIPS_LAST_ARG_REGNUM (gdbarch))
5022                 {
5023                   /* Should shorter than int integer values be
5024                      promoted to int before being stored?  */
5025                   int longword_offset = 0;
5026                   CORE_ADDR addr;
5027                   stack_used_p = 1;
5028                   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
5029                     {
5030                       if ((typecode == TYPE_CODE_INT
5031                            || typecode == TYPE_CODE_PTR)
5032                           && len <= 4)
5033                         longword_offset = MIPS64_REGSIZE - len;
5034                     }
5035
5036                   if (mips_debug)
5037                     {
5038                       fprintf_unfiltered (gdb_stdlog, " - stack_offset=%s",
5039                                           paddress (gdbarch, stack_offset));
5040                       fprintf_unfiltered (gdb_stdlog, " longword_offset=%s",
5041                                           paddress (gdbarch, longword_offset));
5042                     }
5043
5044                   addr = sp + stack_offset + longword_offset;
5045
5046                   if (mips_debug)
5047                     {
5048                       int i;
5049                       fprintf_unfiltered (gdb_stdlog, " @%s ",
5050                                           paddress (gdbarch, addr));
5051                       for (i = 0; i < partial_len; i++)
5052                         {
5053                           fprintf_unfiltered (gdb_stdlog, "%02x",
5054                                               val[i] & 0xff);
5055                         }
5056                     }
5057                   write_memory (addr, val, partial_len);
5058                 }
5059
5060               /* Note!!! This is NOT an else clause.  Odd sized
5061                  structs may go thru BOTH paths.  */
5062               /* Write this portion of the argument to a general
5063                  purpose register.  */
5064               if (argreg <= MIPS_LAST_ARG_REGNUM (gdbarch))
5065                 {
5066                   LONGEST regval;
5067
5068                   /* Sign extend pointers, 32-bit integers and signed
5069                      16-bit and 8-bit integers; everything else is taken
5070                      as is.  */
5071
5072                   if ((partial_len == 4
5073                        && (typecode == TYPE_CODE_PTR
5074                            || typecode == TYPE_CODE_INT))
5075                       || (partial_len < 4
5076                           && typecode == TYPE_CODE_INT
5077                           && !TYPE_UNSIGNED (arg_type)))
5078                     regval = extract_signed_integer (val, partial_len,
5079                                                      byte_order);
5080                   else
5081                     regval = extract_unsigned_integer (val, partial_len,
5082                                                        byte_order);
5083
5084                   /* A non-floating-point argument being passed in a
5085                      general register.  If a struct or union, and if
5086                      the remaining length is smaller than the register
5087                      size, we have to adjust the register value on
5088                      big endian targets.
5089
5090                      It does not seem to be necessary to do the
5091                      same for integral types.  */
5092
5093                   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG
5094                       && partial_len < MIPS64_REGSIZE
5095                       && (typecode == TYPE_CODE_STRUCT
5096                           || typecode == TYPE_CODE_UNION))
5097                     regval <<= ((MIPS64_REGSIZE - partial_len)
5098                                 * TARGET_CHAR_BIT);
5099
5100                   if (mips_debug)
5101                     fprintf_filtered (gdb_stdlog, " - reg=%d val=%s",
5102                                       argreg,
5103                                       phex (regval, MIPS64_REGSIZE));
5104                   regcache_cooked_write_unsigned (regcache, argreg, regval);
5105
5106                   if (mips_n32n64_fp_arg_chunk_p (gdbarch, arg_type,
5107                                                   TYPE_LENGTH (arg_type) - len))
5108                     {
5109                       if (mips_debug)
5110                         fprintf_filtered (gdb_stdlog, " - fpreg=%d val=%s",
5111                                           float_argreg,
5112                                           phex (regval, MIPS64_REGSIZE));
5113                       regcache_cooked_write_unsigned (regcache, float_argreg,
5114                                                       regval);
5115                     }
5116
5117                   float_argreg++;
5118                   argreg++;
5119                 }
5120
5121               len -= partial_len;
5122               val += partial_len;
5123
5124               /* Compute the offset into the stack at which we will
5125                  copy the next parameter.
5126
5127                  In N32 (N64?), the stack_offset only needs to be
5128                  adjusted when it has been used.  */
5129
5130               if (stack_used_p)
5131                 stack_offset += align_up (partial_len, MIPS64_REGSIZE);
5132             }
5133         }
5134       if (mips_debug)
5135         fprintf_unfiltered (gdb_stdlog, "\n");
5136     }
5137
5138   regcache_cooked_write_signed (regcache, MIPS_SP_REGNUM, sp);
5139
5140   /* Return adjusted stack pointer.  */
5141   return sp;
5142 }
5143
5144 static enum return_value_convention
5145 mips_n32n64_return_value (struct gdbarch *gdbarch, struct value *function,
5146                           struct type *type, struct regcache *regcache,
5147                           gdb_byte *readbuf, const gdb_byte *writebuf)
5148 {
5149   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
5150
5151   /* From MIPSpro N32 ABI Handbook, Document Number: 007-2816-004
5152
5153      Function results are returned in $2 (and $3 if needed), or $f0 (and $f2
5154      if needed), as appropriate for the type.  Composite results (struct,
5155      union, or array) are returned in $2/$f0 and $3/$f2 according to the
5156      following rules:
5157
5158      * A struct with only one or two floating point fields is returned in $f0
5159      (and $f2 if necessary).  This is a generalization of the Fortran COMPLEX
5160      case.
5161
5162      * Any other composite results of at most 128 bits are returned in
5163      $2 (first 64 bits) and $3 (remainder, if necessary).
5164
5165      * Larger composite results are handled by converting the function to a
5166      procedure with an implicit first parameter, which is a pointer to an area
5167      reserved by the caller to receive the result.  [The o32-bit ABI requires
5168      that all composite results be handled by conversion to implicit first
5169      parameters.  The MIPS/SGI Fortran implementation has always made a
5170      specific exception to return COMPLEX results in the floating point
5171      registers.]  */
5172
5173   if (TYPE_LENGTH (type) > 2 * MIPS64_REGSIZE)
5174     return RETURN_VALUE_STRUCT_CONVENTION;
5175   else if (TYPE_CODE (type) == TYPE_CODE_FLT
5176            && TYPE_LENGTH (type) == 16
5177            && tdep->mips_fpu_type != MIPS_FPU_NONE)
5178     {
5179       /* A 128-bit floating-point value fills both $f0 and $f2.  The
5180          two registers are used in the same as memory order, so the
5181          eight bytes with the lower memory address are in $f0.  */
5182       if (mips_debug)
5183         fprintf_unfiltered (gdb_stderr, "Return float in $f0 and $f2\n");
5184       mips_xfer_register (gdbarch, regcache,
5185                           (gdbarch_num_regs (gdbarch)
5186                            + mips_regnum (gdbarch)->fp0),
5187                           8, gdbarch_byte_order (gdbarch),
5188                           readbuf, writebuf, 0);
5189       mips_xfer_register (gdbarch, regcache,
5190                           (gdbarch_num_regs (gdbarch)
5191                            + mips_regnum (gdbarch)->fp0 + 2),
5192                           8, gdbarch_byte_order (gdbarch),
5193                           readbuf ? readbuf + 8 : readbuf,
5194                           writebuf ? writebuf + 8 : writebuf, 0);
5195       return RETURN_VALUE_REGISTER_CONVENTION;
5196     }
5197   else if (TYPE_CODE (type) == TYPE_CODE_FLT
5198            && tdep->mips_fpu_type != MIPS_FPU_NONE)
5199     {
5200       /* A single or double floating-point value that fits in FP0.  */
5201       if (mips_debug)
5202         fprintf_unfiltered (gdb_stderr, "Return float in $fp0\n");
5203       mips_xfer_register (gdbarch, regcache,
5204                           (gdbarch_num_regs (gdbarch)
5205                            + mips_regnum (gdbarch)->fp0),
5206                           TYPE_LENGTH (type),
5207                           gdbarch_byte_order (gdbarch),
5208                           readbuf, writebuf, 0);
5209       return RETURN_VALUE_REGISTER_CONVENTION;
5210     }
5211   else if (TYPE_CODE (type) == TYPE_CODE_STRUCT
5212            && TYPE_NFIELDS (type) <= 2
5213            && TYPE_NFIELDS (type) >= 1
5214            && ((TYPE_NFIELDS (type) == 1
5215                 && (TYPE_CODE (check_typedef (TYPE_FIELD_TYPE (type, 0)))
5216                     == TYPE_CODE_FLT))
5217                || (TYPE_NFIELDS (type) == 2
5218                    && (TYPE_CODE (check_typedef (TYPE_FIELD_TYPE (type, 0)))
5219                        == TYPE_CODE_FLT)
5220                    && (TYPE_CODE (check_typedef (TYPE_FIELD_TYPE (type, 1)))
5221                        == TYPE_CODE_FLT))))
5222     {
5223       /* A struct that contains one or two floats.  Each value is part
5224          in the least significant part of their floating point
5225          register (or GPR, for soft float).  */
5226       int regnum;
5227       int field;
5228       for (field = 0, regnum = (tdep->mips_fpu_type != MIPS_FPU_NONE
5229                                 ? mips_regnum (gdbarch)->fp0
5230                                 : MIPS_V0_REGNUM);
5231            field < TYPE_NFIELDS (type); field++, regnum += 2)
5232         {
5233           int offset = (FIELD_BITPOS (TYPE_FIELDS (type)[field])
5234                         / TARGET_CHAR_BIT);
5235           if (mips_debug)
5236             fprintf_unfiltered (gdb_stderr, "Return float struct+%d\n",
5237                                 offset);
5238           if (TYPE_LENGTH (TYPE_FIELD_TYPE (type, field)) == 16)
5239             {
5240               /* A 16-byte long double field goes in two consecutive
5241                  registers.  */
5242               mips_xfer_register (gdbarch, regcache,
5243                                   gdbarch_num_regs (gdbarch) + regnum,
5244                                   8,
5245                                   gdbarch_byte_order (gdbarch),
5246                                   readbuf, writebuf, offset);
5247               mips_xfer_register (gdbarch, regcache,
5248                                   gdbarch_num_regs (gdbarch) + regnum + 1,
5249                                   8,
5250                                   gdbarch_byte_order (gdbarch),
5251                                   readbuf, writebuf, offset + 8);
5252             }
5253           else
5254             mips_xfer_register (gdbarch, regcache,
5255                                 gdbarch_num_regs (gdbarch) + regnum,
5256                                 TYPE_LENGTH (TYPE_FIELD_TYPE (type, field)),
5257                                 gdbarch_byte_order (gdbarch),
5258                                 readbuf, writebuf, offset);
5259         }
5260       return RETURN_VALUE_REGISTER_CONVENTION;
5261     }
5262   else if (TYPE_CODE (type) == TYPE_CODE_STRUCT
5263            || TYPE_CODE (type) == TYPE_CODE_UNION
5264            || TYPE_CODE (type) == TYPE_CODE_ARRAY)
5265     {
5266       /* A composite type.  Extract the left justified value,
5267          regardless of the byte order.  I.e. DO NOT USE
5268          mips_xfer_lower.  */
5269       int offset;
5270       int regnum;
5271       for (offset = 0, regnum = MIPS_V0_REGNUM;
5272            offset < TYPE_LENGTH (type);
5273            offset += register_size (gdbarch, regnum), regnum++)
5274         {
5275           int xfer = register_size (gdbarch, regnum);
5276           if (offset + xfer > TYPE_LENGTH (type))
5277             xfer = TYPE_LENGTH (type) - offset;
5278           if (mips_debug)
5279             fprintf_unfiltered (gdb_stderr, "Return struct+%d:%d in $%d\n",
5280                                 offset, xfer, regnum);
5281           mips_xfer_register (gdbarch, regcache,
5282                               gdbarch_num_regs (gdbarch) + regnum,
5283                               xfer, BFD_ENDIAN_UNKNOWN, readbuf, writebuf,
5284                               offset);
5285         }
5286       return RETURN_VALUE_REGISTER_CONVENTION;
5287     }
5288   else
5289     {
5290       /* A scalar extract each part but least-significant-byte
5291          justified.  */
5292       int offset;
5293       int regnum;
5294       for (offset = 0, regnum = MIPS_V0_REGNUM;
5295            offset < TYPE_LENGTH (type);
5296            offset += register_size (gdbarch, regnum), regnum++)
5297         {
5298           int xfer = register_size (gdbarch, regnum);
5299           if (offset + xfer > TYPE_LENGTH (type))
5300             xfer = TYPE_LENGTH (type) - offset;
5301           if (mips_debug)
5302             fprintf_unfiltered (gdb_stderr, "Return scalar+%d:%d in $%d\n",
5303                                 offset, xfer, regnum);
5304           mips_xfer_register (gdbarch, regcache,
5305                               gdbarch_num_regs (gdbarch) + regnum,
5306                               xfer, gdbarch_byte_order (gdbarch),
5307                               readbuf, writebuf, offset);
5308         }
5309       return RETURN_VALUE_REGISTER_CONVENTION;
5310     }
5311 }
5312
5313 /* Which registers to use for passing floating-point values between
5314    function calls, one of floating-point, general and both kinds of
5315    registers.  O32 and O64 use different register kinds for standard
5316    MIPS and MIPS16 code; to make the handling of cases where we may
5317    not know what kind of code is being used (e.g. no debug information)
5318    easier we sometimes use both kinds.  */
5319
5320 enum mips_fval_reg
5321 {
5322   mips_fval_fpr,
5323   mips_fval_gpr,
5324   mips_fval_both
5325 };
5326
5327 /* O32 ABI stuff.  */
5328
5329 static CORE_ADDR
5330 mips_o32_push_dummy_call (struct gdbarch *gdbarch, struct value *function,
5331                           struct regcache *regcache, CORE_ADDR bp_addr,
5332                           int nargs, struct value **args, CORE_ADDR sp,
5333                           int struct_return, CORE_ADDR struct_addr)
5334 {
5335   int argreg;
5336   int float_argreg;
5337   int argnum;
5338   int len = 0;
5339   int stack_offset = 0;
5340   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
5341   CORE_ADDR func_addr = find_function_addr (function, NULL);
5342
5343   /* For shared libraries, "t9" needs to point at the function
5344      address.  */
5345   regcache_cooked_write_signed (regcache, MIPS_T9_REGNUM, func_addr);
5346
5347   /* Set the return address register to point to the entry point of
5348      the program, where a breakpoint lies in wait.  */
5349   regcache_cooked_write_signed (regcache, MIPS_RA_REGNUM, bp_addr);
5350
5351   /* First ensure that the stack and structure return address (if any)
5352      are properly aligned.  The stack has to be at least 64-bit
5353      aligned even on 32-bit machines, because doubles must be 64-bit
5354      aligned.  For n32 and n64, stack frames need to be 128-bit
5355      aligned, so we round to this widest known alignment.  */
5356
5357   sp = align_down (sp, 16);
5358   struct_addr = align_down (struct_addr, 16);
5359
5360   /* Now make space on the stack for the args.  */
5361   for (argnum = 0; argnum < nargs; argnum++)
5362     {
5363       struct type *arg_type = check_typedef (value_type (args[argnum]));
5364
5365       /* Align to double-word if necessary.  */
5366       if (mips_type_needs_double_align (arg_type))
5367         len = align_up (len, MIPS32_REGSIZE * 2);
5368       /* Allocate space on the stack.  */
5369       len += align_up (TYPE_LENGTH (arg_type), MIPS32_REGSIZE);
5370     }
5371   sp -= align_up (len, 16);
5372
5373   if (mips_debug)
5374     fprintf_unfiltered (gdb_stdlog,
5375                         "mips_o32_push_dummy_call: sp=%s allocated %ld\n",
5376                         paddress (gdbarch, sp), (long) align_up (len, 16));
5377
5378   /* Initialize the integer and float register pointers.  */
5379   argreg = MIPS_A0_REGNUM;
5380   float_argreg = mips_fpa0_regnum (gdbarch);
5381
5382   /* The struct_return pointer occupies the first parameter-passing reg.  */
5383   if (struct_return)
5384     {
5385       if (mips_debug)
5386         fprintf_unfiltered (gdb_stdlog,
5387                             "mips_o32_push_dummy_call: "
5388                             "struct_return reg=%d %s\n",
5389                             argreg, paddress (gdbarch, struct_addr));
5390       regcache_cooked_write_unsigned (regcache, argreg++, struct_addr);
5391       stack_offset += MIPS32_REGSIZE;
5392     }
5393
5394   /* Now load as many as possible of the first arguments into
5395      registers, and push the rest onto the stack.  Loop thru args
5396      from first to last.  */
5397   for (argnum = 0; argnum < nargs; argnum++)
5398     {
5399       const gdb_byte *val;
5400       struct value *arg = args[argnum];
5401       struct type *arg_type = check_typedef (value_type (arg));
5402       int len = TYPE_LENGTH (arg_type);
5403       enum type_code typecode = TYPE_CODE (arg_type);
5404
5405       if (mips_debug)
5406         fprintf_unfiltered (gdb_stdlog,
5407                             "mips_o32_push_dummy_call: %d len=%d type=%d",
5408                             argnum + 1, len, (int) typecode);
5409
5410       val = value_contents (arg);
5411
5412       /* 32-bit ABIs always start floating point arguments in an
5413          even-numbered floating point register.  Round the FP register
5414          up before the check to see if there are any FP registers
5415          left.  O32 targets also pass the FP in the integer registers
5416          so also round up normal registers.  */
5417       if (fp_register_arg_p (gdbarch, typecode, arg_type))
5418         {
5419           if ((float_argreg & 1))
5420             float_argreg++;
5421         }
5422
5423       /* Floating point arguments passed in registers have to be
5424          treated specially.  On 32-bit architectures, doubles are
5425          passed in register pairs; the even FP register gets the
5426          low word, and the odd FP register gets the high word.
5427          On O32, the first two floating point arguments are also
5428          copied to general registers, following their memory order,
5429          because MIPS16 functions don't use float registers for
5430          arguments.  This duplication of arguments in general
5431          registers can't hurt non-MIPS16 functions, because those
5432          registers are normally skipped.  */
5433
5434       if (fp_register_arg_p (gdbarch, typecode, arg_type)
5435           && float_argreg <= MIPS_LAST_FP_ARG_REGNUM (gdbarch))
5436         {
5437           if (register_size (gdbarch, float_argreg) < 8 && len == 8)
5438             {
5439               int freg_offset = gdbarch_byte_order (gdbarch)
5440                                 == BFD_ENDIAN_BIG ? 1 : 0;
5441               unsigned long regval;
5442
5443               /* First word.  */
5444               regval = extract_unsigned_integer (val, 4, byte_order);
5445               if (mips_debug)
5446                 fprintf_unfiltered (gdb_stdlog, " - fpreg=%d val=%s",
5447                                     float_argreg + freg_offset,
5448                                     phex (regval, 4));
5449               regcache_cooked_write_unsigned (regcache,
5450                                               float_argreg++ + freg_offset,
5451                                               regval);
5452               if (mips_debug)
5453                 fprintf_unfiltered (gdb_stdlog, " - reg=%d val=%s",
5454                                     argreg, phex (regval, 4));
5455               regcache_cooked_write_unsigned (regcache, argreg++, regval);
5456
5457               /* Second word.  */
5458               regval = extract_unsigned_integer (val + 4, 4, byte_order);
5459               if (mips_debug)
5460                 fprintf_unfiltered (gdb_stdlog, " - fpreg=%d val=%s",
5461                                     float_argreg - freg_offset,
5462                                     phex (regval, 4));
5463               regcache_cooked_write_unsigned (regcache,
5464                                               float_argreg++ - freg_offset,
5465                                               regval);
5466               if (mips_debug)
5467                 fprintf_unfiltered (gdb_stdlog, " - reg=%d val=%s",
5468                                     argreg, phex (regval, 4));
5469               regcache_cooked_write_unsigned (regcache, argreg++, regval);
5470             }
5471           else
5472             {
5473               /* This is a floating point value that fits entirely
5474                  in a single register.  */
5475               /* On 32 bit ABI's the float_argreg is further adjusted
5476                  above to ensure that it is even register aligned.  */
5477               LONGEST regval = extract_unsigned_integer (val, len, byte_order);
5478               if (mips_debug)
5479                 fprintf_unfiltered (gdb_stdlog, " - fpreg=%d val=%s",
5480                                     float_argreg, phex (regval, len));
5481               regcache_cooked_write_unsigned (regcache,
5482                                               float_argreg++, regval);
5483               /* Although two FP registers are reserved for each
5484                  argument, only one corresponding integer register is
5485                  reserved.  */
5486               if (mips_debug)
5487                 fprintf_unfiltered (gdb_stdlog, " - reg=%d val=%s",
5488                                     argreg, phex (regval, len));
5489               regcache_cooked_write_unsigned (regcache, argreg++, regval);
5490             }
5491           /* Reserve space for the FP register.  */
5492           stack_offset += align_up (len, MIPS32_REGSIZE);
5493         }
5494       else
5495         {
5496           /* Copy the argument to general registers or the stack in
5497              register-sized pieces.  Large arguments are split between
5498              registers and stack.  */
5499           /* Note: structs whose size is not a multiple of MIPS32_REGSIZE
5500              are treated specially: Irix cc passes
5501              them in registers where gcc sometimes puts them on the
5502              stack.  For maximum compatibility, we will put them in
5503              both places.  */
5504           int odd_sized_struct = (len > MIPS32_REGSIZE
5505                                   && len % MIPS32_REGSIZE != 0);
5506           /* Structures should be aligned to eight bytes (even arg registers)
5507              on MIPS_ABI_O32, if their first member has double precision.  */
5508           if (mips_type_needs_double_align (arg_type))
5509             {
5510               if ((argreg & 1))
5511                 {
5512                   argreg++;
5513                   stack_offset += MIPS32_REGSIZE;
5514                 }
5515             }
5516           while (len > 0)
5517             {
5518               /* Remember if the argument was written to the stack.  */
5519               int stack_used_p = 0;
5520               int partial_len = (len < MIPS32_REGSIZE ? len : MIPS32_REGSIZE);
5521
5522               if (mips_debug)
5523                 fprintf_unfiltered (gdb_stdlog, " -- partial=%d",
5524                                     partial_len);
5525
5526               /* Write this portion of the argument to the stack.  */
5527               if (argreg > MIPS_LAST_ARG_REGNUM (gdbarch)
5528                   || odd_sized_struct)
5529                 {
5530                   /* Should shorter than int integer values be
5531                      promoted to int before being stored?  */
5532                   int longword_offset = 0;
5533                   CORE_ADDR addr;
5534                   stack_used_p = 1;
5535
5536                   if (mips_debug)
5537                     {
5538                       fprintf_unfiltered (gdb_stdlog, " - stack_offset=%s",
5539                                           paddress (gdbarch, stack_offset));
5540                       fprintf_unfiltered (gdb_stdlog, " longword_offset=%s",
5541                                           paddress (gdbarch, longword_offset));
5542                     }
5543
5544                   addr = sp + stack_offset + longword_offset;
5545
5546                   if (mips_debug)
5547                     {
5548                       int i;
5549                       fprintf_unfiltered (gdb_stdlog, " @%s ",
5550                                           paddress (gdbarch, addr));
5551                       for (i = 0; i < partial_len; i++)
5552                         {
5553                           fprintf_unfiltered (gdb_stdlog, "%02x",
5554                                               val[i] & 0xff);
5555                         }
5556                     }
5557                   write_memory (addr, val, partial_len);
5558                 }
5559
5560               /* Note!!! This is NOT an else clause.  Odd sized
5561                  structs may go thru BOTH paths.  */
5562               /* Write this portion of the argument to a general
5563                  purpose register.  */
5564               if (argreg <= MIPS_LAST_ARG_REGNUM (gdbarch))
5565                 {
5566                   LONGEST regval = extract_signed_integer (val, partial_len,
5567                                                            byte_order);
5568                   /* Value may need to be sign extended, because
5569                      mips_isa_regsize() != mips_abi_regsize().  */
5570
5571                   /* A non-floating-point argument being passed in a
5572                      general register.  If a struct or union, and if
5573                      the remaining length is smaller than the register
5574                      size, we have to adjust the register value on
5575                      big endian targets.
5576
5577                      It does not seem to be necessary to do the
5578                      same for integral types.
5579
5580                      Also don't do this adjustment on O64 binaries.
5581
5582                      cagney/2001-07-23: gdb/179: Also, GCC, when
5583                      outputting LE O32 with sizeof (struct) <
5584                      mips_abi_regsize(), generates a left shift
5585                      as part of storing the argument in a register
5586                      (the left shift isn't generated when
5587                      sizeof (struct) >= mips_abi_regsize()).  Since
5588                      it is quite possible that this is GCC
5589                      contradicting the LE/O32 ABI, GDB has not been
5590                      adjusted to accommodate this.  Either someone
5591                      needs to demonstrate that the LE/O32 ABI
5592                      specifies such a left shift OR this new ABI gets
5593                      identified as such and GDB gets tweaked
5594                      accordingly.  */
5595
5596                   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG
5597                       && partial_len < MIPS32_REGSIZE
5598                       && (typecode == TYPE_CODE_STRUCT
5599                           || typecode == TYPE_CODE_UNION))
5600                     regval <<= ((MIPS32_REGSIZE - partial_len)
5601                                 * TARGET_CHAR_BIT);
5602
5603                   if (mips_debug)
5604                     fprintf_filtered (gdb_stdlog, " - reg=%d val=%s",
5605                                       argreg,
5606                                       phex (regval, MIPS32_REGSIZE));
5607                   regcache_cooked_write_unsigned (regcache, argreg, regval);
5608                   argreg++;
5609
5610                   /* Prevent subsequent floating point arguments from
5611                      being passed in floating point registers.  */
5612                   float_argreg = MIPS_LAST_FP_ARG_REGNUM (gdbarch) + 1;
5613                 }
5614
5615               len -= partial_len;
5616               val += partial_len;
5617
5618               /* Compute the offset into the stack at which we will
5619                  copy the next parameter.
5620
5621                  In older ABIs, the caller reserved space for
5622                  registers that contained arguments.  This was loosely
5623                  refered to as their "home".  Consequently, space is
5624                  always allocated.  */
5625
5626               stack_offset += align_up (partial_len, MIPS32_REGSIZE);
5627             }
5628         }
5629       if (mips_debug)
5630         fprintf_unfiltered (gdb_stdlog, "\n");
5631     }
5632
5633   regcache_cooked_write_signed (regcache, MIPS_SP_REGNUM, sp);
5634
5635   /* Return adjusted stack pointer.  */
5636   return sp;
5637 }
5638
5639 static enum return_value_convention
5640 mips_o32_return_value (struct gdbarch *gdbarch, struct value *function,
5641                        struct type *type, struct regcache *regcache,
5642                        gdb_byte *readbuf, const gdb_byte *writebuf)
5643 {
5644   CORE_ADDR func_addr = function ? find_function_addr (function, NULL) : 0;
5645   int mips16 = mips_pc_is_mips16 (gdbarch, func_addr);
5646   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
5647   enum mips_fval_reg fval_reg;
5648
5649   fval_reg = readbuf ? mips16 ? mips_fval_gpr : mips_fval_fpr : mips_fval_both;
5650   if (TYPE_CODE (type) == TYPE_CODE_STRUCT
5651       || TYPE_CODE (type) == TYPE_CODE_UNION
5652       || TYPE_CODE (type) == TYPE_CODE_ARRAY)
5653     return RETURN_VALUE_STRUCT_CONVENTION;
5654   else if (TYPE_CODE (type) == TYPE_CODE_FLT
5655            && TYPE_LENGTH (type) == 4 && tdep->mips_fpu_type != MIPS_FPU_NONE)
5656     {
5657       /* A single-precision floating-point value.  If reading in or copying,
5658          then we get it from/put it to FP0 for standard MIPS code or GPR2
5659          for MIPS16 code.  If writing out only, then we put it to both FP0
5660          and GPR2.  We do not support reading in with no function known, if
5661          this safety check ever triggers, then we'll have to try harder.  */
5662       gdb_assert (function || !readbuf);
5663       if (mips_debug)
5664         switch (fval_reg)
5665           {
5666           case mips_fval_fpr:
5667             fprintf_unfiltered (gdb_stderr, "Return float in $fp0\n");
5668             break;
5669           case mips_fval_gpr:
5670             fprintf_unfiltered (gdb_stderr, "Return float in $2\n");
5671             break;
5672           case mips_fval_both:
5673             fprintf_unfiltered (gdb_stderr, "Return float in $fp0 and $2\n");
5674             break;
5675           }
5676       if (fval_reg != mips_fval_gpr)
5677         mips_xfer_register (gdbarch, regcache,
5678                             (gdbarch_num_regs (gdbarch)
5679                              + mips_regnum (gdbarch)->fp0),
5680                             TYPE_LENGTH (type),
5681                             gdbarch_byte_order (gdbarch),
5682                             readbuf, writebuf, 0);
5683       if (fval_reg != mips_fval_fpr)
5684         mips_xfer_register (gdbarch, regcache,
5685                             gdbarch_num_regs (gdbarch) + 2,
5686                             TYPE_LENGTH (type),
5687                             gdbarch_byte_order (gdbarch),
5688                             readbuf, writebuf, 0);
5689       return RETURN_VALUE_REGISTER_CONVENTION;
5690     }
5691   else if (TYPE_CODE (type) == TYPE_CODE_FLT
5692            && TYPE_LENGTH (type) == 8 && tdep->mips_fpu_type != MIPS_FPU_NONE)
5693     {
5694       /* A double-precision floating-point value.  If reading in or copying,
5695          then we get it from/put it to FP1 and FP0 for standard MIPS code or
5696          GPR2 and GPR3 for MIPS16 code.  If writing out only, then we put it
5697          to both FP1/FP0 and GPR2/GPR3.  We do not support reading in with
5698          no function known, if this safety check ever triggers, then we'll
5699          have to try harder.  */
5700       gdb_assert (function || !readbuf);
5701       if (mips_debug)
5702         switch (fval_reg)
5703           {
5704           case mips_fval_fpr:
5705             fprintf_unfiltered (gdb_stderr, "Return float in $fp1/$fp0\n");
5706             break;
5707           case mips_fval_gpr:
5708             fprintf_unfiltered (gdb_stderr, "Return float in $2/$3\n");
5709             break;
5710           case mips_fval_both:
5711             fprintf_unfiltered (gdb_stderr,
5712                                 "Return float in $fp1/$fp0 and $2/$3\n");
5713             break;
5714           }
5715       if (fval_reg != mips_fval_gpr)
5716         {
5717           /* The most significant part goes in FP1, and the least significant
5718              in FP0.  */
5719           switch (gdbarch_byte_order (gdbarch))
5720             {
5721             case BFD_ENDIAN_LITTLE:
5722               mips_xfer_register (gdbarch, regcache,
5723                                   (gdbarch_num_regs (gdbarch)
5724                                    + mips_regnum (gdbarch)->fp0 + 0),
5725                                   4, gdbarch_byte_order (gdbarch),
5726                                   readbuf, writebuf, 0);
5727               mips_xfer_register (gdbarch, regcache,
5728                                   (gdbarch_num_regs (gdbarch)
5729                                    + mips_regnum (gdbarch)->fp0 + 1),
5730                                   4, gdbarch_byte_order (gdbarch),
5731                                   readbuf, writebuf, 4);
5732               break;
5733             case BFD_ENDIAN_BIG:
5734               mips_xfer_register (gdbarch, regcache,
5735                                   (gdbarch_num_regs (gdbarch)
5736                                    + mips_regnum (gdbarch)->fp0 + 1),
5737                                   4, gdbarch_byte_order (gdbarch),
5738                                   readbuf, writebuf, 0);
5739               mips_xfer_register (gdbarch, regcache,
5740                                   (gdbarch_num_regs (gdbarch)
5741                                    + mips_regnum (gdbarch)->fp0 + 0),
5742                                   4, gdbarch_byte_order (gdbarch),
5743                                   readbuf, writebuf, 4);
5744               break;
5745             default:
5746               internal_error (__FILE__, __LINE__, _("bad switch"));
5747             }
5748         }
5749       if (fval_reg != mips_fval_fpr)
5750         {
5751           /* The two 32-bit parts are always placed in GPR2 and GPR3
5752              following these registers' memory order.  */
5753           mips_xfer_register (gdbarch, regcache,
5754                               gdbarch_num_regs (gdbarch) + 2,
5755                               4, gdbarch_byte_order (gdbarch),
5756                               readbuf, writebuf, 0);
5757           mips_xfer_register (gdbarch, regcache,
5758                               gdbarch_num_regs (gdbarch) + 3,
5759                               4, gdbarch_byte_order (gdbarch),
5760                               readbuf, writebuf, 4);
5761         }
5762       return RETURN_VALUE_REGISTER_CONVENTION;
5763     }
5764 #if 0
5765   else if (TYPE_CODE (type) == TYPE_CODE_STRUCT
5766            && TYPE_NFIELDS (type) <= 2
5767            && TYPE_NFIELDS (type) >= 1
5768            && ((TYPE_NFIELDS (type) == 1
5769                 && (TYPE_CODE (TYPE_FIELD_TYPE (type, 0))
5770                     == TYPE_CODE_FLT))
5771                || (TYPE_NFIELDS (type) == 2
5772                    && (TYPE_CODE (TYPE_FIELD_TYPE (type, 0))
5773                        == TYPE_CODE_FLT)
5774                    && (TYPE_CODE (TYPE_FIELD_TYPE (type, 1))
5775                        == TYPE_CODE_FLT)))
5776            && tdep->mips_fpu_type != MIPS_FPU_NONE)
5777     {
5778       /* A struct that contains one or two floats.  Each value is part
5779          in the least significant part of their floating point
5780          register..  */
5781       gdb_byte reg[MAX_REGISTER_SIZE];
5782       int regnum;
5783       int field;
5784       for (field = 0, regnum = mips_regnum (gdbarch)->fp0;
5785            field < TYPE_NFIELDS (type); field++, regnum += 2)
5786         {
5787           int offset = (FIELD_BITPOS (TYPE_FIELDS (type)[field])
5788                         / TARGET_CHAR_BIT);
5789           if (mips_debug)
5790             fprintf_unfiltered (gdb_stderr, "Return float struct+%d\n",
5791                                 offset);
5792           mips_xfer_register (gdbarch, regcache,
5793                               gdbarch_num_regs (gdbarch) + regnum,
5794                               TYPE_LENGTH (TYPE_FIELD_TYPE (type, field)),
5795                               gdbarch_byte_order (gdbarch),
5796                               readbuf, writebuf, offset);
5797         }
5798       return RETURN_VALUE_REGISTER_CONVENTION;
5799     }
5800 #endif
5801 #if 0
5802   else if (TYPE_CODE (type) == TYPE_CODE_STRUCT
5803            || TYPE_CODE (type) == TYPE_CODE_UNION)
5804     {
5805       /* A structure or union.  Extract the left justified value,
5806          regardless of the byte order.  I.e. DO NOT USE
5807          mips_xfer_lower.  */
5808       int offset;
5809       int regnum;
5810       for (offset = 0, regnum = MIPS_V0_REGNUM;
5811            offset < TYPE_LENGTH (type);
5812            offset += register_size (gdbarch, regnum), regnum++)
5813         {
5814           int xfer = register_size (gdbarch, regnum);
5815           if (offset + xfer > TYPE_LENGTH (type))
5816             xfer = TYPE_LENGTH (type) - offset;
5817           if (mips_debug)
5818             fprintf_unfiltered (gdb_stderr, "Return struct+%d:%d in $%d\n",
5819                                 offset, xfer, regnum);
5820           mips_xfer_register (gdbarch, regcache,
5821                               gdbarch_num_regs (gdbarch) + regnum, xfer,
5822                               BFD_ENDIAN_UNKNOWN, readbuf, writebuf, offset);
5823         }
5824       return RETURN_VALUE_REGISTER_CONVENTION;
5825     }
5826 #endif
5827   else
5828     {
5829       /* A scalar extract each part but least-significant-byte
5830          justified.  o32 thinks registers are 4 byte, regardless of
5831          the ISA.  */
5832       int offset;
5833       int regnum;
5834       for (offset = 0, regnum = MIPS_V0_REGNUM;
5835            offset < TYPE_LENGTH (type);
5836            offset += MIPS32_REGSIZE, regnum++)
5837         {
5838           int xfer = MIPS32_REGSIZE;
5839           if (offset + xfer > TYPE_LENGTH (type))
5840             xfer = TYPE_LENGTH (type) - offset;
5841           if (mips_debug)
5842             fprintf_unfiltered (gdb_stderr, "Return scalar+%d:%d in $%d\n",
5843                                 offset, xfer, regnum);
5844           mips_xfer_register (gdbarch, regcache,
5845                               gdbarch_num_regs (gdbarch) + regnum, xfer,
5846                               gdbarch_byte_order (gdbarch),
5847                               readbuf, writebuf, offset);
5848         }
5849       return RETURN_VALUE_REGISTER_CONVENTION;
5850     }
5851 }
5852
5853 /* O64 ABI.  This is a hacked up kind of 64-bit version of the o32
5854    ABI.  */
5855
5856 static CORE_ADDR
5857 mips_o64_push_dummy_call (struct gdbarch *gdbarch, struct value *function,
5858                           struct regcache *regcache, CORE_ADDR bp_addr,
5859                           int nargs,
5860                           struct value **args, CORE_ADDR sp,
5861                           int struct_return, CORE_ADDR struct_addr)
5862 {
5863   int argreg;
5864   int float_argreg;
5865   int argnum;
5866   int len = 0;
5867   int stack_offset = 0;
5868   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
5869   CORE_ADDR func_addr = find_function_addr (function, NULL);
5870
5871   /* For shared libraries, "t9" needs to point at the function
5872      address.  */
5873   regcache_cooked_write_signed (regcache, MIPS_T9_REGNUM, func_addr);
5874
5875   /* Set the return address register to point to the entry point of
5876      the program, where a breakpoint lies in wait.  */
5877   regcache_cooked_write_signed (regcache, MIPS_RA_REGNUM, bp_addr);
5878
5879   /* First ensure that the stack and structure return address (if any)
5880      are properly aligned.  The stack has to be at least 64-bit
5881      aligned even on 32-bit machines, because doubles must be 64-bit
5882      aligned.  For n32 and n64, stack frames need to be 128-bit
5883      aligned, so we round to this widest known alignment.  */
5884
5885   sp = align_down (sp, 16);
5886   struct_addr = align_down (struct_addr, 16);
5887
5888   /* Now make space on the stack for the args.  */
5889   for (argnum = 0; argnum < nargs; argnum++)
5890     {
5891       struct type *arg_type = check_typedef (value_type (args[argnum]));
5892
5893       /* Allocate space on the stack.  */
5894       len += align_up (TYPE_LENGTH (arg_type), MIPS64_REGSIZE);
5895     }
5896   sp -= align_up (len, 16);
5897
5898   if (mips_debug)
5899     fprintf_unfiltered (gdb_stdlog,
5900                         "mips_o64_push_dummy_call: sp=%s allocated %ld\n",
5901                         paddress (gdbarch, sp), (long) align_up (len, 16));
5902
5903   /* Initialize the integer and float register pointers.  */
5904   argreg = MIPS_A0_REGNUM;
5905   float_argreg = mips_fpa0_regnum (gdbarch);
5906
5907   /* The struct_return pointer occupies the first parameter-passing reg.  */
5908   if (struct_return)
5909     {
5910       if (mips_debug)
5911         fprintf_unfiltered (gdb_stdlog,
5912                             "mips_o64_push_dummy_call: "
5913                             "struct_return reg=%d %s\n",
5914                             argreg, paddress (gdbarch, struct_addr));
5915       regcache_cooked_write_unsigned (regcache, argreg++, struct_addr);
5916       stack_offset += MIPS64_REGSIZE;
5917     }
5918
5919   /* Now load as many as possible of the first arguments into
5920      registers, and push the rest onto the stack.  Loop thru args
5921      from first to last.  */
5922   for (argnum = 0; argnum < nargs; argnum++)
5923     {
5924       const gdb_byte *val;
5925       struct value *arg = args[argnum];
5926       struct type *arg_type = check_typedef (value_type (arg));
5927       int len = TYPE_LENGTH (arg_type);
5928       enum type_code typecode = TYPE_CODE (arg_type);
5929
5930       if (mips_debug)
5931         fprintf_unfiltered (gdb_stdlog,
5932                             "mips_o64_push_dummy_call: %d len=%d type=%d",
5933                             argnum + 1, len, (int) typecode);
5934
5935       val = value_contents (arg);
5936
5937       /* Floating point arguments passed in registers have to be
5938          treated specially.  On 32-bit architectures, doubles are
5939          passed in register pairs; the even FP register gets the
5940          low word, and the odd FP register gets the high word.
5941          On O64, the first two floating point arguments are also
5942          copied to general registers, because MIPS16 functions
5943          don't use float registers for arguments.  This duplication
5944          of arguments in general registers can't hurt non-MIPS16
5945          functions because those registers are normally skipped.  */
5946
5947       if (fp_register_arg_p (gdbarch, typecode, arg_type)
5948           && float_argreg <= MIPS_LAST_FP_ARG_REGNUM (gdbarch))
5949         {
5950           LONGEST regval = extract_unsigned_integer (val, len, byte_order);
5951           if (mips_debug)
5952             fprintf_unfiltered (gdb_stdlog, " - fpreg=%d val=%s",
5953                                 float_argreg, phex (regval, len));
5954           regcache_cooked_write_unsigned (regcache, float_argreg++, regval);
5955           if (mips_debug)
5956             fprintf_unfiltered (gdb_stdlog, " - reg=%d val=%s",
5957                                 argreg, phex (regval, len));
5958           regcache_cooked_write_unsigned (regcache, argreg, regval);
5959           argreg++;
5960           /* Reserve space for the FP register.  */
5961           stack_offset += align_up (len, MIPS64_REGSIZE);
5962         }
5963       else
5964         {
5965           /* Copy the argument to general registers or the stack in
5966              register-sized pieces.  Large arguments are split between
5967              registers and stack.  */
5968           /* Note: structs whose size is not a multiple of MIPS64_REGSIZE
5969              are treated specially: Irix cc passes them in registers
5970              where gcc sometimes puts them on the stack.  For maximum
5971              compatibility, we will put them in both places.  */
5972           int odd_sized_struct = (len > MIPS64_REGSIZE
5973                                   && len % MIPS64_REGSIZE != 0);
5974           while (len > 0)
5975             {
5976               /* Remember if the argument was written to the stack.  */
5977               int stack_used_p = 0;
5978               int partial_len = (len < MIPS64_REGSIZE ? len : MIPS64_REGSIZE);
5979
5980               if (mips_debug)
5981                 fprintf_unfiltered (gdb_stdlog, " -- partial=%d",
5982                                     partial_len);
5983
5984               /* Write this portion of the argument to the stack.  */
5985               if (argreg > MIPS_LAST_ARG_REGNUM (gdbarch)
5986                   || odd_sized_struct)
5987                 {
5988                   /* Should shorter than int integer values be
5989                      promoted to int before being stored?  */
5990                   int longword_offset = 0;
5991                   CORE_ADDR addr;
5992                   stack_used_p = 1;
5993                   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
5994                     {
5995                       if ((typecode == TYPE_CODE_INT
5996                            || typecode == TYPE_CODE_PTR
5997                            || typecode == TYPE_CODE_FLT)
5998                           && len <= 4)
5999                         longword_offset = MIPS64_REGSIZE - len;
6000                     }
6001
6002                   if (mips_debug)
6003                     {
6004                       fprintf_unfiltered (gdb_stdlog, " - stack_offset=%s",
6005                                           paddress (gdbarch, stack_offset));
6006                       fprintf_unfiltered (gdb_stdlog, " longword_offset=%s",
6007                                           paddress (gdbarch, longword_offset));
6008                     }
6009
6010                   addr = sp + stack_offset + longword_offset;
6011
6012                   if (mips_debug)
6013                     {
6014                       int i;
6015                       fprintf_unfiltered (gdb_stdlog, " @%s ",
6016                                           paddress (gdbarch, addr));
6017                       for (i = 0; i < partial_len; i++)
6018                         {
6019                           fprintf_unfiltered (gdb_stdlog, "%02x",
6020                                               val[i] & 0xff);
6021                         }
6022                     }
6023                   write_memory (addr, val, partial_len);
6024                 }
6025
6026               /* Note!!! This is NOT an else clause.  Odd sized
6027                  structs may go thru BOTH paths.  */
6028               /* Write this portion of the argument to a general
6029                  purpose register.  */
6030               if (argreg <= MIPS_LAST_ARG_REGNUM (gdbarch))
6031                 {
6032                   LONGEST regval = extract_signed_integer (val, partial_len,
6033                                                            byte_order);
6034                   /* Value may need to be sign extended, because
6035                      mips_isa_regsize() != mips_abi_regsize().  */
6036
6037                   /* A non-floating-point argument being passed in a
6038                      general register.  If a struct or union, and if
6039                      the remaining length is smaller than the register
6040                      size, we have to adjust the register value on
6041                      big endian targets.
6042
6043                      It does not seem to be necessary to do the
6044                      same for integral types.  */
6045
6046                   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG
6047                       && partial_len < MIPS64_REGSIZE
6048                       && (typecode == TYPE_CODE_STRUCT
6049                           || typecode == TYPE_CODE_UNION))
6050                     regval <<= ((MIPS64_REGSIZE - partial_len)
6051                                 * TARGET_CHAR_BIT);
6052
6053                   if (mips_debug)
6054                     fprintf_filtered (gdb_stdlog, " - reg=%d val=%s",
6055                                       argreg,
6056                                       phex (regval, MIPS64_REGSIZE));
6057                   regcache_cooked_write_unsigned (regcache, argreg, regval);
6058                   argreg++;
6059
6060                   /* Prevent subsequent floating point arguments from
6061                      being passed in floating point registers.  */
6062                   float_argreg = MIPS_LAST_FP_ARG_REGNUM (gdbarch) + 1;
6063                 }
6064
6065               len -= partial_len;
6066               val += partial_len;
6067
6068               /* Compute the offset into the stack at which we will
6069                  copy the next parameter.
6070
6071                  In older ABIs, the caller reserved space for
6072                  registers that contained arguments.  This was loosely
6073                  refered to as their "home".  Consequently, space is
6074                  always allocated.  */
6075
6076               stack_offset += align_up (partial_len, MIPS64_REGSIZE);
6077             }
6078         }
6079       if (mips_debug)
6080         fprintf_unfiltered (gdb_stdlog, "\n");
6081     }
6082
6083   regcache_cooked_write_signed (regcache, MIPS_SP_REGNUM, sp);
6084
6085   /* Return adjusted stack pointer.  */
6086   return sp;
6087 }
6088
6089 static enum return_value_convention
6090 mips_o64_return_value (struct gdbarch *gdbarch, struct value *function,
6091                        struct type *type, struct regcache *regcache,
6092                        gdb_byte *readbuf, const gdb_byte *writebuf)
6093 {
6094   CORE_ADDR func_addr = function ? find_function_addr (function, NULL) : 0;
6095   int mips16 = mips_pc_is_mips16 (gdbarch, func_addr);
6096   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
6097   enum mips_fval_reg fval_reg;
6098
6099   fval_reg = readbuf ? mips16 ? mips_fval_gpr : mips_fval_fpr : mips_fval_both;
6100   if (TYPE_CODE (type) == TYPE_CODE_STRUCT
6101       || TYPE_CODE (type) == TYPE_CODE_UNION
6102       || TYPE_CODE (type) == TYPE_CODE_ARRAY)
6103     return RETURN_VALUE_STRUCT_CONVENTION;
6104   else if (fp_register_arg_p (gdbarch, TYPE_CODE (type), type))
6105     {
6106       /* A floating-point value.  If reading in or copying, then we get it
6107          from/put it to FP0 for standard MIPS code or GPR2 for MIPS16 code.
6108          If writing out only, then we put it to both FP0 and GPR2.  We do
6109          not support reading in with no function known, if this safety
6110          check ever triggers, then we'll have to try harder.  */
6111       gdb_assert (function || !readbuf);
6112       if (mips_debug)
6113         switch (fval_reg)
6114           {
6115           case mips_fval_fpr:
6116             fprintf_unfiltered (gdb_stderr, "Return float in $fp0\n");
6117             break;
6118           case mips_fval_gpr:
6119             fprintf_unfiltered (gdb_stderr, "Return float in $2\n");
6120             break;
6121           case mips_fval_both:
6122             fprintf_unfiltered (gdb_stderr, "Return float in $fp0 and $2\n");
6123             break;
6124           }
6125       if (fval_reg != mips_fval_gpr)
6126         mips_xfer_register (gdbarch, regcache,
6127                             (gdbarch_num_regs (gdbarch)
6128                              + mips_regnum (gdbarch)->fp0),
6129                             TYPE_LENGTH (type),
6130                             gdbarch_byte_order (gdbarch),
6131                             readbuf, writebuf, 0);
6132       if (fval_reg != mips_fval_fpr)
6133         mips_xfer_register (gdbarch, regcache,
6134                             gdbarch_num_regs (gdbarch) + 2,
6135                             TYPE_LENGTH (type),
6136                             gdbarch_byte_order (gdbarch),
6137                             readbuf, writebuf, 0);
6138       return RETURN_VALUE_REGISTER_CONVENTION;
6139     }
6140   else
6141     {
6142       /* A scalar extract each part but least-significant-byte
6143          justified.  */
6144       int offset;
6145       int regnum;
6146       for (offset = 0, regnum = MIPS_V0_REGNUM;
6147            offset < TYPE_LENGTH (type);
6148            offset += MIPS64_REGSIZE, regnum++)
6149         {
6150           int xfer = MIPS64_REGSIZE;
6151           if (offset + xfer > TYPE_LENGTH (type))
6152             xfer = TYPE_LENGTH (type) - offset;
6153           if (mips_debug)
6154             fprintf_unfiltered (gdb_stderr, "Return scalar+%d:%d in $%d\n",
6155                                 offset, xfer, regnum);
6156           mips_xfer_register (gdbarch, regcache,
6157                               gdbarch_num_regs (gdbarch) + regnum,
6158                               xfer, gdbarch_byte_order (gdbarch),
6159                               readbuf, writebuf, offset);
6160         }
6161       return RETURN_VALUE_REGISTER_CONVENTION;
6162     }
6163 }
6164
6165 /* Floating point register management.
6166
6167    Background: MIPS1 & 2 fp registers are 32 bits wide.  To support
6168    64bit operations, these early MIPS cpus treat fp register pairs
6169    (f0,f1) as a single register (d0).  Later MIPS cpu's have 64 bit fp
6170    registers and offer a compatibility mode that emulates the MIPS2 fp
6171    model.  When operating in MIPS2 fp compat mode, later cpu's split
6172    double precision floats into two 32-bit chunks and store them in
6173    consecutive fp regs.  To display 64-bit floats stored in this
6174    fashion, we have to combine 32 bits from f0 and 32 bits from f1.
6175    Throw in user-configurable endianness and you have a real mess.
6176
6177    The way this works is:
6178      - If we are in 32-bit mode or on a 32-bit processor, then a 64-bit
6179        double-precision value will be split across two logical registers.
6180        The lower-numbered logical register will hold the low-order bits,
6181        regardless of the processor's endianness.
6182      - If we are on a 64-bit processor, and we are looking for a
6183        single-precision value, it will be in the low ordered bits
6184        of a 64-bit GPR (after mfc1, for example) or a 64-bit register
6185        save slot in memory.
6186      - If we are in 64-bit mode, everything is straightforward.
6187
6188    Note that this code only deals with "live" registers at the top of the
6189    stack.  We will attempt to deal with saved registers later, when
6190    the raw/cooked register interface is in place.  (We need a general
6191    interface that can deal with dynamic saved register sizes -- fp
6192    regs could be 32 bits wide in one frame and 64 on the frame above
6193    and below).  */
6194
6195 /* Copy a 32-bit single-precision value from the current frame
6196    into rare_buffer.  */
6197
6198 static void
6199 mips_read_fp_register_single (struct frame_info *frame, int regno,
6200                               gdb_byte *rare_buffer)
6201 {
6202   struct gdbarch *gdbarch = get_frame_arch (frame);
6203   int raw_size = register_size (gdbarch, regno);
6204   gdb_byte *raw_buffer = alloca (raw_size);
6205
6206   if (!deprecated_frame_register_read (frame, regno, raw_buffer))
6207     error (_("can't read register %d (%s)"),
6208            regno, gdbarch_register_name (gdbarch, regno));
6209   if (raw_size == 8)
6210     {
6211       /* We have a 64-bit value for this register.  Find the low-order
6212          32 bits.  */
6213       int offset;
6214
6215       if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
6216         offset = 4;
6217       else
6218         offset = 0;
6219
6220       memcpy (rare_buffer, raw_buffer + offset, 4);
6221     }
6222   else
6223     {
6224       memcpy (rare_buffer, raw_buffer, 4);
6225     }
6226 }
6227
6228 /* Copy a 64-bit double-precision value from the current frame into
6229    rare_buffer.  This may include getting half of it from the next
6230    register.  */
6231
6232 static void
6233 mips_read_fp_register_double (struct frame_info *frame, int regno,
6234                               gdb_byte *rare_buffer)
6235 {
6236   struct gdbarch *gdbarch = get_frame_arch (frame);
6237   int raw_size = register_size (gdbarch, regno);
6238
6239   if (raw_size == 8 && !mips2_fp_compat (frame))
6240     {
6241       /* We have a 64-bit value for this register, and we should use
6242          all 64 bits.  */
6243       if (!deprecated_frame_register_read (frame, regno, rare_buffer))
6244         error (_("can't read register %d (%s)"),
6245                regno, gdbarch_register_name (gdbarch, regno));
6246     }
6247   else
6248     {
6249       int rawnum = regno % gdbarch_num_regs (gdbarch);
6250
6251       if ((rawnum - mips_regnum (gdbarch)->fp0) & 1)
6252         internal_error (__FILE__, __LINE__,
6253                         _("mips_read_fp_register_double: bad access to "
6254                         "odd-numbered FP register"));
6255
6256       /* mips_read_fp_register_single will find the correct 32 bits from
6257          each register.  */
6258       if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
6259         {
6260           mips_read_fp_register_single (frame, regno, rare_buffer + 4);
6261           mips_read_fp_register_single (frame, regno + 1, rare_buffer);
6262         }
6263       else
6264         {
6265           mips_read_fp_register_single (frame, regno, rare_buffer);
6266           mips_read_fp_register_single (frame, regno + 1, rare_buffer + 4);
6267         }
6268     }
6269 }
6270
6271 static void
6272 mips_print_fp_register (struct ui_file *file, struct frame_info *frame,
6273                         int regnum)
6274 {                               /* Do values for FP (float) regs.  */
6275   struct gdbarch *gdbarch = get_frame_arch (frame);
6276   gdb_byte *raw_buffer;
6277   double doub, flt1;    /* Doubles extracted from raw hex data.  */
6278   int inv1, inv2;
6279
6280   raw_buffer = alloca (2 * register_size (gdbarch,
6281                                           mips_regnum (gdbarch)->fp0));
6282
6283   fprintf_filtered (file, "%s:", gdbarch_register_name (gdbarch, regnum));
6284   fprintf_filtered (file, "%*s",
6285                     4 - (int) strlen (gdbarch_register_name (gdbarch, regnum)),
6286                     "");
6287
6288   if (register_size (gdbarch, regnum) == 4 || mips2_fp_compat (frame))
6289     {
6290       struct value_print_options opts;
6291
6292       /* 4-byte registers: Print hex and floating.  Also print even
6293          numbered registers as doubles.  */
6294       mips_read_fp_register_single (frame, regnum, raw_buffer);
6295       flt1 = unpack_double (builtin_type (gdbarch)->builtin_float,
6296                             raw_buffer, &inv1);
6297
6298       get_formatted_print_options (&opts, 'x');
6299       print_scalar_formatted (raw_buffer,
6300                               builtin_type (gdbarch)->builtin_uint32,
6301                               &opts, 'w', file);
6302
6303       fprintf_filtered (file, " flt: ");
6304       if (inv1)
6305         fprintf_filtered (file, " <invalid float> ");
6306       else
6307         fprintf_filtered (file, "%-17.9g", flt1);
6308
6309       if ((regnum - gdbarch_num_regs (gdbarch)) % 2 == 0)
6310         {
6311           mips_read_fp_register_double (frame, regnum, raw_buffer);
6312           doub = unpack_double (builtin_type (gdbarch)->builtin_double,
6313                                 raw_buffer, &inv2);
6314
6315           fprintf_filtered (file, " dbl: ");
6316           if (inv2)
6317             fprintf_filtered (file, "<invalid double>");
6318           else
6319             fprintf_filtered (file, "%-24.17g", doub);
6320         }
6321     }
6322   else
6323     {
6324       struct value_print_options opts;
6325
6326       /* Eight byte registers: print each one as hex, float and double.  */
6327       mips_read_fp_register_single (frame, regnum, raw_buffer);
6328       flt1 = unpack_double (builtin_type (gdbarch)->builtin_float,
6329                             raw_buffer, &inv1);
6330
6331       mips_read_fp_register_double (frame, regnum, raw_buffer);
6332       doub = unpack_double (builtin_type (gdbarch)->builtin_double,
6333                             raw_buffer, &inv2);
6334
6335       get_formatted_print_options (&opts, 'x');
6336       print_scalar_formatted (raw_buffer,
6337                               builtin_type (gdbarch)->builtin_uint64,
6338                               &opts, 'g', file);
6339
6340       fprintf_filtered (file, " flt: ");
6341       if (inv1)
6342         fprintf_filtered (file, "<invalid float>");
6343       else
6344         fprintf_filtered (file, "%-17.9g", flt1);
6345
6346       fprintf_filtered (file, " dbl: ");
6347       if (inv2)
6348         fprintf_filtered (file, "<invalid double>");
6349       else
6350         fprintf_filtered (file, "%-24.17g", doub);
6351     }
6352 }
6353
6354 static void
6355 mips_print_register (struct ui_file *file, struct frame_info *frame,
6356                      int regnum)
6357 {
6358   struct gdbarch *gdbarch = get_frame_arch (frame);
6359   struct value_print_options opts;
6360   struct value *val;
6361
6362   if (mips_float_register_p (gdbarch, regnum))
6363     {
6364       mips_print_fp_register (file, frame, regnum);
6365       return;
6366     }
6367
6368   val = get_frame_register_value (frame, regnum);
6369
6370   fputs_filtered (gdbarch_register_name (gdbarch, regnum), file);
6371
6372   /* The problem with printing numeric register names (r26, etc.) is that
6373      the user can't use them on input.  Probably the best solution is to
6374      fix it so that either the numeric or the funky (a2, etc.) names
6375      are accepted on input.  */
6376   if (regnum < MIPS_NUMREGS)
6377     fprintf_filtered (file, "(r%d): ", regnum);
6378   else
6379     fprintf_filtered (file, ": ");
6380
6381   get_formatted_print_options (&opts, 'x');
6382   val_print_scalar_formatted (value_type (val),
6383                               value_contents_for_printing (val),
6384                               value_embedded_offset (val),
6385                               val,
6386                               &opts, 0, file);
6387 }
6388
6389 /* Replacement for generic do_registers_info.
6390    Print regs in pretty columns.  */
6391
6392 static int
6393 print_fp_register_row (struct ui_file *file, struct frame_info *frame,
6394                        int regnum)
6395 {
6396   fprintf_filtered (file, " ");
6397   mips_print_fp_register (file, frame, regnum);
6398   fprintf_filtered (file, "\n");
6399   return regnum + 1;
6400 }
6401
6402
6403 /* Print a row's worth of GP (int) registers, with name labels above.  */
6404
6405 static int
6406 print_gp_register_row (struct ui_file *file, struct frame_info *frame,
6407                        int start_regnum)
6408 {
6409   struct gdbarch *gdbarch = get_frame_arch (frame);
6410   /* Do values for GP (int) regs.  */
6411   gdb_byte raw_buffer[MAX_REGISTER_SIZE];
6412   int ncols = (mips_abi_regsize (gdbarch) == 8 ? 4 : 8);    /* display cols
6413                                                                per row.  */
6414   int col, byte;
6415   int regnum;
6416
6417   /* For GP registers, we print a separate row of names above the vals.  */
6418   for (col = 0, regnum = start_regnum;
6419        col < ncols && regnum < gdbarch_num_regs (gdbarch)
6420                                + gdbarch_num_pseudo_regs (gdbarch);
6421        regnum++)
6422     {
6423       if (*gdbarch_register_name (gdbarch, regnum) == '\0')
6424         continue;               /* unused register */
6425       if (mips_float_register_p (gdbarch, regnum))
6426         break;                  /* End the row: reached FP register.  */
6427       /* Large registers are handled separately.  */
6428       if (register_size (gdbarch, regnum) > mips_abi_regsize (gdbarch))
6429         {
6430           if (col > 0)
6431             break;              /* End the row before this register.  */
6432
6433           /* Print this register on a row by itself.  */
6434           mips_print_register (file, frame, regnum);
6435           fprintf_filtered (file, "\n");
6436           return regnum + 1;
6437         }
6438       if (col == 0)
6439         fprintf_filtered (file, "     ");
6440       fprintf_filtered (file,
6441                         mips_abi_regsize (gdbarch) == 8 ? "%17s" : "%9s",
6442                         gdbarch_register_name (gdbarch, regnum));
6443       col++;
6444     }
6445
6446   if (col == 0)
6447     return regnum;
6448
6449   /* Print the R0 to R31 names.  */
6450   if ((start_regnum % gdbarch_num_regs (gdbarch)) < MIPS_NUMREGS)
6451     fprintf_filtered (file, "\n R%-4d",
6452                       start_regnum % gdbarch_num_regs (gdbarch));
6453   else
6454     fprintf_filtered (file, "\n      ");
6455
6456   /* Now print the values in hex, 4 or 8 to the row.  */
6457   for (col = 0, regnum = start_regnum;
6458        col < ncols && regnum < gdbarch_num_regs (gdbarch)
6459                                + gdbarch_num_pseudo_regs (gdbarch);
6460        regnum++)
6461     {
6462       if (*gdbarch_register_name (gdbarch, regnum) == '\0')
6463         continue;               /* unused register */
6464       if (mips_float_register_p (gdbarch, regnum))
6465         break;                  /* End row: reached FP register.  */
6466       if (register_size (gdbarch, regnum) > mips_abi_regsize (gdbarch))
6467         break;                  /* End row: large register.  */
6468
6469       /* OK: get the data in raw format.  */
6470       if (!deprecated_frame_register_read (frame, regnum, raw_buffer))
6471         error (_("can't read register %d (%s)"),
6472                regnum, gdbarch_register_name (gdbarch, regnum));
6473       /* pad small registers */
6474       for (byte = 0;
6475            byte < (mips_abi_regsize (gdbarch)
6476                    - register_size (gdbarch, regnum)); byte++)
6477         printf_filtered ("  ");
6478       /* Now print the register value in hex, endian order.  */
6479       if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
6480         for (byte =
6481              register_size (gdbarch, regnum) - register_size (gdbarch, regnum);
6482              byte < register_size (gdbarch, regnum); byte++)
6483           fprintf_filtered (file, "%02x", raw_buffer[byte]);
6484       else
6485         for (byte = register_size (gdbarch, regnum) - 1;
6486              byte >= 0; byte--)
6487           fprintf_filtered (file, "%02x", raw_buffer[byte]);
6488       fprintf_filtered (file, " ");
6489       col++;
6490     }
6491   if (col > 0)                  /* ie. if we actually printed anything...  */
6492     fprintf_filtered (file, "\n");
6493
6494   return regnum;
6495 }
6496
6497 /* MIPS_DO_REGISTERS_INFO(): called by "info register" command.  */
6498
6499 static void
6500 mips_print_registers_info (struct gdbarch *gdbarch, struct ui_file *file,
6501                            struct frame_info *frame, int regnum, int all)
6502 {
6503   if (regnum != -1)             /* Do one specified register.  */
6504     {
6505       gdb_assert (regnum >= gdbarch_num_regs (gdbarch));
6506       if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
6507         error (_("Not a valid register for the current processor type"));
6508
6509       mips_print_register (file, frame, regnum);
6510       fprintf_filtered (file, "\n");
6511     }
6512   else
6513     /* Do all (or most) registers.  */
6514     {
6515       regnum = gdbarch_num_regs (gdbarch);
6516       while (regnum < gdbarch_num_regs (gdbarch)
6517                       + gdbarch_num_pseudo_regs (gdbarch))
6518         {
6519           if (mips_float_register_p (gdbarch, regnum))
6520             {
6521               if (all)          /* True for "INFO ALL-REGISTERS" command.  */
6522                 regnum = print_fp_register_row (file, frame, regnum);
6523               else
6524                 regnum += MIPS_NUMREGS; /* Skip floating point regs.  */
6525             }
6526           else
6527             regnum = print_gp_register_row (file, frame, regnum);
6528         }
6529     }
6530 }
6531
6532 static int
6533 mips_single_step_through_delay (struct gdbarch *gdbarch,
6534                                 struct frame_info *frame)
6535 {
6536   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
6537   CORE_ADDR pc = get_frame_pc (frame);
6538   struct address_space *aspace;
6539   enum mips_isa isa;
6540   ULONGEST insn;
6541   int status;
6542   int size;
6543
6544   if ((mips_pc_is_mips (pc)
6545        && !mips32_insn_at_pc_has_delay_slot (gdbarch, pc))
6546       || (mips_pc_is_micromips (gdbarch, pc)
6547           && !micromips_insn_at_pc_has_delay_slot (gdbarch, pc, 0))
6548       || (mips_pc_is_mips16 (gdbarch, pc)
6549           && !mips16_insn_at_pc_has_delay_slot (gdbarch, pc, 0)))
6550     return 0;
6551
6552   isa = mips_pc_isa (gdbarch, pc);
6553   /* _has_delay_slot above will have validated the read.  */
6554   insn = mips_fetch_instruction (gdbarch, isa, pc, NULL);
6555   size = mips_insn_size (isa, insn);
6556   aspace = get_frame_address_space (frame);
6557   return breakpoint_here_p (aspace, pc + size) != no_breakpoint_here;
6558 }
6559
6560 /* To skip prologues, I use this predicate.  Returns either PC itself
6561    if the code at PC does not look like a function prologue; otherwise
6562    returns an address that (if we're lucky) follows the prologue.  If
6563    LENIENT, then we must skip everything which is involved in setting
6564    up the frame (it's OK to skip more, just so long as we don't skip
6565    anything which might clobber the registers which are being saved.
6566    We must skip more in the case where part of the prologue is in the
6567    delay slot of a non-prologue instruction).  */
6568
6569 static CORE_ADDR
6570 mips_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR pc)
6571 {
6572   CORE_ADDR limit_pc;
6573   CORE_ADDR func_addr;
6574
6575   /* See if we can determine the end of the prologue via the symbol table.
6576      If so, then return either PC, or the PC after the prologue, whichever
6577      is greater.  */
6578   if (find_pc_partial_function (pc, NULL, &func_addr, NULL))
6579     {
6580       CORE_ADDR post_prologue_pc
6581         = skip_prologue_using_sal (gdbarch, func_addr);
6582       if (post_prologue_pc != 0)
6583         return max (pc, post_prologue_pc);
6584     }
6585
6586   /* Can't determine prologue from the symbol table, need to examine
6587      instructions.  */
6588
6589   /* Find an upper limit on the function prologue using the debug
6590      information.  If the debug information could not be used to provide
6591      that bound, then use an arbitrary large number as the upper bound.  */
6592   limit_pc = skip_prologue_using_sal (gdbarch, pc);
6593   if (limit_pc == 0)
6594     limit_pc = pc + 100;          /* Magic.  */
6595
6596   if (mips_pc_is_mips16 (gdbarch, pc))
6597     return mips16_scan_prologue (gdbarch, pc, limit_pc, NULL, NULL);
6598   else if (mips_pc_is_micromips (gdbarch, pc))
6599     return micromips_scan_prologue (gdbarch, pc, limit_pc, NULL, NULL);
6600   else
6601     return mips32_scan_prologue (gdbarch, pc, limit_pc, NULL, NULL);
6602 }
6603
6604 /* Check whether the PC is in a function epilogue (32-bit version).
6605    This is a helper function for mips_in_function_epilogue_p.  */
6606 static int
6607 mips32_in_function_epilogue_p (struct gdbarch *gdbarch, CORE_ADDR pc)
6608 {
6609   CORE_ADDR func_addr = 0, func_end = 0;
6610
6611   if (find_pc_partial_function (pc, NULL, &func_addr, &func_end))
6612     {
6613       /* The MIPS epilogue is max. 12 bytes long.  */
6614       CORE_ADDR addr = func_end - 12;
6615
6616       if (addr < func_addr + 4)
6617         addr = func_addr + 4;
6618       if (pc < addr)
6619         return 0;
6620
6621       for (; pc < func_end; pc += MIPS_INSN32_SIZE)
6622         {
6623           unsigned long high_word;
6624           unsigned long inst;
6625
6626           inst = mips_fetch_instruction (gdbarch, ISA_MIPS, pc, NULL);
6627           high_word = (inst >> 16) & 0xffff;
6628
6629           if (high_word != 0x27bd       /* addiu $sp,$sp,offset */
6630               && high_word != 0x67bd    /* daddiu $sp,$sp,offset */
6631               && inst != 0x03e00008     /* jr $ra */
6632               && inst != 0x00000000)    /* nop */
6633             return 0;
6634         }
6635
6636       return 1;
6637     }
6638
6639   return 0;
6640 }
6641
6642 /* Check whether the PC is in a function epilogue (microMIPS version).
6643    This is a helper function for mips_in_function_epilogue_p.  */
6644
6645 static int
6646 micromips_in_function_epilogue_p (struct gdbarch *gdbarch, CORE_ADDR pc)
6647 {
6648   CORE_ADDR func_addr = 0;
6649   CORE_ADDR func_end = 0;
6650   CORE_ADDR addr;
6651   ULONGEST insn;
6652   long offset;
6653   int dreg;
6654   int sreg;
6655   int loc;
6656
6657   if (!find_pc_partial_function (pc, NULL, &func_addr, &func_end))
6658     return 0;
6659
6660   /* The microMIPS epilogue is max. 12 bytes long.  */
6661   addr = func_end - 12;
6662
6663   if (addr < func_addr + 2)
6664     addr = func_addr + 2;
6665   if (pc < addr)
6666     return 0;
6667
6668   for (; pc < func_end; pc += loc)
6669     {
6670       loc = 0;
6671       insn = mips_fetch_instruction (gdbarch, ISA_MICROMIPS, pc, NULL);
6672       loc += MIPS_INSN16_SIZE;
6673       switch (mips_insn_size (ISA_MICROMIPS, insn))
6674         {
6675         /* 48-bit instructions.  */
6676         case 3 * MIPS_INSN16_SIZE:
6677           /* No epilogue instructions in this category.  */
6678           return 0;
6679
6680         /* 32-bit instructions.  */
6681         case 2 * MIPS_INSN16_SIZE:
6682           insn <<= 16;
6683           insn |= mips_fetch_instruction (gdbarch,
6684                                           ISA_MICROMIPS, pc + loc, NULL);
6685           loc += MIPS_INSN16_SIZE;
6686           switch (micromips_op (insn >> 16))
6687             {
6688             case 0xc: /* ADDIU: bits 001100 */
6689             case 0x17: /* DADDIU: bits 010111 */
6690               sreg = b0s5_reg (insn >> 16);
6691               dreg = b5s5_reg (insn >> 16);
6692               offset = (b0s16_imm (insn) ^ 0x8000) - 0x8000;
6693               if (sreg == MIPS_SP_REGNUM && dreg == MIPS_SP_REGNUM
6694                             /* (D)ADDIU $sp, imm */
6695                   && offset >= 0)
6696                 break;
6697               return 0;
6698
6699             default:
6700               return 0;
6701             }
6702           break;
6703
6704         /* 16-bit instructions.  */
6705         case MIPS_INSN16_SIZE:
6706           switch (micromips_op (insn))
6707             {
6708             case 0x3: /* MOVE: bits 000011 */
6709               sreg = b0s5_reg (insn);
6710               dreg = b5s5_reg (insn);
6711               if (sreg == 0 && dreg == 0)
6712                                 /* MOVE $zero, $zero aka NOP */
6713                 break;
6714               return 0;
6715
6716             case 0x11: /* POOL16C: bits 010001 */
6717               if (b5s5_op (insn) == 0x18
6718                                 /* JRADDIUSP: bits 010011 11000 */
6719                   || (b5s5_op (insn) == 0xd
6720                                 /* JRC: bits 010011 01101 */
6721                       && b0s5_reg (insn) == MIPS_RA_REGNUM))
6722                                 /* JRC $ra */
6723                 break;
6724               return 0;
6725
6726             case 0x13: /* POOL16D: bits 010011 */
6727               offset = micromips_decode_imm9 (b1s9_imm (insn));
6728               if ((insn & 0x1) == 0x1
6729                                 /* ADDIUSP: bits 010011 1 */
6730                   && offset > 0)
6731                 break;
6732               return 0;
6733
6734             default:
6735               return 0;
6736             }
6737         }
6738     }
6739
6740   return 1;
6741 }
6742
6743 /* Check whether the PC is in a function epilogue (16-bit version).
6744    This is a helper function for mips_in_function_epilogue_p.  */
6745 static int
6746 mips16_in_function_epilogue_p (struct gdbarch *gdbarch, CORE_ADDR pc)
6747 {
6748   CORE_ADDR func_addr = 0, func_end = 0;
6749
6750   if (find_pc_partial_function (pc, NULL, &func_addr, &func_end))
6751     {
6752       /* The MIPS epilogue is max. 12 bytes long.  */
6753       CORE_ADDR addr = func_end - 12;
6754
6755       if (addr < func_addr + 4)
6756         addr = func_addr + 4;
6757       if (pc < addr)
6758         return 0;
6759
6760       for (; pc < func_end; pc += MIPS_INSN16_SIZE)
6761         {
6762           unsigned short inst;
6763
6764           inst = mips_fetch_instruction (gdbarch, ISA_MIPS16, pc, NULL);
6765
6766           if ((inst & 0xf800) == 0xf000)        /* extend */
6767             continue;
6768
6769           if (inst != 0x6300            /* addiu $sp,offset */
6770               && inst != 0xfb00         /* daddiu $sp,$sp,offset */
6771               && inst != 0xe820         /* jr $ra */
6772               && inst != 0xe8a0         /* jrc $ra */
6773               && inst != 0x6500)        /* nop */
6774             return 0;
6775         }
6776
6777       return 1;
6778     }
6779
6780   return 0;
6781 }
6782
6783 /* The epilogue is defined here as the area at the end of a function,
6784    after an instruction which destroys the function's stack frame.  */
6785 static int
6786 mips_in_function_epilogue_p (struct gdbarch *gdbarch, CORE_ADDR pc)
6787 {
6788   if (mips_pc_is_mips16 (gdbarch, pc))
6789     return mips16_in_function_epilogue_p (gdbarch, pc);
6790   else if (mips_pc_is_micromips (gdbarch, pc))
6791     return micromips_in_function_epilogue_p (gdbarch, pc);
6792   else
6793     return mips32_in_function_epilogue_p (gdbarch, pc);
6794 }
6795
6796 /* Root of all "set mips "/"show mips " commands.  This will eventually be
6797    used for all MIPS-specific commands.  */
6798
6799 static void
6800 show_mips_command (char *args, int from_tty)
6801 {
6802   help_list (showmipscmdlist, "show mips ", all_commands, gdb_stdout);
6803 }
6804
6805 static void
6806 set_mips_command (char *args, int from_tty)
6807 {
6808   printf_unfiltered
6809     ("\"set mips\" must be followed by an appropriate subcommand.\n");
6810   help_list (setmipscmdlist, "set mips ", all_commands, gdb_stdout);
6811 }
6812
6813 /* Commands to show/set the MIPS FPU type.  */
6814
6815 static void
6816 show_mipsfpu_command (char *args, int from_tty)
6817 {
6818   char *fpu;
6819
6820   if (gdbarch_bfd_arch_info (target_gdbarch ())->arch != bfd_arch_mips)
6821     {
6822       printf_unfiltered
6823         ("The MIPS floating-point coprocessor is unknown "
6824          "because the current architecture is not MIPS.\n");
6825       return;
6826     }
6827
6828   switch (MIPS_FPU_TYPE (target_gdbarch ()))
6829     {
6830     case MIPS_FPU_SINGLE:
6831       fpu = "single-precision";
6832       break;
6833     case MIPS_FPU_DOUBLE:
6834       fpu = "double-precision";
6835       break;
6836     case MIPS_FPU_NONE:
6837       fpu = "absent (none)";
6838       break;
6839     default:
6840       internal_error (__FILE__, __LINE__, _("bad switch"));
6841     }
6842   if (mips_fpu_type_auto)
6843     printf_unfiltered ("The MIPS floating-point coprocessor "
6844                        "is set automatically (currently %s)\n",
6845                        fpu);
6846   else
6847     printf_unfiltered
6848       ("The MIPS floating-point coprocessor is assumed to be %s\n", fpu);
6849 }
6850
6851
6852 static void
6853 set_mipsfpu_command (char *args, int from_tty)
6854 {
6855   printf_unfiltered ("\"set mipsfpu\" must be followed by \"double\", "
6856                      "\"single\",\"none\" or \"auto\".\n");
6857   show_mipsfpu_command (args, from_tty);
6858 }
6859
6860 static void
6861 set_mipsfpu_single_command (char *args, int from_tty)
6862 {
6863   struct gdbarch_info info;
6864   gdbarch_info_init (&info);
6865   mips_fpu_type = MIPS_FPU_SINGLE;
6866   mips_fpu_type_auto = 0;
6867   /* FIXME: cagney/2003-11-15: Should be setting a field in "info"
6868      instead of relying on globals.  Doing that would let generic code
6869      handle the search for this specific architecture.  */
6870   if (!gdbarch_update_p (info))
6871     internal_error (__FILE__, __LINE__, _("set mipsfpu failed"));
6872 }
6873
6874 static void
6875 set_mipsfpu_double_command (char *args, int from_tty)
6876 {
6877   struct gdbarch_info info;
6878   gdbarch_info_init (&info);
6879   mips_fpu_type = MIPS_FPU_DOUBLE;
6880   mips_fpu_type_auto = 0;
6881   /* FIXME: cagney/2003-11-15: Should be setting a field in "info"
6882      instead of relying on globals.  Doing that would let generic code
6883      handle the search for this specific architecture.  */
6884   if (!gdbarch_update_p (info))
6885     internal_error (__FILE__, __LINE__, _("set mipsfpu failed"));
6886 }
6887
6888 static void
6889 set_mipsfpu_none_command (char *args, int from_tty)
6890 {
6891   struct gdbarch_info info;
6892   gdbarch_info_init (&info);
6893   mips_fpu_type = MIPS_FPU_NONE;
6894   mips_fpu_type_auto = 0;
6895   /* FIXME: cagney/2003-11-15: Should be setting a field in "info"
6896      instead of relying on globals.  Doing that would let generic code
6897      handle the search for this specific architecture.  */
6898   if (!gdbarch_update_p (info))
6899     internal_error (__FILE__, __LINE__, _("set mipsfpu failed"));
6900 }
6901
6902 static void
6903 set_mipsfpu_auto_command (char *args, int from_tty)
6904 {
6905   mips_fpu_type_auto = 1;
6906 }
6907
6908 /* Attempt to identify the particular processor model by reading the
6909    processor id.  NOTE: cagney/2003-11-15: Firstly it isn't clear that
6910    the relevant processor still exists (it dates back to '94) and
6911    secondly this is not the way to do this.  The processor type should
6912    be set by forcing an architecture change.  */
6913
6914 void
6915 deprecated_mips_set_processor_regs_hack (void)
6916 {
6917   struct regcache *regcache = get_current_regcache ();
6918   struct gdbarch *gdbarch = get_regcache_arch (regcache);
6919   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
6920   ULONGEST prid;
6921
6922   regcache_cooked_read_unsigned (regcache, MIPS_PRID_REGNUM, &prid);
6923   if ((prid & ~0xf) == 0x700)
6924     tdep->mips_processor_reg_names = mips_r3041_reg_names;
6925 }
6926
6927 /* Just like reinit_frame_cache, but with the right arguments to be
6928    callable as an sfunc.  */
6929
6930 static void
6931 reinit_frame_cache_sfunc (char *args, int from_tty,
6932                           struct cmd_list_element *c)
6933 {
6934   reinit_frame_cache ();
6935 }
6936
6937 static int
6938 gdb_print_insn_mips (bfd_vma memaddr, struct disassemble_info *info)
6939 {
6940   struct gdbarch *gdbarch = info->application_data;
6941
6942   /* FIXME: cagney/2003-06-26: Is this even necessary?  The
6943      disassembler needs to be able to locally determine the ISA, and
6944      not rely on GDB.  Otherwize the stand-alone 'objdump -d' will not
6945      work.  */
6946   if (mips_pc_is_mips16 (gdbarch, memaddr))
6947     info->mach = bfd_mach_mips16;
6948   else if (mips_pc_is_micromips (gdbarch, memaddr))
6949     info->mach = bfd_mach_mips_micromips;
6950
6951   /* Round down the instruction address to the appropriate boundary.  */
6952   memaddr &= (info->mach == bfd_mach_mips16
6953               || info->mach == bfd_mach_mips_micromips) ? ~1 : ~3;
6954
6955   /* Set the disassembler options.  */
6956   if (!info->disassembler_options)
6957     /* This string is not recognized explicitly by the disassembler,
6958        but it tells the disassembler to not try to guess the ABI from
6959        the bfd elf headers, such that, if the user overrides the ABI
6960        of a program linked as NewABI, the disassembly will follow the
6961        register naming conventions specified by the user.  */
6962     info->disassembler_options = "gpr-names=32";
6963
6964   /* Call the appropriate disassembler based on the target endian-ness.  */
6965   if (info->endian == BFD_ENDIAN_BIG)
6966     return print_insn_big_mips (memaddr, info);
6967   else
6968     return print_insn_little_mips (memaddr, info);
6969 }
6970
6971 static int
6972 gdb_print_insn_mips_n32 (bfd_vma memaddr, struct disassemble_info *info)
6973 {
6974   /* Set up the disassembler info, so that we get the right
6975      register names from libopcodes.  */
6976   info->disassembler_options = "gpr-names=n32";
6977   info->flavour = bfd_target_elf_flavour;
6978
6979   return gdb_print_insn_mips (memaddr, info);
6980 }
6981
6982 static int
6983 gdb_print_insn_mips_n64 (bfd_vma memaddr, struct disassemble_info *info)
6984 {
6985   /* Set up the disassembler info, so that we get the right
6986      register names from libopcodes.  */
6987   info->disassembler_options = "gpr-names=64";
6988   info->flavour = bfd_target_elf_flavour;
6989
6990   return gdb_print_insn_mips (memaddr, info);
6991 }
6992
6993 /* This function implements gdbarch_breakpoint_from_pc.  It uses the
6994    program counter value to determine whether a 16- or 32-bit breakpoint
6995    should be used.  It returns a pointer to a string of bytes that encode a
6996    breakpoint instruction, stores the length of the string to *lenptr, and
6997    adjusts pc (if necessary) to point to the actual memory location where
6998    the breakpoint should be inserted.  */
6999
7000 static const gdb_byte *
7001 mips_breakpoint_from_pc (struct gdbarch *gdbarch,
7002                          CORE_ADDR *pcptr, int *lenptr)
7003 {
7004   CORE_ADDR pc = *pcptr;
7005
7006   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
7007     {
7008       if (mips_pc_is_mips16 (gdbarch, pc))
7009         {
7010           static gdb_byte mips16_big_breakpoint[] = { 0xe8, 0xa5 };
7011           *pcptr = unmake_compact_addr (pc);
7012           *lenptr = sizeof (mips16_big_breakpoint);
7013           return mips16_big_breakpoint;
7014         }
7015       else if (mips_pc_is_micromips (gdbarch, pc))
7016         {
7017           static gdb_byte micromips16_big_breakpoint[] = { 0x46, 0x85 };
7018           static gdb_byte micromips32_big_breakpoint[] = { 0, 0x5, 0, 0x7 };
7019           ULONGEST insn;
7020           int status;
7021           int size;
7022
7023           insn = mips_fetch_instruction (gdbarch, ISA_MICROMIPS, pc, &status);
7024           size = status ? 2
7025                         : mips_insn_size (ISA_MICROMIPS, insn) == 2 ? 2 : 4;
7026           *pcptr = unmake_compact_addr (pc);
7027           *lenptr = size;
7028           return (size == 2) ? micromips16_big_breakpoint
7029                              : micromips32_big_breakpoint;
7030         }
7031       else
7032         {
7033           /* The IDT board uses an unusual breakpoint value, and
7034              sometimes gets confused when it sees the usual MIPS
7035              breakpoint instruction.  */
7036           static gdb_byte big_breakpoint[] = { 0, 0x5, 0, 0xd };
7037           static gdb_byte pmon_big_breakpoint[] = { 0, 0, 0, 0xd };
7038           static gdb_byte idt_big_breakpoint[] = { 0, 0, 0x0a, 0xd };
7039           /* Likewise, IRIX appears to expect a different breakpoint,
7040              although this is not apparent until you try to use pthreads.  */
7041           static gdb_byte irix_big_breakpoint[] = { 0, 0, 0, 0xd };
7042
7043           *lenptr = sizeof (big_breakpoint);
7044
7045           if (strcmp (target_shortname, "mips") == 0)
7046             return idt_big_breakpoint;
7047           else if (strcmp (target_shortname, "ddb") == 0
7048                    || strcmp (target_shortname, "pmon") == 0
7049                    || strcmp (target_shortname, "lsi") == 0)
7050             return pmon_big_breakpoint;
7051           else if (gdbarch_osabi (gdbarch) == GDB_OSABI_IRIX)
7052             return irix_big_breakpoint;
7053           else
7054             return big_breakpoint;
7055         }
7056     }
7057   else
7058     {
7059       if (mips_pc_is_mips16 (gdbarch, pc))
7060         {
7061           static gdb_byte mips16_little_breakpoint[] = { 0xa5, 0xe8 };
7062           *pcptr = unmake_compact_addr (pc);
7063           *lenptr = sizeof (mips16_little_breakpoint);
7064           return mips16_little_breakpoint;
7065         }
7066       else if (mips_pc_is_micromips (gdbarch, pc))
7067         {
7068           static gdb_byte micromips16_little_breakpoint[] = { 0x85, 0x46 };
7069           static gdb_byte micromips32_little_breakpoint[] = { 0x5, 0, 0x7, 0 };
7070           ULONGEST insn;
7071           int status;
7072           int size;
7073
7074           insn = mips_fetch_instruction (gdbarch, ISA_MICROMIPS, pc, &status);
7075           size = status ? 2
7076                         : mips_insn_size (ISA_MICROMIPS, insn) == 2 ? 2 : 4;
7077           *pcptr = unmake_compact_addr (pc);
7078           *lenptr = size;
7079           return (size == 2) ? micromips16_little_breakpoint
7080                              : micromips32_little_breakpoint;
7081         }
7082       else
7083         {
7084           static gdb_byte little_breakpoint[] = { 0xd, 0, 0x5, 0 };
7085           static gdb_byte pmon_little_breakpoint[] = { 0xd, 0, 0, 0 };
7086           static gdb_byte idt_little_breakpoint[] = { 0xd, 0x0a, 0, 0 };
7087
7088           *lenptr = sizeof (little_breakpoint);
7089
7090           if (strcmp (target_shortname, "mips") == 0)
7091             return idt_little_breakpoint;
7092           else if (strcmp (target_shortname, "ddb") == 0
7093                    || strcmp (target_shortname, "pmon") == 0
7094                    || strcmp (target_shortname, "lsi") == 0)
7095             return pmon_little_breakpoint;
7096           else
7097             return little_breakpoint;
7098         }
7099     }
7100 }
7101
7102 /* Determine the remote breakpoint kind suitable for the PC.  The following
7103    kinds are used:
7104
7105    * 2 -- 16-bit MIPS16 mode breakpoint,
7106
7107    * 3 -- 16-bit microMIPS mode breakpoint,
7108
7109    * 4 -- 32-bit standard MIPS mode breakpoint,
7110
7111    * 5 -- 32-bit microMIPS mode breakpoint.  */
7112
7113 static void
7114 mips_remote_breakpoint_from_pc (struct gdbarch *gdbarch, CORE_ADDR *pcptr,
7115                                 int *kindptr)
7116 {
7117   CORE_ADDR pc = *pcptr;
7118
7119   if (mips_pc_is_mips16 (gdbarch, pc))
7120     {
7121       *pcptr = unmake_compact_addr (pc);
7122       *kindptr = 2;
7123     }
7124   else if (mips_pc_is_micromips (gdbarch, pc))
7125     {
7126       ULONGEST insn;
7127       int status;
7128       int size;
7129
7130       insn = mips_fetch_instruction (gdbarch, ISA_MICROMIPS, pc, &status);
7131       size = status ? 2 : mips_insn_size (ISA_MICROMIPS, insn) == 2 ? 2 : 4;
7132       *pcptr = unmake_compact_addr (pc);
7133       *kindptr = size | 1;
7134     }
7135   else
7136     *kindptr = 4;
7137 }
7138
7139 /* Return non-zero if the standard MIPS instruction INST has a branch
7140    delay slot (i.e. it is a jump or branch instruction).  This function
7141    is based on mips32_next_pc.  */
7142
7143 static int
7144 mips32_instruction_has_delay_slot (struct gdbarch *gdbarch, ULONGEST inst)
7145 {
7146   int op;
7147   int rs;
7148   int rt;
7149
7150   op = itype_op (inst);
7151   if ((inst & 0xe0000000) != 0)
7152     {
7153       rs = itype_rs (inst);
7154       rt = itype_rt (inst);
7155       return (is_octeon_bbit_op (op, gdbarch) 
7156               || op >> 2 == 5   /* BEQL, BNEL, BLEZL, BGTZL: bits 0101xx  */
7157               || op == 29       /* JALX: bits 011101  */
7158               || (op == 17
7159                   && (rs == 8
7160                                 /* BC1F, BC1FL, BC1T, BC1TL: 010001 01000  */
7161                       || (rs == 9 && (rt & 0x2) == 0)
7162                                 /* BC1ANY2F, BC1ANY2T: bits 010001 01001  */
7163                       || (rs == 10 && (rt & 0x2) == 0))));
7164                                 /* BC1ANY4F, BC1ANY4T: bits 010001 01010  */
7165     }
7166   else
7167     switch (op & 0x07)          /* extract bits 28,27,26  */
7168       {
7169       case 0:                   /* SPECIAL  */
7170         op = rtype_funct (inst);
7171         return (op == 8         /* JR  */
7172                 || op == 9);    /* JALR  */
7173         break;                  /* end SPECIAL  */
7174       case 1:                   /* REGIMM  */
7175         rs = itype_rs (inst);
7176         rt = itype_rt (inst);   /* branch condition  */
7177         return ((rt & 0xc) == 0
7178                                 /* BLTZ, BLTZL, BGEZ, BGEZL: bits 000xx  */
7179                                 /* BLTZAL, BLTZALL, BGEZAL, BGEZALL: 100xx  */
7180                 || ((rt & 0x1e) == 0x1c && rs == 0));
7181                                 /* BPOSGE32, BPOSGE64: bits 1110x  */
7182         break;                  /* end REGIMM  */
7183       default:                  /* J, JAL, BEQ, BNE, BLEZ, BGTZ  */
7184         return 1;
7185         break;
7186       }
7187 }
7188
7189 /* Return non-zero if a standard MIPS instruction at ADDR has a branch
7190    delay slot (i.e. it is a jump or branch instruction).  */
7191
7192 static int
7193 mips32_insn_at_pc_has_delay_slot (struct gdbarch *gdbarch, CORE_ADDR addr)
7194 {
7195   ULONGEST insn;
7196   int status;
7197
7198   insn = mips_fetch_instruction (gdbarch, ISA_MIPS, addr, &status);
7199   if (status)
7200     return 0;
7201
7202   return mips32_instruction_has_delay_slot (gdbarch, insn);
7203 }
7204
7205 /* Return non-zero if the microMIPS instruction INSN, comprising the
7206    16-bit major opcode word in the high 16 bits and any second word
7207    in the low 16 bits, has a branch delay slot (i.e. it is a non-compact
7208    jump or branch instruction).  The instruction must be 32-bit if
7209    MUSTBE32 is set or can be any instruction otherwise.  */
7210
7211 static int
7212 micromips_instruction_has_delay_slot (ULONGEST insn, int mustbe32)
7213 {
7214   ULONGEST major = insn >> 16;
7215
7216   switch (micromips_op (major))
7217     {
7218     /* 16-bit instructions.  */
7219     case 0x33:                  /* B16: bits 110011 */
7220     case 0x2b:                  /* BNEZ16: bits 101011 */
7221     case 0x23:                  /* BEQZ16: bits 100011 */
7222       return !mustbe32;
7223     case 0x11:                  /* POOL16C: bits 010001 */
7224       return (!mustbe32
7225               && ((b5s5_op (major) == 0xc
7226                                 /* JR16: bits 010001 01100 */
7227                   || (b5s5_op (major) & 0x1e) == 0xe)));
7228                                 /* JALR16, JALRS16: bits 010001 0111x */
7229     /* 32-bit instructions.  */
7230     case 0x3d:                  /* JAL: bits 111101 */
7231     case 0x3c:                  /* JALX: bits 111100 */
7232     case 0x35:                  /* J: bits 110101 */
7233     case 0x2d:                  /* BNE: bits 101101 */
7234     case 0x25:                  /* BEQ: bits 100101 */
7235     case 0x1d:                  /* JALS: bits 011101 */
7236       return 1;
7237     case 0x10:                  /* POOL32I: bits 010000 */
7238       return ((b5s5_op (major) & 0x1c) == 0x0
7239                                 /* BLTZ, BLTZAL, BGEZ, BGEZAL: 010000 000xx */
7240               || (b5s5_op (major) & 0x1d) == 0x4
7241                                 /* BLEZ, BGTZ: bits 010000 001x0 */
7242               || (b5s5_op (major) & 0x1d) == 0x11
7243                                 /* BLTZALS, BGEZALS: bits 010000 100x1 */
7244               || ((b5s5_op (major) & 0x1e) == 0x14
7245                   && (major & 0x3) == 0x0)
7246                                 /* BC2F, BC2T: bits 010000 1010x xxx00 */
7247               || (b5s5_op (major) & 0x1e) == 0x1a
7248                                 /* BPOSGE64, BPOSGE32: bits 010000 1101x */
7249               || ((b5s5_op (major) & 0x1e) == 0x1c
7250                   && (major & 0x3) == 0x0)
7251                                 /* BC1F, BC1T: bits 010000 1110x xxx00 */
7252               || ((b5s5_op (major) & 0x1c) == 0x1c
7253                   && (major & 0x3) == 0x1));
7254                                 /* BC1ANY*: bits 010000 111xx xxx01 */
7255     case 0x0:                   /* POOL32A: bits 000000 */
7256       return (b0s6_op (insn) == 0x3c
7257                                 /* POOL32Axf: bits 000000 ... 111100 */
7258               && (b6s10_ext (insn) & 0x2bf) == 0x3c);
7259                                 /* JALR, JALR.HB: 000000 000x111100 111100 */
7260                                 /* JALRS, JALRS.HB: 000000 010x111100 111100 */
7261     default:
7262       return 0;
7263     }
7264 }
7265
7266 /* Return non-zero if a microMIPS instruction at ADDR has a branch delay
7267    slot (i.e. it is a non-compact jump instruction).  The instruction
7268    must be 32-bit if MUSTBE32 is set or can be any instruction otherwise.  */
7269
7270 static int
7271 micromips_insn_at_pc_has_delay_slot (struct gdbarch *gdbarch,
7272                                      CORE_ADDR addr, int mustbe32)
7273 {
7274   ULONGEST insn;
7275   int status;
7276
7277   insn = mips_fetch_instruction (gdbarch, ISA_MICROMIPS, addr, &status);
7278   if (status)
7279     return 0;
7280   insn <<= 16;
7281   if (mips_insn_size (ISA_MICROMIPS, insn) == 2 * MIPS_INSN16_SIZE)
7282     {
7283       insn |= mips_fetch_instruction (gdbarch, ISA_MICROMIPS, addr, &status);
7284       if (status)
7285         return 0;
7286     }
7287
7288   return micromips_instruction_has_delay_slot (insn, mustbe32);
7289 }
7290
7291 /* Return non-zero if the MIPS16 instruction INST, which must be
7292    a 32-bit instruction if MUSTBE32 is set or can be any instruction
7293    otherwise, has a branch delay slot (i.e. it is a non-compact jump
7294    instruction).  This function is based on mips16_next_pc.  */
7295
7296 static int
7297 mips16_instruction_has_delay_slot (unsigned short inst, int mustbe32)
7298 {
7299   if ((inst & 0xf89f) == 0xe800)        /* JR/JALR (16-bit instruction)  */
7300     return !mustbe32;
7301   return (inst & 0xf800) == 0x1800;     /* JAL/JALX (32-bit instruction)  */
7302 }
7303
7304 /* Return non-zero if a MIPS16 instruction at ADDR has a branch delay
7305    slot (i.e. it is a non-compact jump instruction).  The instruction
7306    must be 32-bit if MUSTBE32 is set or can be any instruction otherwise.  */
7307
7308 static int
7309 mips16_insn_at_pc_has_delay_slot (struct gdbarch *gdbarch,
7310                                   CORE_ADDR addr, int mustbe32)
7311 {
7312   unsigned short insn;
7313   int status;
7314
7315   insn = mips_fetch_instruction (gdbarch, ISA_MIPS16, addr, &status);
7316   if (status)
7317     return 0;
7318
7319   return mips16_instruction_has_delay_slot (insn, mustbe32);
7320 }
7321
7322 /* Calculate the starting address of the MIPS memory segment BPADDR is in.
7323    This assumes KSSEG exists.  */
7324
7325 static CORE_ADDR
7326 mips_segment_boundary (CORE_ADDR bpaddr)
7327 {
7328   CORE_ADDR mask = CORE_ADDR_MAX;
7329   int segsize;
7330
7331   if (sizeof (CORE_ADDR) == 8)
7332     /* Get the topmost two bits of bpaddr in a 32-bit safe manner (avoid
7333        a compiler warning produced where CORE_ADDR is a 32-bit type even
7334        though in that case this is dead code).  */
7335     switch (bpaddr >> ((sizeof (CORE_ADDR) << 3) - 2) & 3)
7336       {
7337       case 3:
7338         if (bpaddr == (bfd_signed_vma) (int32_t) bpaddr)
7339           segsize = 29;                 /* 32-bit compatibility segment  */
7340         else
7341           segsize = 62;                 /* xkseg  */
7342         break;
7343       case 2:                           /* xkphys  */
7344         segsize = 59;
7345         break;
7346       default:                          /* xksseg (1), xkuseg/kuseg (0)  */
7347         segsize = 62;
7348         break;
7349       }
7350   else if (bpaddr & 0x80000000)         /* kernel segment  */
7351     segsize = 29;
7352   else
7353     segsize = 31;                       /* user segment  */
7354   mask <<= segsize;
7355   return bpaddr & mask;
7356 }
7357
7358 /* Move the breakpoint at BPADDR out of any branch delay slot by shifting
7359    it backwards if necessary.  Return the address of the new location.  */
7360
7361 static CORE_ADDR
7362 mips_adjust_breakpoint_address (struct gdbarch *gdbarch, CORE_ADDR bpaddr)
7363 {
7364   CORE_ADDR prev_addr;
7365   CORE_ADDR boundary;
7366   CORE_ADDR func_addr;
7367
7368   /* If a breakpoint is set on the instruction in a branch delay slot,
7369      GDB gets confused.  When the breakpoint is hit, the PC isn't on
7370      the instruction in the branch delay slot, the PC will point to
7371      the branch instruction.  Since the PC doesn't match any known
7372      breakpoints, GDB reports a trap exception.
7373
7374      There are two possible fixes for this problem.
7375
7376      1) When the breakpoint gets hit, see if the BD bit is set in the
7377      Cause register (which indicates the last exception occurred in a
7378      branch delay slot).  If the BD bit is set, fix the PC to point to
7379      the instruction in the branch delay slot.
7380
7381      2) When the user sets the breakpoint, don't allow him to set the
7382      breakpoint on the instruction in the branch delay slot.  Instead
7383      move the breakpoint to the branch instruction (which will have
7384      the same result).
7385
7386      The problem with the first solution is that if the user then
7387      single-steps the processor, the branch instruction will get
7388      skipped (since GDB thinks the PC is on the instruction in the
7389      branch delay slot).
7390
7391      So, we'll use the second solution.  To do this we need to know if
7392      the instruction we're trying to set the breakpoint on is in the
7393      branch delay slot.  */
7394
7395   boundary = mips_segment_boundary (bpaddr);
7396
7397   /* Make sure we don't scan back before the beginning of the current
7398      function, since we may fetch constant data or insns that look like
7399      a jump.  Of course we might do that anyway if the compiler has
7400      moved constants inline. :-(  */
7401   if (find_pc_partial_function (bpaddr, NULL, &func_addr, NULL)
7402       && func_addr > boundary && func_addr <= bpaddr)
7403     boundary = func_addr;
7404
7405   if (mips_pc_is_mips (bpaddr))
7406     {
7407       if (bpaddr == boundary)
7408         return bpaddr;
7409
7410       /* If the previous instruction has a branch delay slot, we have
7411          to move the breakpoint to the branch instruction. */
7412       prev_addr = bpaddr - 4;
7413       if (mips32_insn_at_pc_has_delay_slot (gdbarch, prev_addr))
7414         bpaddr = prev_addr;
7415     }
7416   else
7417     {
7418       int (*insn_at_pc_has_delay_slot) (struct gdbarch *, CORE_ADDR, int);
7419       CORE_ADDR addr, jmpaddr;
7420       int i;
7421
7422       boundary = unmake_compact_addr (boundary);
7423
7424       /* The only MIPS16 instructions with delay slots are JAL, JALX,
7425          JALR and JR.  An absolute JAL/JALX is always 4 bytes long,
7426          so try for that first, then try the 2 byte JALR/JR.
7427          The microMIPS ASE has a whole range of jumps and branches
7428          with delay slots, some of which take 4 bytes and some take
7429          2 bytes, so the idea is the same.
7430          FIXME: We have to assume that bpaddr is not the second half
7431          of an extended instruction.  */
7432       insn_at_pc_has_delay_slot = (mips_pc_is_micromips (gdbarch, bpaddr)
7433                                    ? micromips_insn_at_pc_has_delay_slot
7434                                    : mips16_insn_at_pc_has_delay_slot);
7435
7436       jmpaddr = 0;
7437       addr = bpaddr;
7438       for (i = 1; i < 4; i++)
7439         {
7440           if (unmake_compact_addr (addr) == boundary)
7441             break;
7442           addr -= MIPS_INSN16_SIZE;
7443           if (i == 1 && insn_at_pc_has_delay_slot (gdbarch, addr, 0))
7444             /* Looks like a JR/JALR at [target-1], but it could be
7445                the second word of a previous JAL/JALX, so record it
7446                and check back one more.  */
7447             jmpaddr = addr;
7448           else if (i > 1 && insn_at_pc_has_delay_slot (gdbarch, addr, 1))
7449             {
7450               if (i == 2)
7451                 /* Looks like a JAL/JALX at [target-2], but it could also
7452                    be the second word of a previous JAL/JALX, record it,
7453                    and check back one more.  */
7454                 jmpaddr = addr;
7455               else
7456                 /* Looks like a JAL/JALX at [target-3], so any previously
7457                    recorded JAL/JALX or JR/JALR must be wrong, because:
7458
7459                    >-3: JAL
7460                     -2: JAL-ext (can't be JAL/JALX)
7461                     -1: bdslot (can't be JR/JALR)
7462                      0: target insn
7463
7464                    Of course it could be another JAL-ext which looks
7465                    like a JAL, but in that case we'd have broken out
7466                    of this loop at [target-2]:
7467
7468                     -4: JAL
7469                    >-3: JAL-ext
7470                     -2: bdslot (can't be jmp)
7471                     -1: JR/JALR
7472                      0: target insn  */
7473                 jmpaddr = 0;
7474             }
7475           else
7476             {
7477               /* Not a jump instruction: if we're at [target-1] this
7478                  could be the second word of a JAL/JALX, so continue;
7479                  otherwise we're done.  */
7480               if (i > 1)
7481                 break;
7482             }
7483         }
7484
7485       if (jmpaddr)
7486         bpaddr = jmpaddr;
7487     }
7488
7489   return bpaddr;
7490 }
7491
7492 /* Return non-zero if SUFFIX is one of the numeric suffixes used for MIPS16
7493    call stubs, one of 1, 2, 5, 6, 9, 10, or, if ZERO is non-zero, also 0.  */
7494
7495 static int
7496 mips_is_stub_suffix (const char *suffix, int zero)
7497 {
7498   switch (suffix[0])
7499    {
7500    case '0':
7501      return zero && suffix[1] == '\0';
7502    case '1':
7503      return suffix[1] == '\0' || (suffix[1] == '0' && suffix[2] == '\0');
7504    case '2':
7505    case '5':
7506    case '6':
7507    case '9':
7508      return suffix[1] == '\0';
7509    default:
7510      return 0;
7511    }
7512 }
7513
7514 /* Return non-zero if MODE is one of the mode infixes used for MIPS16
7515    call stubs, one of sf, df, sc, or dc.  */
7516
7517 static int
7518 mips_is_stub_mode (const char *mode)
7519 {
7520   return ((mode[0] == 's' || mode[0] == 'd')
7521           && (mode[1] == 'f' || mode[1] == 'c'));
7522 }
7523
7524 /* Code at PC is a compiler-generated stub.  Such a stub for a function
7525    bar might have a name like __fn_stub_bar, and might look like this:
7526
7527       mfc1    $4, $f13
7528       mfc1    $5, $f12
7529       mfc1    $6, $f15
7530       mfc1    $7, $f14
7531
7532    followed by (or interspersed with):
7533
7534       j       bar
7535
7536    or:
7537
7538       lui     $25, %hi(bar)
7539       addiu   $25, $25, %lo(bar)
7540       jr      $25
7541
7542    ($1 may be used in old code; for robustness we accept any register)
7543    or, in PIC code:
7544
7545       lui     $28, %hi(_gp_disp)
7546       addiu   $28, $28, %lo(_gp_disp)
7547       addu    $28, $28, $25
7548       lw      $25, %got(bar)
7549       addiu   $25, $25, %lo(bar)
7550       jr      $25
7551
7552    In the case of a __call_stub_bar stub, the sequence to set up
7553    arguments might look like this:
7554
7555       mtc1    $4, $f13
7556       mtc1    $5, $f12
7557       mtc1    $6, $f15
7558       mtc1    $7, $f14
7559
7560    followed by (or interspersed with) one of the jump sequences above.
7561
7562    In the case of a __call_stub_fp_bar stub, JAL or JALR is used instead
7563    of J or JR, respectively, followed by:
7564
7565       mfc1    $2, $f0
7566       mfc1    $3, $f1
7567       jr      $18
7568
7569    We are at the beginning of the stub here, and scan down and extract
7570    the target address from the jump immediate instruction or, if a jump
7571    register instruction is used, from the register referred.  Return
7572    the value of PC calculated or 0 if inconclusive.
7573
7574    The limit on the search is arbitrarily set to 20 instructions.  FIXME.  */
7575
7576 static CORE_ADDR
7577 mips_get_mips16_fn_stub_pc (struct frame_info *frame, CORE_ADDR pc)
7578 {
7579   struct gdbarch *gdbarch = get_frame_arch (frame);
7580   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
7581   int addrreg = MIPS_ZERO_REGNUM;
7582   CORE_ADDR start_pc = pc;
7583   CORE_ADDR target_pc = 0;
7584   CORE_ADDR addr = 0;
7585   CORE_ADDR gp = 0;
7586   int status = 0;
7587   int i;
7588
7589   for (i = 0;
7590        status == 0 && target_pc == 0 && i < 20;
7591        i++, pc += MIPS_INSN32_SIZE)
7592     {
7593       ULONGEST inst = mips_fetch_instruction (gdbarch, ISA_MIPS, pc, NULL);
7594       CORE_ADDR imm;
7595       int rt;
7596       int rs;
7597       int rd;
7598
7599       switch (itype_op (inst))
7600         {
7601         case 0:         /* SPECIAL */
7602           switch (rtype_funct (inst))
7603             {
7604             case 8:             /* JR */
7605             case 9:             /* JALR */
7606               rs = rtype_rs (inst);
7607               if (rs == MIPS_GP_REGNUM)
7608                 target_pc = gp;                         /* Hmm...  */
7609               else if (rs == addrreg)
7610                 target_pc = addr;
7611               break;
7612
7613             case 0x21:          /* ADDU */
7614               rt = rtype_rt (inst);
7615               rs = rtype_rs (inst);
7616               rd = rtype_rd (inst);
7617               if (rd == MIPS_GP_REGNUM
7618                   && ((rs == MIPS_GP_REGNUM && rt == MIPS_T9_REGNUM)
7619                       || (rs == MIPS_T9_REGNUM && rt == MIPS_GP_REGNUM)))
7620                 gp += start_pc;
7621               break;
7622             }
7623           break;
7624
7625         case 2:         /* J */
7626         case 3:         /* JAL */
7627           target_pc = jtype_target (inst) << 2;
7628           target_pc += ((pc + 4) & ~(CORE_ADDR) 0x0fffffff);
7629           break;
7630
7631         case 9:         /* ADDIU */
7632           rt = itype_rt (inst);
7633           rs = itype_rs (inst);
7634           if (rt == rs)
7635             {
7636               imm = (itype_immediate (inst) ^ 0x8000) - 0x8000;
7637               if (rt == MIPS_GP_REGNUM)
7638                 gp += imm;
7639               else if (rt == addrreg)
7640                 addr += imm;
7641             }
7642           break;
7643
7644         case 0xf:       /* LUI */
7645           rt = itype_rt (inst);
7646           imm = ((itype_immediate (inst) ^ 0x8000) - 0x8000) << 16;
7647           if (rt == MIPS_GP_REGNUM)
7648             gp = imm;
7649           else if (rt != MIPS_ZERO_REGNUM)
7650             {
7651               addrreg = rt;
7652               addr = imm;
7653             }
7654           break;
7655
7656         case 0x23:      /* LW */
7657           rt = itype_rt (inst);
7658           rs = itype_rs (inst);
7659           imm = (itype_immediate (inst) ^ 0x8000) - 0x8000;
7660           if (gp != 0 && rs == MIPS_GP_REGNUM)
7661             {
7662               gdb_byte buf[4];
7663
7664               memset (buf, 0, sizeof (buf));
7665               status = target_read_memory (gp + imm, buf, sizeof (buf));
7666               addrreg = rt;
7667               addr = extract_signed_integer (buf, sizeof (buf), byte_order);
7668             }
7669           break;
7670         }
7671     }
7672
7673   return target_pc;
7674 }
7675
7676 /* If PC is in a MIPS16 call or return stub, return the address of the
7677    target PC, which is either the callee or the caller.  There are several
7678    cases which must be handled:
7679
7680    * If the PC is in __mips16_ret_{d,s}{f,c}, this is a return stub
7681      and the target PC is in $31 ($ra).
7682    * If the PC is in __mips16_call_stub_{1..10}, this is a call stub
7683      and the target PC is in $2.
7684    * If the PC at the start of __mips16_call_stub_{s,d}{f,c}_{0..10},
7685      i.e. before the JALR instruction, this is effectively a call stub
7686      and the target PC is in $2.  Otherwise this is effectively
7687      a return stub and the target PC is in $18.
7688    * If the PC is at the start of __call_stub_fp_*, i.e. before the
7689      JAL or JALR instruction, this is effectively a call stub and the
7690      target PC is buried in the instruction stream.  Otherwise this
7691      is effectively a return stub and the target PC is in $18.
7692    * If the PC is in __call_stub_* or in __fn_stub_*, this is a call
7693      stub and the target PC is buried in the instruction stream.
7694
7695    See the source code for the stubs in gcc/config/mips/mips16.S, or the
7696    stub builder in gcc/config/mips/mips.c (mips16_build_call_stub) for the
7697    gory details.  */
7698
7699 static CORE_ADDR
7700 mips_skip_mips16_trampoline_code (struct frame_info *frame, CORE_ADDR pc)
7701 {
7702   struct gdbarch *gdbarch = get_frame_arch (frame);
7703   CORE_ADDR start_addr;
7704   const char *name;
7705   size_t prefixlen;
7706
7707   /* Find the starting address and name of the function containing the PC.  */
7708   if (find_pc_partial_function (pc, &name, &start_addr, NULL) == 0)
7709     return 0;
7710
7711   /* If the PC is in __mips16_ret_{d,s}{f,c}, this is a return stub
7712      and the target PC is in $31 ($ra).  */
7713   prefixlen = strlen (mips_str_mips16_ret_stub);
7714   if (strncmp (name, mips_str_mips16_ret_stub, prefixlen) == 0
7715       && mips_is_stub_mode (name + prefixlen)
7716       && name[prefixlen + 2] == '\0')
7717     return get_frame_register_signed
7718              (frame, gdbarch_num_regs (gdbarch) + MIPS_RA_REGNUM);
7719
7720   /* If the PC is in __mips16_call_stub_*, this is one of the call
7721      call/return stubs.  */
7722   prefixlen = strlen (mips_str_mips16_call_stub);
7723   if (strncmp (name, mips_str_mips16_call_stub, prefixlen) == 0)
7724     {
7725       /* If the PC is in __mips16_call_stub_{1..10}, this is a call stub
7726          and the target PC is in $2.  */
7727       if (mips_is_stub_suffix (name + prefixlen, 0))
7728         return get_frame_register_signed
7729                  (frame, gdbarch_num_regs (gdbarch) + MIPS_V0_REGNUM);
7730
7731       /* If the PC at the start of __mips16_call_stub_{s,d}{f,c}_{0..10},
7732          i.e. before the JALR instruction, this is effectively a call stub
7733          and the target PC is in $2.  Otherwise this is effectively
7734          a return stub and the target PC is in $18.  */
7735       else if (mips_is_stub_mode (name + prefixlen)
7736                && name[prefixlen + 2] == '_'
7737                && mips_is_stub_suffix (name + prefixlen + 3, 0))
7738         {
7739           if (pc == start_addr)
7740             /* This is the 'call' part of a call stub.  The return
7741                address is in $2.  */
7742             return get_frame_register_signed
7743                      (frame, gdbarch_num_regs (gdbarch) + MIPS_V0_REGNUM);
7744           else
7745             /* This is the 'return' part of a call stub.  The return
7746                address is in $18.  */
7747             return get_frame_register_signed
7748                      (frame, gdbarch_num_regs (gdbarch) + MIPS_S2_REGNUM);
7749         }
7750       else
7751         return 0;               /* Not a stub.  */
7752     }
7753
7754   /* If the PC is in __call_stub_* or __fn_stub*, this is one of the
7755      compiler-generated call or call/return stubs.  */
7756   if (strncmp (name, mips_str_fn_stub, strlen (mips_str_fn_stub)) == 0
7757       || strncmp (name, mips_str_call_stub, strlen (mips_str_call_stub)) == 0)
7758     {
7759       if (pc == start_addr)
7760         /* This is the 'call' part of a call stub.  Call this helper
7761            to scan through this code for interesting instructions
7762            and determine the final PC.  */
7763         return mips_get_mips16_fn_stub_pc (frame, pc);
7764       else
7765         /* This is the 'return' part of a call stub.  The return address
7766            is in $18.  */
7767         return get_frame_register_signed
7768                  (frame, gdbarch_num_regs (gdbarch) + MIPS_S2_REGNUM);
7769     }
7770
7771   return 0;                     /* Not a stub.  */
7772 }
7773
7774 /* Return non-zero if the PC is inside a return thunk (aka stub or trampoline).
7775    This implements the IN_SOLIB_RETURN_TRAMPOLINE macro.  */
7776
7777 static int
7778 mips_in_return_stub (struct gdbarch *gdbarch, CORE_ADDR pc, const char *name)
7779 {
7780   CORE_ADDR start_addr;
7781   size_t prefixlen;
7782
7783   /* Find the starting address of the function containing the PC.  */
7784   if (find_pc_partial_function (pc, NULL, &start_addr, NULL) == 0)
7785     return 0;
7786
7787   /* If the PC is in __mips16_call_stub_{s,d}{f,c}_{0..10} but not at
7788      the start, i.e. after the JALR instruction, this is effectively
7789      a return stub.  */
7790   prefixlen = strlen (mips_str_mips16_call_stub);
7791   if (pc != start_addr
7792       && strncmp (name, mips_str_mips16_call_stub, prefixlen) == 0
7793       && mips_is_stub_mode (name + prefixlen)
7794       && name[prefixlen + 2] == '_'
7795       && mips_is_stub_suffix (name + prefixlen + 3, 1))
7796     return 1;
7797
7798   /* If the PC is in __call_stub_fp_* but not at the start, i.e. after
7799      the JAL or JALR instruction, this is effectively a return stub.  */
7800   prefixlen = strlen (mips_str_call_fp_stub);
7801   if (pc != start_addr
7802       && strncmp (name, mips_str_call_fp_stub, prefixlen) == 0)
7803     return 1;
7804
7805   /* Consume the .pic. prefix of any PIC stub, this function must return
7806      true when the PC is in a PIC stub of a __mips16_ret_{d,s}{f,c} stub
7807      or the call stub path will trigger in handle_inferior_event causing
7808      it to go astray.  */
7809   prefixlen = strlen (mips_str_pic);
7810   if (strncmp (name, mips_str_pic, prefixlen) == 0)
7811     name += prefixlen;
7812
7813   /* If the PC is in __mips16_ret_{d,s}{f,c}, this is a return stub.  */
7814   prefixlen = strlen (mips_str_mips16_ret_stub);
7815   if (strncmp (name, mips_str_mips16_ret_stub, prefixlen) == 0
7816       && mips_is_stub_mode (name + prefixlen)
7817       && name[prefixlen + 2] == '\0')
7818     return 1;
7819
7820   return 0;                     /* Not a stub.  */
7821 }
7822
7823 /* If the current PC is the start of a non-PIC-to-PIC stub, return the
7824    PC of the stub target.  The stub just loads $t9 and jumps to it,
7825    so that $t9 has the correct value at function entry.  */
7826
7827 static CORE_ADDR
7828 mips_skip_pic_trampoline_code (struct frame_info *frame, CORE_ADDR pc)
7829 {
7830   struct gdbarch *gdbarch = get_frame_arch (frame);
7831   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
7832   struct bound_minimal_symbol msym;
7833   int i;
7834   gdb_byte stub_code[16];
7835   int32_t stub_words[4];
7836
7837   /* The stub for foo is named ".pic.foo", and is either two
7838      instructions inserted before foo or a three instruction sequence
7839      which jumps to foo.  */
7840   msym = lookup_minimal_symbol_by_pc (pc);
7841   if (msym.minsym == NULL
7842       || BMSYMBOL_VALUE_ADDRESS (msym) != pc
7843       || MSYMBOL_LINKAGE_NAME (msym.minsym) == NULL
7844       || strncmp (MSYMBOL_LINKAGE_NAME (msym.minsym), ".pic.", 5) != 0)
7845     return 0;
7846
7847   /* A two-instruction header.  */
7848   if (MSYMBOL_SIZE (msym.minsym) == 8)
7849     return pc + 8;
7850
7851   /* A three-instruction (plus delay slot) trampoline.  */
7852   if (MSYMBOL_SIZE (msym.minsym) == 16)
7853     {
7854       if (target_read_memory (pc, stub_code, 16) != 0)
7855         return 0;
7856       for (i = 0; i < 4; i++)
7857         stub_words[i] = extract_unsigned_integer (stub_code + i * 4,
7858                                                   4, byte_order);
7859
7860       /* A stub contains these instructions:
7861          lui    t9, %hi(target)
7862          j      target
7863           addiu t9, t9, %lo(target)
7864          nop
7865
7866          This works even for N64, since stubs are only generated with
7867          -msym32.  */
7868       if ((stub_words[0] & 0xffff0000U) == 0x3c190000
7869           && (stub_words[1] & 0xfc000000U) == 0x08000000
7870           && (stub_words[2] & 0xffff0000U) == 0x27390000
7871           && stub_words[3] == 0x00000000)
7872         return ((((stub_words[0] & 0x0000ffff) << 16)
7873                  + (stub_words[2] & 0x0000ffff)) ^ 0x8000) - 0x8000;
7874     }
7875
7876   /* Not a recognized stub.  */
7877   return 0;
7878 }
7879
7880 static CORE_ADDR
7881 mips_skip_trampoline_code (struct frame_info *frame, CORE_ADDR pc)
7882 {
7883   CORE_ADDR requested_pc = pc;
7884   CORE_ADDR target_pc;
7885   CORE_ADDR new_pc;
7886
7887   do
7888     {
7889       target_pc = pc;
7890
7891       new_pc = mips_skip_mips16_trampoline_code (frame, pc);
7892       if (new_pc)
7893         pc = new_pc;
7894
7895       new_pc = find_solib_trampoline_target (frame, pc);
7896       if (new_pc)
7897         pc = new_pc;
7898
7899       new_pc = mips_skip_pic_trampoline_code (frame, pc);
7900       if (new_pc)
7901         pc = new_pc;
7902     }
7903   while (pc != target_pc);
7904
7905   return pc != requested_pc ? pc : 0;
7906 }
7907
7908 /* Convert a dbx stab register number (from `r' declaration) to a GDB
7909    [1 * gdbarch_num_regs .. 2 * gdbarch_num_regs) REGNUM.  */
7910
7911 static int
7912 mips_stab_reg_to_regnum (struct gdbarch *gdbarch, int num)
7913 {
7914   int regnum;
7915   if (num >= 0 && num < 32)
7916     regnum = num;
7917   else if (num >= 38 && num < 70)
7918     regnum = num + mips_regnum (gdbarch)->fp0 - 38;
7919   else if (num == 70)
7920     regnum = mips_regnum (gdbarch)->hi;
7921   else if (num == 71)
7922     regnum = mips_regnum (gdbarch)->lo;
7923   else if (mips_regnum (gdbarch)->dspacc != -1 && num >= 72 && num < 78)
7924     regnum = num + mips_regnum (gdbarch)->dspacc - 72;
7925   else
7926     /* This will hopefully (eventually) provoke a warning.  Should
7927        we be calling complaint() here?  */
7928     return gdbarch_num_regs (gdbarch) + gdbarch_num_pseudo_regs (gdbarch);
7929   return gdbarch_num_regs (gdbarch) + regnum;
7930 }
7931
7932
7933 /* Convert a dwarf, dwarf2, or ecoff register number to a GDB [1 *
7934    gdbarch_num_regs .. 2 * gdbarch_num_regs) REGNUM.  */
7935
7936 static int
7937 mips_dwarf_dwarf2_ecoff_reg_to_regnum (struct gdbarch *gdbarch, int num)
7938 {
7939   int regnum;
7940   if (num >= 0 && num < 32)
7941     regnum = num;
7942   else if (num >= 32 && num < 64)
7943     regnum = num + mips_regnum (gdbarch)->fp0 - 32;
7944   else if (num == 64)
7945     regnum = mips_regnum (gdbarch)->hi;
7946   else if (num == 65)
7947     regnum = mips_regnum (gdbarch)->lo;
7948   else if (mips_regnum (gdbarch)->dspacc != -1 && num >= 66 && num < 72)
7949     regnum = num + mips_regnum (gdbarch)->dspacc - 66;
7950   else
7951     /* This will hopefully (eventually) provoke a warning.  Should we
7952        be calling complaint() here?  */
7953     return gdbarch_num_regs (gdbarch) + gdbarch_num_pseudo_regs (gdbarch);
7954   return gdbarch_num_regs (gdbarch) + regnum;
7955 }
7956
7957 static int
7958 mips_register_sim_regno (struct gdbarch *gdbarch, int regnum)
7959 {
7960   /* Only makes sense to supply raw registers.  */
7961   gdb_assert (regnum >= 0 && regnum < gdbarch_num_regs (gdbarch));
7962   /* FIXME: cagney/2002-05-13: Need to look at the pseudo register to
7963      decide if it is valid.  Should instead define a standard sim/gdb
7964      register numbering scheme.  */
7965   if (gdbarch_register_name (gdbarch,
7966                              gdbarch_num_regs (gdbarch) + regnum) != NULL
7967       && gdbarch_register_name (gdbarch,
7968                                 gdbarch_num_regs (gdbarch)
7969                                 + regnum)[0] != '\0')
7970     return regnum;
7971   else
7972     return LEGACY_SIM_REGNO_IGNORE;
7973 }
7974
7975
7976 /* Convert an integer into an address.  Extracting the value signed
7977    guarantees a correctly sign extended address.  */
7978
7979 static CORE_ADDR
7980 mips_integer_to_address (struct gdbarch *gdbarch,
7981                          struct type *type, const gdb_byte *buf)
7982 {
7983   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
7984   return extract_signed_integer (buf, TYPE_LENGTH (type), byte_order);
7985 }
7986
7987 /* Dummy virtual frame pointer method.  This is no more or less accurate
7988    than most other architectures; we just need to be explicit about it,
7989    because the pseudo-register gdbarch_sp_regnum will otherwise lead to
7990    an assertion failure.  */
7991
7992 static void
7993 mips_virtual_frame_pointer (struct gdbarch *gdbarch, 
7994                             CORE_ADDR pc, int *reg, LONGEST *offset)
7995 {
7996   *reg = MIPS_SP_REGNUM;
7997   *offset = 0;
7998 }
7999
8000 static void
8001 mips_find_abi_section (bfd *abfd, asection *sect, void *obj)
8002 {
8003   enum mips_abi *abip = (enum mips_abi *) obj;
8004   const char *name = bfd_get_section_name (abfd, sect);
8005
8006   if (*abip != MIPS_ABI_UNKNOWN)
8007     return;
8008
8009   if (strncmp (name, ".mdebug.", 8) != 0)
8010     return;
8011
8012   if (strcmp (name, ".mdebug.abi32") == 0)
8013     *abip = MIPS_ABI_O32;
8014   else if (strcmp (name, ".mdebug.abiN32") == 0)
8015     *abip = MIPS_ABI_N32;
8016   else if (strcmp (name, ".mdebug.abi64") == 0)
8017     *abip = MIPS_ABI_N64;
8018   else if (strcmp (name, ".mdebug.abiO64") == 0)
8019     *abip = MIPS_ABI_O64;
8020   else if (strcmp (name, ".mdebug.eabi32") == 0)
8021     *abip = MIPS_ABI_EABI32;
8022   else if (strcmp (name, ".mdebug.eabi64") == 0)
8023     *abip = MIPS_ABI_EABI64;
8024   else
8025     warning (_("unsupported ABI %s."), name + 8);
8026 }
8027
8028 static void
8029 mips_find_long_section (bfd *abfd, asection *sect, void *obj)
8030 {
8031   int *lbp = (int *) obj;
8032   const char *name = bfd_get_section_name (abfd, sect);
8033
8034   if (strncmp (name, ".gcc_compiled_long32", 20) == 0)
8035     *lbp = 32;
8036   else if (strncmp (name, ".gcc_compiled_long64", 20) == 0)
8037     *lbp = 64;
8038   else if (strncmp (name, ".gcc_compiled_long", 18) == 0)
8039     warning (_("unrecognized .gcc_compiled_longXX"));
8040 }
8041
8042 static enum mips_abi
8043 global_mips_abi (void)
8044 {
8045   int i;
8046
8047   for (i = 0; mips_abi_strings[i] != NULL; i++)
8048     if (mips_abi_strings[i] == mips_abi_string)
8049       return (enum mips_abi) i;
8050
8051   internal_error (__FILE__, __LINE__, _("unknown ABI string"));
8052 }
8053
8054 /* Return the default compressed instruction set, either of MIPS16
8055    or microMIPS, selected when none could have been determined from
8056    the ELF header of the binary being executed (or no binary has been
8057    selected.  */
8058
8059 static enum mips_isa
8060 global_mips_compression (void)
8061 {
8062   int i;
8063
8064   for (i = 0; mips_compression_strings[i] != NULL; i++)
8065     if (mips_compression_strings[i] == mips_compression_string)
8066       return (enum mips_isa) i;
8067
8068   internal_error (__FILE__, __LINE__, _("unknown compressed ISA string"));
8069 }
8070
8071 static void
8072 mips_register_g_packet_guesses (struct gdbarch *gdbarch)
8073 {
8074   /* If the size matches the set of 32-bit or 64-bit integer registers,
8075      assume that's what we've got.  */
8076   register_remote_g_packet_guess (gdbarch, 38 * 4, mips_tdesc_gp32);
8077   register_remote_g_packet_guess (gdbarch, 38 * 8, mips_tdesc_gp64);
8078
8079   /* If the size matches the full set of registers GDB traditionally
8080      knows about, including floating point, for either 32-bit or
8081      64-bit, assume that's what we've got.  */
8082   register_remote_g_packet_guess (gdbarch, 90 * 4, mips_tdesc_gp32);
8083   register_remote_g_packet_guess (gdbarch, 90 * 8, mips_tdesc_gp64);
8084
8085   /* Otherwise we don't have a useful guess.  */
8086 }
8087
8088 static struct value *
8089 value_of_mips_user_reg (struct frame_info *frame, const void *baton)
8090 {
8091   const int *reg_p = baton;
8092   return value_of_register (*reg_p, frame);
8093 }
8094
8095 static struct gdbarch *
8096 mips_gdbarch_init (struct gdbarch_info info, struct gdbarch_list *arches)
8097 {
8098   struct gdbarch *gdbarch;
8099   struct gdbarch_tdep *tdep;
8100   int elf_flags;
8101   enum mips_abi mips_abi, found_abi, wanted_abi;
8102   int i, num_regs;
8103   enum mips_fpu_type fpu_type;
8104   struct tdesc_arch_data *tdesc_data = NULL;
8105   int elf_fpu_type = Val_GNU_MIPS_ABI_FP_ANY;
8106   const char **reg_names;
8107   struct mips_regnum mips_regnum, *regnum;
8108   enum mips_isa mips_isa;
8109   int dspacc;
8110   int dspctl;
8111
8112   /* Fill in the OS dependent register numbers and names.  */
8113   if (info.osabi == GDB_OSABI_IRIX)
8114     {
8115       mips_regnum.fp0 = 32;
8116       mips_regnum.pc = 64;
8117       mips_regnum.cause = 65;
8118       mips_regnum.badvaddr = 66;
8119       mips_regnum.hi = 67;
8120       mips_regnum.lo = 68;
8121       mips_regnum.fp_control_status = 69;
8122       mips_regnum.fp_implementation_revision = 70;
8123       mips_regnum.dspacc = dspacc = -1;
8124       mips_regnum.dspctl = dspctl = -1;
8125       num_regs = 71;
8126       reg_names = mips_irix_reg_names;
8127     }
8128   else if (info.osabi == GDB_OSABI_LINUX)
8129     {
8130       mips_regnum.fp0 = 38;
8131       mips_regnum.pc = 37;
8132       mips_regnum.cause = 36;
8133       mips_regnum.badvaddr = 35;
8134       mips_regnum.hi = 34;
8135       mips_regnum.lo = 33;
8136       mips_regnum.fp_control_status = 70;
8137       mips_regnum.fp_implementation_revision = 71;
8138       mips_regnum.dspacc = -1;
8139       mips_regnum.dspctl = -1;
8140       dspacc = 72;
8141       dspctl = 78;
8142       num_regs = 79;
8143       reg_names = mips_linux_reg_names;
8144     }
8145   else
8146     {
8147       mips_regnum.lo = MIPS_EMBED_LO_REGNUM;
8148       mips_regnum.hi = MIPS_EMBED_HI_REGNUM;
8149       mips_regnum.badvaddr = MIPS_EMBED_BADVADDR_REGNUM;
8150       mips_regnum.cause = MIPS_EMBED_CAUSE_REGNUM;
8151       mips_regnum.pc = MIPS_EMBED_PC_REGNUM;
8152       mips_regnum.fp0 = MIPS_EMBED_FP0_REGNUM;
8153       mips_regnum.fp_control_status = 70;
8154       mips_regnum.fp_implementation_revision = 71;
8155       mips_regnum.dspacc = dspacc = -1;
8156       mips_regnum.dspctl = dspctl = -1;
8157       num_regs = MIPS_LAST_EMBED_REGNUM + 1;
8158       if (info.bfd_arch_info != NULL
8159           && info.bfd_arch_info->mach == bfd_mach_mips3900)
8160         reg_names = mips_tx39_reg_names;
8161       else
8162         reg_names = mips_generic_reg_names;
8163     }
8164
8165   /* Check any target description for validity.  */
8166   if (tdesc_has_registers (info.target_desc))
8167     {
8168       static const char *const mips_gprs[] = {
8169         "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
8170         "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
8171         "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
8172         "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31"
8173       };
8174       static const char *const mips_fprs[] = {
8175         "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7",
8176         "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15",
8177         "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23",
8178         "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31",
8179       };
8180
8181       const struct tdesc_feature *feature;
8182       int valid_p;
8183
8184       feature = tdesc_find_feature (info.target_desc,
8185                                     "org.gnu.gdb.mips.cpu");
8186       if (feature == NULL)
8187         return NULL;
8188
8189       tdesc_data = tdesc_data_alloc ();
8190
8191       valid_p = 1;
8192       for (i = MIPS_ZERO_REGNUM; i <= MIPS_RA_REGNUM; i++)
8193         valid_p &= tdesc_numbered_register (feature, tdesc_data, i,
8194                                             mips_gprs[i]);
8195
8196
8197       valid_p &= tdesc_numbered_register (feature, tdesc_data,
8198                                           mips_regnum.lo, "lo");
8199       valid_p &= tdesc_numbered_register (feature, tdesc_data,
8200                                           mips_regnum.hi, "hi");
8201       valid_p &= tdesc_numbered_register (feature, tdesc_data,
8202                                           mips_regnum.pc, "pc");
8203
8204       if (!valid_p)
8205         {
8206           tdesc_data_cleanup (tdesc_data);
8207           return NULL;
8208         }
8209
8210       feature = tdesc_find_feature (info.target_desc,
8211                                     "org.gnu.gdb.mips.cp0");
8212       if (feature == NULL)
8213         {
8214           tdesc_data_cleanup (tdesc_data);
8215           return NULL;
8216         }
8217
8218       valid_p = 1;
8219       valid_p &= tdesc_numbered_register (feature, tdesc_data,
8220                                           mips_regnum.badvaddr, "badvaddr");
8221       valid_p &= tdesc_numbered_register (feature, tdesc_data,
8222                                           MIPS_PS_REGNUM, "status");
8223       valid_p &= tdesc_numbered_register (feature, tdesc_data,
8224                                           mips_regnum.cause, "cause");
8225
8226       if (!valid_p)
8227         {
8228           tdesc_data_cleanup (tdesc_data);
8229           return NULL;
8230         }
8231
8232       /* FIXME drow/2007-05-17: The FPU should be optional.  The MIPS
8233          backend is not prepared for that, though.  */
8234       feature = tdesc_find_feature (info.target_desc,
8235                                     "org.gnu.gdb.mips.fpu");
8236       if (feature == NULL)
8237         {
8238           tdesc_data_cleanup (tdesc_data);
8239           return NULL;
8240         }
8241
8242       valid_p = 1;
8243       for (i = 0; i < 32; i++)
8244         valid_p &= tdesc_numbered_register (feature, tdesc_data,
8245                                             i + mips_regnum.fp0, mips_fprs[i]);
8246
8247       valid_p &= tdesc_numbered_register (feature, tdesc_data,
8248                                           mips_regnum.fp_control_status,
8249                                           "fcsr");
8250       valid_p
8251         &= tdesc_numbered_register (feature, tdesc_data,
8252                                     mips_regnum.fp_implementation_revision,
8253                                     "fir");
8254
8255       if (!valid_p)
8256         {
8257           tdesc_data_cleanup (tdesc_data);
8258           return NULL;
8259         }
8260
8261       if (dspacc >= 0)
8262         {
8263           feature = tdesc_find_feature (info.target_desc,
8264                                         "org.gnu.gdb.mips.dsp");
8265           /* The DSP registers are optional; it's OK if they are absent.  */
8266           if (feature != NULL)
8267             {
8268               i = 0;
8269               valid_p = 1;
8270               valid_p &= tdesc_numbered_register (feature, tdesc_data,
8271                                                   dspacc + i++, "hi1");
8272               valid_p &= tdesc_numbered_register (feature, tdesc_data,
8273                                                   dspacc + i++, "lo1");
8274               valid_p &= tdesc_numbered_register (feature, tdesc_data,
8275                                                   dspacc + i++, "hi2");
8276               valid_p &= tdesc_numbered_register (feature, tdesc_data,
8277                                                   dspacc + i++, "lo2");
8278               valid_p &= tdesc_numbered_register (feature, tdesc_data,
8279                                                   dspacc + i++, "hi3");
8280               valid_p &= tdesc_numbered_register (feature, tdesc_data,
8281                                                   dspacc + i++, "lo3");
8282
8283               valid_p &= tdesc_numbered_register (feature, tdesc_data,
8284                                                   dspctl, "dspctl");
8285
8286               if (!valid_p)
8287                 {
8288                   tdesc_data_cleanup (tdesc_data);
8289                   return NULL;
8290                 }
8291
8292               mips_regnum.dspacc = dspacc;
8293               mips_regnum.dspctl = dspctl;
8294             }
8295         }
8296
8297       /* It would be nice to detect an attempt to use a 64-bit ABI
8298          when only 32-bit registers are provided.  */
8299       reg_names = NULL;
8300     }
8301
8302   /* First of all, extract the elf_flags, if available.  */
8303   if (info.abfd && bfd_get_flavour (info.abfd) == bfd_target_elf_flavour)
8304     elf_flags = elf_elfheader (info.abfd)->e_flags;
8305   else if (arches != NULL)
8306     elf_flags = gdbarch_tdep (arches->gdbarch)->elf_flags;
8307   else
8308     elf_flags = 0;
8309   if (gdbarch_debug)
8310     fprintf_unfiltered (gdb_stdlog,
8311                         "mips_gdbarch_init: elf_flags = 0x%08x\n", elf_flags);
8312
8313   /* Check ELF_FLAGS to see if it specifies the ABI being used.  */
8314   switch ((elf_flags & EF_MIPS_ABI))
8315     {
8316     case E_MIPS_ABI_O32:
8317       found_abi = MIPS_ABI_O32;
8318       break;
8319     case E_MIPS_ABI_O64:
8320       found_abi = MIPS_ABI_O64;
8321       break;
8322     case E_MIPS_ABI_EABI32:
8323       found_abi = MIPS_ABI_EABI32;
8324       break;
8325     case E_MIPS_ABI_EABI64:
8326       found_abi = MIPS_ABI_EABI64;
8327       break;
8328     default:
8329       if ((elf_flags & EF_MIPS_ABI2))
8330         found_abi = MIPS_ABI_N32;
8331       else
8332         found_abi = MIPS_ABI_UNKNOWN;
8333       break;
8334     }
8335
8336   /* GCC creates a pseudo-section whose name describes the ABI.  */
8337   if (found_abi == MIPS_ABI_UNKNOWN && info.abfd != NULL)
8338     bfd_map_over_sections (info.abfd, mips_find_abi_section, &found_abi);
8339
8340   /* If we have no useful BFD information, use the ABI from the last
8341      MIPS architecture (if there is one).  */
8342   if (found_abi == MIPS_ABI_UNKNOWN && info.abfd == NULL && arches != NULL)
8343     found_abi = gdbarch_tdep (arches->gdbarch)->found_abi;
8344
8345   /* Try the architecture for any hint of the correct ABI.  */
8346   if (found_abi == MIPS_ABI_UNKNOWN
8347       && info.bfd_arch_info != NULL
8348       && info.bfd_arch_info->arch == bfd_arch_mips)
8349     {
8350       switch (info.bfd_arch_info->mach)
8351         {
8352         case bfd_mach_mips3900:
8353           found_abi = MIPS_ABI_EABI32;
8354           break;
8355         case bfd_mach_mips4100:
8356         case bfd_mach_mips5000:
8357           found_abi = MIPS_ABI_EABI64;
8358           break;
8359         case bfd_mach_mips8000:
8360         case bfd_mach_mips10000:
8361           /* On Irix, ELF64 executables use the N64 ABI.  The
8362              pseudo-sections which describe the ABI aren't present
8363              on IRIX.  (Even for executables created by gcc.)  */
8364           if (bfd_get_flavour (info.abfd) == bfd_target_elf_flavour
8365               && elf_elfheader (info.abfd)->e_ident[EI_CLASS] == ELFCLASS64)
8366             found_abi = MIPS_ABI_N64;
8367           else
8368             found_abi = MIPS_ABI_N32;
8369           break;
8370         }
8371     }
8372
8373   /* Default 64-bit objects to N64 instead of O32.  */
8374   if (found_abi == MIPS_ABI_UNKNOWN
8375       && info.abfd != NULL
8376       && bfd_get_flavour (info.abfd) == bfd_target_elf_flavour
8377       && elf_elfheader (info.abfd)->e_ident[EI_CLASS] == ELFCLASS64)
8378     found_abi = MIPS_ABI_N64;
8379
8380   if (gdbarch_debug)
8381     fprintf_unfiltered (gdb_stdlog, "mips_gdbarch_init: found_abi = %d\n",
8382                         found_abi);
8383
8384   /* What has the user specified from the command line?  */
8385   wanted_abi = global_mips_abi ();
8386   if (gdbarch_debug)
8387     fprintf_unfiltered (gdb_stdlog, "mips_gdbarch_init: wanted_abi = %d\n",
8388                         wanted_abi);
8389
8390   /* Now that we have found what the ABI for this binary would be,
8391      check whether the user is overriding it.  */
8392   if (wanted_abi != MIPS_ABI_UNKNOWN)
8393     mips_abi = wanted_abi;
8394   else if (found_abi != MIPS_ABI_UNKNOWN)
8395     mips_abi = found_abi;
8396   else
8397     mips_abi = MIPS_ABI_O32;
8398   if (gdbarch_debug)
8399     fprintf_unfiltered (gdb_stdlog, "mips_gdbarch_init: mips_abi = %d\n",
8400                         mips_abi);
8401
8402   /* Determine the default compressed ISA.  */
8403   if ((elf_flags & EF_MIPS_ARCH_ASE_MICROMIPS) != 0
8404       && (elf_flags & EF_MIPS_ARCH_ASE_M16) == 0)
8405     mips_isa = ISA_MICROMIPS;
8406   else if ((elf_flags & EF_MIPS_ARCH_ASE_M16) != 0
8407            && (elf_flags & EF_MIPS_ARCH_ASE_MICROMIPS) == 0)
8408     mips_isa = ISA_MIPS16;
8409   else
8410     mips_isa = global_mips_compression ();
8411   mips_compression_string = mips_compression_strings[mips_isa];
8412
8413   /* Also used when doing an architecture lookup.  */
8414   if (gdbarch_debug)
8415     fprintf_unfiltered (gdb_stdlog,
8416                         "mips_gdbarch_init: "
8417                         "mips64_transfers_32bit_regs_p = %d\n",
8418                         mips64_transfers_32bit_regs_p);
8419
8420   /* Determine the MIPS FPU type.  */
8421 #ifdef HAVE_ELF
8422   if (info.abfd
8423       && bfd_get_flavour (info.abfd) == bfd_target_elf_flavour)
8424     elf_fpu_type = bfd_elf_get_obj_attr_int (info.abfd, OBJ_ATTR_GNU,
8425                                              Tag_GNU_MIPS_ABI_FP);
8426 #endif /* HAVE_ELF */
8427
8428   if (!mips_fpu_type_auto)
8429     fpu_type = mips_fpu_type;
8430   else if (elf_fpu_type != Val_GNU_MIPS_ABI_FP_ANY)
8431     {
8432       switch (elf_fpu_type)
8433         {
8434         case Val_GNU_MIPS_ABI_FP_DOUBLE:
8435           fpu_type = MIPS_FPU_DOUBLE;
8436           break;
8437         case Val_GNU_MIPS_ABI_FP_SINGLE:
8438           fpu_type = MIPS_FPU_SINGLE;
8439           break;
8440         case Val_GNU_MIPS_ABI_FP_SOFT:
8441         default:
8442           /* Soft float or unknown.  */
8443           fpu_type = MIPS_FPU_NONE;
8444           break;
8445         }
8446     }
8447   else if (info.bfd_arch_info != NULL
8448            && info.bfd_arch_info->arch == bfd_arch_mips)
8449     switch (info.bfd_arch_info->mach)
8450       {
8451       case bfd_mach_mips3900:
8452       case bfd_mach_mips4100:
8453       case bfd_mach_mips4111:
8454       case bfd_mach_mips4120:
8455         fpu_type = MIPS_FPU_NONE;
8456         break;
8457       case bfd_mach_mips4650:
8458         fpu_type = MIPS_FPU_SINGLE;
8459         break;
8460       default:
8461         fpu_type = MIPS_FPU_DOUBLE;
8462         break;
8463       }
8464   else if (arches != NULL)
8465     fpu_type = gdbarch_tdep (arches->gdbarch)->mips_fpu_type;
8466   else
8467     fpu_type = MIPS_FPU_DOUBLE;
8468   if (gdbarch_debug)
8469     fprintf_unfiltered (gdb_stdlog,
8470                         "mips_gdbarch_init: fpu_type = %d\n", fpu_type);
8471
8472   /* Check for blatant incompatibilities.  */
8473
8474   /* If we have only 32-bit registers, then we can't debug a 64-bit
8475      ABI.  */
8476   if (info.target_desc
8477       && tdesc_property (info.target_desc, PROPERTY_GP32) != NULL
8478       && mips_abi != MIPS_ABI_EABI32
8479       && mips_abi != MIPS_ABI_O32)
8480     {
8481       if (tdesc_data != NULL)
8482         tdesc_data_cleanup (tdesc_data);
8483       return NULL;
8484     }
8485
8486   /* Try to find a pre-existing architecture.  */
8487   for (arches = gdbarch_list_lookup_by_info (arches, &info);
8488        arches != NULL;
8489        arches = gdbarch_list_lookup_by_info (arches->next, &info))
8490     {
8491       /* MIPS needs to be pedantic about which ABI and the compressed
8492          ISA variation the object is using.  */
8493       if (gdbarch_tdep (arches->gdbarch)->elf_flags != elf_flags)
8494         continue;
8495       if (gdbarch_tdep (arches->gdbarch)->mips_abi != mips_abi)
8496         continue;
8497       if (gdbarch_tdep (arches->gdbarch)->mips_isa != mips_isa)
8498         continue;
8499       /* Need to be pedantic about which register virtual size is
8500          used.  */
8501       if (gdbarch_tdep (arches->gdbarch)->mips64_transfers_32bit_regs_p
8502           != mips64_transfers_32bit_regs_p)
8503         continue;
8504       /* Be pedantic about which FPU is selected.  */
8505       if (gdbarch_tdep (arches->gdbarch)->mips_fpu_type != fpu_type)
8506         continue;
8507
8508       if (tdesc_data != NULL)
8509         tdesc_data_cleanup (tdesc_data);
8510       return arches->gdbarch;
8511     }
8512
8513   /* Need a new architecture.  Fill in a target specific vector.  */
8514   tdep = (struct gdbarch_tdep *) xmalloc (sizeof (struct gdbarch_tdep));
8515   gdbarch = gdbarch_alloc (&info, tdep);
8516   tdep->elf_flags = elf_flags;
8517   tdep->mips64_transfers_32bit_regs_p = mips64_transfers_32bit_regs_p;
8518   tdep->found_abi = found_abi;
8519   tdep->mips_abi = mips_abi;
8520   tdep->mips_isa = mips_isa;
8521   tdep->mips_fpu_type = fpu_type;
8522   tdep->register_size_valid_p = 0;
8523   tdep->register_size = 0;
8524
8525   if (info.target_desc)
8526     {
8527       /* Some useful properties can be inferred from the target.  */
8528       if (tdesc_property (info.target_desc, PROPERTY_GP32) != NULL)
8529         {
8530           tdep->register_size_valid_p = 1;
8531           tdep->register_size = 4;
8532         }
8533       else if (tdesc_property (info.target_desc, PROPERTY_GP64) != NULL)
8534         {
8535           tdep->register_size_valid_p = 1;
8536           tdep->register_size = 8;
8537         }
8538     }
8539
8540   /* Initially set everything according to the default ABI/ISA.  */
8541   set_gdbarch_short_bit (gdbarch, 16);
8542   set_gdbarch_int_bit (gdbarch, 32);
8543   set_gdbarch_float_bit (gdbarch, 32);
8544   set_gdbarch_double_bit (gdbarch, 64);
8545   set_gdbarch_long_double_bit (gdbarch, 64);
8546   set_gdbarch_register_reggroup_p (gdbarch, mips_register_reggroup_p);
8547   set_gdbarch_pseudo_register_read (gdbarch, mips_pseudo_register_read);
8548   set_gdbarch_pseudo_register_write (gdbarch, mips_pseudo_register_write);
8549
8550   set_gdbarch_ax_pseudo_register_collect (gdbarch,
8551                                           mips_ax_pseudo_register_collect);
8552   set_gdbarch_ax_pseudo_register_push_stack
8553       (gdbarch, mips_ax_pseudo_register_push_stack);
8554
8555   set_gdbarch_elf_make_msymbol_special (gdbarch,
8556                                         mips_elf_make_msymbol_special);
8557   set_gdbarch_make_symbol_special (gdbarch, mips_make_symbol_special);
8558   set_gdbarch_adjust_dwarf2_addr (gdbarch, mips_adjust_dwarf2_addr);
8559   set_gdbarch_adjust_dwarf2_line (gdbarch, mips_adjust_dwarf2_line);
8560
8561   regnum = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct mips_regnum);
8562   *regnum = mips_regnum;
8563   set_gdbarch_fp0_regnum (gdbarch, regnum->fp0);
8564   set_gdbarch_num_regs (gdbarch, num_regs);
8565   set_gdbarch_num_pseudo_regs (gdbarch, num_regs);
8566   set_gdbarch_register_name (gdbarch, mips_register_name);
8567   set_gdbarch_virtual_frame_pointer (gdbarch, mips_virtual_frame_pointer);
8568   tdep->mips_processor_reg_names = reg_names;
8569   tdep->regnum = regnum;
8570
8571   switch (mips_abi)
8572     {
8573     case MIPS_ABI_O32:
8574       set_gdbarch_push_dummy_call (gdbarch, mips_o32_push_dummy_call);
8575       set_gdbarch_return_value (gdbarch, mips_o32_return_value);
8576       tdep->mips_last_arg_regnum = MIPS_A0_REGNUM + 4 - 1;
8577       tdep->mips_last_fp_arg_regnum = tdep->regnum->fp0 + 12 + 4 - 1;
8578       tdep->default_mask_address_p = 0;
8579       set_gdbarch_long_bit (gdbarch, 32);
8580       set_gdbarch_ptr_bit (gdbarch, 32);
8581       set_gdbarch_long_long_bit (gdbarch, 64);
8582       break;
8583     case MIPS_ABI_O64:
8584       set_gdbarch_push_dummy_call (gdbarch, mips_o64_push_dummy_call);
8585       set_gdbarch_return_value (gdbarch, mips_o64_return_value);
8586       tdep->mips_last_arg_regnum = MIPS_A0_REGNUM + 4 - 1;
8587       tdep->mips_last_fp_arg_regnum = tdep->regnum->fp0 + 12 + 4 - 1;
8588       tdep->default_mask_address_p = 0;
8589       set_gdbarch_long_bit (gdbarch, 32);
8590       set_gdbarch_ptr_bit (gdbarch, 32);
8591       set_gdbarch_long_long_bit (gdbarch, 64);
8592       break;
8593     case MIPS_ABI_EABI32:
8594       set_gdbarch_push_dummy_call (gdbarch, mips_eabi_push_dummy_call);
8595       set_gdbarch_return_value (gdbarch, mips_eabi_return_value);
8596       tdep->mips_last_arg_regnum = MIPS_A0_REGNUM + 8 - 1;
8597       tdep->mips_last_fp_arg_regnum = tdep->regnum->fp0 + 12 + 8 - 1;
8598       tdep->default_mask_address_p = 0;
8599       set_gdbarch_long_bit (gdbarch, 32);
8600       set_gdbarch_ptr_bit (gdbarch, 32);
8601       set_gdbarch_long_long_bit (gdbarch, 64);
8602       break;
8603     case MIPS_ABI_EABI64:
8604       set_gdbarch_push_dummy_call (gdbarch, mips_eabi_push_dummy_call);
8605       set_gdbarch_return_value (gdbarch, mips_eabi_return_value);
8606       tdep->mips_last_arg_regnum = MIPS_A0_REGNUM + 8 - 1;
8607       tdep->mips_last_fp_arg_regnum = tdep->regnum->fp0 + 12 + 8 - 1;
8608       tdep->default_mask_address_p = 0;
8609       set_gdbarch_long_bit (gdbarch, 64);
8610       set_gdbarch_ptr_bit (gdbarch, 64);
8611       set_gdbarch_long_long_bit (gdbarch, 64);
8612       break;
8613     case MIPS_ABI_N32:
8614       set_gdbarch_push_dummy_call (gdbarch, mips_n32n64_push_dummy_call);
8615       set_gdbarch_return_value (gdbarch, mips_n32n64_return_value);
8616       tdep->mips_last_arg_regnum = MIPS_A0_REGNUM + 8 - 1;
8617       tdep->mips_last_fp_arg_regnum = tdep->regnum->fp0 + 12 + 8 - 1;
8618       tdep->default_mask_address_p = 0;
8619       set_gdbarch_long_bit (gdbarch, 32);
8620       set_gdbarch_ptr_bit (gdbarch, 32);
8621       set_gdbarch_long_long_bit (gdbarch, 64);
8622       set_gdbarch_long_double_bit (gdbarch, 128);
8623       set_gdbarch_long_double_format (gdbarch, floatformats_ibm_long_double);
8624       break;
8625     case MIPS_ABI_N64:
8626       set_gdbarch_push_dummy_call (gdbarch, mips_n32n64_push_dummy_call);
8627       set_gdbarch_return_value (gdbarch, mips_n32n64_return_value);
8628       tdep->mips_last_arg_regnum = MIPS_A0_REGNUM + 8 - 1;
8629       tdep->mips_last_fp_arg_regnum = tdep->regnum->fp0 + 12 + 8 - 1;
8630       tdep->default_mask_address_p = 0;
8631       set_gdbarch_long_bit (gdbarch, 64);
8632       set_gdbarch_ptr_bit (gdbarch, 64);
8633       set_gdbarch_long_long_bit (gdbarch, 64);
8634       set_gdbarch_long_double_bit (gdbarch, 128);
8635       set_gdbarch_long_double_format (gdbarch, floatformats_ibm_long_double);
8636       break;
8637     default:
8638       internal_error (__FILE__, __LINE__, _("unknown ABI in switch"));
8639     }
8640
8641   /* GCC creates a pseudo-section whose name specifies the size of
8642      longs, since -mlong32 or -mlong64 may be used independent of
8643      other options.  How those options affect pointer sizes is ABI and
8644      architecture dependent, so use them to override the default sizes
8645      set by the ABI.  This table shows the relationship between ABI,
8646      -mlongXX, and size of pointers:
8647
8648      ABI                -mlongXX        ptr bits
8649      ---                --------        --------
8650      o32                32              32
8651      o32                64              32
8652      n32                32              32
8653      n32                64              64
8654      o64                32              32
8655      o64                64              64
8656      n64                32              32
8657      n64                64              64
8658      eabi32             32              32
8659      eabi32             64              32
8660      eabi64             32              32
8661      eabi64             64              64
8662
8663     Note that for o32 and eabi32, pointers are always 32 bits
8664     regardless of any -mlongXX option.  For all others, pointers and
8665     longs are the same, as set by -mlongXX or set by defaults.  */
8666
8667   if (info.abfd != NULL)
8668     {
8669       int long_bit = 0;
8670
8671       bfd_map_over_sections (info.abfd, mips_find_long_section, &long_bit);
8672       if (long_bit)
8673         {
8674           set_gdbarch_long_bit (gdbarch, long_bit);
8675           switch (mips_abi)
8676             {
8677             case MIPS_ABI_O32:
8678             case MIPS_ABI_EABI32:
8679               break;
8680             case MIPS_ABI_N32:
8681             case MIPS_ABI_O64:
8682             case MIPS_ABI_N64:
8683             case MIPS_ABI_EABI64:
8684               set_gdbarch_ptr_bit (gdbarch, long_bit);
8685               break;
8686             default:
8687               internal_error (__FILE__, __LINE__, _("unknown ABI in switch"));
8688             }
8689         }
8690     }
8691
8692   /* FIXME: jlarmour/2000-04-07: There *is* a flag EF_MIPS_32BIT_MODE
8693      that could indicate -gp32 BUT gas/config/tc-mips.c contains the
8694      comment:
8695
8696      ``We deliberately don't allow "-gp32" to set the MIPS_32BITMODE
8697      flag in object files because to do so would make it impossible to
8698      link with libraries compiled without "-gp32".  This is
8699      unnecessarily restrictive.
8700
8701      We could solve this problem by adding "-gp32" multilibs to gcc,
8702      but to set this flag before gcc is built with such multilibs will
8703      break too many systems.''
8704
8705      But even more unhelpfully, the default linker output target for
8706      mips64-elf is elf32-bigmips, and has EF_MIPS_32BIT_MODE set, even
8707      for 64-bit programs - you need to change the ABI to change this,
8708      and not all gcc targets support that currently.  Therefore using
8709      this flag to detect 32-bit mode would do the wrong thing given
8710      the current gcc - it would make GDB treat these 64-bit programs
8711      as 32-bit programs by default.  */
8712
8713   set_gdbarch_read_pc (gdbarch, mips_read_pc);
8714   set_gdbarch_write_pc (gdbarch, mips_write_pc);
8715
8716   /* Add/remove bits from an address.  The MIPS needs be careful to
8717      ensure that all 32 bit addresses are sign extended to 64 bits.  */
8718   set_gdbarch_addr_bits_remove (gdbarch, mips_addr_bits_remove);
8719
8720   /* Unwind the frame.  */
8721   set_gdbarch_unwind_pc (gdbarch, mips_unwind_pc);
8722   set_gdbarch_unwind_sp (gdbarch, mips_unwind_sp);
8723   set_gdbarch_dummy_id (gdbarch, mips_dummy_id);
8724
8725   /* Map debug register numbers onto internal register numbers.  */
8726   set_gdbarch_stab_reg_to_regnum (gdbarch, mips_stab_reg_to_regnum);
8727   set_gdbarch_ecoff_reg_to_regnum (gdbarch,
8728                                    mips_dwarf_dwarf2_ecoff_reg_to_regnum);
8729   set_gdbarch_dwarf2_reg_to_regnum (gdbarch,
8730                                     mips_dwarf_dwarf2_ecoff_reg_to_regnum);
8731   set_gdbarch_register_sim_regno (gdbarch, mips_register_sim_regno);
8732
8733   /* MIPS version of CALL_DUMMY.  */
8734
8735   set_gdbarch_call_dummy_location (gdbarch, ON_STACK);
8736   set_gdbarch_push_dummy_code (gdbarch, mips_push_dummy_code);
8737   set_gdbarch_frame_align (gdbarch, mips_frame_align);
8738
8739   set_gdbarch_convert_register_p (gdbarch, mips_convert_register_p);
8740   set_gdbarch_register_to_value (gdbarch, mips_register_to_value);
8741   set_gdbarch_value_to_register (gdbarch, mips_value_to_register);
8742
8743   set_gdbarch_inner_than (gdbarch, core_addr_lessthan);
8744   set_gdbarch_breakpoint_from_pc (gdbarch, mips_breakpoint_from_pc);
8745   set_gdbarch_remote_breakpoint_from_pc (gdbarch,
8746                                          mips_remote_breakpoint_from_pc);
8747   set_gdbarch_adjust_breakpoint_address (gdbarch,
8748                                          mips_adjust_breakpoint_address);
8749
8750   set_gdbarch_skip_prologue (gdbarch, mips_skip_prologue);
8751
8752   set_gdbarch_in_function_epilogue_p (gdbarch, mips_in_function_epilogue_p);
8753
8754   set_gdbarch_pointer_to_address (gdbarch, signed_pointer_to_address);
8755   set_gdbarch_address_to_pointer (gdbarch, address_to_signed_pointer);
8756   set_gdbarch_integer_to_address (gdbarch, mips_integer_to_address);
8757
8758   set_gdbarch_register_type (gdbarch, mips_register_type);
8759
8760   set_gdbarch_print_registers_info (gdbarch, mips_print_registers_info);
8761
8762   if (mips_abi == MIPS_ABI_N32)
8763     set_gdbarch_print_insn (gdbarch, gdb_print_insn_mips_n32);
8764   else if (mips_abi == MIPS_ABI_N64)
8765     set_gdbarch_print_insn (gdbarch, gdb_print_insn_mips_n64);
8766   else
8767     set_gdbarch_print_insn (gdbarch, gdb_print_insn_mips);
8768
8769   /* FIXME: cagney/2003-08-29: The macros target_have_steppable_watchpoint,
8770      HAVE_NONSTEPPABLE_WATCHPOINT, and target_have_continuable_watchpoint
8771      need to all be folded into the target vector.  Since they are
8772      being used as guards for target_stopped_by_watchpoint, why not have
8773      target_stopped_by_watchpoint return the type of watchpoint that the code
8774      is sitting on?  */
8775   set_gdbarch_have_nonsteppable_watchpoint (gdbarch, 1);
8776
8777   set_gdbarch_skip_trampoline_code (gdbarch, mips_skip_trampoline_code);
8778
8779   /* NOTE drow/2012-04-25: We overload the core solib trampoline code
8780      to support MIPS16.  This is a bad thing.  Make sure not to do it
8781      if we have an OS ABI that actually supports shared libraries, since
8782      shared library support is more important.  If we have an OS someday
8783      that supports both shared libraries and MIPS16, we'll have to find
8784      a better place for these.
8785      macro/2012-04-25: But that applies to return trampolines only and
8786      currently no MIPS OS ABI uses shared libraries that have them.  */
8787   set_gdbarch_in_solib_return_trampoline (gdbarch, mips_in_return_stub);
8788
8789   set_gdbarch_single_step_through_delay (gdbarch,
8790                                          mips_single_step_through_delay);
8791
8792   /* Virtual tables.  */
8793   set_gdbarch_vbit_in_delta (gdbarch, 1);
8794
8795   mips_register_g_packet_guesses (gdbarch);
8796
8797   /* Hook in OS ABI-specific overrides, if they have been registered.  */
8798   info.tdep_info = (void *) tdesc_data;
8799   gdbarch_init_osabi (info, gdbarch);
8800
8801   /* The hook may have adjusted num_regs, fetch the final value and
8802      set pc_regnum and sp_regnum now that it has been fixed.  */
8803   num_regs = gdbarch_num_regs (gdbarch);
8804   set_gdbarch_pc_regnum (gdbarch, regnum->pc + num_regs);
8805   set_gdbarch_sp_regnum (gdbarch, MIPS_SP_REGNUM + num_regs);
8806
8807   /* Unwind the frame.  */
8808   dwarf2_append_unwinders (gdbarch);
8809   frame_unwind_append_unwinder (gdbarch, &mips_stub_frame_unwind);
8810   frame_unwind_append_unwinder (gdbarch, &mips_insn16_frame_unwind);
8811   frame_unwind_append_unwinder (gdbarch, &mips_micro_frame_unwind);
8812   frame_unwind_append_unwinder (gdbarch, &mips_insn32_frame_unwind);
8813   frame_base_append_sniffer (gdbarch, dwarf2_frame_base_sniffer);
8814   frame_base_append_sniffer (gdbarch, mips_stub_frame_base_sniffer);
8815   frame_base_append_sniffer (gdbarch, mips_insn16_frame_base_sniffer);
8816   frame_base_append_sniffer (gdbarch, mips_micro_frame_base_sniffer);
8817   frame_base_append_sniffer (gdbarch, mips_insn32_frame_base_sniffer);
8818
8819   if (tdesc_data)
8820     {
8821       set_tdesc_pseudo_register_type (gdbarch, mips_pseudo_register_type);
8822       tdesc_use_registers (gdbarch, info.target_desc, tdesc_data);
8823
8824       /* Override the normal target description methods to handle our
8825          dual real and pseudo registers.  */
8826       set_gdbarch_register_name (gdbarch, mips_register_name);
8827       set_gdbarch_register_reggroup_p (gdbarch,
8828                                        mips_tdesc_register_reggroup_p);
8829
8830       num_regs = gdbarch_num_regs (gdbarch);
8831       set_gdbarch_num_pseudo_regs (gdbarch, num_regs);
8832       set_gdbarch_pc_regnum (gdbarch, tdep->regnum->pc + num_regs);
8833       set_gdbarch_sp_regnum (gdbarch, MIPS_SP_REGNUM + num_regs);
8834     }
8835
8836   /* Add ABI-specific aliases for the registers.  */
8837   if (mips_abi == MIPS_ABI_N32 || mips_abi == MIPS_ABI_N64)
8838     for (i = 0; i < ARRAY_SIZE (mips_n32_n64_aliases); i++)
8839       user_reg_add (gdbarch, mips_n32_n64_aliases[i].name,
8840                     value_of_mips_user_reg, &mips_n32_n64_aliases[i].regnum);
8841   else
8842     for (i = 0; i < ARRAY_SIZE (mips_o32_aliases); i++)
8843       user_reg_add (gdbarch, mips_o32_aliases[i].name,
8844                     value_of_mips_user_reg, &mips_o32_aliases[i].regnum);
8845
8846   /* Add some other standard aliases.  */
8847   for (i = 0; i < ARRAY_SIZE (mips_register_aliases); i++)
8848     user_reg_add (gdbarch, mips_register_aliases[i].name,
8849                   value_of_mips_user_reg, &mips_register_aliases[i].regnum);
8850
8851   for (i = 0; i < ARRAY_SIZE (mips_numeric_register_aliases); i++)
8852     user_reg_add (gdbarch, mips_numeric_register_aliases[i].name,
8853                   value_of_mips_user_reg, 
8854                   &mips_numeric_register_aliases[i].regnum);
8855
8856   return gdbarch;
8857 }
8858
8859 static void
8860 mips_abi_update (char *ignore_args, int from_tty, struct cmd_list_element *c)
8861 {
8862   struct gdbarch_info info;
8863
8864   /* Force the architecture to update, and (if it's a MIPS architecture)
8865      mips_gdbarch_init will take care of the rest.  */
8866   gdbarch_info_init (&info);
8867   gdbarch_update_p (info);
8868 }
8869
8870 /* Print out which MIPS ABI is in use.  */
8871
8872 static void
8873 show_mips_abi (struct ui_file *file,
8874                int from_tty,
8875                struct cmd_list_element *ignored_cmd,
8876                const char *ignored_value)
8877 {
8878   if (gdbarch_bfd_arch_info (target_gdbarch ())->arch != bfd_arch_mips)
8879     fprintf_filtered
8880       (file, 
8881        "The MIPS ABI is unknown because the current architecture "
8882        "is not MIPS.\n");
8883   else
8884     {
8885       enum mips_abi global_abi = global_mips_abi ();
8886       enum mips_abi actual_abi = mips_abi (target_gdbarch ());
8887       const char *actual_abi_str = mips_abi_strings[actual_abi];
8888
8889       if (global_abi == MIPS_ABI_UNKNOWN)
8890         fprintf_filtered
8891           (file, 
8892            "The MIPS ABI is set automatically (currently \"%s\").\n",
8893            actual_abi_str);
8894       else if (global_abi == actual_abi)
8895         fprintf_filtered
8896           (file,
8897            "The MIPS ABI is assumed to be \"%s\" (due to user setting).\n",
8898            actual_abi_str);
8899       else
8900         {
8901           /* Probably shouldn't happen...  */
8902           fprintf_filtered (file,
8903                             "The (auto detected) MIPS ABI \"%s\" is in use "
8904                             "even though the user setting was \"%s\".\n",
8905              actual_abi_str, mips_abi_strings[global_abi]);
8906         }
8907     }
8908 }
8909
8910 /* Print out which MIPS compressed ISA encoding is used.  */
8911
8912 static void
8913 show_mips_compression (struct ui_file *file, int from_tty,
8914                        struct cmd_list_element *c, const char *value)
8915 {
8916   fprintf_filtered (file, _("The compressed ISA encoding used is %s.\n"),
8917                     value);
8918 }
8919
8920 static void
8921 mips_dump_tdep (struct gdbarch *gdbarch, struct ui_file *file)
8922 {
8923   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
8924   if (tdep != NULL)
8925     {
8926       int ef_mips_arch;
8927       int ef_mips_32bitmode;
8928       /* Determine the ISA.  */
8929       switch (tdep->elf_flags & EF_MIPS_ARCH)
8930         {
8931         case E_MIPS_ARCH_1:
8932           ef_mips_arch = 1;
8933           break;
8934         case E_MIPS_ARCH_2:
8935           ef_mips_arch = 2;
8936           break;
8937         case E_MIPS_ARCH_3:
8938           ef_mips_arch = 3;
8939           break;
8940         case E_MIPS_ARCH_4:
8941           ef_mips_arch = 4;
8942           break;
8943         default:
8944           ef_mips_arch = 0;
8945           break;
8946         }
8947       /* Determine the size of a pointer.  */
8948       ef_mips_32bitmode = (tdep->elf_flags & EF_MIPS_32BITMODE);
8949       fprintf_unfiltered (file,
8950                           "mips_dump_tdep: tdep->elf_flags = 0x%x\n",
8951                           tdep->elf_flags);
8952       fprintf_unfiltered (file,
8953                           "mips_dump_tdep: ef_mips_32bitmode = %d\n",
8954                           ef_mips_32bitmode);
8955       fprintf_unfiltered (file,
8956                           "mips_dump_tdep: ef_mips_arch = %d\n",
8957                           ef_mips_arch);
8958       fprintf_unfiltered (file,
8959                           "mips_dump_tdep: tdep->mips_abi = %d (%s)\n",
8960                           tdep->mips_abi, mips_abi_strings[tdep->mips_abi]);
8961       fprintf_unfiltered (file,
8962                           "mips_dump_tdep: "
8963                           "mips_mask_address_p() %d (default %d)\n",
8964                           mips_mask_address_p (tdep),
8965                           tdep->default_mask_address_p);
8966     }
8967   fprintf_unfiltered (file,
8968                       "mips_dump_tdep: MIPS_DEFAULT_FPU_TYPE = %d (%s)\n",
8969                       MIPS_DEFAULT_FPU_TYPE,
8970                       (MIPS_DEFAULT_FPU_TYPE == MIPS_FPU_NONE ? "none"
8971                        : MIPS_DEFAULT_FPU_TYPE == MIPS_FPU_SINGLE ? "single"
8972                        : MIPS_DEFAULT_FPU_TYPE == MIPS_FPU_DOUBLE ? "double"
8973                        : "???"));
8974   fprintf_unfiltered (file, "mips_dump_tdep: MIPS_EABI = %d\n",
8975                       MIPS_EABI (gdbarch));
8976   fprintf_unfiltered (file,
8977                       "mips_dump_tdep: MIPS_FPU_TYPE = %d (%s)\n",
8978                       MIPS_FPU_TYPE (gdbarch),
8979                       (MIPS_FPU_TYPE (gdbarch) == MIPS_FPU_NONE ? "none"
8980                        : MIPS_FPU_TYPE (gdbarch) == MIPS_FPU_SINGLE ? "single"
8981                        : MIPS_FPU_TYPE (gdbarch) == MIPS_FPU_DOUBLE ? "double"
8982                        : "???"));
8983 }
8984
8985 extern initialize_file_ftype _initialize_mips_tdep; /* -Wmissing-prototypes */
8986
8987 void
8988 _initialize_mips_tdep (void)
8989 {
8990   static struct cmd_list_element *mipsfpulist = NULL;
8991   struct cmd_list_element *c;
8992
8993   mips_abi_string = mips_abi_strings[MIPS_ABI_UNKNOWN];
8994   if (MIPS_ABI_LAST + 1
8995       != sizeof (mips_abi_strings) / sizeof (mips_abi_strings[0]))
8996     internal_error (__FILE__, __LINE__, _("mips_abi_strings out of sync"));
8997
8998   gdbarch_register (bfd_arch_mips, mips_gdbarch_init, mips_dump_tdep);
8999
9000   mips_pdr_data = register_objfile_data ();
9001
9002   /* Create feature sets with the appropriate properties.  The values
9003      are not important.  */
9004   mips_tdesc_gp32 = allocate_target_description ();
9005   set_tdesc_property (mips_tdesc_gp32, PROPERTY_GP32, "");
9006
9007   mips_tdesc_gp64 = allocate_target_description ();
9008   set_tdesc_property (mips_tdesc_gp64, PROPERTY_GP64, "");
9009
9010   /* Add root prefix command for all "set mips"/"show mips" commands.  */
9011   add_prefix_cmd ("mips", no_class, set_mips_command,
9012                   _("Various MIPS specific commands."),
9013                   &setmipscmdlist, "set mips ", 0, &setlist);
9014
9015   add_prefix_cmd ("mips", no_class, show_mips_command,
9016                   _("Various MIPS specific commands."),
9017                   &showmipscmdlist, "show mips ", 0, &showlist);
9018
9019   /* Allow the user to override the ABI.  */
9020   add_setshow_enum_cmd ("abi", class_obscure, mips_abi_strings,
9021                         &mips_abi_string, _("\
9022 Set the MIPS ABI used by this program."), _("\
9023 Show the MIPS ABI used by this program."), _("\
9024 This option can be set to one of:\n\
9025   auto  - the default ABI associated with the current binary\n\
9026   o32\n\
9027   o64\n\
9028   n32\n\
9029   n64\n\
9030   eabi32\n\
9031   eabi64"),
9032                         mips_abi_update,
9033                         show_mips_abi,
9034                         &setmipscmdlist, &showmipscmdlist);
9035
9036   /* Allow the user to set the ISA to assume for compressed code if ELF
9037      file flags don't tell or there is no program file selected.  This
9038      setting is updated whenever unambiguous ELF file flags are interpreted,
9039      and carried over to subsequent sessions.  */
9040   add_setshow_enum_cmd ("compression", class_obscure, mips_compression_strings,
9041                         &mips_compression_string, _("\
9042 Set the compressed ISA encoding used by MIPS code."), _("\
9043 Show the compressed ISA encoding used by MIPS code."), _("\
9044 Select the compressed ISA encoding used in functions that have no symbol\n\
9045 information available.  The encoding can be set to either of:\n\
9046   mips16\n\
9047   micromips\n\
9048 and is updated automatically from ELF file flags if available."),
9049                         mips_abi_update,
9050                         show_mips_compression,
9051                         &setmipscmdlist, &showmipscmdlist);
9052
9053   /* Let the user turn off floating point and set the fence post for
9054      heuristic_proc_start.  */
9055
9056   add_prefix_cmd ("mipsfpu", class_support, set_mipsfpu_command,
9057                   _("Set use of MIPS floating-point coprocessor."),
9058                   &mipsfpulist, "set mipsfpu ", 0, &setlist);
9059   add_cmd ("single", class_support, set_mipsfpu_single_command,
9060            _("Select single-precision MIPS floating-point coprocessor."),
9061            &mipsfpulist);
9062   add_cmd ("double", class_support, set_mipsfpu_double_command,
9063            _("Select double-precision MIPS floating-point coprocessor."),
9064            &mipsfpulist);
9065   add_alias_cmd ("on", "double", class_support, 1, &mipsfpulist);
9066   add_alias_cmd ("yes", "double", class_support, 1, &mipsfpulist);
9067   add_alias_cmd ("1", "double", class_support, 1, &mipsfpulist);
9068   add_cmd ("none", class_support, set_mipsfpu_none_command,
9069            _("Select no MIPS floating-point coprocessor."), &mipsfpulist);
9070   add_alias_cmd ("off", "none", class_support, 1, &mipsfpulist);
9071   add_alias_cmd ("no", "none", class_support, 1, &mipsfpulist);
9072   add_alias_cmd ("0", "none", class_support, 1, &mipsfpulist);
9073   add_cmd ("auto", class_support, set_mipsfpu_auto_command,
9074            _("Select MIPS floating-point coprocessor automatically."),
9075            &mipsfpulist);
9076   add_cmd ("mipsfpu", class_support, show_mipsfpu_command,
9077            _("Show current use of MIPS floating-point coprocessor target."),
9078            &showlist);
9079
9080   /* We really would like to have both "0" and "unlimited" work, but
9081      command.c doesn't deal with that.  So make it a var_zinteger
9082      because the user can always use "999999" or some such for unlimited.  */
9083   add_setshow_zinteger_cmd ("heuristic-fence-post", class_support,
9084                             &heuristic_fence_post, _("\
9085 Set the distance searched for the start of a function."), _("\
9086 Show the distance searched for the start of a function."), _("\
9087 If you are debugging a stripped executable, GDB needs to search through the\n\
9088 program for the start of a function.  This command sets the distance of the\n\
9089 search.  The only need to set it is when debugging a stripped executable."),
9090                             reinit_frame_cache_sfunc,
9091                             NULL, /* FIXME: i18n: The distance searched for
9092                                      the start of a function is %s.  */
9093                             &setlist, &showlist);
9094
9095   /* Allow the user to control whether the upper bits of 64-bit
9096      addresses should be zeroed.  */
9097   add_setshow_auto_boolean_cmd ("mask-address", no_class,
9098                                 &mask_address_var, _("\
9099 Set zeroing of upper 32 bits of 64-bit addresses."), _("\
9100 Show zeroing of upper 32 bits of 64-bit addresses."), _("\
9101 Use \"on\" to enable the masking, \"off\" to disable it and \"auto\" to\n\
9102 allow GDB to determine the correct value."),
9103                                 NULL, show_mask_address,
9104                                 &setmipscmdlist, &showmipscmdlist);
9105
9106   /* Allow the user to control the size of 32 bit registers within the
9107      raw remote packet.  */
9108   add_setshow_boolean_cmd ("remote-mips64-transfers-32bit-regs", class_obscure,
9109                            &mips64_transfers_32bit_regs_p, _("\
9110 Set compatibility with 64-bit MIPS target that transfers 32-bit quantities."),
9111                            _("\
9112 Show compatibility with 64-bit MIPS target that transfers 32-bit quantities."),
9113                            _("\
9114 Use \"on\" to enable backward compatibility with older MIPS 64 GDB+target\n\
9115 that would transfer 32 bits for some registers (e.g. SR, FSR) and\n\
9116 64 bits for others.  Use \"off\" to disable compatibility mode"),
9117                            set_mips64_transfers_32bit_regs,
9118                            NULL, /* FIXME: i18n: Compatibility with 64-bit
9119                                     MIPS target that transfers 32-bit
9120                                     quantities is %s.  */
9121                            &setlist, &showlist);
9122
9123   /* Debug this files internals.  */
9124   add_setshow_zuinteger_cmd ("mips", class_maintenance,
9125                              &mips_debug, _("\
9126 Set mips debugging."), _("\
9127 Show mips debugging."), _("\
9128 When non-zero, mips specific debugging is enabled."),
9129                              NULL,
9130                              NULL, /* FIXME: i18n: Mips debugging is
9131                                       currently %s.  */
9132                              &setdebuglist, &showdebuglist);
9133 }