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