xref: /netbsd-src/external/gpl3/gdb.old/dist/gdb/mep-tdep.c (revision 8b657b0747480f8989760d71343d6dd33f8d4cf9)
1 /* Target-dependent code for the Toshiba MeP for GDB, the GNU debugger.
2 
3    Copyright (C) 2001-2023 Free Software Foundation, Inc.
4 
5    Contributed by Red Hat, Inc.
6 
7    This file is part of GDB.
8 
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13 
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18 
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21 
22 #include "defs.h"
23 #include "frame.h"
24 #include "frame-unwind.h"
25 #include "frame-base.h"
26 #include "symtab.h"
27 #include "gdbtypes.h"
28 #include "gdbcmd.h"
29 #include "gdbcore.h"
30 #include "value.h"
31 #include "inferior.h"
32 #include "dis-asm.h"
33 #include "symfile.h"
34 #include "objfiles.h"
35 #include "language.h"
36 #include "arch-utils.h"
37 #include "regcache.h"
38 #include "remote.h"
39 #include "sim-regno.h"
40 #include "trad-frame.h"
41 #include "reggroups.h"
42 #include "elf-bfd.h"
43 #include "elf/mep.h"
44 #include "prologue-value.h"
45 #include "cgen/bitset.h"
46 #include "infcall.h"
47 #include "gdbarch.h"
48 
49 /* Get the user's customized MeP coprocessor register names from
50    libopcodes.  */
51 #include "opcodes/mep-desc.h"
52 #include "opcodes/mep-opc.h"
53 
54 
55 /* The gdbarch_tdep structure.  */
56 
57 /* A quick recap for GDB hackers not familiar with the whole Toshiba
58    Media Processor story:
59 
60    The MeP media engine is a configureable processor: users can design
61    their own coprocessors, implement custom instructions, adjust cache
62    sizes, select optional standard facilities like add-and-saturate
63    instructions, and so on.  Then, they can build custom versions of
64    the GNU toolchain to support their customized chips.  The
65    MeP-Integrator program (see utils/mep) takes a GNU toolchain source
66    tree, and a config file pointing to various files provided by the
67    user describing their customizations, and edits the source tree to
68    produce a compiler that can generate their custom instructions, an
69    assembler that can assemble them and recognize their custom
70    register names, and so on.
71 
72    Furthermore, the user can actually specify several of these custom
73    configurations, called 'me_modules', and get a toolchain which can
74    produce code for any of them, given a compiler/assembler switch;
75    you say something like 'gcc -mconfig=mm_max' to generate code for
76    the me_module named 'mm_max'.
77 
78    GDB, in particular, needs to:
79 
80    - use the coprocessor control register names provided by the user
81      in their hardware description, in expressions, 'info register'
82      output, and disassembly,
83 
84    - know the number, names, and types of the coprocessor's
85      general-purpose registers, adjust the 'info all-registers' output
86      accordingly, and print error messages if the user refers to one
87      that doesn't exist
88 
89    - allow access to the control bus space only when the configuration
90      actually has a control bus, and recognize which regions of the
91      control bus space are actually populated,
92 
93    - disassemble using the user's provided mnemonics for their custom
94      instructions, and
95 
96    - recognize whether the $hi and $lo registers are present, and
97      allow access to them only when they are actually there.
98 
99    There are three sources of information about what sort of me_module
100    we're actually dealing with:
101 
102    - A MeP executable file indicates which me_module it was compiled
103      for, and libopcodes has tables describing each module.  So, given
104      an executable file, we can find out about the processor it was
105      compiled for.
106 
107    - There are SID command-line options to select a particular
108      me_module, overriding the one specified in the ELF file.  SID
109      provides GDB with a fake read-only register, 'module', which
110      indicates which me_module GDB is communicating with an instance
111      of.
112 
113    - There are SID command-line options to enable or disable certain
114      optional processor features, overriding the defaults for the
115      selected me_module.  The MeP $OPT register indicates which
116      options are present on the current processor.  */
117 
118 
119 struct mep_gdbarch_tdep : gdbarch_tdep_base
120 {
121   /* A CGEN cpu descriptor for this BFD architecture and machine.
122 
123      Note: this is *not* customized for any particular me_module; the
124      MeP libopcodes machinery actually puts off module-specific
125      customization until the last minute.  So this contains
126      information about all supported me_modules.  */
127   CGEN_CPU_DESC cpu_desc = nullptr;
128 
129   /* The me_module index from the ELF file we used to select this
130      architecture, or CONFIG_NONE if there was none.
131 
132      Note that we should prefer to use the me_module number available
133      via the 'module' register, whenever we're actually talking to a
134      real target.
135 
136      In the absence of live information, we'd like to get the
137      me_module number from the ELF file.  But which ELF file: the
138      executable file, the core file, ... ?  The answer is, "the last
139      ELF file we used to set the current architecture".  Thus, we
140      create a separate instance of the gdbarch structure for each
141      me_module value mep_gdbarch_init sees, and store the me_module
142      value from the ELF file here.  */
143   CONFIG_ATTR me_module {};
144 };
145 
146 
147 
148 /* Getting me_module information from the CGEN tables.  */
149 
150 
151 /* Find an entry in the DESC's hardware table whose name begins with
152    PREFIX, and whose ISA mask intersects COPRO_ISA_MASK, but does not
153    intersect with GENERIC_ISA_MASK.  If there is no matching entry,
154    return zero.  */
155 static const CGEN_HW_ENTRY *
156 find_hw_entry_by_prefix_and_isa (CGEN_CPU_DESC desc,
157 				 const char *prefix,
158 				 CGEN_BITSET *copro_isa_mask,
159 				 CGEN_BITSET *generic_isa_mask)
160 {
161   int prefix_len = strlen (prefix);
162   int i;
163 
164   for (i = 0; i < desc->hw_table.num_entries; i++)
165     {
166       const CGEN_HW_ENTRY *hw = desc->hw_table.entries[i];
167       if (strncmp (prefix, hw->name, prefix_len) == 0)
168 	{
169 	  CGEN_BITSET *hw_isa_mask
170 	    = ((CGEN_BITSET *)
171 	       &CGEN_ATTR_CGEN_HW_ISA_VALUE (CGEN_HW_ATTRS (hw)));
172 
173 	  if (cgen_bitset_intersect_p (hw_isa_mask, copro_isa_mask)
174 	      && ! cgen_bitset_intersect_p (hw_isa_mask, generic_isa_mask))
175 	    return hw;
176 	}
177     }
178 
179   return 0;
180 }
181 
182 
183 /* Find an entry in DESC's hardware table whose type is TYPE.  Return
184    zero if there is none.  */
185 static const CGEN_HW_ENTRY *
186 find_hw_entry_by_type (CGEN_CPU_DESC desc, CGEN_HW_TYPE type)
187 {
188   int i;
189 
190   for (i = 0; i < desc->hw_table.num_entries; i++)
191     {
192       const CGEN_HW_ENTRY *hw = desc->hw_table.entries[i];
193 
194       if (hw->type == type)
195 	return hw;
196     }
197 
198   return 0;
199 }
200 
201 
202 /* Return the CGEN hardware table entry for the coprocessor register
203    set for ME_MODULE, whose name prefix is PREFIX.  If ME_MODULE has
204    no such register set, return zero.  If ME_MODULE is the generic
205    me_module CONFIG_NONE, return the table entry for the register set
206    whose hardware type is GENERIC_TYPE.  */
207 static const CGEN_HW_ENTRY *
208 me_module_register_set (CONFIG_ATTR me_module,
209 			const char *prefix,
210 			CGEN_HW_TYPE generic_type)
211 {
212   /* This is kind of tricky, because the hardware table is constructed
213      in a way that isn't very helpful.  Perhaps we can fix that, but
214      here's how it works at the moment:
215 
216      The configuration map, `mep_config_map', is indexed by me_module
217      number, and indicates which coprocessor and core ISAs that
218      me_module supports.  The 'core_isa' mask includes all the core
219      ISAs, and the 'cop_isa' mask includes all the coprocessor ISAs.
220      The entry for the generic me_module, CONFIG_NONE, has an empty
221      'cop_isa', and its 'core_isa' selects only the standard MeP
222      instruction set.
223 
224      The CGEN CPU descriptor's hardware table, desc->hw_table, has
225      entries for all the register sets, for all me_modules.  Each
226      entry has a mask indicating which ISAs use that register set.
227      So, if an me_module supports some coprocessor ISA, we can find
228      applicable register sets by scanning the hardware table for
229      register sets whose masks include (at least some of) those ISAs.
230 
231      Each hardware table entry also has a name, whose prefix says
232      whether it's a general-purpose ("h-cr") or control ("h-ccr")
233      coprocessor register set.  It might be nicer to have an attribute
234      indicating what sort of register set it was, that we could use
235      instead of pattern-matching on the name.
236 
237      When there is no hardware table entry whose mask includes a
238      particular coprocessor ISA and whose name starts with a given
239      prefix, then that means that that coprocessor doesn't have any
240      registers of that type.  In such cases, this function must return
241      a null pointer.
242 
243      Coprocessor register sets' masks may or may not include the core
244      ISA for the me_module they belong to.  Those generated by a2cgen
245      do, but the sample me_module included in the unconfigured tree,
246      'ccfx', does not.
247 
248      There are generic coprocessor register sets, intended only for
249      use with the generic me_module.  Unfortunately, their masks
250      include *all* ISAs --- even those for coprocessors that don't
251      have such register sets.  This makes detecting the case where a
252      coprocessor lacks a particular register set more complicated.
253 
254      So, here's the approach we take:
255 
256      - For CONFIG_NONE, we return the generic coprocessor register set.
257 
258      - For any other me_module, we search for a register set whose
259        mask contains any of the me_module's coprocessor ISAs,
260        specifically excluding the generic coprocessor register sets.  */
261 
262   mep_gdbarch_tdep *tdep
263     = gdbarch_tdep<mep_gdbarch_tdep> (target_gdbarch ());
264   CGEN_CPU_DESC desc = tdep->cpu_desc;
265   const CGEN_HW_ENTRY *hw;
266 
267   if (me_module == CONFIG_NONE)
268     hw = find_hw_entry_by_type (desc, generic_type);
269   else
270     {
271       CGEN_BITSET *cop = &mep_config_map[me_module].cop_isa;
272       CGEN_BITSET *core = &mep_config_map[me_module].core_isa;
273       CGEN_BITSET *generic = &mep_config_map[CONFIG_NONE].core_isa;
274       CGEN_BITSET *cop_and_core;
275 
276       /* The coprocessor ISAs include the ISA for the specific core which
277 	 has that coprocessor.  */
278       cop_and_core = cgen_bitset_copy (cop);
279       cgen_bitset_union (cop, core, cop_and_core);
280       hw = find_hw_entry_by_prefix_and_isa (desc, prefix, cop_and_core, generic);
281     }
282 
283   return hw;
284 }
285 
286 
287 /* Given a hardware table entry HW representing a register set, return
288    a pointer to the keyword table with all the register names.  If HW
289    is NULL, return NULL, to propagate the "no such register set" info
290    along.  */
291 static CGEN_KEYWORD *
292 register_set_keyword_table (const CGEN_HW_ENTRY *hw)
293 {
294   if (! hw)
295     return NULL;
296 
297   /* Check that HW is actually a keyword table.  */
298   gdb_assert (hw->asm_type == CGEN_ASM_KEYWORD);
299 
300   /* The 'asm_data' field of a register set's hardware table entry
301      refers to a keyword table.  */
302   return (CGEN_KEYWORD *) hw->asm_data;
303 }
304 
305 
306 /* Given a keyword table KEYWORD and a register number REGNUM, return
307    the name of the register, or "" if KEYWORD contains no register
308    whose number is REGNUM.  */
309 static const char *
310 register_name_from_keyword (CGEN_KEYWORD *keyword_table, int regnum)
311 {
312   const CGEN_KEYWORD_ENTRY *entry
313     = cgen_keyword_lookup_value (keyword_table, regnum);
314 
315   if (entry)
316     {
317       char *name = entry->name;
318 
319       /* The CGEN keyword entries for register names include the
320 	 leading $, which appears in MeP assembly as well as in GDB.
321 	 But we don't want to return that; GDB core code adds that
322 	 itself.  */
323       if (name[0] == '$')
324 	name++;
325 
326       return name;
327     }
328   else
329     return "";
330 }
331 
332 
333 /* Masks for option bits in the OPT special-purpose register.  */
334 enum {
335   MEP_OPT_DIV = 1 << 25,        /* 32-bit divide instruction option */
336   MEP_OPT_MUL = 1 << 24,        /* 32-bit multiply instruction option */
337   MEP_OPT_BIT = 1 << 23,        /* bit manipulation instruction option */
338   MEP_OPT_SAT = 1 << 22,        /* saturation instruction option */
339   MEP_OPT_CLP = 1 << 21,        /* clip instruction option */
340   MEP_OPT_MIN = 1 << 20,        /* min/max instruction option */
341   MEP_OPT_AVE = 1 << 19,        /* average instruction option */
342   MEP_OPT_ABS = 1 << 18,        /* absolute difference instruction option */
343   MEP_OPT_LDZ = 1 << 16,        /* leading zero instruction option */
344   MEP_OPT_VL64 = 1 << 6,        /* 64-bit VLIW operation mode option */
345   MEP_OPT_VL32 = 1 << 5,        /* 32-bit VLIW operation mode option */
346   MEP_OPT_COP = 1 << 4,         /* coprocessor option */
347   MEP_OPT_DSP = 1 << 2,         /* DSP option */
348   MEP_OPT_UCI = 1 << 1,         /* UCI option */
349   MEP_OPT_DBG = 1 << 0,         /* DBG function option */
350 };
351 
352 
353 /* Given the option_mask value for a particular entry in
354    mep_config_map, produce the value the processor's OPT register
355    would use to represent the same set of options.  */
356 static unsigned int
357 opt_from_option_mask (unsigned int option_mask)
358 {
359   /* A table mapping OPT register bits onto CGEN config map option
360      bits.  */
361   struct {
362     unsigned int opt_bit, option_mask_bit;
363   } bits[] = {
364     { MEP_OPT_DIV, 1 << CGEN_INSN_OPTIONAL_DIV_INSN },
365     { MEP_OPT_MUL, 1 << CGEN_INSN_OPTIONAL_MUL_INSN },
366     { MEP_OPT_DIV, 1 << CGEN_INSN_OPTIONAL_DIV_INSN },
367     { MEP_OPT_DBG, 1 << CGEN_INSN_OPTIONAL_DEBUG_INSN },
368     { MEP_OPT_LDZ, 1 << CGEN_INSN_OPTIONAL_LDZ_INSN },
369     { MEP_OPT_ABS, 1 << CGEN_INSN_OPTIONAL_ABS_INSN },
370     { MEP_OPT_AVE, 1 << CGEN_INSN_OPTIONAL_AVE_INSN },
371     { MEP_OPT_MIN, 1 << CGEN_INSN_OPTIONAL_MINMAX_INSN },
372     { MEP_OPT_CLP, 1 << CGEN_INSN_OPTIONAL_CLIP_INSN },
373     { MEP_OPT_SAT, 1 << CGEN_INSN_OPTIONAL_SAT_INSN },
374     { MEP_OPT_UCI, 1 << CGEN_INSN_OPTIONAL_UCI_INSN },
375     { MEP_OPT_DSP, 1 << CGEN_INSN_OPTIONAL_DSP_INSN },
376     { MEP_OPT_COP, 1 << CGEN_INSN_OPTIONAL_CP_INSN },
377   };
378 
379   int i;
380   unsigned int opt = 0;
381 
382   for (i = 0; i < (sizeof (bits) / sizeof (bits[0])); i++)
383     if (option_mask & bits[i].option_mask_bit)
384       opt |= bits[i].opt_bit;
385 
386   return opt;
387 }
388 
389 
390 /* Return the value the $OPT register would use to represent the set
391    of options for ME_MODULE.  */
392 static unsigned int
393 me_module_opt (CONFIG_ATTR me_module)
394 {
395   return opt_from_option_mask (mep_config_map[me_module].option_mask);
396 }
397 
398 
399 /* Return the width of ME_MODULE's coprocessor data bus, in bits.
400    This is either 32 or 64.  */
401 static int
402 me_module_cop_data_bus_width (CONFIG_ATTR me_module)
403 {
404   if (mep_config_map[me_module].option_mask
405       & (1 << CGEN_INSN_OPTIONAL_CP64_INSN))
406     return 64;
407   else
408     return 32;
409 }
410 
411 
412 /* Return true if ME_MODULE is big-endian, false otherwise.  */
413 static int
414 me_module_big_endian (CONFIG_ATTR me_module)
415 {
416   return mep_config_map[me_module].big_endian;
417 }
418 
419 
420 /* Return the name of ME_MODULE, or NULL if it has no name.  */
421 static const char *
422 me_module_name (CONFIG_ATTR me_module)
423 {
424   /* The default me_module has "" as its name, but it's easier for our
425      callers to test for NULL.  */
426   if (! mep_config_map[me_module].name
427       || mep_config_map[me_module].name[0] == '\0')
428     return NULL;
429   else
430     return mep_config_map[me_module].name;
431 }
432 
433 /* Register set.  */
434 
435 
436 /* The MeP spec defines the following registers:
437    16 general purpose registers (r0-r15)
438    32 control/special registers (csr0-csr31)
439    32 coprocessor general-purpose registers (c0 -- c31)
440    64 coprocessor control registers (ccr0 -- ccr63)
441 
442    For the raw registers, we assign numbers here explicitly, instead
443    of letting the enum assign them for us; the numbers are a matter of
444    external protocol, and shouldn't shift around as things are edited.
445 
446    We access the control/special registers via pseudoregisters, to
447    enforce read-only portions that some registers have.
448 
449    We access the coprocessor general purpose and control registers via
450    pseudoregisters, to make sure they appear in the proper order in
451    the 'info all-registers' command (which uses the register number
452    ordering), and also to allow them to be renamed and resized
453    depending on the me_module in use.
454 
455    The MeP allows coprocessor general-purpose registers to be either
456    32 or 64 bits long, depending on the configuration.  Since we don't
457    want the format of the 'g' packet to vary from one core to another,
458    the raw coprocessor GPRs are always 64 bits.  GDB doesn't allow the
459    types of registers to change (see the implementation of
460    register_type), so we have four banks of pseudoregisters for the
461    coprocessor gprs --- 32-bit vs. 64-bit, and integer
462    vs. floating-point --- and we show or hide them depending on the
463    configuration.  */
464 enum
465 {
466   MEP_FIRST_RAW_REGNUM = 0,
467 
468   MEP_FIRST_GPR_REGNUM = 0,
469   MEP_R0_REGNUM = 0,
470   MEP_R1_REGNUM = 1,
471   MEP_R2_REGNUM = 2,
472   MEP_R3_REGNUM = 3,
473   MEP_R4_REGNUM = 4,
474   MEP_R5_REGNUM = 5,
475   MEP_R6_REGNUM = 6,
476   MEP_R7_REGNUM = 7,
477   MEP_R8_REGNUM = 8,
478   MEP_R9_REGNUM = 9,
479   MEP_R10_REGNUM = 10,
480   MEP_R11_REGNUM = 11,
481   MEP_R12_REGNUM = 12,
482   MEP_FP_REGNUM = MEP_R8_REGNUM,
483   MEP_R13_REGNUM = 13,
484   MEP_TP_REGNUM = MEP_R13_REGNUM,	/* (r13) Tiny data pointer */
485   MEP_R14_REGNUM = 14,
486   MEP_GP_REGNUM = MEP_R14_REGNUM,	/* (r14) Global pointer */
487   MEP_R15_REGNUM = 15,
488   MEP_SP_REGNUM = MEP_R15_REGNUM,	/* (r15) Stack pointer */
489   MEP_LAST_GPR_REGNUM = MEP_R15_REGNUM,
490 
491   /* The raw control registers.  These are the values as received via
492      the remote protocol, directly from the target; we only let user
493      code touch the via the pseudoregisters, which enforce read-only
494      bits.  */
495   MEP_FIRST_RAW_CSR_REGNUM = 16,
496   MEP_RAW_PC_REGNUM    = 16,    /* Program counter */
497   MEP_RAW_LP_REGNUM    = 17,    /* Link pointer */
498   MEP_RAW_SAR_REGNUM   = 18,    /* Raw shift amount */
499   MEP_RAW_CSR3_REGNUM  = 19,    /* csr3: reserved */
500   MEP_RAW_RPB_REGNUM   = 20,    /* Raw repeat begin address */
501   MEP_RAW_RPE_REGNUM   = 21,    /* Repeat end address */
502   MEP_RAW_RPC_REGNUM   = 22,    /* Repeat count */
503   MEP_RAW_HI_REGNUM    = 23, /* Upper 32 bits of result of 64 bit mult/div */
504   MEP_RAW_LO_REGNUM    = 24, /* Lower 32 bits of result of 64 bit mult/div */
505   MEP_RAW_CSR9_REGNUM  = 25,    /* csr3: reserved */
506   MEP_RAW_CSR10_REGNUM = 26,    /* csr3: reserved */
507   MEP_RAW_CSR11_REGNUM = 27,    /* csr3: reserved */
508   MEP_RAW_MB0_REGNUM   = 28,    /* Raw modulo begin address 0 */
509   MEP_RAW_ME0_REGNUM   = 29,    /* Raw modulo end address 0 */
510   MEP_RAW_MB1_REGNUM   = 30,    /* Raw modulo begin address 1 */
511   MEP_RAW_ME1_REGNUM   = 31,    /* Raw modulo end address 1 */
512   MEP_RAW_PSW_REGNUM   = 32,    /* Raw program status word */
513   MEP_RAW_ID_REGNUM    = 33,    /* Raw processor ID/revision */
514   MEP_RAW_TMP_REGNUM   = 34,    /* Temporary */
515   MEP_RAW_EPC_REGNUM   = 35,    /* Exception program counter */
516   MEP_RAW_EXC_REGNUM   = 36,    /* Raw exception cause */
517   MEP_RAW_CFG_REGNUM   = 37,    /* Raw processor configuration*/
518   MEP_RAW_CSR22_REGNUM = 38,    /* csr3: reserved */
519   MEP_RAW_NPC_REGNUM   = 39,    /* Nonmaskable interrupt PC */
520   MEP_RAW_DBG_REGNUM   = 40,    /* Raw debug */
521   MEP_RAW_DEPC_REGNUM  = 41,    /* Debug exception PC */
522   MEP_RAW_OPT_REGNUM   = 42,    /* Raw options */
523   MEP_RAW_RCFG_REGNUM  = 43,    /* Raw local ram config */
524   MEP_RAW_CCFG_REGNUM  = 44,    /* Raw cache config */
525   MEP_RAW_CSR29_REGNUM = 45,    /* csr3: reserved */
526   MEP_RAW_CSR30_REGNUM = 46,    /* csr3: reserved */
527   MEP_RAW_CSR31_REGNUM = 47,    /* csr3: reserved */
528   MEP_LAST_RAW_CSR_REGNUM = MEP_RAW_CSR31_REGNUM,
529 
530   /* The raw coprocessor general-purpose registers.  These are all 64
531      bits wide.  */
532   MEP_FIRST_RAW_CR_REGNUM = 48,
533   MEP_LAST_RAW_CR_REGNUM = MEP_FIRST_RAW_CR_REGNUM + 31,
534 
535   MEP_FIRST_RAW_CCR_REGNUM = 80,
536   MEP_LAST_RAW_CCR_REGNUM = MEP_FIRST_RAW_CCR_REGNUM + 63,
537 
538   /* The module number register.  This is the index of the me_module
539      of which the current target is an instance.  (This is not a real
540      MeP-specified register; it's provided by SID.)  */
541   MEP_MODULE_REGNUM,
542 
543   MEP_LAST_RAW_REGNUM = MEP_MODULE_REGNUM,
544 
545   MEP_NUM_RAW_REGS = MEP_LAST_RAW_REGNUM + 1,
546 
547   /* Pseudoregisters.  See mep_pseudo_register_read and
548      mep_pseudo_register_write.  */
549   MEP_FIRST_PSEUDO_REGNUM = MEP_NUM_RAW_REGS,
550 
551   /* We have a pseudoregister for every control/special register, to
552      implement registers with read-only bits.  */
553   MEP_FIRST_CSR_REGNUM = MEP_FIRST_PSEUDO_REGNUM,
554   MEP_PC_REGNUM = MEP_FIRST_CSR_REGNUM, /* Program counter */
555   MEP_LP_REGNUM,                /* Link pointer */
556   MEP_SAR_REGNUM,               /* shift amount */
557   MEP_CSR3_REGNUM,              /* csr3: reserved */
558   MEP_RPB_REGNUM,               /* repeat begin address */
559   MEP_RPE_REGNUM,               /* Repeat end address */
560   MEP_RPC_REGNUM,               /* Repeat count */
561   MEP_HI_REGNUM,  /* Upper 32 bits of the result of 64 bit mult/div */
562   MEP_LO_REGNUM,  /* Lower 32 bits of the result of 64 bit mult/div */
563   MEP_CSR9_REGNUM,              /* csr3: reserved */
564   MEP_CSR10_REGNUM,             /* csr3: reserved */
565   MEP_CSR11_REGNUM,             /* csr3: reserved */
566   MEP_MB0_REGNUM,               /* modulo begin address 0 */
567   MEP_ME0_REGNUM,               /* modulo end address 0 */
568   MEP_MB1_REGNUM,               /* modulo begin address 1 */
569   MEP_ME1_REGNUM,               /* modulo end address 1 */
570   MEP_PSW_REGNUM,               /* program status word */
571   MEP_ID_REGNUM,                /* processor ID/revision */
572   MEP_TMP_REGNUM,               /* Temporary */
573   MEP_EPC_REGNUM,               /* Exception program counter */
574   MEP_EXC_REGNUM,               /* exception cause */
575   MEP_CFG_REGNUM,               /* processor configuration*/
576   MEP_CSR22_REGNUM,             /* csr3: reserved */
577   MEP_NPC_REGNUM,               /* Nonmaskable interrupt PC */
578   MEP_DBG_REGNUM,               /* debug */
579   MEP_DEPC_REGNUM,              /* Debug exception PC */
580   MEP_OPT_REGNUM,               /* options */
581   MEP_RCFG_REGNUM,              /* local ram config */
582   MEP_CCFG_REGNUM,              /* cache config */
583   MEP_CSR29_REGNUM,             /* csr3: reserved */
584   MEP_CSR30_REGNUM,             /* csr3: reserved */
585   MEP_CSR31_REGNUM,             /* csr3: reserved */
586   MEP_LAST_CSR_REGNUM = MEP_CSR31_REGNUM,
587 
588   /* The 32-bit integer view of the coprocessor GPR's.  */
589   MEP_FIRST_CR32_REGNUM,
590   MEP_LAST_CR32_REGNUM = MEP_FIRST_CR32_REGNUM + 31,
591 
592   /* The 32-bit floating-point view of the coprocessor GPR's.  */
593   MEP_FIRST_FP_CR32_REGNUM,
594   MEP_LAST_FP_CR32_REGNUM = MEP_FIRST_FP_CR32_REGNUM + 31,
595 
596   /* The 64-bit integer view of the coprocessor GPR's.  */
597   MEP_FIRST_CR64_REGNUM,
598   MEP_LAST_CR64_REGNUM = MEP_FIRST_CR64_REGNUM + 31,
599 
600   /* The 64-bit floating-point view of the coprocessor GPR's.  */
601   MEP_FIRST_FP_CR64_REGNUM,
602   MEP_LAST_FP_CR64_REGNUM = MEP_FIRST_FP_CR64_REGNUM + 31,
603 
604   MEP_FIRST_CCR_REGNUM,
605   MEP_LAST_CCR_REGNUM = MEP_FIRST_CCR_REGNUM + 63,
606 
607   MEP_LAST_PSEUDO_REGNUM = MEP_LAST_CCR_REGNUM,
608 
609   MEP_NUM_PSEUDO_REGS = (MEP_LAST_PSEUDO_REGNUM - MEP_LAST_RAW_REGNUM),
610 
611   MEP_NUM_REGS = MEP_NUM_RAW_REGS + MEP_NUM_PSEUDO_REGS
612 };
613 
614 
615 #define IN_SET(set, n) \
616   (MEP_FIRST_ ## set ## _REGNUM <= (n) && (n) <= MEP_LAST_ ## set ## _REGNUM)
617 
618 #define IS_GPR_REGNUM(n)     (IN_SET (GPR,     (n)))
619 #define IS_RAW_CSR_REGNUM(n) (IN_SET (RAW_CSR, (n)))
620 #define IS_RAW_CR_REGNUM(n)  (IN_SET (RAW_CR,  (n)))
621 #define IS_RAW_CCR_REGNUM(n) (IN_SET (RAW_CCR, (n)))
622 
623 #define IS_CSR_REGNUM(n)     (IN_SET (CSR,     (n)))
624 #define IS_CR32_REGNUM(n)    (IN_SET (CR32,    (n)))
625 #define IS_FP_CR32_REGNUM(n) (IN_SET (FP_CR32, (n)))
626 #define IS_CR64_REGNUM(n)    (IN_SET (CR64,    (n)))
627 #define IS_FP_CR64_REGNUM(n) (IN_SET (FP_CR64, (n)))
628 #define IS_CR_REGNUM(n)      (IS_CR32_REGNUM (n) || IS_FP_CR32_REGNUM (n) \
629 			      || IS_CR64_REGNUM (n) || IS_FP_CR64_REGNUM (n))
630 #define IS_CCR_REGNUM(n)     (IN_SET (CCR,     (n)))
631 
632 #define IS_RAW_REGNUM(n)     (IN_SET (RAW,     (n)))
633 #define IS_PSEUDO_REGNUM(n)  (IN_SET (PSEUDO,  (n)))
634 
635 #define NUM_REGS_IN_SET(set) \
636   (MEP_LAST_ ## set ## _REGNUM - MEP_FIRST_ ## set ## _REGNUM + 1)
637 
638 #define MEP_GPR_SIZE (4)        /* Size of a MeP general-purpose register.  */
639 #define MEP_PSW_SIZE (4)        /* Size of the PSW register.  */
640 #define MEP_LP_SIZE (4)         /* Size of the LP register.  */
641 
642 
643 /* Many of the control/special registers contain bits that cannot be
644    written to; some are entirely read-only.  So we present them all as
645    pseudoregisters.
646 
647    The following table describes the special properties of each CSR.  */
648 struct mep_csr_register
649 {
650   /* The number of this CSR's raw register.  */
651   int raw;
652 
653   /* The number of this CSR's pseudoregister.  */
654   int pseudo;
655 
656   /* A mask of the bits that are writeable: if a bit is set here, then
657      it can be modified; if the bit is clear, then it cannot.  */
658   LONGEST writeable_bits;
659 };
660 
661 
662 /* mep_csr_registers[i] describes the i'th CSR.
663    We just list the register numbers here explicitly to help catch
664    typos.  */
665 #define CSR(name) MEP_RAW_ ## name ## _REGNUM, MEP_ ## name ## _REGNUM
666 static mep_csr_register mep_csr_registers[] = {
667   { CSR(PC),    0xffffffff },   /* manual says r/o, but we can write it */
668   { CSR(LP),    0xffffffff },
669   { CSR(SAR),   0x0000003f },
670   { CSR(CSR3),  0xffffffff },
671   { CSR(RPB),   0xfffffffe },
672   { CSR(RPE),   0xffffffff },
673   { CSR(RPC),   0xffffffff },
674   { CSR(HI),    0xffffffff },
675   { CSR(LO),    0xffffffff },
676   { CSR(CSR9),  0xffffffff },
677   { CSR(CSR10), 0xffffffff },
678   { CSR(CSR11), 0xffffffff },
679   { CSR(MB0),   0x0000ffff },
680   { CSR(ME0),   0x0000ffff },
681   { CSR(MB1),   0x0000ffff },
682   { CSR(ME1),   0x0000ffff },
683   { CSR(PSW),   0x000003ff },
684   { CSR(ID),    0x00000000 },
685   { CSR(TMP),   0xffffffff },
686   { CSR(EPC),   0xffffffff },
687   { CSR(EXC),   0x000030f0 },
688   { CSR(CFG),   0x00c0001b },
689   { CSR(CSR22), 0xffffffff },
690   { CSR(NPC),   0xffffffff },
691   { CSR(DBG),   0x00000580 },
692   { CSR(DEPC),  0xffffffff },
693   { CSR(OPT),   0x00000000 },
694   { CSR(RCFG),  0x00000000 },
695   { CSR(CCFG),  0x00000000 },
696   { CSR(CSR29), 0xffffffff },
697   { CSR(CSR30), 0xffffffff },
698   { CSR(CSR31), 0xffffffff },
699 };
700 
701 
702 /* If R is the number of a raw register, then mep_raw_to_pseudo[R] is
703    the number of the corresponding pseudoregister.  Otherwise,
704    mep_raw_to_pseudo[R] == R.  */
705 static int mep_raw_to_pseudo[MEP_NUM_REGS];
706 
707 /* If R is the number of a pseudoregister, then mep_pseudo_to_raw[R]
708    is the number of the underlying raw register.  Otherwise
709    mep_pseudo_to_raw[R] == R.  */
710 static int mep_pseudo_to_raw[MEP_NUM_REGS];
711 
712 static void
713 mep_init_pseudoregister_maps (void)
714 {
715   int i;
716 
717   /* Verify that mep_csr_registers covers all the CSRs, in order.  */
718   gdb_assert (ARRAY_SIZE (mep_csr_registers) == NUM_REGS_IN_SET (CSR));
719   gdb_assert (ARRAY_SIZE (mep_csr_registers) == NUM_REGS_IN_SET (RAW_CSR));
720 
721   /* Verify that the raw and pseudo ranges have matching sizes.  */
722   gdb_assert (NUM_REGS_IN_SET (RAW_CSR) == NUM_REGS_IN_SET (CSR));
723   gdb_assert (NUM_REGS_IN_SET (RAW_CR)  == NUM_REGS_IN_SET (CR32));
724   gdb_assert (NUM_REGS_IN_SET (RAW_CR)  == NUM_REGS_IN_SET (CR64));
725   gdb_assert (NUM_REGS_IN_SET (RAW_CCR) == NUM_REGS_IN_SET (CCR));
726 
727   for (i = 0; i < ARRAY_SIZE (mep_csr_registers); i++)
728     {
729       struct mep_csr_register *r = &mep_csr_registers[i];
730 
731       gdb_assert (r->pseudo == MEP_FIRST_CSR_REGNUM + i);
732       gdb_assert (r->raw    == MEP_FIRST_RAW_CSR_REGNUM + i);
733     }
734 
735   /* Set up the initial  raw<->pseudo mappings.  */
736   for (i = 0; i < MEP_NUM_REGS; i++)
737     {
738       mep_raw_to_pseudo[i] = i;
739       mep_pseudo_to_raw[i] = i;
740     }
741 
742   /* Add the CSR raw<->pseudo mappings.  */
743   for (i = 0; i < ARRAY_SIZE (mep_csr_registers); i++)
744     {
745       struct mep_csr_register *r = &mep_csr_registers[i];
746 
747       mep_raw_to_pseudo[r->raw] = r->pseudo;
748       mep_pseudo_to_raw[r->pseudo] = r->raw;
749     }
750 
751   /* Add the CR raw<->pseudo mappings.  */
752   for (i = 0; i < NUM_REGS_IN_SET (RAW_CR); i++)
753     {
754       int raw = MEP_FIRST_RAW_CR_REGNUM + i;
755       int pseudo32 = MEP_FIRST_CR32_REGNUM + i;
756       int pseudofp32 = MEP_FIRST_FP_CR32_REGNUM + i;
757       int pseudo64 = MEP_FIRST_CR64_REGNUM + i;
758       int pseudofp64 = MEP_FIRST_FP_CR64_REGNUM + i;
759 
760       /* Truly, the raw->pseudo mapping depends on the current module.
761 	 But we use the raw->pseudo mapping when we read the debugging
762 	 info; at that point, we don't know what module we'll actually
763 	 be running yet.  So, we always supply the 64-bit register
764 	 numbers; GDB knows how to pick a smaller value out of a
765 	 larger register properly.  */
766       mep_raw_to_pseudo[raw] = pseudo64;
767       mep_pseudo_to_raw[pseudo32] = raw;
768       mep_pseudo_to_raw[pseudofp32] = raw;
769       mep_pseudo_to_raw[pseudo64] = raw;
770       mep_pseudo_to_raw[pseudofp64] = raw;
771     }
772 
773   /* Add the CCR raw<->pseudo mappings.  */
774   for (i = 0; i < NUM_REGS_IN_SET (CCR); i++)
775     {
776       int raw = MEP_FIRST_RAW_CCR_REGNUM + i;
777       int pseudo = MEP_FIRST_CCR_REGNUM + i;
778       mep_raw_to_pseudo[raw] = pseudo;
779       mep_pseudo_to_raw[pseudo] = raw;
780     }
781 }
782 
783 
784 static int
785 mep_debug_reg_to_regnum (struct gdbarch *gdbarch, int debug_reg)
786 {
787   /* The debug info uses the raw register numbers.  */
788   if (debug_reg >= 0 && debug_reg < ARRAY_SIZE (mep_raw_to_pseudo))
789     return mep_raw_to_pseudo[debug_reg];
790   return -1;
791 }
792 
793 
794 /* Return the size, in bits, of the coprocessor pseudoregister
795    numbered PSEUDO.  */
796 static int
797 mep_pseudo_cr_size (int pseudo)
798 {
799   if (IS_CR32_REGNUM (pseudo)
800       || IS_FP_CR32_REGNUM (pseudo))
801     return 32;
802   else if (IS_CR64_REGNUM (pseudo)
803 	   || IS_FP_CR64_REGNUM (pseudo))
804     return 64;
805   else
806     gdb_assert_not_reached ("unexpected coprocessor pseudo register");
807 }
808 
809 
810 /* If the coprocessor pseudoregister numbered PSEUDO is a
811    floating-point register, return non-zero; if it is an integer
812    register, return zero.  */
813 static int
814 mep_pseudo_cr_is_float (int pseudo)
815 {
816   return (IS_FP_CR32_REGNUM (pseudo)
817 	  || IS_FP_CR64_REGNUM (pseudo));
818 }
819 
820 
821 /* Given a coprocessor GPR pseudoregister number, return its index
822    within that register bank.  */
823 static int
824 mep_pseudo_cr_index (int pseudo)
825 {
826   if (IS_CR32_REGNUM (pseudo))
827     return pseudo - MEP_FIRST_CR32_REGNUM;
828   else if (IS_FP_CR32_REGNUM (pseudo))
829       return pseudo - MEP_FIRST_FP_CR32_REGNUM;
830   else if (IS_CR64_REGNUM (pseudo))
831       return pseudo - MEP_FIRST_CR64_REGNUM;
832   else if (IS_FP_CR64_REGNUM (pseudo))
833       return pseudo - MEP_FIRST_FP_CR64_REGNUM;
834   else
835     gdb_assert_not_reached ("unexpected coprocessor pseudo register");
836 }
837 
838 
839 /* Return the me_module index describing the current target.
840 
841    If the current target has registers (e.g., simulator, remote
842    target), then this uses the value of the 'module' register, raw
843    register MEP_MODULE_REGNUM.  Otherwise, this retrieves the value
844    from the ELF header's e_flags field of the current executable
845    file.  */
846 static CONFIG_ATTR
847 current_me_module (void)
848 {
849   if (target_has_registers ())
850     {
851       ULONGEST regval;
852       regcache_cooked_read_unsigned (get_current_regcache (),
853 				     MEP_MODULE_REGNUM, &regval);
854       return (CONFIG_ATTR) regval;
855     }
856   else
857     {
858       mep_gdbarch_tdep *tdep
859 	= gdbarch_tdep<mep_gdbarch_tdep> (target_gdbarch ());
860       return tdep->me_module;
861     }
862 }
863 
864 
865 /* Return the set of options for the current target, in the form that
866    the OPT register would use.
867 
868    If the current target has registers (e.g., simulator, remote
869    target), then this is the actual value of the OPT register.  If the
870    current target does not have registers (e.g., an executable file),
871    then use the 'module_opt' field we computed when we build the
872    gdbarch object for this module.  */
873 static unsigned int
874 current_options (void)
875 {
876   if (target_has_registers ())
877     {
878       ULONGEST regval;
879       regcache_cooked_read_unsigned (get_current_regcache (),
880 				     MEP_OPT_REGNUM, &regval);
881       return regval;
882     }
883   else
884     return me_module_opt (current_me_module ());
885 }
886 
887 
888 /* Return the width of the current me_module's coprocessor data bus,
889    in bits.  This is either 32 or 64.  */
890 static int
891 current_cop_data_bus_width (void)
892 {
893   return me_module_cop_data_bus_width (current_me_module ());
894 }
895 
896 
897 /* Return the keyword table of coprocessor general-purpose register
898    names appropriate for the me_module we're dealing with.  */
899 static CGEN_KEYWORD *
900 current_cr_names (void)
901 {
902   const CGEN_HW_ENTRY *hw
903     = me_module_register_set (current_me_module (), "h-cr-", HW_H_CR);
904 
905   return register_set_keyword_table (hw);
906 }
907 
908 
909 /* Return non-zero if the coprocessor general-purpose registers are
910    floating-point values, zero otherwise.  */
911 static int
912 current_cr_is_float (void)
913 {
914   const CGEN_HW_ENTRY *hw
915     = me_module_register_set (current_me_module (), "h-cr-", HW_H_CR);
916 
917   return CGEN_ATTR_CGEN_HW_IS_FLOAT_VALUE (CGEN_HW_ATTRS (hw));
918 }
919 
920 
921 /* Return the keyword table of coprocessor control register names
922    appropriate for the me_module we're dealing with.  */
923 static CGEN_KEYWORD *
924 current_ccr_names (void)
925 {
926   const CGEN_HW_ENTRY *hw
927     = me_module_register_set (current_me_module (), "h-ccr-", HW_H_CCR);
928 
929   return register_set_keyword_table (hw);
930 }
931 
932 
933 static const char *
934 mep_register_name (struct gdbarch *gdbarch, int regnr)
935 {
936   /* General-purpose registers.  */
937   static const char *gpr_names[] = {
938     "r0",   "r1",   "r2",   "r3",   /* 0 */
939     "r4",   "r5",   "r6",   "r7",   /* 4 */
940     "fp",   "r9",   "r10",  "r11",  /* 8 */
941     "r12",  "tp",   "gp",   "sp"    /* 12 */
942   };
943 
944   /* Special-purpose registers.  */
945   static const char *csr_names[] = {
946     "pc",   "lp",   "sar",  "",     /* 0  csr3: reserved */
947     "rpb",  "rpe",  "rpc",  "hi",   /* 4 */
948     "lo",   "",     "",     "",     /* 8  csr9-csr11: reserved */
949     "mb0",  "me0",  "mb1",  "me1",  /* 12 */
950 
951     "psw",  "id",   "tmp",  "epc",  /* 16 */
952     "exc",  "cfg",  "",     "npc",  /* 20  csr22: reserved */
953     "dbg",  "depc", "opt",  "rcfg", /* 24 */
954     "ccfg", "",     "",     ""      /* 28  csr29-csr31: reserved */
955   };
956 
957   if (IS_GPR_REGNUM (regnr))
958     return gpr_names[regnr - MEP_R0_REGNUM];
959   else if (IS_CSR_REGNUM (regnr))
960     {
961       /* The 'hi' and 'lo' registers are only present on processors
962 	 that have the 'MUL' or 'DIV' instructions enabled.  */
963       if ((regnr == MEP_HI_REGNUM || regnr == MEP_LO_REGNUM)
964 	  && (! (current_options () & (MEP_OPT_MUL | MEP_OPT_DIV))))
965 	return "";
966 
967       return csr_names[regnr - MEP_FIRST_CSR_REGNUM];
968     }
969   else if (IS_CR_REGNUM (regnr))
970     {
971       CGEN_KEYWORD *names;
972       int cr_size;
973       int cr_is_float;
974 
975       /* Does this module have a coprocessor at all?  */
976       if (! (current_options () & MEP_OPT_COP))
977 	return "";
978 
979       names = current_cr_names ();
980       if (! names)
981 	/* This module's coprocessor has no general-purpose registers.  */
982 	return "";
983 
984       cr_size = current_cop_data_bus_width ();
985       if (cr_size != mep_pseudo_cr_size (regnr))
986 	/* This module's coprocessor's GPR's are of a different size.  */
987 	return "";
988 
989       cr_is_float = current_cr_is_float ();
990       /* The extra ! operators ensure we get boolean equality, not
991 	 numeric equality.  */
992       if (! cr_is_float != ! mep_pseudo_cr_is_float (regnr))
993 	/* This module's coprocessor's GPR's are of a different type.  */
994 	return "";
995 
996       return register_name_from_keyword (names, mep_pseudo_cr_index (regnr));
997     }
998   else if (IS_CCR_REGNUM (regnr))
999     {
1000       /* Does this module have a coprocessor at all?  */
1001       if (! (current_options () & MEP_OPT_COP))
1002 	return "";
1003 
1004       {
1005 	CGEN_KEYWORD *names = current_ccr_names ();
1006 
1007 	if (! names)
1008 	  /* This me_module's coprocessor has no control registers.  */
1009 	  return "";
1010 
1011 	return register_name_from_keyword (names, regnr-MEP_FIRST_CCR_REGNUM);
1012       }
1013     }
1014 
1015   /* It might be nice to give the 'module' register a name, but that
1016      would affect the output of 'info all-registers', which would
1017      disturb the test suites.  So we leave it invisible.  */
1018   else
1019     return "";
1020 }
1021 
1022 
1023 /* Custom register groups for the MeP.  */
1024 static const reggroup *mep_csr_reggroup; /* control/special */
1025 static const reggroup *mep_cr_reggroup;  /* coprocessor general-purpose */
1026 static const reggroup *mep_ccr_reggroup; /* coprocessor control */
1027 
1028 
1029 static int
1030 mep_register_reggroup_p (struct gdbarch *gdbarch, int regnum,
1031 			 const struct reggroup *group)
1032 {
1033   /* Filter reserved or unused register numbers.  */
1034   {
1035     const char *name = mep_register_name (gdbarch, regnum);
1036 
1037     if (! name || name[0] == '\0')
1038       return 0;
1039   }
1040 
1041   /* We could separate the GPRs and the CSRs.  Toshiba has approved of
1042      the existing behavior, so we'd want to run that by them.  */
1043   if (group == general_reggroup)
1044     return (IS_GPR_REGNUM (regnum)
1045 	    || IS_CSR_REGNUM (regnum));
1046 
1047   /* Everything is in the 'all' reggroup, except for the raw CSR's.  */
1048   else if (group == all_reggroup)
1049     return (IS_GPR_REGNUM (regnum)
1050 	    || IS_CSR_REGNUM (regnum)
1051 	    || IS_CR_REGNUM (regnum)
1052 	    || IS_CCR_REGNUM (regnum));
1053 
1054   /* All registers should be saved and restored, except for the raw
1055      CSR's.
1056 
1057      This is probably right if the coprocessor is something like a
1058      floating-point unit, but would be wrong if the coprocessor is
1059      something that does I/O, where register accesses actually cause
1060      externally-visible actions.  But I get the impression that the
1061      coprocessor isn't supposed to do things like that --- you'd use a
1062      hardware engine, perhaps.  */
1063   else if (group == save_reggroup || group == restore_reggroup)
1064     return (IS_GPR_REGNUM (regnum)
1065 	    || IS_CSR_REGNUM (regnum)
1066 	    || IS_CR_REGNUM (regnum)
1067 	    || IS_CCR_REGNUM (regnum));
1068 
1069   else if (group == mep_csr_reggroup)
1070     return IS_CSR_REGNUM (regnum);
1071   else if (group == mep_cr_reggroup)
1072     return IS_CR_REGNUM (regnum);
1073   else if (group == mep_ccr_reggroup)
1074     return IS_CCR_REGNUM (regnum);
1075   else
1076     return 0;
1077 }
1078 
1079 
1080 static struct type *
1081 mep_register_type (struct gdbarch *gdbarch, int reg_nr)
1082 {
1083   /* Coprocessor general-purpose registers may be either 32 or 64 bits
1084      long.  So for them, the raw registers are always 64 bits long (to
1085      keep the 'g' packet format fixed), and the pseudoregisters vary
1086      in length.  */
1087   if (IS_RAW_CR_REGNUM (reg_nr))
1088     return builtin_type (gdbarch)->builtin_uint64;
1089 
1090   /* Since GDB doesn't allow registers to change type, we have two
1091      banks of pseudoregisters for the coprocessor general-purpose
1092      registers: one that gives a 32-bit view, and one that gives a
1093      64-bit view.  We hide or show one or the other depending on the
1094      current module.  */
1095   if (IS_CR_REGNUM (reg_nr))
1096     {
1097       int size = mep_pseudo_cr_size (reg_nr);
1098       if (size == 32)
1099 	{
1100 	  if (mep_pseudo_cr_is_float (reg_nr))
1101 	    return builtin_type (gdbarch)->builtin_float;
1102 	  else
1103 	    return builtin_type (gdbarch)->builtin_uint32;
1104 	}
1105       else if (size == 64)
1106 	{
1107 	  if (mep_pseudo_cr_is_float (reg_nr))
1108 	    return builtin_type (gdbarch)->builtin_double;
1109 	  else
1110 	    return builtin_type (gdbarch)->builtin_uint64;
1111 	}
1112       else
1113 	gdb_assert_not_reached ("unexpected cr size");
1114     }
1115 
1116   /* All other registers are 32 bits long.  */
1117   else
1118     return builtin_type (gdbarch)->builtin_uint32;
1119 }
1120 
1121 static enum register_status
1122 mep_pseudo_cr32_read (struct gdbarch *gdbarch,
1123 		      readable_regcache *regcache,
1124 		      int cookednum,
1125 		      gdb_byte *buf)
1126 {
1127   enum register_status status;
1128   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1129   /* Read the raw register into a 64-bit buffer, and then return the
1130      appropriate end of that buffer.  */
1131   int rawnum = mep_pseudo_to_raw[cookednum];
1132   gdb_byte buf64[8];
1133 
1134   gdb_assert (register_type (gdbarch, rawnum)->length () == sizeof (buf64));
1135   gdb_assert (register_type (gdbarch, cookednum)->length () == 4);
1136   status = regcache->raw_read (rawnum, buf64);
1137   if (status == REG_VALID)
1138     {
1139       /* Slow, but legible.  */
1140       store_unsigned_integer (buf, 4, byte_order,
1141 			      extract_unsigned_integer (buf64, 8, byte_order));
1142     }
1143   return status;
1144 }
1145 
1146 
1147 static enum register_status
1148 mep_pseudo_cr64_read (struct gdbarch *gdbarch,
1149 		      readable_regcache *regcache,
1150 		      int cookednum,
1151 		      gdb_byte *buf)
1152 {
1153   return regcache->raw_read (mep_pseudo_to_raw[cookednum], buf);
1154 }
1155 
1156 
1157 static enum register_status
1158 mep_pseudo_register_read (struct gdbarch *gdbarch,
1159 			  readable_regcache *regcache,
1160 			  int cookednum,
1161 			  gdb_byte *buf)
1162 {
1163   if (IS_CSR_REGNUM (cookednum)
1164       || IS_CCR_REGNUM (cookednum))
1165     return regcache->raw_read (mep_pseudo_to_raw[cookednum], buf);
1166   else if (IS_CR32_REGNUM (cookednum)
1167 	   || IS_FP_CR32_REGNUM (cookednum))
1168     return mep_pseudo_cr32_read (gdbarch, regcache, cookednum, buf);
1169   else if (IS_CR64_REGNUM (cookednum)
1170 	   || IS_FP_CR64_REGNUM (cookednum))
1171     return mep_pseudo_cr64_read (gdbarch, regcache, cookednum, buf);
1172   else
1173     gdb_assert_not_reached ("unexpected pseudo register");
1174 }
1175 
1176 
1177 static void
1178 mep_pseudo_csr_write (struct gdbarch *gdbarch,
1179 		      struct regcache *regcache,
1180 		      int cookednum,
1181 		      const gdb_byte *buf)
1182 {
1183   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1184   int size = register_size (gdbarch, cookednum);
1185   struct mep_csr_register *r
1186     = &mep_csr_registers[cookednum - MEP_FIRST_CSR_REGNUM];
1187 
1188   if (r->writeable_bits == 0)
1189     /* A completely read-only register; avoid the read-modify-
1190        write cycle, and juts ignore the entire write.  */
1191     ;
1192   else
1193     {
1194       /* A partially writeable register; do a read-modify-write cycle.  */
1195       ULONGEST old_bits;
1196       ULONGEST new_bits;
1197       ULONGEST mixed_bits;
1198 
1199       regcache_raw_read_unsigned (regcache, r->raw, &old_bits);
1200       new_bits = extract_unsigned_integer (buf, size, byte_order);
1201       mixed_bits = ((r->writeable_bits & new_bits)
1202 		    | (~r->writeable_bits & old_bits));
1203       regcache_raw_write_unsigned (regcache, r->raw, mixed_bits);
1204     }
1205 }
1206 
1207 
1208 static void
1209 mep_pseudo_cr32_write (struct gdbarch *gdbarch,
1210 		       struct regcache *regcache,
1211 		       int cookednum,
1212 		       const gdb_byte *buf)
1213 {
1214   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1215   /* Expand the 32-bit value into a 64-bit value, and write that to
1216      the pseudoregister.  */
1217   int rawnum = mep_pseudo_to_raw[cookednum];
1218   gdb_byte buf64[8];
1219 
1220   gdb_assert (register_type (gdbarch, rawnum)->length () == sizeof (buf64));
1221   gdb_assert (register_type (gdbarch, cookednum)->length () == 4);
1222   /* Slow, but legible.  */
1223   store_unsigned_integer (buf64, 8, byte_order,
1224 			  extract_unsigned_integer (buf, 4, byte_order));
1225   regcache->raw_write (rawnum, buf64);
1226 }
1227 
1228 
1229 static void
1230 mep_pseudo_cr64_write (struct gdbarch *gdbarch,
1231 		     struct regcache *regcache,
1232 		     int cookednum,
1233 		     const gdb_byte *buf)
1234 {
1235   regcache->raw_write (mep_pseudo_to_raw[cookednum], buf);
1236 }
1237 
1238 
1239 static void
1240 mep_pseudo_register_write (struct gdbarch *gdbarch,
1241 			   struct regcache *regcache,
1242 			   int cookednum,
1243 			   const gdb_byte *buf)
1244 {
1245   if (IS_CSR_REGNUM (cookednum))
1246     mep_pseudo_csr_write (gdbarch, regcache, cookednum, buf);
1247   else if (IS_CR32_REGNUM (cookednum)
1248 	   || IS_FP_CR32_REGNUM (cookednum))
1249     mep_pseudo_cr32_write (gdbarch, regcache, cookednum, buf);
1250   else if (IS_CR64_REGNUM (cookednum)
1251 	   || IS_FP_CR64_REGNUM (cookednum))
1252     mep_pseudo_cr64_write (gdbarch, regcache, cookednum, buf);
1253   else if (IS_CCR_REGNUM (cookednum))
1254     regcache->raw_write (mep_pseudo_to_raw[cookednum], buf);
1255   else
1256     gdb_assert_not_reached ("unexpected pseudo register");
1257 }
1258 
1259 
1260 
1261 /* Disassembly.  */
1262 
1263 static int
1264 mep_gdb_print_insn (bfd_vma pc, disassemble_info * info)
1265 {
1266   struct obj_section * s = find_pc_section (pc);
1267 
1268   info->arch = bfd_arch_mep;
1269   if (s)
1270     {
1271       /* The libopcodes disassembly code uses the section to find the
1272 	 BFD, the BFD to find the ELF header, the ELF header to find
1273 	 the me_module index, and the me_module index to select the
1274 	 right instructions to print.  */
1275       info->section = s->the_bfd_section;
1276     }
1277 
1278   return print_insn_mep (pc, info);
1279 }
1280 
1281 
1282 /* Prologue analysis.  */
1283 
1284 
1285 /* The MeP has two classes of instructions: "core" instructions, which
1286    are pretty normal RISC chip stuff, and "coprocessor" instructions,
1287    which are mostly concerned with moving data in and out of
1288    coprocessor registers, and branching on coprocessor condition
1289    codes.  There's space in the instruction set for custom coprocessor
1290    instructions, too.
1291 
1292    Instructions can be 16 or 32 bits long; the top two bits of the
1293    first byte indicate the length.  The coprocessor instructions are
1294    mixed in with the core instructions, and there's no easy way to
1295    distinguish them; you have to completely decode them to tell one
1296    from the other.
1297 
1298    The MeP also supports a "VLIW" operation mode, where instructions
1299    always occur in fixed-width bundles.  The bundles are either 32
1300    bits or 64 bits long, depending on a fixed configuration flag.  You
1301    decode the first part of the bundle as normal; if it's a core
1302    instruction, and there's any space left in the bundle, the
1303    remainder of the bundle is a coprocessor instruction, which will
1304    execute in parallel with the core instruction.  If the first part
1305    of the bundle is a coprocessor instruction, it occupies the entire
1306    bundle.
1307 
1308    So, here are all the cases:
1309 
1310    - 32-bit VLIW mode:
1311      Every bundle is four bytes long, and naturally aligned, and can hold
1312      one or two instructions:
1313      - 16-bit core instruction; 16-bit coprocessor instruction
1314        These execute in parallel.
1315      - 32-bit core instruction
1316      - 32-bit coprocessor instruction
1317 
1318    - 64-bit VLIW mode:
1319      Every bundle is eight bytes long, and naturally aligned, and can hold
1320      one or two instructions:
1321      - 16-bit core instruction; 48-bit (!) coprocessor instruction
1322        These execute in parallel.
1323      - 32-bit core instruction; 32-bit coprocessor instruction
1324        These execute in parallel.
1325      - 64-bit coprocessor instruction
1326 
1327    Now, the MeP manual doesn't define any 48- or 64-bit coprocessor
1328    instruction, so I don't really know what's up there; perhaps these
1329    are always the user-defined coprocessor instructions.  */
1330 
1331 
1332 /* Return non-zero if PC is in a VLIW code section, zero
1333    otherwise.  */
1334 static int
1335 mep_pc_in_vliw_section (CORE_ADDR pc)
1336 {
1337   struct obj_section *s = find_pc_section (pc);
1338   if (s)
1339     return (s->the_bfd_section->flags & SEC_MEP_VLIW);
1340   return 0;
1341 }
1342 
1343 
1344 /* Set *INSN to the next core instruction at PC, and return the
1345    address of the next instruction.
1346 
1347    The MeP instruction encoding is endian-dependent.  16- and 32-bit
1348    instructions are encoded as one or two two-byte parts, and each
1349    part is byte-swapped independently.  Thus:
1350 
1351       void
1352       foo (void)
1353       {
1354 	asm ("movu $1, 0x123456");
1355 	asm ("sb $1,0x5678($2)");
1356 	asm ("clip $1, 19");
1357       }
1358 
1359    compiles to this big-endian code:
1360 
1361        0:	d1 56 12 34 	movu $1,0x123456
1362        4:	c1 28 56 78 	sb $1,22136($2)
1363        8:	f1 01 10 98 	clip $1,0x13
1364        c:	70 02       	ret
1365 
1366    and this little-endian code:
1367 
1368        0:	56 d1 34 12 	movu $1,0x123456
1369        4:	28 c1 78 56 	sb $1,22136($2)
1370        8:	01 f1 98 10 	clip $1,0x13
1371        c:	02 70       	ret
1372 
1373    Instructions are returned in *INSN in an endian-independent form: a
1374    given instruction always appears in *INSN the same way, regardless
1375    of whether the instruction stream is big-endian or little-endian.
1376 
1377    *INSN's most significant 16 bits are the first (i.e., at lower
1378    addresses) 16 bit part of the instruction.  Its least significant
1379    16 bits are the second (i.e., higher-addressed) 16 bit part of the
1380    instruction, or zero for a 16-bit instruction.  Both 16-bit parts
1381    are fetched using the current endianness.
1382 
1383    So, the *INSN values for the instruction sequence above would be
1384    the following, in either endianness:
1385 
1386        0xd1561234       movu $1,0x123456
1387        0xc1285678 	sb $1,22136($2)
1388        0xf1011098 	clip $1,0x13
1389        0x70020000      	ret
1390 
1391    (In a sense, it would be more natural to return 16-bit instructions
1392    in the least significant 16 bits of *INSN, but that would be
1393    ambiguous.  In order to tell whether you're looking at a 16- or a
1394    32-bit instruction, you have to consult the major opcode field ---
1395    the most significant four bits of the instruction's first 16-bit
1396    part.  But if we put 16-bit instructions at the least significant
1397    end of *INSN, then you don't know where to find the major opcode
1398    field until you know if it's a 16- or a 32-bit instruction ---
1399    which is where we started.)
1400 
1401    If PC points to a core / coprocessor bundle in a VLIW section, set
1402    *INSN to the core instruction, and return the address of the next
1403    bundle.  This has the effect of skipping the bundled coprocessor
1404    instruction.  That's okay, since coprocessor instructions aren't
1405    significant to prologue analysis --- for the time being,
1406    anyway.  */
1407 
1408 static CORE_ADDR
1409 mep_get_insn (struct gdbarch *gdbarch, CORE_ADDR pc, unsigned long *insn)
1410 {
1411   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1412   int pc_in_vliw_section;
1413   int vliw_mode;
1414   int insn_len;
1415   gdb_byte buf[2];
1416 
1417   *insn = 0;
1418 
1419   /* Are we in a VLIW section?  */
1420   pc_in_vliw_section = mep_pc_in_vliw_section (pc);
1421   if (pc_in_vliw_section)
1422     {
1423       /* Yes, find out which bundle size.  */
1424       vliw_mode = current_options () & (MEP_OPT_VL32 | MEP_OPT_VL64);
1425 
1426       /* If PC is in a VLIW section, but the current core doesn't say
1427 	 that it supports either VLIW mode, then we don't have enough
1428 	 information to parse the instruction stream it contains.
1429 	 Since the "undifferentiated" standard core doesn't have
1430 	 either VLIW mode bit set, this could happen.
1431 
1432 	 But it shouldn't be an error to (say) set a breakpoint in a
1433 	 VLIW section, if you know you'll never reach it.  (Perhaps
1434 	 you have a script that sets a bunch of standard breakpoints.)
1435 
1436 	 So we'll just return zero here, and hope for the best.  */
1437       if (! (vliw_mode & (MEP_OPT_VL32 | MEP_OPT_VL64)))
1438 	return 0;
1439 
1440       /* If both VL32 and VL64 are set, that's bogus, too.  */
1441       if (vliw_mode == (MEP_OPT_VL32 | MEP_OPT_VL64))
1442 	return 0;
1443     }
1444   else
1445     vliw_mode = 0;
1446 
1447   read_memory (pc, buf, sizeof (buf));
1448   *insn = extract_unsigned_integer (buf, 2, byte_order) << 16;
1449 
1450   /* The major opcode --- the top four bits of the first 16-bit
1451      part --- indicates whether this instruction is 16 or 32 bits
1452      long.  All 32-bit instructions have a major opcode whose top
1453      two bits are 11; all the rest are 16-bit instructions.  */
1454   if ((*insn & 0xc0000000) == 0xc0000000)
1455     {
1456       /* Fetch the second 16-bit part of the instruction.  */
1457       read_memory (pc + 2, buf, sizeof (buf));
1458       *insn = *insn | extract_unsigned_integer (buf, 2, byte_order);
1459     }
1460 
1461   /* If we're in VLIW code, then the VLIW width determines the address
1462      of the next instruction.  */
1463   if (vliw_mode)
1464     {
1465       /* In 32-bit VLIW code, all bundles are 32 bits long.  We ignore the
1466 	 coprocessor half of a core / copro bundle.  */
1467       if (vliw_mode == MEP_OPT_VL32)
1468 	insn_len = 4;
1469 
1470       /* In 64-bit VLIW code, all bundles are 64 bits long.  We ignore the
1471 	 coprocessor half of a core / copro bundle.  */
1472       else if (vliw_mode == MEP_OPT_VL64)
1473 	insn_len = 8;
1474 
1475       /* We'd better be in either core, 32-bit VLIW, or 64-bit VLIW mode.  */
1476       else
1477 	gdb_assert_not_reached ("unexpected vliw mode");
1478     }
1479 
1480   /* Otherwise, the top two bits of the major opcode are (again) what
1481      we need to check.  */
1482   else if ((*insn & 0xc0000000) == 0xc0000000)
1483     insn_len = 4;
1484   else
1485     insn_len = 2;
1486 
1487   return pc + insn_len;
1488 }
1489 
1490 
1491 /* Sign-extend the LEN-bit value N.  */
1492 #define SEXT(n, len) ((((int) (n)) ^ (1 << ((len) - 1))) - (1 << ((len) - 1)))
1493 
1494 /* Return the LEN-bit field at POS from I.  */
1495 #define FIELD(i, pos, len) (((i) >> (pos)) & ((1 << (len)) - 1))
1496 
1497 /* Like FIELD, but sign-extend the field's value.  */
1498 #define SFIELD(i, pos, len) (SEXT (FIELD ((i), (pos), (len)), (len)))
1499 
1500 
1501 /* Macros for decoding instructions.
1502 
1503    Remember that 16-bit instructions are placed in bits 16..31 of i,
1504    not at the least significant end; this means that the major opcode
1505    field is always in the same place, regardless of the width of the
1506    instruction.  As a reminder of this, we show the lower 16 bits of a
1507    16-bit instruction as xxxx_xxxx_xxxx_xxxx.  */
1508 
1509 /* SB Rn,(Rm)		      0000_nnnn_mmmm_1000 */
1510 /* SH Rn,(Rm)		      0000_nnnn_mmmm_1001 */
1511 /* SW Rn,(Rm)		      0000_nnnn_mmmm_1010 */
1512 
1513 /* SW Rn,disp16(Rm)	      1100_nnnn_mmmm_1010 dddd_dddd_dddd_dddd */
1514 #define IS_SW(i)	      (((i) & 0xf00f0000) == 0xc00a0000)
1515 /* SB Rn,disp16(Rm)	      1100_nnnn_mmmm_1000 dddd_dddd_dddd_dddd */
1516 #define IS_SB(i)	      (((i) & 0xf00f0000) == 0xc0080000)
1517 /* SH Rn,disp16(Rm)	      1100_nnnn_mmmm_1001 dddd_dddd_dddd_dddd */
1518 #define IS_SH(i)	      (((i) & 0xf00f0000) == 0xc0090000)
1519 #define SWBH_32_BASE(i)       (FIELD (i, 20, 4))
1520 #define SWBH_32_SOURCE(i)     (FIELD (i, 24, 4))
1521 #define SWBH_32_OFFSET(i)     (SFIELD (i, 0, 16))
1522 
1523 /* SW Rn,disp7.align4(SP)     0100_nnnn_0ddd_dd10 xxxx_xxxx_xxxx_xxxx */
1524 #define IS_SW_IMMD(i)	      (((i) & 0xf0830000) == 0x40020000)
1525 #define SW_IMMD_SOURCE(i)     (FIELD (i, 24, 4))
1526 #define SW_IMMD_OFFSET(i)     (FIELD (i, 18, 5) << 2)
1527 
1528 /* SW Rn,(Rm)                 0000_nnnn_mmmm_1010 xxxx_xxxx_xxxx_xxxx */
1529 #define IS_SW_REG(i)	      (((i) & 0xf00f0000) == 0x000a0000)
1530 #define SW_REG_SOURCE(i)      (FIELD (i, 24, 4))
1531 #define SW_REG_BASE(i)        (FIELD (i, 20, 4))
1532 
1533 /* ADD3 Rl,Rn,Rm              1001_nnnn_mmmm_llll xxxx_xxxx_xxxx_xxxx */
1534 #define IS_ADD3_16_REG(i)     (((i) & 0xf0000000) == 0x90000000)
1535 #define ADD3_16_REG_SRC1(i)   (FIELD (i, 20, 4))               /* n */
1536 #define ADD3_16_REG_SRC2(i)   (FIELD (i, 24, 4))               /* m */
1537 
1538 /* ADD3 Rn,Rm,imm16           1100_nnnn_mmmm_0000 iiii_iiii_iiii_iiii */
1539 #define IS_ADD3_32(i)	      (((i) & 0xf00f0000) == 0xc0000000)
1540 #define ADD3_32_TARGET(i)     (FIELD (i, 24, 4))
1541 #define ADD3_32_SOURCE(i)     (FIELD (i, 20, 4))
1542 #define ADD3_32_OFFSET(i)     (SFIELD (i, 0, 16))
1543 
1544 /* ADD3 Rn,SP,imm7.align4     0100_nnnn_0iii_ii00 xxxx_xxxx_xxxx_xxxx */
1545 #define IS_ADD3_16(i)  	      (((i) & 0xf0830000) == 0x40000000)
1546 #define ADD3_16_TARGET(i)     (FIELD (i, 24, 4))
1547 #define ADD3_16_OFFSET(i)     (FIELD (i, 18, 5) << 2)
1548 
1549 /* ADD Rn,imm6		      0110_nnnn_iiii_ii00 xxxx_xxxx_xxxx_xxxx */
1550 #define IS_ADD(i) 	      (((i) & 0xf0030000) == 0x60000000)
1551 #define ADD_TARGET(i)	      (FIELD (i, 24, 4))
1552 #define ADD_OFFSET(i)         (SFIELD (i, 18, 6))
1553 
1554 /* LDC Rn,imm5		      0111_nnnn_iiii_101I xxxx_xxxx_xxxx_xxxx
1555 			      imm5 = I||i[7:4] */
1556 #define IS_LDC(i)	      (((i) & 0xf00e0000) == 0x700a0000)
1557 #define LDC_IMM(i)            ((FIELD (i, 16, 1) << 4) | FIELD (i, 20, 4))
1558 #define LDC_TARGET(i)         (FIELD (i, 24, 4))
1559 
1560 /* LW Rn,disp16(Rm)           1100_nnnn_mmmm_1110 dddd_dddd_dddd_dddd  */
1561 #define IS_LW(i)              (((i) & 0xf00f0000) == 0xc00e0000)
1562 #define LW_TARGET(i)          (FIELD (i, 24, 4))
1563 #define LW_BASE(i)            (FIELD (i, 20, 4))
1564 #define LW_OFFSET(i)          (SFIELD (i, 0, 16))
1565 
1566 /* MOV Rn,Rm		      0000_nnnn_mmmm_0000 xxxx_xxxx_xxxx_xxxx */
1567 #define IS_MOV(i)	      (((i) & 0xf00f0000) == 0x00000000)
1568 #define MOV_TARGET(i)	      (FIELD (i, 24, 4))
1569 #define MOV_SOURCE(i)	      (FIELD (i, 20, 4))
1570 
1571 /* BRA disp12.align2	      1011_dddd_dddd_ddd0 xxxx_xxxx_xxxx_xxxx */
1572 #define IS_BRA(i)	      (((i) & 0xf0010000) == 0xb0000000)
1573 #define BRA_DISP(i)           (SFIELD (i, 17, 11) << 1)
1574 
1575 
1576 /* This structure holds the results of a prologue analysis.  */
1577 struct mep_prologue
1578 {
1579   /* The architecture for which we generated this prologue info.  */
1580   struct gdbarch *gdbarch;
1581 
1582   /* The offset from the frame base to the stack pointer --- always
1583      zero or negative.
1584 
1585      Calling this a "size" is a bit misleading, but given that the
1586      stack grows downwards, using offsets for everything keeps one
1587      from going completely sign-crazy: you never change anything's
1588      sign for an ADD instruction; always change the second operand's
1589      sign for a SUB instruction; and everything takes care of
1590      itself.  */
1591   int frame_size;
1592 
1593   /* Non-zero if this function has initialized the frame pointer from
1594      the stack pointer, zero otherwise.  */
1595   int has_frame_ptr;
1596 
1597   /* If has_frame_ptr is non-zero, this is the offset from the frame
1598      base to where the frame pointer points.  This is always zero or
1599      negative.  */
1600   int frame_ptr_offset;
1601 
1602   /* The address of the first instruction at which the frame has been
1603      set up and the arguments are where the debug info says they are
1604      --- as best as we can tell.  */
1605   CORE_ADDR prologue_end;
1606 
1607   /* reg_offset[R] is the offset from the CFA at which register R is
1608      saved, or 1 if register R has not been saved.  (Real values are
1609      always zero or negative.)  */
1610   int reg_offset[MEP_NUM_REGS];
1611 };
1612 
1613 /* Return non-zero if VALUE is an incoming argument register.  */
1614 
1615 static int
1616 is_arg_reg (pv_t value)
1617 {
1618   return (value.kind == pvk_register
1619 	  && MEP_R1_REGNUM <= value.reg && value.reg <= MEP_R4_REGNUM
1620 	  && value.k == 0);
1621 }
1622 
1623 /* Return non-zero if a store of REG's current value VALUE to ADDR is
1624    probably spilling an argument register to its stack slot in STACK.
1625    Such instructions should be included in the prologue, if possible.
1626 
1627    The store is a spill if:
1628    - the value being stored is REG's original value;
1629    - the value has not already been stored somewhere in STACK; and
1630    - ADDR is a stack slot's address (e.g., relative to the original
1631      value of the SP).  */
1632 static int
1633 is_arg_spill (struct gdbarch *gdbarch, pv_t value, pv_t addr,
1634 	      struct pv_area *stack)
1635 {
1636   return (is_arg_reg (value)
1637 	  && pv_is_register (addr, MEP_SP_REGNUM)
1638 	  && ! stack->find_reg (gdbarch, value.reg, 0));
1639 }
1640 
1641 
1642 /* Function for finding saved registers in a 'struct pv_area'; we pass
1643    this to pv_area::scan.
1644 
1645    If VALUE is a saved register, ADDR says it was saved at a constant
1646    offset from the frame base, and SIZE indicates that the whole
1647    register was saved, record its offset in RESULT_UNTYPED.  */
1648 static void
1649 check_for_saved (void *result_untyped, pv_t addr, CORE_ADDR size, pv_t value)
1650 {
1651   struct mep_prologue *result = (struct mep_prologue *) result_untyped;
1652 
1653   if (value.kind == pvk_register
1654       && value.k == 0
1655       && pv_is_register (addr, MEP_SP_REGNUM)
1656       && size == register_size (result->gdbarch, value.reg))
1657     result->reg_offset[value.reg] = addr.k;
1658 }
1659 
1660 
1661 /* Analyze a prologue starting at START_PC, going no further than
1662    LIMIT_PC.  Fill in RESULT as appropriate.  */
1663 static void
1664 mep_analyze_prologue (struct gdbarch *gdbarch,
1665 		      CORE_ADDR start_pc, CORE_ADDR limit_pc,
1666 		      struct mep_prologue *result)
1667 {
1668   CORE_ADDR pc;
1669   unsigned long insn;
1670   pv_t reg[MEP_NUM_REGS];
1671   CORE_ADDR after_last_frame_setup_insn = start_pc;
1672 
1673   memset (result, 0, sizeof (*result));
1674   result->gdbarch = gdbarch;
1675 
1676   for (int rn = 0; rn < MEP_NUM_REGS; rn++)
1677     {
1678       reg[rn] = pv_register (rn, 0);
1679       result->reg_offset[rn] = 1;
1680     }
1681 
1682   pv_area stack (MEP_SP_REGNUM, gdbarch_addr_bit (gdbarch));
1683 
1684   pc = start_pc;
1685   while (pc < limit_pc)
1686     {
1687       CORE_ADDR next_pc;
1688       pv_t pre_insn_fp, pre_insn_sp;
1689 
1690       next_pc = mep_get_insn (gdbarch, pc, &insn);
1691 
1692       /* A zero return from mep_get_insn means that either we weren't
1693 	 able to read the instruction from memory, or that we don't
1694 	 have enough information to be able to reliably decode it.  So
1695 	 we'll store here and hope for the best.  */
1696       if (! next_pc)
1697 	break;
1698 
1699       /* Note the current values of the SP and FP, so we can tell if
1700 	 this instruction changed them, below.  */
1701       pre_insn_fp = reg[MEP_FP_REGNUM];
1702       pre_insn_sp = reg[MEP_SP_REGNUM];
1703 
1704       if (IS_ADD (insn))
1705 	{
1706 	  int rn = ADD_TARGET (insn);
1707 	  CORE_ADDR imm6 = ADD_OFFSET (insn);
1708 
1709 	  reg[rn] = pv_add_constant (reg[rn], imm6);
1710 	}
1711       else if (IS_ADD3_16 (insn))
1712 	{
1713 	  int rn = ADD3_16_TARGET (insn);
1714 	  int imm7 = ADD3_16_OFFSET (insn);
1715 
1716 	  reg[rn] = pv_add_constant (reg[MEP_SP_REGNUM], imm7);
1717 	}
1718       else if (IS_ADD3_32 (insn))
1719 	{
1720 	  int rn = ADD3_32_TARGET (insn);
1721 	  int rm = ADD3_32_SOURCE (insn);
1722 	  int imm16 = ADD3_32_OFFSET (insn);
1723 
1724 	  reg[rn] = pv_add_constant (reg[rm], imm16);
1725 	}
1726       else if (IS_SW_REG (insn))
1727 	{
1728 	  int rn = SW_REG_SOURCE (insn);
1729 	  int rm = SW_REG_BASE (insn);
1730 
1731 	  /* If simulating this store would require us to forget
1732 	     everything we know about the stack frame in the name of
1733 	     accuracy, it would be better to just quit now.  */
1734 	  if (stack.store_would_trash (reg[rm]))
1735 	    break;
1736 
1737 	  if (is_arg_spill (gdbarch, reg[rn], reg[rm], &stack))
1738 	    after_last_frame_setup_insn = next_pc;
1739 
1740 	  stack.store (reg[rm], 4, reg[rn]);
1741 	}
1742       else if (IS_SW_IMMD (insn))
1743 	{
1744 	  int rn = SW_IMMD_SOURCE (insn);
1745 	  int offset = SW_IMMD_OFFSET (insn);
1746 	  pv_t addr = pv_add_constant (reg[MEP_SP_REGNUM], offset);
1747 
1748 	  /* If simulating this store would require us to forget
1749 	     everything we know about the stack frame in the name of
1750 	     accuracy, it would be better to just quit now.  */
1751 	  if (stack.store_would_trash (addr))
1752 	    break;
1753 
1754 	  if (is_arg_spill (gdbarch, reg[rn], addr, &stack))
1755 	    after_last_frame_setup_insn = next_pc;
1756 
1757 	  stack.store (addr, 4, reg[rn]);
1758 	}
1759       else if (IS_MOV (insn))
1760 	{
1761 	  int rn = MOV_TARGET (insn);
1762 	  int rm = MOV_SOURCE (insn);
1763 
1764 	  reg[rn] = reg[rm];
1765 
1766 	  if (pv_is_register (reg[rm], rm) && is_arg_reg (reg[rm]))
1767 	    after_last_frame_setup_insn = next_pc;
1768 	}
1769       else if (IS_SB (insn) || IS_SH (insn) || IS_SW (insn))
1770 	{
1771 	  int rn = SWBH_32_SOURCE (insn);
1772 	  int rm = SWBH_32_BASE (insn);
1773 	  int disp = SWBH_32_OFFSET (insn);
1774 	  int size = (IS_SB (insn) ? 1
1775 		      : IS_SH (insn) ? 2
1776 		      : (gdb_assert (IS_SW (insn)), 4));
1777 	  pv_t addr = pv_add_constant (reg[rm], disp);
1778 
1779 	  if (stack.store_would_trash (addr))
1780 	    break;
1781 
1782 	  if (is_arg_spill (gdbarch, reg[rn], addr, &stack))
1783 	    after_last_frame_setup_insn = next_pc;
1784 
1785 	  stack.store (addr, size, reg[rn]);
1786 	}
1787       else if (IS_LDC (insn))
1788 	{
1789 	  int rn = LDC_TARGET (insn);
1790 	  int cr = LDC_IMM (insn) + MEP_FIRST_CSR_REGNUM;
1791 
1792 	  reg[rn] = reg[cr];
1793 	}
1794       else if (IS_LW (insn))
1795 	{
1796 	  int rn = LW_TARGET (insn);
1797 	  int rm = LW_BASE (insn);
1798 	  int offset = LW_OFFSET (insn);
1799 	  pv_t addr = pv_add_constant (reg[rm], offset);
1800 
1801 	  reg[rn] = stack.fetch (addr, 4);
1802 	}
1803       else if (IS_BRA (insn) && BRA_DISP (insn) > 0)
1804 	{
1805 	  /* When a loop appears as the first statement of a function
1806 	     body, gcc 4.x will use a BRA instruction to branch to the
1807 	     loop condition checking code.  This BRA instruction is
1808 	     marked as part of the prologue.  We therefore set next_pc
1809 	     to this branch target and also stop the prologue scan.
1810 	     The instructions at and beyond the branch target should
1811 	     no longer be associated with the prologue.
1812 
1813 	     Note that we only consider forward branches here.  We
1814 	     presume that a forward branch is being used to skip over
1815 	     a loop body.
1816 
1817 	     A backwards branch is covered by the default case below.
1818 	     If we were to encounter a backwards branch, that would
1819 	     most likely mean that we've scanned through a loop body.
1820 	     We definitely want to stop the prologue scan when this
1821 	     happens and that is precisely what is done by the default
1822 	     case below.  */
1823 	  next_pc = pc + BRA_DISP (insn);
1824 	  after_last_frame_setup_insn = next_pc;
1825 	  break;
1826 	}
1827       else
1828 	/* We've hit some instruction we don't know how to simulate.
1829 	   Strictly speaking, we should set every value we're
1830 	   tracking to "unknown".  But we'll be optimistic, assume
1831 	   that we have enough information already, and stop
1832 	   analysis here.  */
1833 	break;
1834 
1835       /* If this instruction changed the FP or decreased the SP (i.e.,
1836 	 allocated more stack space), then this may be a good place to
1837 	 declare the prologue finished.  However, there are some
1838 	 exceptions:
1839 
1840 	 - If the instruction just changed the FP back to its original
1841 	   value, then that's probably a restore instruction.  The
1842 	   prologue should definitely end before that.
1843 
1844 	 - If the instruction increased the value of the SP (that is,
1845 	   shrunk the frame), then it's probably part of a frame
1846 	   teardown sequence, and the prologue should end before that.  */
1847 
1848       if (! pv_is_identical (reg[MEP_FP_REGNUM], pre_insn_fp))
1849 	{
1850 	  if (! pv_is_register_k (reg[MEP_FP_REGNUM], MEP_FP_REGNUM, 0))
1851 	    after_last_frame_setup_insn = next_pc;
1852 	}
1853       else if (! pv_is_identical (reg[MEP_SP_REGNUM], pre_insn_sp))
1854 	{
1855 	  /* The comparison of constants looks odd, there, because .k
1856 	     is unsigned.  All it really means is that the new value
1857 	     is lower than it was before the instruction.  */
1858 	  if (pv_is_register (pre_insn_sp, MEP_SP_REGNUM)
1859 	      && pv_is_register (reg[MEP_SP_REGNUM], MEP_SP_REGNUM)
1860 	      && ((pre_insn_sp.k - reg[MEP_SP_REGNUM].k)
1861 		  < (reg[MEP_SP_REGNUM].k - pre_insn_sp.k)))
1862 	    after_last_frame_setup_insn = next_pc;
1863 	}
1864 
1865       pc = next_pc;
1866     }
1867 
1868   /* Is the frame size (offset, really) a known constant?  */
1869   if (pv_is_register (reg[MEP_SP_REGNUM], MEP_SP_REGNUM))
1870     result->frame_size = reg[MEP_SP_REGNUM].k;
1871 
1872   /* Was the frame pointer initialized?  */
1873   if (pv_is_register (reg[MEP_FP_REGNUM], MEP_SP_REGNUM))
1874     {
1875       result->has_frame_ptr = 1;
1876       result->frame_ptr_offset = reg[MEP_FP_REGNUM].k;
1877     }
1878 
1879   /* Record where all the registers were saved.  */
1880   stack.scan (check_for_saved, (void *) result);
1881 
1882   result->prologue_end = after_last_frame_setup_insn;
1883 }
1884 
1885 
1886 static CORE_ADDR
1887 mep_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR pc)
1888 {
1889   const char *name;
1890   CORE_ADDR func_addr, func_end;
1891   struct mep_prologue p;
1892 
1893   /* Try to find the extent of the function that contains PC.  */
1894   if (! find_pc_partial_function (pc, &name, &func_addr, &func_end))
1895     return pc;
1896 
1897   mep_analyze_prologue (gdbarch, pc, func_end, &p);
1898   return p.prologue_end;
1899 }
1900 
1901 
1902 
1903 /* Breakpoints.  */
1904 constexpr gdb_byte mep_break_insn[] = { 0x70, 0x32 };
1905 
1906 typedef BP_MANIPULATION (mep_break_insn) mep_breakpoint;
1907 
1908 
1909 /* Frames and frame unwinding.  */
1910 
1911 
1912 static struct mep_prologue *
1913 mep_analyze_frame_prologue (frame_info_ptr this_frame,
1914 			    void **this_prologue_cache)
1915 {
1916   if (! *this_prologue_cache)
1917     {
1918       CORE_ADDR func_start, stop_addr;
1919 
1920       *this_prologue_cache
1921 	= FRAME_OBSTACK_ZALLOC (struct mep_prologue);
1922 
1923       func_start = get_frame_func (this_frame);
1924       stop_addr = get_frame_pc (this_frame);
1925 
1926       /* If we couldn't find any function containing the PC, then
1927 	 just initialize the prologue cache, but don't do anything.  */
1928       if (! func_start)
1929 	stop_addr = func_start;
1930 
1931       mep_analyze_prologue (get_frame_arch (this_frame),
1932 			    func_start, stop_addr,
1933 			    (struct mep_prologue *) *this_prologue_cache);
1934     }
1935 
1936   return (struct mep_prologue *) *this_prologue_cache;
1937 }
1938 
1939 
1940 /* Given the next frame and a prologue cache, return this frame's
1941    base.  */
1942 static CORE_ADDR
1943 mep_frame_base (frame_info_ptr this_frame,
1944 		void **this_prologue_cache)
1945 {
1946   struct mep_prologue *p
1947     = mep_analyze_frame_prologue (this_frame, this_prologue_cache);
1948 
1949   /* In functions that use alloca, the distance between the stack
1950      pointer and the frame base varies dynamically, so we can't use
1951      the SP plus static information like prologue analysis to find the
1952      frame base.  However, such functions must have a frame pointer,
1953      to be able to restore the SP on exit.  So whenever we do have a
1954      frame pointer, use that to find the base.  */
1955   if (p->has_frame_ptr)
1956     {
1957       CORE_ADDR fp
1958 	= get_frame_register_unsigned (this_frame, MEP_FP_REGNUM);
1959       return fp - p->frame_ptr_offset;
1960     }
1961   else
1962     {
1963       CORE_ADDR sp
1964 	= get_frame_register_unsigned (this_frame, MEP_SP_REGNUM);
1965       return sp - p->frame_size;
1966     }
1967 }
1968 
1969 
1970 static void
1971 mep_frame_this_id (frame_info_ptr this_frame,
1972 		   void **this_prologue_cache,
1973 		   struct frame_id *this_id)
1974 {
1975   *this_id = frame_id_build (mep_frame_base (this_frame, this_prologue_cache),
1976 			     get_frame_func (this_frame));
1977 }
1978 
1979 
1980 static struct value *
1981 mep_frame_prev_register (frame_info_ptr this_frame,
1982 			 void **this_prologue_cache, int regnum)
1983 {
1984   struct mep_prologue *p
1985     = mep_analyze_frame_prologue (this_frame, this_prologue_cache);
1986 
1987   /* There are a number of complications in unwinding registers on the
1988      MeP, having to do with core functions calling VLIW functions and
1989      vice versa.
1990 
1991      The least significant bit of the link register, LP.LTOM, is the
1992      VLIW mode toggle bit: it's set if a core function called a VLIW
1993      function, or vice versa, and clear when the caller and callee
1994      were both in the same mode.
1995 
1996      So, if we're asked to unwind the PC, then we really want to
1997      unwind the LP and clear the least significant bit.  (Real return
1998      addresses are always even.)  And if we want to unwind the program
1999      status word (PSW), we need to toggle PSW.OM if LP.LTOM is set.
2000 
2001      Tweaking the register values we return in this way means that the
2002      bits in BUFFERP[] are not the same as the bits you'd find at
2003      ADDRP in the inferior, so we make sure lvalp is not_lval when we
2004      do this.  */
2005   if (regnum == MEP_PC_REGNUM)
2006     {
2007       struct value *value;
2008       CORE_ADDR lp;
2009       value = mep_frame_prev_register (this_frame, this_prologue_cache,
2010 				       MEP_LP_REGNUM);
2011       lp = value_as_long (value);
2012       release_value (value);
2013 
2014       return frame_unwind_got_constant (this_frame, regnum, lp & ~1);
2015     }
2016   else
2017     {
2018       CORE_ADDR frame_base = mep_frame_base (this_frame, this_prologue_cache);
2019       struct value *value;
2020 
2021       /* Our caller's SP is our frame base.  */
2022       if (regnum == MEP_SP_REGNUM)
2023 	return frame_unwind_got_constant (this_frame, regnum, frame_base);
2024 
2025       /* If prologue analysis says we saved this register somewhere,
2026 	 return a description of the stack slot holding it.  */
2027       if (p->reg_offset[regnum] != 1)
2028 	value = frame_unwind_got_memory (this_frame, regnum,
2029 					 frame_base + p->reg_offset[regnum]);
2030 
2031       /* Otherwise, presume we haven't changed the value of this
2032 	 register, and get it from the next frame.  */
2033       else
2034 	value = frame_unwind_got_register (this_frame, regnum, regnum);
2035 
2036       /* If we need to toggle the operating mode, do so.  */
2037       if (regnum == MEP_PSW_REGNUM)
2038 	{
2039 	  CORE_ADDR psw, lp;
2040 
2041 	  psw = value_as_long (value);
2042 	  release_value (value);
2043 
2044 	  /* Get the LP's value, too.  */
2045 	  value = get_frame_register_value (this_frame, MEP_LP_REGNUM);
2046 	  lp = value_as_long (value);
2047 	  release_value (value);
2048 
2049 	  /* If LP.LTOM is set, then toggle PSW.OM.  */
2050 	  if (lp & 0x1)
2051 	    psw ^= 0x1000;
2052 
2053 	  return frame_unwind_got_constant (this_frame, regnum, psw);
2054 	}
2055 
2056       return value;
2057     }
2058 }
2059 
2060 
2061 static const struct frame_unwind mep_frame_unwind = {
2062   "mep prologue",
2063   NORMAL_FRAME,
2064   default_frame_unwind_stop_reason,
2065   mep_frame_this_id,
2066   mep_frame_prev_register,
2067   NULL,
2068   default_frame_sniffer
2069 };
2070 
2071 
2072 /* Return values.  */
2073 
2074 
2075 static int
2076 mep_use_struct_convention (struct type *type)
2077 {
2078   return (type->length () > MEP_GPR_SIZE);
2079 }
2080 
2081 
2082 static void
2083 mep_extract_return_value (struct gdbarch *arch,
2084 			  struct type *type,
2085 			  struct regcache *regcache,
2086 			  gdb_byte *valbuf)
2087 {
2088   int byte_order = gdbarch_byte_order (arch);
2089 
2090   /* Values that don't occupy a full register appear at the less
2091      significant end of the value.  This is the offset to where the
2092      value starts.  */
2093   int offset;
2094 
2095   /* Return values > MEP_GPR_SIZE bytes are returned in memory,
2096      pointed to by R0.  */
2097   gdb_assert (type->length () <= MEP_GPR_SIZE);
2098 
2099   if (byte_order == BFD_ENDIAN_BIG)
2100     offset = MEP_GPR_SIZE - type->length ();
2101   else
2102     offset = 0;
2103 
2104   /* Return values that do fit in a single register are returned in R0.  */
2105   regcache->cooked_read_part (MEP_R0_REGNUM, offset, type->length (),
2106 			      valbuf);
2107 }
2108 
2109 
2110 static void
2111 mep_store_return_value (struct gdbarch *arch,
2112 			struct type *type,
2113 			struct regcache *regcache,
2114 			const gdb_byte *valbuf)
2115 {
2116   int byte_order = gdbarch_byte_order (arch);
2117 
2118   /* Values that fit in a single register go in R0.  */
2119   if (type->length () <= MEP_GPR_SIZE)
2120     {
2121       /* Values that don't occupy a full register appear at the least
2122 	 significant end of the value.  This is the offset to where the
2123 	 value starts.  */
2124       int offset;
2125 
2126       if (byte_order == BFD_ENDIAN_BIG)
2127 	offset = MEP_GPR_SIZE - type->length ();
2128       else
2129 	offset = 0;
2130 
2131       regcache->cooked_write_part (MEP_R0_REGNUM, offset, type->length (),
2132 				   valbuf);
2133     }
2134 
2135   /* Return values larger than a single register are returned in
2136      memory, pointed to by R0.  Unfortunately, we can't count on R0
2137      pointing to the return buffer, so we raise an error here.  */
2138   else
2139     error (_("\
2140 GDB cannot set return values larger than four bytes; the Media Processor's\n\
2141 calling conventions do not provide enough information to do this.\n\
2142 Try using the 'return' command with no argument."));
2143 }
2144 
2145 static enum return_value_convention
2146 mep_return_value (struct gdbarch *gdbarch, struct value *function,
2147 		  struct type *type, struct regcache *regcache,
2148 		  gdb_byte *readbuf, const gdb_byte *writebuf)
2149 {
2150   if (mep_use_struct_convention (type))
2151     {
2152       if (readbuf)
2153 	{
2154 	  ULONGEST addr;
2155 	  /* Although the address of the struct buffer gets passed in R1, it's
2156 	     returned in R0.  Fetch R0's value and then read the memory
2157 	     at that address.  */
2158 	  regcache_raw_read_unsigned (regcache, MEP_R0_REGNUM, &addr);
2159 	  read_memory (addr, readbuf, type->length ());
2160 	}
2161       if (writebuf)
2162 	{
2163 	  /* Return values larger than a single register are returned in
2164 	     memory, pointed to by R0.  Unfortunately, we can't count on R0
2165 	     pointing to the return buffer, so we raise an error here.  */
2166 	  error (_("\
2167 GDB cannot set return values larger than four bytes; the Media Processor's\n\
2168 calling conventions do not provide enough information to do this.\n\
2169 Try using the 'return' command with no argument."));
2170 	}
2171       return RETURN_VALUE_ABI_RETURNS_ADDRESS;
2172     }
2173 
2174   if (readbuf)
2175     mep_extract_return_value (gdbarch, type, regcache, readbuf);
2176   if (writebuf)
2177     mep_store_return_value (gdbarch, type, regcache, writebuf);
2178 
2179   return RETURN_VALUE_REGISTER_CONVENTION;
2180 }
2181 
2182 
2183 /* Inferior calls.  */
2184 
2185 
2186 static CORE_ADDR
2187 mep_frame_align (struct gdbarch *gdbarch, CORE_ADDR sp)
2188 {
2189   /* Require word alignment.  */
2190   return sp & -4;
2191 }
2192 
2193 
2194 /* From "lang_spec2.txt":
2195 
2196    4.2 Calling conventions
2197 
2198    4.2.1 Core register conventions
2199 
2200    - Parameters should be evaluated from left to right, and they
2201      should be held in $1,$2,$3,$4 in order.  The fifth parameter or
2202      after should be held in the stack.  If the size is larger than 4
2203      bytes in the first four parameters, the pointer should be held in
2204      the registers instead.  If the size is larger than 4 bytes in the
2205      fifth parameter or after, the pointer should be held in the stack.
2206 
2207    - Return value of a function should be held in register $0.  If the
2208      size of return value is larger than 4 bytes, $1 should hold the
2209      pointer pointing memory that would hold the return value.  In this
2210      case, the first parameter should be held in $2, the second one in
2211      $3, and the third one in $4, and the forth parameter or after
2212      should be held in the stack.
2213 
2214    [This doesn't say so, but arguments shorter than four bytes are
2215    passed in the least significant end of a four-byte word when
2216    they're passed on the stack.]  */
2217 
2218 
2219 /* Traverse the list of ARGC arguments ARGV; for every ARGV[i] too
2220    large to fit in a register, save it on the stack, and place its
2221    address in COPY[i].  SP is the initial stack pointer; return the
2222    new stack pointer.  */
2223 static CORE_ADDR
2224 push_large_arguments (CORE_ADDR sp, int argc, struct value **argv,
2225 		      CORE_ADDR copy[])
2226 {
2227   int i;
2228 
2229   for (i = 0; i < argc; i++)
2230     {
2231       unsigned arg_len = value_type (argv[i])->length ();
2232 
2233       if (arg_len > MEP_GPR_SIZE)
2234 	{
2235 	  /* Reserve space for the copy, and then round the SP down, to
2236 	     make sure it's all aligned properly.  */
2237 	  sp = (sp - arg_len) & -4;
2238 	  write_memory (sp, value_contents (argv[i]).data (), arg_len);
2239 	  copy[i] = sp;
2240 	}
2241     }
2242 
2243   return sp;
2244 }
2245 
2246 
2247 static CORE_ADDR
2248 mep_push_dummy_call (struct gdbarch *gdbarch, struct value *function,
2249 		     struct regcache *regcache, CORE_ADDR bp_addr,
2250 		     int argc, struct value **argv, CORE_ADDR sp,
2251 		     function_call_return_method return_method,
2252 		     CORE_ADDR struct_addr)
2253 {
2254   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2255   CORE_ADDR *copy = (CORE_ADDR *) alloca (argc * sizeof (copy[0]));
2256   int i;
2257 
2258   /* The number of the next register available to hold an argument.  */
2259   int arg_reg;
2260 
2261   /* The address of the next stack slot available to hold an argument.  */
2262   CORE_ADDR arg_stack;
2263 
2264   /* The address of the end of the stack area for arguments.  This is
2265      just for error checking.  */
2266   CORE_ADDR arg_stack_end;
2267 
2268   sp = push_large_arguments (sp, argc, argv, copy);
2269 
2270   /* Reserve space for the stack arguments, if any.  */
2271   arg_stack_end = sp;
2272   if (argc + (struct_addr ? 1 : 0) > 4)
2273     sp -= ((argc + (struct_addr ? 1 : 0)) - 4) * MEP_GPR_SIZE;
2274 
2275   arg_reg = MEP_R1_REGNUM;
2276   arg_stack = sp;
2277 
2278   /* If we're returning a structure by value, push the pointer to the
2279      buffer as the first argument.  */
2280   if (return_method == return_method_struct)
2281     {
2282       regcache_cooked_write_unsigned (regcache, arg_reg, struct_addr);
2283       arg_reg++;
2284     }
2285 
2286   for (i = 0; i < argc; i++)
2287     {
2288       ULONGEST value;
2289 
2290       /* Arguments that fit in a GPR get expanded to fill the GPR.  */
2291       if (value_type (argv[i])->length () <= MEP_GPR_SIZE)
2292 	value = extract_unsigned_integer (value_contents (argv[i]).data (),
2293 					  value_type (argv[i])->length (),
2294 					  byte_order);
2295 
2296       /* Arguments too large to fit in a GPR get copied to the stack,
2297 	 and we pass a pointer to the copy.  */
2298       else
2299 	value = copy[i];
2300 
2301       /* We use $1 -- $4 for passing arguments, then use the stack.  */
2302       if (arg_reg <= MEP_R4_REGNUM)
2303 	{
2304 	  regcache_cooked_write_unsigned (regcache, arg_reg, value);
2305 	  arg_reg++;
2306 	}
2307       else
2308 	{
2309 	  gdb_byte buf[MEP_GPR_SIZE];
2310 	  store_unsigned_integer (buf, MEP_GPR_SIZE, byte_order, value);
2311 	  write_memory (arg_stack, buf, MEP_GPR_SIZE);
2312 	  arg_stack += MEP_GPR_SIZE;
2313 	}
2314     }
2315 
2316   gdb_assert (arg_stack <= arg_stack_end);
2317 
2318   /* Set the return address.  */
2319   regcache_cooked_write_unsigned (regcache, MEP_LP_REGNUM, bp_addr);
2320 
2321   /* Update the stack pointer.  */
2322   regcache_cooked_write_unsigned (regcache, MEP_SP_REGNUM, sp);
2323 
2324   return sp;
2325 }
2326 
2327 
2328 /* Initialization.  */
2329 
2330 
2331 static struct gdbarch *
2332 mep_gdbarch_init (struct gdbarch_info info, struct gdbarch_list *arches)
2333 {
2334   struct gdbarch *gdbarch;
2335 
2336   /* Which me_module are we building a gdbarch object for?  */
2337   CONFIG_ATTR me_module;
2338 
2339   /* If we have a BFD in hand, figure out which me_module it was built
2340      for.  Otherwise, use the no-particular-me_module code.  */
2341   if (info.abfd)
2342     {
2343       /* The way to get the me_module code depends on the object file
2344 	 format.  At the moment, we only know how to handle ELF.  */
2345       if (bfd_get_flavour (info.abfd) == bfd_target_elf_flavour)
2346 	{
2347 	  int flag = elf_elfheader (info.abfd)->e_flags & EF_MEP_INDEX_MASK;
2348 	  me_module = (CONFIG_ATTR) flag;
2349 	}
2350       else
2351 	me_module = CONFIG_NONE;
2352     }
2353   else
2354     me_module = CONFIG_NONE;
2355 
2356   /* If we're setting the architecture from a file, check the
2357      endianness of the file against that of the me_module.  */
2358   if (info.abfd)
2359     {
2360       /* The negations on either side make the comparison treat all
2361 	 non-zero (true) values as equal.  */
2362       if (! bfd_big_endian (info.abfd) != ! me_module_big_endian (me_module))
2363 	{
2364 	  const char *module_name = me_module_name (me_module);
2365 	  const char *module_endianness
2366 	    = me_module_big_endian (me_module) ? "big" : "little";
2367 	  const char *file_name = bfd_get_filename (info.abfd);
2368 	  const char *file_endianness
2369 	    = bfd_big_endian (info.abfd) ? "big" : "little";
2370 
2371 	  gdb_putc ('\n', gdb_stderr);
2372 	  if (module_name)
2373 	    warning (_("the MeP module '%s' is %s-endian, but the executable\n"
2374 		       "%s is %s-endian."),
2375 		     module_name, module_endianness,
2376 		     file_name, file_endianness);
2377 	  else
2378 	    warning (_("the selected MeP module is %s-endian, but the "
2379 		       "executable\n"
2380 		       "%s is %s-endian."),
2381 		     module_endianness, file_name, file_endianness);
2382 	}
2383     }
2384 
2385   /* Find a candidate among the list of architectures we've created
2386      already.  info->bfd_arch_info needs to match, but we also want
2387      the right me_module: the ELF header's e_flags field needs to
2388      match as well.  */
2389   for (arches = gdbarch_list_lookup_by_info (arches, &info);
2390        arches != NULL;
2391        arches = gdbarch_list_lookup_by_info (arches->next, &info))
2392     {
2393       mep_gdbarch_tdep *tdep
2394 	= gdbarch_tdep<mep_gdbarch_tdep> (arches->gdbarch);
2395 
2396       if (tdep->me_module == me_module)
2397 	return arches->gdbarch;
2398     }
2399 
2400   mep_gdbarch_tdep *tdep = new mep_gdbarch_tdep;
2401   gdbarch = gdbarch_alloc (&info, tdep);
2402 
2403   /* Get a CGEN CPU descriptor for this architecture.  */
2404   {
2405     const char *mach_name = info.bfd_arch_info->printable_name;
2406     enum cgen_endian endian = (info.byte_order == BFD_ENDIAN_BIG
2407 			       ? CGEN_ENDIAN_BIG
2408 			       : CGEN_ENDIAN_LITTLE);
2409 
2410     tdep->cpu_desc = mep_cgen_cpu_open (CGEN_CPU_OPEN_BFDMACH, mach_name,
2411 					CGEN_CPU_OPEN_ENDIAN, endian,
2412 					CGEN_CPU_OPEN_END);
2413   }
2414 
2415   tdep->me_module = me_module;
2416 
2417   /* Register set.  */
2418   set_gdbarch_num_regs (gdbarch, MEP_NUM_RAW_REGS);
2419   set_gdbarch_pc_regnum (gdbarch, MEP_PC_REGNUM);
2420   set_gdbarch_sp_regnum (gdbarch, MEP_SP_REGNUM);
2421   set_gdbarch_register_name (gdbarch, mep_register_name);
2422   set_gdbarch_register_type (gdbarch, mep_register_type);
2423   set_gdbarch_num_pseudo_regs (gdbarch, MEP_NUM_PSEUDO_REGS);
2424   set_gdbarch_pseudo_register_read (gdbarch, mep_pseudo_register_read);
2425   set_gdbarch_pseudo_register_write (gdbarch, mep_pseudo_register_write);
2426   set_gdbarch_dwarf2_reg_to_regnum (gdbarch, mep_debug_reg_to_regnum);
2427   set_gdbarch_stab_reg_to_regnum (gdbarch, mep_debug_reg_to_regnum);
2428 
2429   set_gdbarch_register_reggroup_p (gdbarch, mep_register_reggroup_p);
2430   reggroup_add (gdbarch, mep_csr_reggroup);
2431   reggroup_add (gdbarch, mep_cr_reggroup);
2432   reggroup_add (gdbarch, mep_ccr_reggroup);
2433 
2434   /* Disassembly.  */
2435   set_gdbarch_print_insn (gdbarch, mep_gdb_print_insn);
2436 
2437   /* Breakpoints.  */
2438   set_gdbarch_breakpoint_kind_from_pc (gdbarch, mep_breakpoint::kind_from_pc);
2439   set_gdbarch_sw_breakpoint_from_kind (gdbarch, mep_breakpoint::bp_from_kind);
2440   set_gdbarch_decr_pc_after_break (gdbarch, 0);
2441   set_gdbarch_skip_prologue (gdbarch, mep_skip_prologue);
2442 
2443   /* Frames and frame unwinding.  */
2444   frame_unwind_append_unwinder (gdbarch, &mep_frame_unwind);
2445   set_gdbarch_inner_than (gdbarch, core_addr_lessthan);
2446   set_gdbarch_frame_args_skip (gdbarch, 0);
2447 
2448   /* Return values.  */
2449   set_gdbarch_return_value (gdbarch, mep_return_value);
2450 
2451   /* Inferior function calls.  */
2452   set_gdbarch_frame_align (gdbarch, mep_frame_align);
2453   set_gdbarch_push_dummy_call (gdbarch, mep_push_dummy_call);
2454 
2455   return gdbarch;
2456 }
2457 
2458 void _initialize_mep_tdep ();
2459 void
2460 _initialize_mep_tdep ()
2461 {
2462   mep_csr_reggroup = reggroup_new ("csr", USER_REGGROUP);
2463   mep_cr_reggroup  = reggroup_new ("cr", USER_REGGROUP);
2464   mep_ccr_reggroup = reggroup_new ("ccr", USER_REGGROUP);
2465 
2466   gdbarch_register (bfd_arch_mep, mep_gdbarch_init);
2467 
2468   mep_init_pseudoregister_maps ();
2469 }
2470