Include gdb_assert.h in common-defs.h
[external/binutils.git] / gdb / mep-tdep.c
1 /* Target-dependent code for the Toshiba MeP for GDB, the GNU debugger.
2
3    Copyright (C) 2001-2014 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 <string.h>
31 #include "value.h"
32 #include "inferior.h"
33 #include "dis-asm.h"
34 #include "symfile.h"
35 #include "objfiles.h"
36 #include "language.h"
37 #include "arch-utils.h"
38 #include "regcache.h"
39 #include "remote.h"
40 #include "floatformat.h"
41 #include "sim-regno.h"
42 #include "disasm.h"
43 #include "trad-frame.h"
44 #include "reggroups.h"
45 #include "elf-bfd.h"
46 #include "elf/mep.h"
47 #include "prologue-value.h"
48 #include "cgen/bitset.h"
49 #include "infcall.h"
50
51 /* Get the user's customized MeP coprocessor register names from
52    libopcodes.  */
53 #include "opcodes/mep-desc.h"
54 #include "opcodes/mep-opc.h"
55
56 \f
57 /* The gdbarch_tdep structure.  */
58
59 /* A quick recap for GDB hackers not familiar with the whole Toshiba
60    Media Processor story:
61
62    The MeP media engine is a configureable processor: users can design
63    their own coprocessors, implement custom instructions, adjust cache
64    sizes, select optional standard facilities like add-and-saturate
65    instructions, and so on.  Then, they can build custom versions of
66    the GNU toolchain to support their customized chips.  The
67    MeP-Integrator program (see utils/mep) takes a GNU toolchain source
68    tree, and a config file pointing to various files provided by the
69    user describing their customizations, and edits the source tree to
70    produce a compiler that can generate their custom instructions, an
71    assembler that can assemble them and recognize their custom
72    register names, and so on.
73
74    Furthermore, the user can actually specify several of these custom
75    configurations, called 'me_modules', and get a toolchain which can
76    produce code for any of them, given a compiler/assembler switch;
77    you say something like 'gcc -mconfig=mm_max' to generate code for
78    the me_module named 'mm_max'.
79
80    GDB, in particular, needs to:
81
82    - use the coprocessor control register names provided by the user
83      in their hardware description, in expressions, 'info register'
84      output, and disassembly,
85
86    - know the number, names, and types of the coprocessor's
87      general-purpose registers, adjust the 'info all-registers' output
88      accordingly, and print error messages if the user refers to one
89      that doesn't exist
90
91    - allow access to the control bus space only when the configuration
92      actually has a control bus, and recognize which regions of the
93      control bus space are actually populated,
94
95    - disassemble using the user's provided mnemonics for their custom
96      instructions, and
97
98    - recognize whether the $hi and $lo registers are present, and
99      allow access to them only when they are actually there.
100
101    There are three sources of information about what sort of me_module
102    we're actually dealing with:
103
104    - A MeP executable file indicates which me_module it was compiled
105      for, and libopcodes has tables describing each module.  So, given
106      an executable file, we can find out about the processor it was
107      compiled for.
108
109    - There are SID command-line options to select a particular
110      me_module, overriding the one specified in the ELF file.  SID
111      provides GDB with a fake read-only register, 'module', which
112      indicates which me_module GDB is communicating with an instance
113      of.
114
115    - There are SID command-line options to enable or disable certain
116      optional processor features, overriding the defaults for the
117      selected me_module.  The MeP $OPT register indicates which
118      options are present on the current processor.  */
119
120
121 struct gdbarch_tdep
122 {
123   /* A CGEN cpu descriptor for this BFD architecture and machine.
124
125      Note: this is *not* customized for any particular me_module; the
126      MeP libopcodes machinery actually puts off module-specific
127      customization until the last minute.  So this contains
128      information about all supported me_modules.  */
129   CGEN_CPU_DESC cpu_desc;
130
131   /* The me_module index from the ELF file we used to select this
132      architecture, or CONFIG_NONE if there was none.
133
134      Note that we should prefer to use the me_module number available
135      via the 'module' register, whenever we're actually talking to a
136      real target.
137
138      In the absence of live information, we'd like to get the
139      me_module number from the ELF file.  But which ELF file: the
140      executable file, the core file, ... ?  The answer is, "the last
141      ELF file we used to set the current architecture".  Thus, we
142      create a separate instance of the gdbarch structure for each
143      me_module value mep_gdbarch_init sees, and store the me_module
144      value from the ELF file here.  */
145   CONFIG_ATTR me_module;
146 };
147
148
149 \f
150 /* Getting me_module information from the CGEN tables.  */
151
152
153 /* Find an entry in the DESC's hardware table whose name begins with
154    PREFIX, and whose ISA mask intersects COPRO_ISA_MASK, but does not
155    intersect with GENERIC_ISA_MASK.  If there is no matching entry,
156    return zero.  */
157 static const CGEN_HW_ENTRY *
158 find_hw_entry_by_prefix_and_isa (CGEN_CPU_DESC desc,
159                                  const char *prefix,
160                                  CGEN_BITSET *copro_isa_mask,
161                                  CGEN_BITSET *generic_isa_mask)
162 {
163   int prefix_len = strlen (prefix);
164   int i;
165
166   for (i = 0; i < desc->hw_table.num_entries; i++)
167     {
168       const CGEN_HW_ENTRY *hw = desc->hw_table.entries[i];
169       if (strncmp (prefix, hw->name, prefix_len) == 0)
170         {
171           CGEN_BITSET *hw_isa_mask
172             = ((CGEN_BITSET *)
173                &CGEN_ATTR_CGEN_HW_ISA_VALUE (CGEN_HW_ATTRS (hw)));
174
175           if (cgen_bitset_intersect_p (hw_isa_mask, copro_isa_mask)
176               && ! cgen_bitset_intersect_p (hw_isa_mask, generic_isa_mask))
177             return hw;
178         }
179     }
180
181   return 0;
182 }
183
184
185 /* Find an entry in DESC's hardware table whose type is TYPE.  Return
186    zero if there is none.  */
187 static const CGEN_HW_ENTRY *
188 find_hw_entry_by_type (CGEN_CPU_DESC desc, CGEN_HW_TYPE type)
189 {
190   int i;
191
192   for (i = 0; i < desc->hw_table.num_entries; i++)
193     {
194       const CGEN_HW_ENTRY *hw = desc->hw_table.entries[i];
195
196       if (hw->type == type)
197         return hw;
198     }
199
200   return 0;
201 }
202
203
204 /* Return the CGEN hardware table entry for the coprocessor register
205    set for ME_MODULE, whose name prefix is PREFIX.  If ME_MODULE has
206    no such register set, return zero.  If ME_MODULE is the generic
207    me_module CONFIG_NONE, return the table entry for the register set
208    whose hardware type is GENERIC_TYPE.  */
209 static const CGEN_HW_ENTRY *
210 me_module_register_set (CONFIG_ATTR me_module,
211                         const char *prefix,
212                         CGEN_HW_TYPE generic_type)
213 {
214   /* This is kind of tricky, because the hardware table is constructed
215      in a way that isn't very helpful.  Perhaps we can fix that, but
216      here's how it works at the moment:
217
218      The configuration map, `mep_config_map', is indexed by me_module
219      number, and indicates which coprocessor and core ISAs that
220      me_module supports.  The 'core_isa' mask includes all the core
221      ISAs, and the 'cop_isa' mask includes all the coprocessor ISAs.
222      The entry for the generic me_module, CONFIG_NONE, has an empty
223      'cop_isa', and its 'core_isa' selects only the standard MeP
224      instruction set.
225
226      The CGEN CPU descriptor's hardware table, desc->hw_table, has
227      entries for all the register sets, for all me_modules.  Each
228      entry has a mask indicating which ISAs use that register set.
229      So, if an me_module supports some coprocessor ISA, we can find
230      applicable register sets by scanning the hardware table for
231      register sets whose masks include (at least some of) those ISAs.
232
233      Each hardware table entry also has a name, whose prefix says
234      whether it's a general-purpose ("h-cr") or control ("h-ccr")
235      coprocessor register set.  It might be nicer to have an attribute
236      indicating what sort of register set it was, that we could use
237      instead of pattern-matching on the name.
238
239      When there is no hardware table entry whose mask includes a
240      particular coprocessor ISA and whose name starts with a given
241      prefix, then that means that that coprocessor doesn't have any
242      registers of that type.  In such cases, this function must return
243      a null pointer.
244
245      Coprocessor register sets' masks may or may not include the core
246      ISA for the me_module they belong to.  Those generated by a2cgen
247      do, but the sample me_module included in the unconfigured tree,
248      'ccfx', does not.
249
250      There are generic coprocessor register sets, intended only for
251      use with the generic me_module.  Unfortunately, their masks
252      include *all* ISAs --- even those for coprocessors that don't
253      have such register sets.  This makes detecting the case where a
254      coprocessor lacks a particular register set more complicated.
255
256      So, here's the approach we take:
257
258      - For CONFIG_NONE, we return the generic coprocessor register set.
259
260      - For any other me_module, we search for a register set whose
261        mask contains any of the me_module's coprocessor ISAs,
262        specifically excluding the generic coprocessor register sets.  */
263
264   CGEN_CPU_DESC desc = gdbarch_tdep (target_gdbarch ())->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 propage 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 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 \f
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 struct 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   return mep_raw_to_pseudo[debug_reg];
789 }
790
791
792 /* Return the size, in bits, of the coprocessor pseudoregister
793    numbered PSEUDO.  */
794 static int
795 mep_pseudo_cr_size (int pseudo)
796 {
797   if (IS_CR32_REGNUM (pseudo)
798       || IS_FP_CR32_REGNUM (pseudo))
799     return 32;
800   else if (IS_CR64_REGNUM (pseudo)
801            || IS_FP_CR64_REGNUM (pseudo))
802     return 64;
803   else
804     gdb_assert_not_reached ("unexpected coprocessor pseudo register");
805 }
806
807
808 /* If the coprocessor pseudoregister numbered PSEUDO is a
809    floating-point register, return non-zero; if it is an integer
810    register, return zero.  */
811 static int
812 mep_pseudo_cr_is_float (int pseudo)
813 {
814   return (IS_FP_CR32_REGNUM (pseudo)
815           || IS_FP_CR64_REGNUM (pseudo));
816 }
817
818
819 /* Given a coprocessor GPR pseudoregister number, return its index
820    within that register bank.  */
821 static int
822 mep_pseudo_cr_index (int pseudo)
823 {
824   if (IS_CR32_REGNUM (pseudo))
825     return pseudo - MEP_FIRST_CR32_REGNUM;
826   else if (IS_FP_CR32_REGNUM (pseudo))
827       return pseudo - MEP_FIRST_FP_CR32_REGNUM;
828   else if (IS_CR64_REGNUM (pseudo))
829       return pseudo - MEP_FIRST_CR64_REGNUM;
830   else if (IS_FP_CR64_REGNUM (pseudo))
831       return pseudo - MEP_FIRST_FP_CR64_REGNUM;
832   else
833     gdb_assert_not_reached ("unexpected coprocessor pseudo register");
834 }
835
836
837 /* Return the me_module index describing the current target.
838
839    If the current target has registers (e.g., simulator, remote
840    target), then this uses the value of the 'module' register, raw
841    register MEP_MODULE_REGNUM.  Otherwise, this retrieves the value
842    from the ELF header's e_flags field of the current executable
843    file.  */
844 static CONFIG_ATTR
845 current_me_module (void)
846 {
847   if (target_has_registers)
848     {
849       ULONGEST regval;
850       regcache_cooked_read_unsigned (get_current_regcache (),
851                                      MEP_MODULE_REGNUM, &regval);
852       return regval;
853     }
854   else
855     return gdbarch_tdep (target_gdbarch ())->me_module;
856 }
857
858
859 /* Return the set of options for the current target, in the form that
860    the OPT register would use.
861
862    If the current target has registers (e.g., simulator, remote
863    target), then this is the actual value of the OPT register.  If the
864    current target does not have registers (e.g., an executable file),
865    then use the 'module_opt' field we computed when we build the
866    gdbarch object for this module.  */
867 static unsigned int
868 current_options (void)
869 {
870   if (target_has_registers)
871     {
872       ULONGEST regval;
873       regcache_cooked_read_unsigned (get_current_regcache (),
874                                      MEP_OPT_REGNUM, &regval);
875       return regval;
876     }
877   else
878     return me_module_opt (current_me_module ());
879 }
880
881
882 /* Return the width of the current me_module's coprocessor data bus,
883    in bits.  This is either 32 or 64.  */
884 static int
885 current_cop_data_bus_width (void)
886 {
887   return me_module_cop_data_bus_width (current_me_module ());
888 }
889
890
891 /* Return the keyword table of coprocessor general-purpose register
892    names appropriate for the me_module we're dealing with.  */
893 static CGEN_KEYWORD *
894 current_cr_names (void)
895 {
896   const CGEN_HW_ENTRY *hw
897     = me_module_register_set (current_me_module (), "h-cr-", HW_H_CR);
898
899   return register_set_keyword_table (hw);
900 }
901
902
903 /* Return non-zero if the coprocessor general-purpose registers are
904    floating-point values, zero otherwise.  */
905 static int
906 current_cr_is_float (void)
907 {
908   const CGEN_HW_ENTRY *hw
909     = me_module_register_set (current_me_module (), "h-cr-", HW_H_CR);
910
911   return CGEN_ATTR_CGEN_HW_IS_FLOAT_VALUE (CGEN_HW_ATTRS (hw));
912 }
913
914
915 /* Return the keyword table of coprocessor control register names
916    appropriate for the me_module we're dealing with.  */
917 static CGEN_KEYWORD *
918 current_ccr_names (void)
919 {
920   const CGEN_HW_ENTRY *hw
921     = me_module_register_set (current_me_module (), "h-ccr-", HW_H_CCR);
922
923   return register_set_keyword_table (hw);
924 }
925
926
927 static const char *
928 mep_register_name (struct gdbarch *gdbarch, int regnr)
929 {
930   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);  
931
932   /* General-purpose registers.  */
933   static const char *gpr_names[] = {
934     "r0",   "r1",   "r2",   "r3",   /* 0 */
935     "r4",   "r5",   "r6",   "r7",   /* 4 */
936     "fp",   "r9",   "r10",  "r11",  /* 8 */
937     "r12",  "tp",   "gp",   "sp"    /* 12 */
938   };
939
940   /* Special-purpose registers.  */
941   static const char *csr_names[] = {
942     "pc",   "lp",   "sar",  "",     /* 0  csr3: reserved */ 
943     "rpb",  "rpe",  "rpc",  "hi",   /* 4 */
944     "lo",   "",     "",     "",     /* 8  csr9-csr11: reserved */
945     "mb0",  "me0",  "mb1",  "me1",  /* 12 */
946
947     "psw",  "id",   "tmp",  "epc",  /* 16 */
948     "exc",  "cfg",  "",     "npc",  /* 20  csr22: reserved */
949     "dbg",  "depc", "opt",  "rcfg", /* 24 */
950     "ccfg", "",     "",     ""      /* 28  csr29-csr31: reserved */
951   };
952
953   if (IS_GPR_REGNUM (regnr))
954     return gpr_names[regnr - MEP_R0_REGNUM];
955   else if (IS_CSR_REGNUM (regnr))
956     {
957       /* The 'hi' and 'lo' registers are only present on processors
958          that have the 'MUL' or 'DIV' instructions enabled.  */
959       if ((regnr == MEP_HI_REGNUM || regnr == MEP_LO_REGNUM)
960           && (! (current_options () & (MEP_OPT_MUL | MEP_OPT_DIV))))
961         return "";
962
963       return csr_names[regnr - MEP_FIRST_CSR_REGNUM];
964     }
965   else if (IS_CR_REGNUM (regnr))
966     {
967       CGEN_KEYWORD *names;
968       int cr_size;
969       int cr_is_float;
970
971       /* Does this module have a coprocessor at all?  */
972       if (! (current_options () & MEP_OPT_COP))
973         return "";
974
975       names = current_cr_names ();
976       if (! names)
977         /* This module's coprocessor has no general-purpose registers.  */
978         return "";
979
980       cr_size = current_cop_data_bus_width ();
981       if (cr_size != mep_pseudo_cr_size (regnr))
982         /* This module's coprocessor's GPR's are of a different size.  */
983         return "";
984
985       cr_is_float = current_cr_is_float ();
986       /* The extra ! operators ensure we get boolean equality, not
987          numeric equality.  */
988       if (! cr_is_float != ! mep_pseudo_cr_is_float (regnr))
989         /* This module's coprocessor's GPR's are of a different type.  */
990         return "";
991
992       return register_name_from_keyword (names, mep_pseudo_cr_index (regnr));
993     }
994   else if (IS_CCR_REGNUM (regnr))
995     {
996       /* Does this module have a coprocessor at all?  */
997       if (! (current_options () & MEP_OPT_COP))
998         return "";
999
1000       {
1001         CGEN_KEYWORD *names = current_ccr_names ();
1002
1003         if (! names)
1004           /* This me_module's coprocessor has no control registers.  */
1005           return "";
1006
1007         return register_name_from_keyword (names, regnr-MEP_FIRST_CCR_REGNUM);
1008       }
1009     }
1010
1011   /* It might be nice to give the 'module' register a name, but that
1012      would affect the output of 'info all-registers', which would
1013      disturb the test suites.  So we leave it invisible.  */
1014   else
1015     return NULL;
1016 }
1017
1018
1019 /* Custom register groups for the MeP.  */
1020 static struct reggroup *mep_csr_reggroup; /* control/special */
1021 static struct reggroup *mep_cr_reggroup;  /* coprocessor general-purpose */
1022 static struct reggroup *mep_ccr_reggroup; /* coprocessor control */
1023
1024
1025 static int
1026 mep_register_reggroup_p (struct gdbarch *gdbarch, int regnum,
1027                          struct reggroup *group)
1028 {
1029   /* Filter reserved or unused register numbers.  */
1030   {
1031     const char *name = mep_register_name (gdbarch, regnum);
1032
1033     if (! name || name[0] == '\0')
1034       return 0;
1035   }
1036
1037   /* We could separate the GPRs and the CSRs.  Toshiba has approved of
1038      the existing behavior, so we'd want to run that by them.  */
1039   if (group == general_reggroup)
1040     return (IS_GPR_REGNUM (regnum)
1041             || IS_CSR_REGNUM (regnum));
1042
1043   /* Everything is in the 'all' reggroup, except for the raw CSR's.  */
1044   else if (group == all_reggroup)
1045     return (IS_GPR_REGNUM (regnum)
1046             || IS_CSR_REGNUM (regnum)
1047             || IS_CR_REGNUM (regnum)
1048             || IS_CCR_REGNUM (regnum));
1049
1050   /* All registers should be saved and restored, except for the raw
1051      CSR's.
1052
1053      This is probably right if the coprocessor is something like a
1054      floating-point unit, but would be wrong if the coprocessor is
1055      something that does I/O, where register accesses actually cause
1056      externally-visible actions.  But I get the impression that the
1057      coprocessor isn't supposed to do things like that --- you'd use a
1058      hardware engine, perhaps.  */
1059   else if (group == save_reggroup || group == restore_reggroup)
1060     return (IS_GPR_REGNUM (regnum)
1061             || IS_CSR_REGNUM (regnum)
1062             || IS_CR_REGNUM (regnum)
1063             || IS_CCR_REGNUM (regnum));
1064
1065   else if (group == mep_csr_reggroup)
1066     return IS_CSR_REGNUM (regnum);
1067   else if (group == mep_cr_reggroup)
1068     return IS_CR_REGNUM (regnum);
1069   else if (group == mep_ccr_reggroup)
1070     return IS_CCR_REGNUM (regnum);
1071   else
1072     return 0;
1073 }
1074
1075
1076 static struct type *
1077 mep_register_type (struct gdbarch *gdbarch, int reg_nr)
1078 {
1079   /* Coprocessor general-purpose registers may be either 32 or 64 bits
1080      long.  So for them, the raw registers are always 64 bits long (to
1081      keep the 'g' packet format fixed), and the pseudoregisters vary
1082      in length.  */
1083   if (IS_RAW_CR_REGNUM (reg_nr))
1084     return builtin_type (gdbarch)->builtin_uint64;
1085
1086   /* Since GDB doesn't allow registers to change type, we have two
1087      banks of pseudoregisters for the coprocessor general-purpose
1088      registers: one that gives a 32-bit view, and one that gives a
1089      64-bit view.  We hide or show one or the other depending on the
1090      current module.  */
1091   if (IS_CR_REGNUM (reg_nr))
1092     {
1093       int size = mep_pseudo_cr_size (reg_nr);
1094       if (size == 32)
1095         {
1096           if (mep_pseudo_cr_is_float (reg_nr))
1097             return builtin_type (gdbarch)->builtin_float;
1098           else
1099             return builtin_type (gdbarch)->builtin_uint32;
1100         }
1101       else if (size == 64)
1102         {
1103           if (mep_pseudo_cr_is_float (reg_nr))
1104             return builtin_type (gdbarch)->builtin_double;
1105           else
1106             return builtin_type (gdbarch)->builtin_uint64;
1107         }
1108       else
1109         gdb_assert_not_reached ("unexpected cr size");
1110     }
1111
1112   /* All other registers are 32 bits long.  */
1113   else
1114     return builtin_type (gdbarch)->builtin_uint32;
1115 }
1116
1117
1118 static CORE_ADDR
1119 mep_read_pc (struct regcache *regcache)
1120 {
1121   ULONGEST pc;
1122   regcache_cooked_read_unsigned (regcache, MEP_PC_REGNUM, &pc);
1123   return pc;
1124 }
1125
1126 static enum register_status
1127 mep_pseudo_cr32_read (struct gdbarch *gdbarch,
1128                       struct regcache *regcache,
1129                       int cookednum,
1130                       void *buf)
1131 {
1132   enum register_status status;
1133   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1134   /* Read the raw register into a 64-bit buffer, and then return the
1135      appropriate end of that buffer.  */
1136   int rawnum = mep_pseudo_to_raw[cookednum];
1137   gdb_byte buf64[8];
1138
1139   gdb_assert (TYPE_LENGTH (register_type (gdbarch, rawnum)) == sizeof (buf64));
1140   gdb_assert (TYPE_LENGTH (register_type (gdbarch, cookednum)) == 4);
1141   status = regcache_raw_read (regcache, rawnum, buf64);
1142   if (status == REG_VALID)
1143     {
1144       /* Slow, but legible.  */
1145       store_unsigned_integer (buf, 4, byte_order,
1146                               extract_unsigned_integer (buf64, 8, byte_order));
1147     }
1148   return status;
1149 }
1150
1151
1152 static enum register_status
1153 mep_pseudo_cr64_read (struct gdbarch *gdbarch,
1154                       struct regcache *regcache,
1155                       int cookednum,
1156                       void *buf)
1157 {
1158   return regcache_raw_read (regcache, mep_pseudo_to_raw[cookednum], buf);
1159 }
1160
1161
1162 static enum register_status
1163 mep_pseudo_register_read (struct gdbarch *gdbarch,
1164                           struct regcache *regcache,
1165                           int cookednum,
1166                           gdb_byte *buf)
1167 {
1168   if (IS_CSR_REGNUM (cookednum)
1169       || IS_CCR_REGNUM (cookednum))
1170     return regcache_raw_read (regcache, mep_pseudo_to_raw[cookednum], buf);
1171   else if (IS_CR32_REGNUM (cookednum)
1172            || IS_FP_CR32_REGNUM (cookednum))
1173     return mep_pseudo_cr32_read (gdbarch, regcache, cookednum, buf);
1174   else if (IS_CR64_REGNUM (cookednum)
1175            || IS_FP_CR64_REGNUM (cookednum))
1176     return mep_pseudo_cr64_read (gdbarch, regcache, cookednum, buf);
1177   else
1178     gdb_assert_not_reached ("unexpected pseudo register");
1179 }
1180
1181
1182 static void
1183 mep_pseudo_csr_write (struct gdbarch *gdbarch,
1184                       struct regcache *regcache,
1185                       int cookednum,
1186                       const void *buf)
1187 {
1188   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1189   int size = register_size (gdbarch, cookednum);
1190   struct mep_csr_register *r
1191     = &mep_csr_registers[cookednum - MEP_FIRST_CSR_REGNUM];
1192
1193   if (r->writeable_bits == 0)
1194     /* A completely read-only register; avoid the read-modify-
1195        write cycle, and juts ignore the entire write.  */
1196     ;
1197   else
1198     {
1199       /* A partially writeable register; do a read-modify-write cycle.  */
1200       ULONGEST old_bits;
1201       ULONGEST new_bits;
1202       ULONGEST mixed_bits;
1203           
1204       regcache_raw_read_unsigned (regcache, r->raw, &old_bits);
1205       new_bits = extract_unsigned_integer (buf, size, byte_order);
1206       mixed_bits = ((r->writeable_bits & new_bits)
1207                     | (~r->writeable_bits & old_bits));
1208       regcache_raw_write_unsigned (regcache, r->raw, mixed_bits);
1209     }
1210 }
1211                       
1212
1213 static void
1214 mep_pseudo_cr32_write (struct gdbarch *gdbarch,
1215                        struct regcache *regcache,
1216                        int cookednum,
1217                        const void *buf)
1218 {
1219   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1220   /* Expand the 32-bit value into a 64-bit value, and write that to
1221      the pseudoregister.  */
1222   int rawnum = mep_pseudo_to_raw[cookednum];
1223   gdb_byte buf64[8];
1224   
1225   gdb_assert (TYPE_LENGTH (register_type (gdbarch, rawnum)) == sizeof (buf64));
1226   gdb_assert (TYPE_LENGTH (register_type (gdbarch, cookednum)) == 4);
1227   /* Slow, but legible.  */
1228   store_unsigned_integer (buf64, 8, byte_order,
1229                           extract_unsigned_integer (buf, 4, byte_order));
1230   regcache_raw_write (regcache, rawnum, buf64);
1231 }
1232
1233
1234 static void
1235 mep_pseudo_cr64_write (struct gdbarch *gdbarch,
1236                      struct regcache *regcache,
1237                      int cookednum,
1238                      const void *buf)
1239 {
1240   regcache_raw_write (regcache, mep_pseudo_to_raw[cookednum], buf);
1241 }
1242
1243
1244 static void
1245 mep_pseudo_register_write (struct gdbarch *gdbarch,
1246                            struct regcache *regcache,
1247                            int cookednum,
1248                            const gdb_byte *buf)
1249 {
1250   if (IS_CSR_REGNUM (cookednum))
1251     mep_pseudo_csr_write (gdbarch, regcache, cookednum, buf);
1252   else if (IS_CR32_REGNUM (cookednum)
1253            || IS_FP_CR32_REGNUM (cookednum))
1254     mep_pseudo_cr32_write (gdbarch, regcache, cookednum, buf);
1255   else if (IS_CR64_REGNUM (cookednum)
1256            || IS_FP_CR64_REGNUM (cookednum))
1257     mep_pseudo_cr64_write (gdbarch, regcache, cookednum, buf);
1258   else if (IS_CCR_REGNUM (cookednum))
1259     regcache_raw_write (regcache, mep_pseudo_to_raw[cookednum], buf);
1260   else
1261     gdb_assert_not_reached ("unexpected pseudo register");
1262 }
1263
1264
1265 \f
1266 /* Disassembly.  */
1267
1268 /* The mep disassembler needs to know about the section in order to
1269    work correctly.  */
1270 static int
1271 mep_gdb_print_insn (bfd_vma pc, disassemble_info * info)
1272 {
1273   struct obj_section * s = find_pc_section (pc);
1274
1275   if (s)
1276     {
1277       /* The libopcodes disassembly code uses the section to find the
1278          BFD, the BFD to find the ELF header, the ELF header to find
1279          the me_module index, and the me_module index to select the
1280          right instructions to print.  */
1281       info->section = s->the_bfd_section;
1282       info->arch = bfd_arch_mep;
1283         
1284       return print_insn_mep (pc, info);
1285     }
1286   
1287   return 0;
1288 }
1289
1290 \f
1291 /* Prologue analysis.  */
1292
1293
1294 /* The MeP has two classes of instructions: "core" instructions, which
1295    are pretty normal RISC chip stuff, and "coprocessor" instructions,
1296    which are mostly concerned with moving data in and out of
1297    coprocessor registers, and branching on coprocessor condition
1298    codes.  There's space in the instruction set for custom coprocessor
1299    instructions, too.
1300
1301    Instructions can be 16 or 32 bits long; the top two bits of the
1302    first byte indicate the length.  The coprocessor instructions are
1303    mixed in with the core instructions, and there's no easy way to
1304    distinguish them; you have to completely decode them to tell one
1305    from the other.
1306
1307    The MeP also supports a "VLIW" operation mode, where instructions
1308    always occur in fixed-width bundles.  The bundles are either 32
1309    bits or 64 bits long, depending on a fixed configuration flag.  You
1310    decode the first part of the bundle as normal; if it's a core
1311    instruction, and there's any space left in the bundle, the
1312    remainder of the bundle is a coprocessor instruction, which will
1313    execute in parallel with the core instruction.  If the first part
1314    of the bundle is a coprocessor instruction, it occupies the entire
1315    bundle.
1316
1317    So, here are all the cases:
1318
1319    - 32-bit VLIW mode:
1320      Every bundle is four bytes long, and naturally aligned, and can hold
1321      one or two instructions:
1322      - 16-bit core instruction; 16-bit coprocessor instruction
1323        These execute in parallel.
1324      - 32-bit core instruction
1325      - 32-bit coprocessor instruction
1326
1327    - 64-bit VLIW mode:
1328      Every bundle is eight bytes long, and naturally aligned, and can hold
1329      one or two instructions:
1330      - 16-bit core instruction; 48-bit (!) coprocessor instruction
1331        These execute in parallel.
1332      - 32-bit core instruction; 32-bit coprocessor instruction
1333        These execute in parallel.
1334      - 64-bit coprocessor instruction
1335
1336    Now, the MeP manual doesn't define any 48- or 64-bit coprocessor
1337    instruction, so I don't really know what's up there; perhaps these
1338    are always the user-defined coprocessor instructions.  */
1339
1340
1341 /* Return non-zero if PC is in a VLIW code section, zero
1342    otherwise.  */
1343 static int
1344 mep_pc_in_vliw_section (CORE_ADDR pc)
1345 {
1346   struct obj_section *s = find_pc_section (pc);
1347   if (s)
1348     return (s->the_bfd_section->flags & SEC_MEP_VLIW);
1349   return 0;
1350 }
1351
1352
1353 /* Set *INSN to the next core instruction at PC, and return the
1354    address of the next instruction.
1355
1356    The MeP instruction encoding is endian-dependent.  16- and 32-bit
1357    instructions are encoded as one or two two-byte parts, and each
1358    part is byte-swapped independently.  Thus:
1359
1360       void
1361       foo (void)
1362       {
1363         asm ("movu $1, 0x123456");
1364         asm ("sb $1,0x5678($2)");
1365         asm ("clip $1, 19");
1366       }
1367
1368    compiles to this big-endian code:
1369
1370        0:       d1 56 12 34     movu $1,0x123456
1371        4:       c1 28 56 78     sb $1,22136($2)
1372        8:       f1 01 10 98     clip $1,0x13
1373        c:       70 02           ret
1374
1375    and this little-endian code:
1376
1377        0:       56 d1 34 12     movu $1,0x123456
1378        4:       28 c1 78 56     sb $1,22136($2)
1379        8:       01 f1 98 10     clip $1,0x13
1380        c:       02 70           ret
1381
1382    Instructions are returned in *INSN in an endian-independent form: a
1383    given instruction always appears in *INSN the same way, regardless
1384    of whether the instruction stream is big-endian or little-endian.
1385
1386    *INSN's most significant 16 bits are the first (i.e., at lower
1387    addresses) 16 bit part of the instruction.  Its least significant
1388    16 bits are the second (i.e., higher-addressed) 16 bit part of the
1389    instruction, or zero for a 16-bit instruction.  Both 16-bit parts
1390    are fetched using the current endianness.
1391
1392    So, the *INSN values for the instruction sequence above would be
1393    the following, in either endianness:
1394
1395        0xd1561234       movu $1,0x123456     
1396        0xc1285678       sb $1,22136($2)
1397        0xf1011098       clip $1,0x13
1398        0x70020000       ret
1399
1400    (In a sense, it would be more natural to return 16-bit instructions
1401    in the least significant 16 bits of *INSN, but that would be
1402    ambiguous.  In order to tell whether you're looking at a 16- or a
1403    32-bit instruction, you have to consult the major opcode field ---
1404    the most significant four bits of the instruction's first 16-bit
1405    part.  But if we put 16-bit instructions at the least significant
1406    end of *INSN, then you don't know where to find the major opcode
1407    field until you know if it's a 16- or a 32-bit instruction ---
1408    which is where we started.)
1409
1410    If PC points to a core / coprocessor bundle in a VLIW section, set
1411    *INSN to the core instruction, and return the address of the next
1412    bundle.  This has the effect of skipping the bundled coprocessor
1413    instruction.  That's okay, since coprocessor instructions aren't
1414    significant to prologue analysis --- for the time being,
1415    anyway.  */
1416
1417 static CORE_ADDR 
1418 mep_get_insn (struct gdbarch *gdbarch, CORE_ADDR pc, unsigned long *insn)
1419 {
1420   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1421   int pc_in_vliw_section;
1422   int vliw_mode;
1423   int insn_len;
1424   gdb_byte buf[2];
1425
1426   *insn = 0;
1427
1428   /* Are we in a VLIW section?  */
1429   pc_in_vliw_section = mep_pc_in_vliw_section (pc);
1430   if (pc_in_vliw_section)
1431     {
1432       /* Yes, find out which bundle size.  */
1433       vliw_mode = current_options () & (MEP_OPT_VL32 | MEP_OPT_VL64);
1434
1435       /* If PC is in a VLIW section, but the current core doesn't say
1436          that it supports either VLIW mode, then we don't have enough
1437          information to parse the instruction stream it contains.
1438          Since the "undifferentiated" standard core doesn't have
1439          either VLIW mode bit set, this could happen.
1440
1441          But it shouldn't be an error to (say) set a breakpoint in a
1442          VLIW section, if you know you'll never reach it.  (Perhaps
1443          you have a script that sets a bunch of standard breakpoints.)
1444
1445          So we'll just return zero here, and hope for the best.  */
1446       if (! (vliw_mode & (MEP_OPT_VL32 | MEP_OPT_VL64)))
1447         return 0;
1448
1449       /* If both VL32 and VL64 are set, that's bogus, too.  */
1450       if (vliw_mode == (MEP_OPT_VL32 | MEP_OPT_VL64))
1451         return 0;
1452     }
1453   else
1454     vliw_mode = 0;
1455
1456   read_memory (pc, buf, sizeof (buf));
1457   *insn = extract_unsigned_integer (buf, 2, byte_order) << 16;
1458
1459   /* The major opcode --- the top four bits of the first 16-bit
1460      part --- indicates whether this instruction is 16 or 32 bits
1461      long.  All 32-bit instructions have a major opcode whose top
1462      two bits are 11; all the rest are 16-bit instructions.  */
1463   if ((*insn & 0xc0000000) == 0xc0000000)
1464     {
1465       /* Fetch the second 16-bit part of the instruction.  */
1466       read_memory (pc + 2, buf, sizeof (buf));
1467       *insn = *insn | extract_unsigned_integer (buf, 2, byte_order);
1468     }
1469
1470   /* If we're in VLIW code, then the VLIW width determines the address
1471      of the next instruction.  */
1472   if (vliw_mode)
1473     {
1474       /* In 32-bit VLIW code, all bundles are 32 bits long.  We ignore the
1475          coprocessor half of a core / copro bundle.  */
1476       if (vliw_mode == MEP_OPT_VL32)
1477         insn_len = 4;
1478
1479       /* In 64-bit VLIW code, all bundles are 64 bits long.  We ignore the
1480          coprocessor half of a core / copro bundle.  */
1481       else if (vliw_mode == MEP_OPT_VL64)
1482         insn_len = 8;
1483
1484       /* We'd better be in either core, 32-bit VLIW, or 64-bit VLIW mode.  */
1485       else
1486         gdb_assert_not_reached ("unexpected vliw mode");
1487     }
1488   
1489   /* Otherwise, the top two bits of the major opcode are (again) what
1490      we need to check.  */
1491   else if ((*insn & 0xc0000000) == 0xc0000000)
1492     insn_len = 4;
1493   else
1494     insn_len = 2;
1495
1496   return pc + insn_len;
1497 }
1498
1499
1500 /* Sign-extend the LEN-bit value N.  */
1501 #define SEXT(n, len) ((((int) (n)) ^ (1 << ((len) - 1))) - (1 << ((len) - 1)))
1502
1503 /* Return the LEN-bit field at POS from I.  */
1504 #define FIELD(i, pos, len) (((i) >> (pos)) & ((1 << (len)) - 1))
1505
1506 /* Like FIELD, but sign-extend the field's value.  */
1507 #define SFIELD(i, pos, len) (SEXT (FIELD ((i), (pos), (len)), (len)))
1508
1509
1510 /* Macros for decoding instructions.
1511
1512    Remember that 16-bit instructions are placed in bits 16..31 of i,
1513    not at the least significant end; this means that the major opcode
1514    field is always in the same place, regardless of the width of the
1515    instruction.  As a reminder of this, we show the lower 16 bits of a
1516    16-bit instruction as xxxx_xxxx_xxxx_xxxx.  */
1517
1518 /* SB Rn,(Rm)                 0000_nnnn_mmmm_1000 */
1519 /* SH Rn,(Rm)                 0000_nnnn_mmmm_1001 */
1520 /* SW Rn,(Rm)                 0000_nnnn_mmmm_1010 */
1521
1522 /* SW Rn,disp16(Rm)           1100_nnnn_mmmm_1010 dddd_dddd_dddd_dddd */
1523 #define IS_SW(i)              (((i) & 0xf00f0000) == 0xc00a0000)
1524 /* SB Rn,disp16(Rm)           1100_nnnn_mmmm_1000 dddd_dddd_dddd_dddd */
1525 #define IS_SB(i)              (((i) & 0xf00f0000) == 0xc0080000)
1526 /* SH Rn,disp16(Rm)           1100_nnnn_mmmm_1001 dddd_dddd_dddd_dddd */
1527 #define IS_SH(i)              (((i) & 0xf00f0000) == 0xc0090000)
1528 #define SWBH_32_BASE(i)       (FIELD (i, 20, 4))
1529 #define SWBH_32_SOURCE(i)     (FIELD (i, 24, 4))
1530 #define SWBH_32_OFFSET(i)     (SFIELD (i, 0, 16))
1531
1532 /* SW Rn,disp7.align4(SP)     0100_nnnn_0ddd_dd10 xxxx_xxxx_xxxx_xxxx */
1533 #define IS_SW_IMMD(i)         (((i) & 0xf0830000) == 0x40020000)
1534 #define SW_IMMD_SOURCE(i)     (FIELD (i, 24, 4))
1535 #define SW_IMMD_OFFSET(i)     (FIELD (i, 18, 5) << 2)
1536
1537 /* SW Rn,(Rm)                 0000_nnnn_mmmm_1010 xxxx_xxxx_xxxx_xxxx */
1538 #define IS_SW_REG(i)          (((i) & 0xf00f0000) == 0x000a0000)
1539 #define SW_REG_SOURCE(i)      (FIELD (i, 24, 4))
1540 #define SW_REG_BASE(i)        (FIELD (i, 20, 4))
1541
1542 /* ADD3 Rl,Rn,Rm              1001_nnnn_mmmm_llll xxxx_xxxx_xxxx_xxxx */
1543 #define IS_ADD3_16_REG(i)     (((i) & 0xf0000000) == 0x90000000)
1544 #define ADD3_16_REG_SRC1(i)   (FIELD (i, 20, 4))               /* n */
1545 #define ADD3_16_REG_SRC2(i)   (FIELD (i, 24, 4))               /* m */
1546
1547 /* ADD3 Rn,Rm,imm16           1100_nnnn_mmmm_0000 iiii_iiii_iiii_iiii */
1548 #define IS_ADD3_32(i)         (((i) & 0xf00f0000) == 0xc0000000)
1549 #define ADD3_32_TARGET(i)     (FIELD (i, 24, 4))
1550 #define ADD3_32_SOURCE(i)     (FIELD (i, 20, 4))
1551 #define ADD3_32_OFFSET(i)     (SFIELD (i, 0, 16))
1552
1553 /* ADD3 Rn,SP,imm7.align4     0100_nnnn_0iii_ii00 xxxx_xxxx_xxxx_xxxx */
1554 #define IS_ADD3_16(i)         (((i) & 0xf0830000) == 0x40000000)
1555 #define ADD3_16_TARGET(i)     (FIELD (i, 24, 4))
1556 #define ADD3_16_OFFSET(i)     (FIELD (i, 18, 5) << 2)
1557
1558 /* ADD Rn,imm6                0110_nnnn_iiii_ii00 xxxx_xxxx_xxxx_xxxx */
1559 #define IS_ADD(i)             (((i) & 0xf0030000) == 0x60000000)
1560 #define ADD_TARGET(i)         (FIELD (i, 24, 4))
1561 #define ADD_OFFSET(i)         (SFIELD (i, 18, 6))
1562
1563 /* LDC Rn,imm5                0111_nnnn_iiii_101I xxxx_xxxx_xxxx_xxxx
1564                               imm5 = I||i[7:4] */
1565 #define IS_LDC(i)             (((i) & 0xf00e0000) == 0x700a0000)
1566 #define LDC_IMM(i)            ((FIELD (i, 16, 1) << 4) | FIELD (i, 20, 4))
1567 #define LDC_TARGET(i)         (FIELD (i, 24, 4))
1568
1569 /* LW Rn,disp16(Rm)           1100_nnnn_mmmm_1110 dddd_dddd_dddd_dddd  */
1570 #define IS_LW(i)              (((i) & 0xf00f0000) == 0xc00e0000)
1571 #define LW_TARGET(i)          (FIELD (i, 24, 4))
1572 #define LW_BASE(i)            (FIELD (i, 20, 4))
1573 #define LW_OFFSET(i)          (SFIELD (i, 0, 16))
1574
1575 /* MOV Rn,Rm                  0000_nnnn_mmmm_0000 xxxx_xxxx_xxxx_xxxx */
1576 #define IS_MOV(i)             (((i) & 0xf00f0000) == 0x00000000)
1577 #define MOV_TARGET(i)         (FIELD (i, 24, 4))
1578 #define MOV_SOURCE(i)         (FIELD (i, 20, 4))
1579
1580 /* BRA disp12.align2          1011_dddd_dddd_ddd0 xxxx_xxxx_xxxx_xxxx */
1581 #define IS_BRA(i)             (((i) & 0xf0010000) == 0xb0000000)
1582 #define BRA_DISP(i)           (SFIELD (i, 17, 11) << 1)
1583
1584
1585 /* This structure holds the results of a prologue analysis.  */
1586 struct mep_prologue
1587 {
1588   /* The architecture for which we generated this prologue info.  */
1589   struct gdbarch *gdbarch;
1590
1591   /* The offset from the frame base to the stack pointer --- always
1592      zero or negative.
1593
1594      Calling this a "size" is a bit misleading, but given that the
1595      stack grows downwards, using offsets for everything keeps one
1596      from going completely sign-crazy: you never change anything's
1597      sign for an ADD instruction; always change the second operand's
1598      sign for a SUB instruction; and everything takes care of
1599      itself.  */
1600   int frame_size;
1601
1602   /* Non-zero if this function has initialized the frame pointer from
1603      the stack pointer, zero otherwise.  */
1604   int has_frame_ptr;
1605
1606   /* If has_frame_ptr is non-zero, this is the offset from the frame
1607      base to where the frame pointer points.  This is always zero or
1608      negative.  */
1609   int frame_ptr_offset;
1610
1611   /* The address of the first instruction at which the frame has been
1612      set up and the arguments are where the debug info says they are
1613      --- as best as we can tell.  */
1614   CORE_ADDR prologue_end;
1615
1616   /* reg_offset[R] is the offset from the CFA at which register R is
1617      saved, or 1 if register R has not been saved.  (Real values are
1618      always zero or negative.)  */
1619   int reg_offset[MEP_NUM_REGS];
1620 };
1621
1622 /* Return non-zero if VALUE is an incoming argument register.  */
1623
1624 static int
1625 is_arg_reg (pv_t value)
1626 {
1627   return (value.kind == pvk_register
1628           && MEP_R1_REGNUM <= value.reg && value.reg <= MEP_R4_REGNUM
1629           && value.k == 0);
1630 }
1631
1632 /* Return non-zero if a store of REG's current value VALUE to ADDR is
1633    probably spilling an argument register to its stack slot in STACK.
1634    Such instructions should be included in the prologue, if possible.
1635
1636    The store is a spill if:
1637    - the value being stored is REG's original value;
1638    - the value has not already been stored somewhere in STACK; and
1639    - ADDR is a stack slot's address (e.g., relative to the original
1640      value of the SP).  */
1641 static int
1642 is_arg_spill (struct gdbarch *gdbarch, pv_t value, pv_t addr,
1643               struct pv_area *stack)
1644 {
1645   return (is_arg_reg (value)
1646           && pv_is_register (addr, MEP_SP_REGNUM)
1647           && ! pv_area_find_reg (stack, gdbarch, value.reg, 0));
1648 }
1649
1650
1651 /* Function for finding saved registers in a 'struct pv_area'; we pass
1652    this to pv_area_scan.
1653
1654    If VALUE is a saved register, ADDR says it was saved at a constant
1655    offset from the frame base, and SIZE indicates that the whole
1656    register was saved, record its offset in RESULT_UNTYPED.  */
1657 static void
1658 check_for_saved (void *result_untyped, pv_t addr, CORE_ADDR size, pv_t value)
1659 {
1660   struct mep_prologue *result = (struct mep_prologue *) result_untyped;
1661
1662   if (value.kind == pvk_register
1663       && value.k == 0
1664       && pv_is_register (addr, MEP_SP_REGNUM)
1665       && size == register_size (result->gdbarch, value.reg))
1666     result->reg_offset[value.reg] = addr.k;
1667 }
1668
1669
1670 /* Analyze a prologue starting at START_PC, going no further than
1671    LIMIT_PC.  Fill in RESULT as appropriate.  */
1672 static void
1673 mep_analyze_prologue (struct gdbarch *gdbarch,
1674                       CORE_ADDR start_pc, CORE_ADDR limit_pc,
1675                       struct mep_prologue *result)
1676 {
1677   CORE_ADDR pc;
1678   unsigned long insn;
1679   int rn;
1680   int found_lp = 0;
1681   pv_t reg[MEP_NUM_REGS];
1682   struct pv_area *stack;
1683   struct cleanup *back_to;
1684   CORE_ADDR after_last_frame_setup_insn = start_pc;
1685
1686   memset (result, 0, sizeof (*result));
1687   result->gdbarch = gdbarch;
1688
1689   for (rn = 0; rn < MEP_NUM_REGS; rn++)
1690     {
1691       reg[rn] = pv_register (rn, 0);
1692       result->reg_offset[rn] = 1;
1693     }
1694
1695   stack = make_pv_area (MEP_SP_REGNUM, gdbarch_addr_bit (gdbarch));
1696   back_to = make_cleanup_free_pv_area (stack);
1697
1698   pc = start_pc;
1699   while (pc < limit_pc)
1700     {
1701       CORE_ADDR next_pc;
1702       pv_t pre_insn_fp, pre_insn_sp;
1703
1704       next_pc = mep_get_insn (gdbarch, pc, &insn);
1705
1706       /* A zero return from mep_get_insn means that either we weren't
1707          able to read the instruction from memory, or that we don't
1708          have enough information to be able to reliably decode it.  So
1709          we'll store here and hope for the best.  */
1710       if (! next_pc)
1711         break;
1712
1713       /* Note the current values of the SP and FP, so we can tell if
1714          this instruction changed them, below.  */
1715       pre_insn_fp = reg[MEP_FP_REGNUM];
1716       pre_insn_sp = reg[MEP_SP_REGNUM];
1717
1718       if (IS_ADD (insn))
1719         {
1720           int rn = ADD_TARGET (insn);
1721           CORE_ADDR imm6 = ADD_OFFSET (insn);
1722
1723           reg[rn] = pv_add_constant (reg[rn], imm6);
1724         }
1725       else if (IS_ADD3_16 (insn))
1726         {
1727           int rn = ADD3_16_TARGET (insn);
1728           int imm7 = ADD3_16_OFFSET (insn);
1729
1730           reg[rn] = pv_add_constant (reg[MEP_SP_REGNUM], imm7);
1731         }
1732       else if (IS_ADD3_32 (insn))
1733         {
1734           int rn = ADD3_32_TARGET (insn);
1735           int rm = ADD3_32_SOURCE (insn);
1736           int imm16 = ADD3_32_OFFSET (insn);
1737
1738           reg[rn] = pv_add_constant (reg[rm], imm16);
1739         }
1740       else if (IS_SW_REG (insn))
1741         {
1742           int rn = SW_REG_SOURCE (insn);
1743           int rm = SW_REG_BASE (insn);
1744
1745           /* If simulating this store would require us to forget
1746              everything we know about the stack frame in the name of
1747              accuracy, it would be better to just quit now.  */
1748           if (pv_area_store_would_trash (stack, reg[rm]))
1749             break;
1750           
1751           if (is_arg_spill (gdbarch, reg[rn], reg[rm], stack))
1752             after_last_frame_setup_insn = next_pc;
1753
1754           pv_area_store (stack, reg[rm], 4, reg[rn]);
1755         }
1756       else if (IS_SW_IMMD (insn))
1757         {
1758           int rn = SW_IMMD_SOURCE (insn);
1759           int offset = SW_IMMD_OFFSET (insn);
1760           pv_t addr = pv_add_constant (reg[MEP_SP_REGNUM], offset);
1761
1762           /* If simulating this store would require us to forget
1763              everything we know about the stack frame in the name of
1764              accuracy, it would be better to just quit now.  */
1765           if (pv_area_store_would_trash (stack, addr))
1766             break;
1767
1768           if (is_arg_spill (gdbarch, reg[rn], addr, stack))
1769             after_last_frame_setup_insn = next_pc;
1770
1771           pv_area_store (stack, addr, 4, reg[rn]);
1772         }
1773       else if (IS_MOV (insn))
1774         {
1775           int rn = MOV_TARGET (insn);
1776           int rm = MOV_SOURCE (insn);
1777
1778           reg[rn] = reg[rm];
1779
1780           if (pv_is_register (reg[rm], rm) && is_arg_reg (reg[rm]))
1781             after_last_frame_setup_insn = next_pc;
1782         }
1783       else if (IS_SB (insn) || IS_SH (insn) || IS_SW (insn))
1784         {
1785           int rn = SWBH_32_SOURCE (insn);
1786           int rm = SWBH_32_BASE (insn);
1787           int disp = SWBH_32_OFFSET (insn);
1788           int size = (IS_SB (insn) ? 1
1789                       : IS_SH (insn) ? 2
1790                       : (gdb_assert (IS_SW (insn)), 4));
1791           pv_t addr = pv_add_constant (reg[rm], disp);
1792
1793           if (pv_area_store_would_trash (stack, addr))
1794             break;
1795
1796           if (is_arg_spill (gdbarch, reg[rn], addr, stack))
1797             after_last_frame_setup_insn = next_pc;
1798
1799           pv_area_store (stack, addr, size, reg[rn]);
1800         }
1801       else if (IS_LDC (insn))
1802         {
1803           int rn = LDC_TARGET (insn);
1804           int cr = LDC_IMM (insn) + MEP_FIRST_CSR_REGNUM;
1805
1806           reg[rn] = reg[cr];
1807         }
1808       else if (IS_LW (insn))
1809         {
1810           int rn = LW_TARGET (insn);
1811           int rm = LW_BASE (insn);
1812           int offset = LW_OFFSET (insn);
1813           pv_t addr = pv_add_constant (reg[rm], offset);
1814
1815           reg[rn] = pv_area_fetch (stack, addr, 4);
1816         }
1817       else if (IS_BRA (insn) && BRA_DISP (insn) > 0)
1818         {
1819           /* When a loop appears as the first statement of a function
1820              body, gcc 4.x will use a BRA instruction to branch to the
1821              loop condition checking code.  This BRA instruction is
1822              marked as part of the prologue.  We therefore set next_pc
1823              to this branch target and also stop the prologue scan.
1824              The instructions at and beyond the branch target should
1825              no longer be associated with the prologue.
1826              
1827              Note that we only consider forward branches here.  We
1828              presume that a forward branch is being used to skip over
1829              a loop body.
1830              
1831              A backwards branch is covered by the default case below.
1832              If we were to encounter a backwards branch, that would
1833              most likely mean that we've scanned through a loop body.
1834              We definitely want to stop the prologue scan when this
1835              happens and that is precisely what is done by the default
1836              case below.  */
1837           next_pc = pc + BRA_DISP (insn);
1838           after_last_frame_setup_insn = next_pc;
1839           break;
1840         }
1841       else
1842         /* We've hit some instruction we don't know how to simulate.
1843            Strictly speaking, we should set every value we're
1844            tracking to "unknown".  But we'll be optimistic, assume
1845            that we have enough information already, and stop
1846            analysis here.  */
1847         break;
1848
1849       /* If this instruction changed the FP or decreased the SP (i.e.,
1850          allocated more stack space), then this may be a good place to
1851          declare the prologue finished.  However, there are some
1852          exceptions:
1853
1854          - If the instruction just changed the FP back to its original
1855            value, then that's probably a restore instruction.  The
1856            prologue should definitely end before that.  
1857
1858          - If the instruction increased the value of the SP (that is,
1859            shrunk the frame), then it's probably part of a frame
1860            teardown sequence, and the prologue should end before that.  */
1861
1862       if (! pv_is_identical (reg[MEP_FP_REGNUM], pre_insn_fp))
1863         {
1864           if (! pv_is_register_k (reg[MEP_FP_REGNUM], MEP_FP_REGNUM, 0))
1865             after_last_frame_setup_insn = next_pc;
1866         }
1867       else if (! pv_is_identical (reg[MEP_SP_REGNUM], pre_insn_sp))
1868         {
1869           /* The comparison of constants looks odd, there, because .k
1870              is unsigned.  All it really means is that the new value
1871              is lower than it was before the instruction.  */
1872           if (pv_is_register (pre_insn_sp, MEP_SP_REGNUM)
1873               && pv_is_register (reg[MEP_SP_REGNUM], MEP_SP_REGNUM)
1874               && ((pre_insn_sp.k - reg[MEP_SP_REGNUM].k)
1875                   < (reg[MEP_SP_REGNUM].k - pre_insn_sp.k)))
1876             after_last_frame_setup_insn = next_pc;
1877         }
1878
1879       pc = next_pc;
1880     }
1881
1882   /* Is the frame size (offset, really) a known constant?  */
1883   if (pv_is_register (reg[MEP_SP_REGNUM], MEP_SP_REGNUM))
1884     result->frame_size = reg[MEP_SP_REGNUM].k;
1885
1886   /* Was the frame pointer initialized?  */
1887   if (pv_is_register (reg[MEP_FP_REGNUM], MEP_SP_REGNUM))
1888     {
1889       result->has_frame_ptr = 1;
1890       result->frame_ptr_offset = reg[MEP_FP_REGNUM].k;
1891     }
1892
1893   /* Record where all the registers were saved.  */
1894   pv_area_scan (stack, check_for_saved, (void *) result);
1895
1896   result->prologue_end = after_last_frame_setup_insn;
1897
1898   do_cleanups (back_to);
1899 }
1900
1901
1902 static CORE_ADDR
1903 mep_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR pc)
1904 {
1905   const char *name;
1906   CORE_ADDR func_addr, func_end;
1907   struct mep_prologue p;
1908
1909   /* Try to find the extent of the function that contains PC.  */
1910   if (! find_pc_partial_function (pc, &name, &func_addr, &func_end))
1911     return pc;
1912
1913   mep_analyze_prologue (gdbarch, pc, func_end, &p);
1914   return p.prologue_end;
1915 }
1916
1917
1918 \f
1919 /* Breakpoints.  */
1920
1921 static const unsigned char *
1922 mep_breakpoint_from_pc (struct gdbarch *gdbarch, CORE_ADDR * pcptr, int *lenptr)
1923 {
1924   static unsigned char breakpoint[] = { 0x70, 0x32 };
1925   *lenptr = sizeof (breakpoint);
1926   return breakpoint;
1927 }
1928
1929
1930 \f
1931 /* Frames and frame unwinding.  */
1932
1933
1934 static struct mep_prologue *
1935 mep_analyze_frame_prologue (struct frame_info *this_frame,
1936                             void **this_prologue_cache)
1937 {
1938   if (! *this_prologue_cache)
1939     {
1940       CORE_ADDR func_start, stop_addr;
1941
1942       *this_prologue_cache 
1943         = FRAME_OBSTACK_ZALLOC (struct mep_prologue);
1944
1945       func_start = get_frame_func (this_frame);
1946       stop_addr = get_frame_pc (this_frame);
1947
1948       /* If we couldn't find any function containing the PC, then
1949          just initialize the prologue cache, but don't do anything.  */
1950       if (! func_start)
1951         stop_addr = func_start;
1952
1953       mep_analyze_prologue (get_frame_arch (this_frame),
1954                             func_start, stop_addr, *this_prologue_cache);
1955     }
1956
1957   return *this_prologue_cache;
1958 }
1959
1960
1961 /* Given the next frame and a prologue cache, return this frame's
1962    base.  */
1963 static CORE_ADDR
1964 mep_frame_base (struct frame_info *this_frame,
1965                 void **this_prologue_cache)
1966 {
1967   struct mep_prologue *p
1968     = mep_analyze_frame_prologue (this_frame, this_prologue_cache);
1969
1970   /* In functions that use alloca, the distance between the stack
1971      pointer and the frame base varies dynamically, so we can't use
1972      the SP plus static information like prologue analysis to find the
1973      frame base.  However, such functions must have a frame pointer,
1974      to be able to restore the SP on exit.  So whenever we do have a
1975      frame pointer, use that to find the base.  */
1976   if (p->has_frame_ptr)
1977     {
1978       CORE_ADDR fp
1979         = get_frame_register_unsigned (this_frame, MEP_FP_REGNUM);
1980       return fp - p->frame_ptr_offset;
1981     }
1982   else
1983     {
1984       CORE_ADDR sp
1985         = get_frame_register_unsigned (this_frame, MEP_SP_REGNUM);
1986       return sp - p->frame_size;
1987     }
1988 }
1989
1990
1991 static void
1992 mep_frame_this_id (struct frame_info *this_frame,
1993                    void **this_prologue_cache,
1994                    struct frame_id *this_id)
1995 {
1996   *this_id = frame_id_build (mep_frame_base (this_frame, this_prologue_cache),
1997                              get_frame_func (this_frame));
1998 }
1999
2000
2001 static struct value *
2002 mep_frame_prev_register (struct frame_info *this_frame,
2003                          void **this_prologue_cache, int regnum)
2004 {
2005   struct mep_prologue *p
2006     = mep_analyze_frame_prologue (this_frame, this_prologue_cache);
2007
2008   /* There are a number of complications in unwinding registers on the
2009      MeP, having to do with core functions calling VLIW functions and
2010      vice versa.
2011
2012      The least significant bit of the link register, LP.LTOM, is the
2013      VLIW mode toggle bit: it's set if a core function called a VLIW
2014      function, or vice versa, and clear when the caller and callee
2015      were both in the same mode.
2016
2017      So, if we're asked to unwind the PC, then we really want to
2018      unwind the LP and clear the least significant bit.  (Real return
2019      addresses are always even.)  And if we want to unwind the program
2020      status word (PSW), we need to toggle PSW.OM if LP.LTOM is set.
2021
2022      Tweaking the register values we return in this way means that the
2023      bits in BUFFERP[] are not the same as the bits you'd find at
2024      ADDRP in the inferior, so we make sure lvalp is not_lval when we
2025      do this.  */
2026   if (regnum == MEP_PC_REGNUM)
2027     {
2028       struct value *value;
2029       CORE_ADDR lp;
2030       value = mep_frame_prev_register (this_frame, this_prologue_cache,
2031                                        MEP_LP_REGNUM);
2032       lp = value_as_long (value);
2033       release_value (value);
2034       value_free (value);
2035
2036       return frame_unwind_got_constant (this_frame, regnum, lp & ~1);
2037     }
2038   else
2039     {
2040       CORE_ADDR frame_base = mep_frame_base (this_frame, this_prologue_cache);
2041       struct value *value;
2042
2043       /* Our caller's SP is our frame base.  */
2044       if (regnum == MEP_SP_REGNUM)
2045         return frame_unwind_got_constant (this_frame, regnum, frame_base);
2046
2047       /* If prologue analysis says we saved this register somewhere,
2048          return a description of the stack slot holding it.  */
2049       if (p->reg_offset[regnum] != 1)
2050         value = frame_unwind_got_memory (this_frame, regnum,
2051                                          frame_base + p->reg_offset[regnum]);
2052
2053       /* Otherwise, presume we haven't changed the value of this
2054          register, and get it from the next frame.  */
2055       else
2056         value = frame_unwind_got_register (this_frame, regnum, regnum);
2057
2058       /* If we need to toggle the operating mode, do so.  */
2059       if (regnum == MEP_PSW_REGNUM)
2060         {
2061           CORE_ADDR psw, lp;
2062
2063           psw = value_as_long (value);
2064           release_value (value);
2065           value_free (value);
2066
2067           /* Get the LP's value, too.  */
2068           value = get_frame_register_value (this_frame, MEP_LP_REGNUM);
2069           lp = value_as_long (value);
2070           release_value (value);
2071           value_free (value);
2072
2073           /* If LP.LTOM is set, then toggle PSW.OM.  */
2074           if (lp & 0x1)
2075             psw ^= 0x1000;
2076
2077           return frame_unwind_got_constant (this_frame, regnum, psw);
2078         }
2079
2080       return value;
2081     }
2082 }
2083
2084
2085 static const struct frame_unwind mep_frame_unwind = {
2086   NORMAL_FRAME,
2087   default_frame_unwind_stop_reason,
2088   mep_frame_this_id,
2089   mep_frame_prev_register,
2090   NULL,
2091   default_frame_sniffer
2092 };
2093
2094
2095 /* Our general unwinding function can handle unwinding the PC.  */
2096 static CORE_ADDR
2097 mep_unwind_pc (struct gdbarch *gdbarch, struct frame_info *next_frame)
2098 {
2099   return frame_unwind_register_unsigned (next_frame, MEP_PC_REGNUM);
2100 }
2101
2102
2103 /* Our general unwinding function can handle unwinding the SP.  */
2104 static CORE_ADDR
2105 mep_unwind_sp (struct gdbarch *gdbarch, struct frame_info *next_frame)
2106 {
2107   return frame_unwind_register_unsigned (next_frame, MEP_SP_REGNUM);
2108 }
2109
2110
2111 \f
2112 /* Return values.  */
2113
2114
2115 static int
2116 mep_use_struct_convention (struct type *type)
2117 {
2118   return (TYPE_LENGTH (type) > MEP_GPR_SIZE);
2119 }
2120
2121
2122 static void
2123 mep_extract_return_value (struct gdbarch *arch,
2124                           struct type *type,
2125                           struct regcache *regcache,
2126                           gdb_byte *valbuf)
2127 {
2128   int byte_order = gdbarch_byte_order (arch);
2129
2130   /* Values that don't occupy a full register appear at the less
2131      significant end of the value.  This is the offset to where the
2132      value starts.  */
2133   int offset;
2134
2135   /* Return values > MEP_GPR_SIZE bytes are returned in memory,
2136      pointed to by R0.  */
2137   gdb_assert (TYPE_LENGTH (type) <= MEP_GPR_SIZE);
2138
2139   if (byte_order == BFD_ENDIAN_BIG)
2140     offset = MEP_GPR_SIZE - TYPE_LENGTH (type);
2141   else
2142     offset = 0;
2143
2144   /* Return values that do fit in a single register are returned in R0.  */
2145   regcache_cooked_read_part (regcache, MEP_R0_REGNUM,
2146                              offset, TYPE_LENGTH (type),
2147                              valbuf);
2148 }
2149
2150
2151 static void
2152 mep_store_return_value (struct gdbarch *arch,
2153                         struct type *type,
2154                         struct regcache *regcache,
2155                         const gdb_byte *valbuf)
2156 {
2157   int byte_order = gdbarch_byte_order (arch);
2158
2159   /* Values that fit in a single register go in R0.  */
2160   if (TYPE_LENGTH (type) <= MEP_GPR_SIZE)
2161     {
2162       /* Values that don't occupy a full register appear at the least
2163          significant end of the value.  This is the offset to where the
2164          value starts.  */
2165       int offset;
2166
2167       if (byte_order == BFD_ENDIAN_BIG)
2168         offset = MEP_GPR_SIZE - TYPE_LENGTH (type);
2169       else
2170         offset = 0;
2171
2172       regcache_cooked_write_part (regcache, MEP_R0_REGNUM,
2173                                   offset, TYPE_LENGTH (type),
2174                                   valbuf);
2175     }
2176
2177   /* Return values larger than a single register are returned in
2178      memory, pointed to by R0.  Unfortunately, we can't count on R0
2179      pointing to the return buffer, so we raise an error here.  */
2180   else
2181     error (_("\
2182 GDB cannot set return values larger than four bytes; the Media Processor's\n\
2183 calling conventions do not provide enough information to do this.\n\
2184 Try using the 'return' command with no argument."));
2185 }
2186
2187 static enum return_value_convention
2188 mep_return_value (struct gdbarch *gdbarch, struct value *function,
2189                   struct type *type, struct regcache *regcache,
2190                   gdb_byte *readbuf, const gdb_byte *writebuf)
2191 {
2192   if (mep_use_struct_convention (type))
2193     {
2194       if (readbuf)
2195         {
2196           ULONGEST addr;
2197           /* Although the address of the struct buffer gets passed in R1, it's
2198              returned in R0.  Fetch R0's value and then read the memory
2199              at that address.  */
2200           regcache_raw_read_unsigned (regcache, MEP_R0_REGNUM, &addr);
2201           read_memory (addr, readbuf, TYPE_LENGTH (type));
2202         }
2203       if (writebuf)
2204         {
2205           /* Return values larger than a single register are returned in
2206              memory, pointed to by R0.  Unfortunately, we can't count on R0
2207              pointing to the return buffer, so we raise an error here.  */
2208           error (_("\
2209 GDB cannot set return values larger than four bytes; the Media Processor's\n\
2210 calling conventions do not provide enough information to do this.\n\
2211 Try using the 'return' command with no argument."));
2212         }
2213       return RETURN_VALUE_ABI_RETURNS_ADDRESS;
2214     }
2215
2216   if (readbuf)
2217     mep_extract_return_value (gdbarch, type, regcache, readbuf);
2218   if (writebuf)
2219     mep_store_return_value (gdbarch, type, regcache, writebuf);
2220
2221   return RETURN_VALUE_REGISTER_CONVENTION;
2222 }
2223
2224 \f
2225 /* Inferior calls.  */
2226
2227
2228 static CORE_ADDR
2229 mep_frame_align (struct gdbarch *gdbarch, CORE_ADDR sp)
2230 {
2231   /* Require word alignment.  */
2232   return sp & -4;
2233 }
2234
2235
2236 /* From "lang_spec2.txt":
2237
2238    4.2 Calling conventions
2239
2240    4.2.1 Core register conventions
2241
2242    - Parameters should be evaluated from left to right, and they
2243      should be held in $1,$2,$3,$4 in order.  The fifth parameter or
2244      after should be held in the stack.  If the size is larger than 4
2245      bytes in the first four parameters, the pointer should be held in
2246      the registers instead.  If the size is larger than 4 bytes in the
2247      fifth parameter or after, the pointer should be held in the stack.
2248
2249    - Return value of a function should be held in register $0.  If the
2250      size of return value is larger than 4 bytes, $1 should hold the
2251      pointer pointing memory that would hold the return value.  In this
2252      case, the first parameter should be held in $2, the second one in
2253      $3, and the third one in $4, and the forth parameter or after
2254      should be held in the stack.
2255
2256    [This doesn't say so, but arguments shorter than four bytes are
2257    passed in the least significant end of a four-byte word when
2258    they're passed on the stack.]  */
2259
2260
2261 /* Traverse the list of ARGC arguments ARGV; for every ARGV[i] too
2262    large to fit in a register, save it on the stack, and place its
2263    address in COPY[i].  SP is the initial stack pointer; return the
2264    new stack pointer.  */
2265 static CORE_ADDR
2266 push_large_arguments (CORE_ADDR sp, int argc, struct value **argv,
2267                       CORE_ADDR copy[])
2268 {
2269   int i;
2270
2271   for (i = 0; i < argc; i++)
2272     {
2273       unsigned arg_len = TYPE_LENGTH (value_type (argv[i]));
2274
2275       if (arg_len > MEP_GPR_SIZE)
2276         {
2277           /* Reserve space for the copy, and then round the SP down, to
2278              make sure it's all aligned properly.  */
2279           sp = (sp - arg_len) & -4;
2280           write_memory (sp, value_contents (argv[i]), arg_len);
2281           copy[i] = sp;
2282         }
2283     }
2284
2285   return sp;
2286 }
2287
2288
2289 static CORE_ADDR
2290 mep_push_dummy_call (struct gdbarch *gdbarch, struct value *function,
2291                      struct regcache *regcache, CORE_ADDR bp_addr,
2292                      int argc, struct value **argv, CORE_ADDR sp,
2293                      int struct_return,
2294                      CORE_ADDR struct_addr)
2295 {
2296   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2297   CORE_ADDR *copy = (CORE_ADDR *) alloca (argc * sizeof (copy[0]));
2298   CORE_ADDR func_addr = find_function_addr (function, NULL);
2299   int i;
2300
2301   /* The number of the next register available to hold an argument.  */
2302   int arg_reg;
2303
2304   /* The address of the next stack slot available to hold an argument.  */
2305   CORE_ADDR arg_stack;
2306
2307   /* The address of the end of the stack area for arguments.  This is
2308      just for error checking.  */
2309   CORE_ADDR arg_stack_end;
2310   
2311   sp = push_large_arguments (sp, argc, argv, copy);
2312
2313   /* Reserve space for the stack arguments, if any.  */
2314   arg_stack_end = sp;
2315   if (argc + (struct_addr ? 1 : 0) > 4)
2316     sp -= ((argc + (struct_addr ? 1 : 0)) - 4) * MEP_GPR_SIZE;
2317
2318   arg_reg = MEP_R1_REGNUM;
2319   arg_stack = sp;
2320
2321   /* If we're returning a structure by value, push the pointer to the
2322      buffer as the first argument.  */
2323   if (struct_return)
2324     {
2325       regcache_cooked_write_unsigned (regcache, arg_reg, struct_addr);
2326       arg_reg++;
2327     }
2328
2329   for (i = 0; i < argc; i++)
2330     {
2331       ULONGEST value;
2332
2333       /* Arguments that fit in a GPR get expanded to fill the GPR.  */
2334       if (TYPE_LENGTH (value_type (argv[i])) <= MEP_GPR_SIZE)
2335         value = extract_unsigned_integer (value_contents (argv[i]),
2336                                           TYPE_LENGTH (value_type (argv[i])),
2337                                           byte_order);
2338
2339       /* Arguments too large to fit in a GPR get copied to the stack,
2340          and we pass a pointer to the copy.  */
2341       else
2342         value = copy[i];
2343
2344       /* We use $1 -- $4 for passing arguments, then use the stack.  */
2345       if (arg_reg <= MEP_R4_REGNUM)
2346         {
2347           regcache_cooked_write_unsigned (regcache, arg_reg, value);
2348           arg_reg++;
2349         }
2350       else
2351         {
2352           gdb_byte buf[MEP_GPR_SIZE];
2353           store_unsigned_integer (buf, MEP_GPR_SIZE, byte_order, value);
2354           write_memory (arg_stack, buf, MEP_GPR_SIZE);
2355           arg_stack += MEP_GPR_SIZE;
2356         }
2357     }
2358
2359   gdb_assert (arg_stack <= arg_stack_end);
2360
2361   /* Set the return address.  */
2362   regcache_cooked_write_unsigned (regcache, MEP_LP_REGNUM, bp_addr);
2363
2364   /* Update the stack pointer.  */
2365   regcache_cooked_write_unsigned (regcache, MEP_SP_REGNUM, sp);
2366   
2367   return sp;
2368 }
2369
2370
2371 static struct frame_id
2372 mep_dummy_id (struct gdbarch *gdbarch, struct frame_info *this_frame)
2373 {
2374   CORE_ADDR sp = get_frame_register_unsigned (this_frame, MEP_SP_REGNUM);
2375   return frame_id_build (sp, get_frame_pc (this_frame));
2376 }
2377
2378
2379 \f
2380 /* Initialization.  */
2381
2382
2383 static struct gdbarch *
2384 mep_gdbarch_init (struct gdbarch_info info, struct gdbarch_list *arches)
2385 {
2386   struct gdbarch *gdbarch;
2387   struct gdbarch_tdep *tdep;
2388
2389   /* Which me_module are we building a gdbarch object for?  */
2390   CONFIG_ATTR me_module;
2391
2392   /* If we have a BFD in hand, figure out which me_module it was built
2393      for.  Otherwise, use the no-particular-me_module code.  */
2394   if (info.abfd)
2395     {
2396       /* The way to get the me_module code depends on the object file
2397          format.  At the moment, we only know how to handle ELF.  */
2398       if (bfd_get_flavour (info.abfd) == bfd_target_elf_flavour)
2399         me_module = elf_elfheader (info.abfd)->e_flags & EF_MEP_INDEX_MASK;
2400       else
2401         me_module = CONFIG_NONE;
2402     }
2403   else
2404     me_module = CONFIG_NONE;
2405
2406   /* If we're setting the architecture from a file, check the
2407      endianness of the file against that of the me_module.  */
2408   if (info.abfd)
2409     {
2410       /* The negations on either side make the comparison treat all
2411          non-zero (true) values as equal.  */
2412       if (! bfd_big_endian (info.abfd) != ! me_module_big_endian (me_module))
2413         {
2414           const char *module_name = me_module_name (me_module);
2415           const char *module_endianness
2416             = me_module_big_endian (me_module) ? "big" : "little";
2417           const char *file_name = bfd_get_filename (info.abfd);
2418           const char *file_endianness
2419             = bfd_big_endian (info.abfd) ? "big" : "little";
2420           
2421           fputc_unfiltered ('\n', gdb_stderr);
2422           if (module_name)
2423             warning (_("the MeP module '%s' is %s-endian, but the executable\n"
2424                        "%s is %s-endian."),
2425                      module_name, module_endianness,
2426                      file_name, file_endianness);
2427           else
2428             warning (_("the selected MeP module is %s-endian, but the "
2429                        "executable\n"
2430                        "%s is %s-endian."),
2431                      module_endianness, file_name, file_endianness);
2432         }
2433     }
2434
2435   /* Find a candidate among the list of architectures we've created
2436      already.  info->bfd_arch_info needs to match, but we also want
2437      the right me_module: the ELF header's e_flags field needs to
2438      match as well.  */
2439   for (arches = gdbarch_list_lookup_by_info (arches, &info); 
2440        arches != NULL;
2441        arches = gdbarch_list_lookup_by_info (arches->next, &info))
2442     if (gdbarch_tdep (arches->gdbarch)->me_module == me_module)
2443       return arches->gdbarch;
2444
2445   tdep = (struct gdbarch_tdep *) xmalloc (sizeof (struct gdbarch_tdep));
2446   gdbarch = gdbarch_alloc (&info, tdep);
2447
2448   /* Get a CGEN CPU descriptor for this architecture.  */
2449   {
2450     const char *mach_name = info.bfd_arch_info->printable_name;
2451     enum cgen_endian endian = (info.byte_order == BFD_ENDIAN_BIG
2452                                ? CGEN_ENDIAN_BIG
2453                                : CGEN_ENDIAN_LITTLE);
2454
2455     tdep->cpu_desc = mep_cgen_cpu_open (CGEN_CPU_OPEN_BFDMACH, mach_name,
2456                                         CGEN_CPU_OPEN_ENDIAN, endian,
2457                                         CGEN_CPU_OPEN_END);
2458   }
2459
2460   tdep->me_module = me_module;
2461
2462   /* Register set.  */
2463   set_gdbarch_read_pc (gdbarch, mep_read_pc);
2464   set_gdbarch_num_regs (gdbarch, MEP_NUM_RAW_REGS);
2465   set_gdbarch_pc_regnum (gdbarch, MEP_PC_REGNUM);
2466   set_gdbarch_sp_regnum (gdbarch, MEP_SP_REGNUM);
2467   set_gdbarch_register_name (gdbarch, mep_register_name);
2468   set_gdbarch_register_type (gdbarch, mep_register_type);
2469   set_gdbarch_num_pseudo_regs (gdbarch, MEP_NUM_PSEUDO_REGS);
2470   set_gdbarch_pseudo_register_read (gdbarch, mep_pseudo_register_read);
2471   set_gdbarch_pseudo_register_write (gdbarch, mep_pseudo_register_write);
2472   set_gdbarch_dwarf2_reg_to_regnum (gdbarch, mep_debug_reg_to_regnum);
2473   set_gdbarch_stab_reg_to_regnum (gdbarch, mep_debug_reg_to_regnum);
2474
2475   set_gdbarch_register_reggroup_p (gdbarch, mep_register_reggroup_p);
2476   reggroup_add (gdbarch, all_reggroup);
2477   reggroup_add (gdbarch, general_reggroup);
2478   reggroup_add (gdbarch, save_reggroup);
2479   reggroup_add (gdbarch, restore_reggroup);
2480   reggroup_add (gdbarch, mep_csr_reggroup);
2481   reggroup_add (gdbarch, mep_cr_reggroup);
2482   reggroup_add (gdbarch, mep_ccr_reggroup);
2483
2484   /* Disassembly.  */
2485   set_gdbarch_print_insn (gdbarch, mep_gdb_print_insn); 
2486
2487   /* Breakpoints.  */
2488   set_gdbarch_breakpoint_from_pc (gdbarch, mep_breakpoint_from_pc);
2489   set_gdbarch_decr_pc_after_break (gdbarch, 0);
2490   set_gdbarch_skip_prologue (gdbarch, mep_skip_prologue);
2491
2492   /* Frames and frame unwinding.  */
2493   frame_unwind_append_unwinder (gdbarch, &mep_frame_unwind);
2494   set_gdbarch_unwind_pc (gdbarch, mep_unwind_pc);
2495   set_gdbarch_unwind_sp (gdbarch, mep_unwind_sp);
2496   set_gdbarch_inner_than (gdbarch, core_addr_lessthan);
2497   set_gdbarch_frame_args_skip (gdbarch, 0);
2498
2499   /* Return values.  */
2500   set_gdbarch_return_value (gdbarch, mep_return_value);
2501   
2502   /* Inferior function calls.  */
2503   set_gdbarch_frame_align (gdbarch, mep_frame_align);
2504   set_gdbarch_push_dummy_call (gdbarch, mep_push_dummy_call);
2505   set_gdbarch_dummy_id (gdbarch, mep_dummy_id);
2506
2507   return gdbarch;
2508 }
2509
2510 /* Provide a prototype to silence -Wmissing-prototypes.  */
2511 extern initialize_file_ftype _initialize_mep_tdep;
2512
2513 void
2514 _initialize_mep_tdep (void)
2515 {
2516   mep_csr_reggroup = reggroup_new ("csr", USER_REGGROUP);
2517   mep_cr_reggroup  = reggroup_new ("cr", USER_REGGROUP); 
2518   mep_ccr_reggroup = reggroup_new ("ccr", USER_REGGROUP);
2519
2520   register_gdbarch_init (bfd_arch_mep, mep_gdbarch_init);
2521
2522   mep_init_pseudoregister_maps ();
2523 }