2008-04-23 Maxim Grigoriev <maxim2405@gmail.com>
[external/binutils.git] / gdb / xtensa-tdep.c
1 /* Target-dependent code for the Xtensa port of GDB, the GNU debugger.
2
3    Copyright (C) 2003, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "frame.h"
22 #include "solib-svr4.h"
23 #include "symtab.h"
24 #include "symfile.h"
25 #include "objfiles.h"
26 #include "gdbtypes.h"
27 #include "gdbcore.h"
28 #include "value.h"
29 #include "dis-asm.h"
30 #include "inferior.h"
31 #include "floatformat.h"
32 #include "regcache.h"
33 #include "reggroups.h"
34 #include "regset.h"
35
36 #include "dummy-frame.h"
37 #include "elf/dwarf2.h"
38 #include "dwarf2-frame.h"
39 #include "dwarf2loc.h"
40 #include "frame.h"
41 #include "frame-base.h"
42 #include "frame-unwind.h"
43
44 #include "arch-utils.h"
45 #include "gdbarch.h"
46 #include "remote.h"
47 #include "serial.h"
48
49 #include "command.h"
50 #include "gdbcmd.h"
51 #include "gdb_assert.h"
52
53 #include "xtensa-isa.h"
54 #include "xtensa-tdep.h"
55 #include "xtensa-config.h"
56
57
58 static int xtensa_debug_level = 0;
59
60 #define DEBUGWARN(args...) \
61   if (xtensa_debug_level > 0) \
62     fprintf_unfiltered (gdb_stdlog, "(warn ) " args)
63
64 #define DEBUGINFO(args...) \
65   if (xtensa_debug_level > 1) \
66     fprintf_unfiltered (gdb_stdlog, "(info ) " args)
67
68 #define DEBUGTRACE(args...) \
69   if (xtensa_debug_level > 2) \
70     fprintf_unfiltered (gdb_stdlog, "(trace) " args)
71
72 #define DEBUGVERB(args...) \
73   if (xtensa_debug_level > 3) \
74     fprintf_unfiltered (gdb_stdlog, "(verb ) " args)
75
76
77 /* According to the ABI, the SP must be aligned to 16-byte boundaries.  */
78 #define SP_ALIGNMENT 16
79
80
81 /* On Windowed ABI, we use a6 through a11 for passing arguments
82    to a function called by GDB because CALL4 is used.  */
83 #define ARGS_NUM_REGS           6
84 #define REGISTER_SIZE           4
85
86
87 /* Extract the call size from the return address or PS register.  */
88 #define PS_CALLINC_SHIFT        16
89 #define PS_CALLINC_MASK         0x00030000
90 #define CALLINC(ps)             (((ps) & PS_CALLINC_MASK) >> PS_CALLINC_SHIFT)
91 #define WINSIZE(ra)             (4 * (( (ra) >> 30) & 0x3))
92
93 /* ABI-independent macros.  */
94 #define ARG_NOF(gdbarch) \
95   (gdbarch_tdep (gdbarch)->call_abi \
96    == CallAbiCall0Only ? C0_NARGS : (ARGS_NUM_REGS))
97 #define ARG_1ST(gdbarch) \
98   (gdbarch_tdep (gdbarch)->call_abi  == CallAbiCall0Only \
99    ? (gdbarch_tdep (gdbarch)->a0_base + C0_ARGS) \
100    : (gdbarch_tdep (gdbarch)->a0_base + 6))
101
102 /* XTENSA_IS_ENTRY tests whether the first byte of an instruction
103    indicates that the instruction is an ENTRY instruction.  */
104
105 #define XTENSA_IS_ENTRY(gdbarch, op1) \
106   ((gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG) \
107    ? ((op1) == 0x6c) : ((op1) == 0x36))
108
109 #define XTENSA_ENTRY_LENGTH     3
110
111 /* windowing_enabled() returns true, if windowing is enabled.
112    WOE must be set to 1; EXCM to 0.
113    Note: We assume that EXCM is always 0 for XEA1.  */
114
115 #define PS_WOE                  (1<<18)
116 #define PS_EXC                  (1<<4)
117
118 /* Convert a live A-register number to the corresponding AR-register number.  */
119 static int
120 arreg_number (struct gdbarch *gdbarch, int a_regnum, ULONGEST wb)
121 {
122   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
123   int arreg;
124
125   arreg = a_regnum - tdep->a0_base;
126   arreg += (wb & ((tdep->num_aregs - 1) >> 2)) << WB_SHIFT;
127   arreg &= tdep->num_aregs - 1;
128
129   return arreg + tdep->ar_base;
130 }
131
132 /* Convert a live AR-register number to the corresponding A-register order
133    number in a range [0..15].  Return -1, if AR_REGNUM is out of WB window.  */
134 static int
135 areg_number (struct gdbarch *gdbarch, int ar_regnum, unsigned int wb)
136 {
137   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
138   int areg;
139
140   areg = ar_regnum - tdep->ar_base;
141   if (areg < 0 || areg >= tdep->num_aregs)
142     return -1;
143   areg = (areg - wb * 4) & (tdep->num_aregs - 1);
144   return (areg > 15) ? -1 : areg;
145 }
146
147 static inline int
148 windowing_enabled (CORE_ADDR ps)
149 {
150   return ((ps & PS_EXC) == 0 && (ps & PS_WOE) != 0);
151 }
152
153 /* Return the window size of the previous call to the function from which we
154    have just returned.
155
156    This function is used to extract the return value after a called function
157    has returned to the caller.  On Xtensa, the register that holds the return
158    value (from the perspective of the caller) depends on what call
159    instruction was used.  For now, we are assuming that the call instruction
160    precedes the current address, so we simply analyze the call instruction.
161    If we are in a dummy frame, we simply return 4 as we used a 'pseudo-call4'
162    method to call the inferior function.  */
163
164 static int
165 extract_call_winsize (struct gdbarch *gdbarch, CORE_ADDR pc)
166 {
167   int winsize = 4;
168   int insn;
169   gdb_byte buf[4];
170
171   DEBUGTRACE ("extract_call_winsize (pc = 0x%08x)\n", (int) pc);
172
173   /* Read the previous instruction (should be a call[x]{4|8|12}.  */
174   read_memory (pc-3, buf, 3);
175   insn = extract_unsigned_integer (buf, 3);
176
177   /* Decode call instruction:
178      Little Endian
179        call{0,4,8,12}   OFFSET || {00,01,10,11} || 0101
180        callx{0,4,8,12}  OFFSET || 11 || {00,01,10,11} || 0000
181      Big Endian
182        call{0,4,8,12}   0101 || {00,01,10,11} || OFFSET
183        callx{0,4,8,12}  0000 || {00,01,10,11} || 11 || OFFSET.  */
184
185   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_LITTLE)
186     {
187       if (((insn & 0xf) == 0x5) || ((insn & 0xcf) == 0xc0))
188         winsize = (insn & 0x30) >> 2;   /* 0, 4, 8, 12.  */
189     }
190   else
191     {
192       if (((insn >> 20) == 0x5) || (((insn >> 16) & 0xf3) == 0x03))
193         winsize = (insn >> 16) & 0xc;   /* 0, 4, 8, 12.  */
194     }
195   return winsize;
196 }
197
198
199 /* REGISTER INFORMATION */
200
201 /* Returns the name of a register.  */
202 static const char *
203 xtensa_register_name (struct gdbarch *gdbarch, int regnum)
204 {
205   /* Return the name stored in the register map.  */
206   if (regnum >= 0 && regnum < gdbarch_num_regs (gdbarch)
207                               + gdbarch_num_pseudo_regs (gdbarch))
208     return gdbarch_tdep (gdbarch)->regmap[regnum].name;
209
210   internal_error (__FILE__, __LINE__, _("invalid register %d"), regnum);
211   return 0;
212 }
213
214 static unsigned long
215 xtensa_read_register (int regnum)
216 {
217   ULONGEST value;
218
219   regcache_raw_read_unsigned (get_current_regcache (), regnum, &value);
220   return (unsigned long) value;
221 }
222
223 /* Return the type of a register.  Create a new type, if necessary.  */
224
225 static struct ctype_cache
226 {
227   struct ctype_cache *next;
228   int size;
229   struct type *virtual_type;
230 } *type_entries = NULL;
231
232 static struct type *
233 xtensa_register_type (struct gdbarch *gdbarch, int regnum)
234 {
235   /* Return signed integer for ARx and Ax registers.  */
236   if ((regnum >= gdbarch_tdep (gdbarch)->ar_base
237       && regnum < gdbarch_tdep (gdbarch)->ar_base
238                     + gdbarch_tdep (gdbarch)->num_aregs)
239       || (regnum >= gdbarch_tdep (gdbarch)->a0_base
240       && regnum < gdbarch_tdep (gdbarch)->a0_base + 16))
241     return builtin_type_int;
242
243   if (regnum == gdbarch_pc_regnum (gdbarch)
244       || regnum == gdbarch_tdep (gdbarch)->a0_base + 1)
245     return lookup_pointer_type (builtin_type_void);
246
247   /* Return the stored type for all other registers.  */
248   else if (regnum >= 0 && regnum < gdbarch_num_regs (gdbarch)
249                                    + gdbarch_num_pseudo_regs (gdbarch))
250     {
251       xtensa_register_t* reg = &gdbarch_tdep (gdbarch)->regmap[regnum];
252
253       /* Set ctype for this register (only the first time).  */
254
255       if (reg->ctype == 0)
256         {
257           struct ctype_cache *tp;
258           int size = reg->byte_size;
259
260           /* We always use the memory representation,
261              even if the register width is smaller.  */
262           switch (size)
263             {
264             case 1:
265               reg->ctype = builtin_type_uint8;
266               break;
267
268             case 2:
269               reg->ctype = builtin_type_uint16;
270               break;
271
272             case 4:
273               reg->ctype = builtin_type_uint32;
274               break;
275
276             case 8:
277               reg->ctype = builtin_type_uint64;
278               break;
279
280             case 16:
281               reg->ctype = builtin_type_uint128;
282               break;
283
284             default:
285               for (tp = type_entries; tp != NULL; tp = tp->next)
286                 if (tp->size == size)
287                   break;
288
289               if (tp == NULL)
290                 {
291                   char *name = xmalloc (16);
292                   tp = xmalloc (sizeof (struct ctype_cache));
293                   tp->next = type_entries;
294                   type_entries = tp;
295                   tp->size = size;
296
297                   sprintf (name, "int%d", size * 8);
298                   tp->virtual_type = init_type (TYPE_CODE_INT, size,
299                                                 TYPE_FLAG_UNSIGNED, name,
300                                                 NULL);
301                 }
302
303               reg->ctype = tp->virtual_type;
304             }
305         }
306       return reg->ctype;
307     }
308
309   internal_error (__FILE__, __LINE__, _("invalid register number %d"), regnum);
310   return 0;
311 }
312
313
314 /* Return the 'local' register number for stubs, dwarf2, etc.
315    The debugging information enumerates registers starting from 0 for A0
316    to n for An.  So, we only have to add the base number for A0.  */
317
318 static int
319 xtensa_reg_to_regnum (struct gdbarch *gdbarch, int regnum)
320 {
321   int i;
322
323   if (regnum >= 0 && regnum < 16)
324     return gdbarch_tdep (gdbarch)->a0_base + regnum;
325
326   for (i = 0;
327        i < gdbarch_num_regs (gdbarch) + gdbarch_num_pseudo_regs (gdbarch);
328        i++)
329     if (regnum == gdbarch_tdep (gdbarch)->regmap[i].target_number)
330       return i;
331
332   internal_error (__FILE__, __LINE__,
333                   _("invalid dwarf/stabs register number %d"), regnum);
334   return 0;
335 }
336
337
338 /* Write the bits of a masked register to the various registers.
339    Only the masked areas of these registers are modified; the other
340    fields are untouched.  The size of masked registers is always less
341    than or equal to 32 bits.  */
342
343 static void
344 xtensa_register_write_masked (struct regcache *regcache,
345                               xtensa_register_t *reg, const gdb_byte *buffer)
346 {
347   unsigned int value[(MAX_REGISTER_SIZE + 3) / 4];
348   const xtensa_mask_t *mask = reg->mask;
349
350   int shift = 0;                /* Shift for next mask (mod 32).  */
351   int start, size;              /* Start bit and size of current mask.  */
352
353   unsigned int *ptr = value;
354   unsigned int regval, m, mem = 0;
355
356   int bytesize = reg->byte_size;
357   int bitsize = bytesize * 8;
358   int i, r;
359
360   DEBUGTRACE ("xtensa_register_write_masked ()\n");
361
362   /* Copy the masked register to host byte-order.  */
363   if (gdbarch_byte_order (get_regcache_arch (regcache)) == BFD_ENDIAN_BIG)
364     for (i = 0; i < bytesize; i++)
365       {
366         mem >>= 8;
367         mem |= (buffer[bytesize - i - 1] << 24);
368         if ((i & 3) == 3)
369           *ptr++ = mem;
370       }
371   else
372     for (i = 0; i < bytesize; i++)
373       {
374         mem >>= 8;
375         mem |= (buffer[i] << 24);
376         if ((i & 3) == 3)
377           *ptr++ = mem;
378       }
379
380   /* We might have to shift the final value:
381      bytesize & 3 == 0 -> nothing to do, we use the full 32 bits,
382      bytesize & 3 == x -> shift (4-x) * 8.  */
383
384   *ptr = mem >> (((0 - bytesize) & 3) * 8);
385   ptr = value;
386   mem = *ptr;
387
388   /* Write the bits to the masked areas of the other registers.  */
389   for (i = 0; i < mask->count; i++)
390     {
391       start = mask->mask[i].bit_start;
392       size = mask->mask[i].bit_size;
393       regval = mem >> shift;
394
395       if ((shift += size) > bitsize)
396         error (_("size of all masks is larger than the register"));
397
398       if (shift >= 32)
399         {
400           mem = *(++ptr);
401           shift -= 32;
402           bitsize -= 32;
403
404           if (shift > 0)
405             regval |= mem << (size - shift);
406         }
407
408       /* Make sure we have a valid register.  */
409       r = mask->mask[i].reg_num;
410       if (r >= 0 && size > 0)
411         {
412           /* Don't overwrite the unmasked areas.  */
413           ULONGEST old_val;
414           regcache_cooked_read_unsigned (regcache, r, &old_val);
415           m = 0xffffffff >> (32 - size) << start;
416           regval <<= start;
417           regval = (regval & m) | (old_val & ~m);
418           regcache_cooked_write_unsigned (regcache, r, regval);
419         }
420     }
421 }
422
423
424 /* Read a tie state or mapped registers.  Read the masked areas
425    of the registers and assemble them into a single value.  */
426
427 static void
428 xtensa_register_read_masked (struct regcache *regcache,
429                              xtensa_register_t *reg, gdb_byte *buffer)
430 {
431   unsigned int value[(MAX_REGISTER_SIZE + 3) / 4];
432   const xtensa_mask_t *mask = reg->mask;
433
434   int shift = 0;
435   int start, size;
436
437   unsigned int *ptr = value;
438   unsigned int regval, mem = 0;
439
440   int bytesize = reg->byte_size;
441   int bitsize = bytesize * 8;
442   int i;
443
444   DEBUGTRACE ("xtensa_register_read_masked (reg \"%s\", ...)\n",
445               reg->name == 0 ? "" : reg->name);
446
447   /* Assemble the register from the masked areas of other registers.  */
448   for (i = 0; i < mask->count; i++)
449     {
450       int r = mask->mask[i].reg_num;
451       if (r >= 0)
452         {
453           ULONGEST val;
454           regcache_cooked_read_unsigned (regcache, r, &val);
455           regval = (unsigned int) val;
456         }
457       else
458         regval = 0;
459
460       start = mask->mask[i].bit_start;
461       size = mask->mask[i].bit_size;
462
463       regval >>= start;
464
465       if (size < 32)
466         regval &= (0xffffffff >> (32 - size));
467
468       mem |= regval << shift;
469
470       if ((shift += size) > bitsize)
471         error (_("size of all masks is larger than the register"));
472
473       if (shift >= 32)
474         {
475           *ptr++ = mem;
476           bitsize -= 32;
477           shift -= 32;
478
479           if (shift == 0)
480             mem = 0;
481           else
482             mem = regval >> (size - shift);
483         }
484     }
485
486   if (shift > 0)
487     *ptr = mem;
488
489   /* Copy value to target byte order.  */
490   ptr = value;
491   mem = *ptr;
492
493   if (gdbarch_byte_order (get_regcache_arch (regcache)) == BFD_ENDIAN_BIG)
494     for (i = 0; i < bytesize; i++)
495       {
496         if ((i & 3) == 0)
497           mem = *ptr++;
498         buffer[bytesize - i - 1] = mem & 0xff;
499         mem >>= 8;
500       }
501   else
502     for (i = 0; i < bytesize; i++)
503       {
504         if ((i & 3) == 0)
505           mem = *ptr++;
506         buffer[i] = mem & 0xff;
507         mem >>= 8;
508       }
509 }
510
511
512 /* Read pseudo registers.  */
513
514 static void
515 xtensa_pseudo_register_read (struct gdbarch *gdbarch,
516                              struct regcache *regcache,
517                              int regnum,
518                              gdb_byte *buffer)
519 {
520   DEBUGTRACE ("xtensa_pseudo_register_read (... regnum = %d (%s) ...)\n",
521               regnum, xtensa_register_name (gdbarch, regnum));
522
523   if (regnum == gdbarch_num_regs (gdbarch)
524                 + gdbarch_num_pseudo_regs (gdbarch) - 1)
525      regnum = gdbarch_tdep (gdbarch)->a0_base + 1;
526
527   /* Read aliases a0..a15, if this is a Windowed ABI.  */
528   if (gdbarch_tdep (gdbarch)->isa_use_windowed_registers
529       && (regnum >= gdbarch_tdep (gdbarch)->a0_base)
530       && (regnum <= gdbarch_tdep (gdbarch)->a0_base + 15))
531     {
532       gdb_byte *buf = (gdb_byte *) alloca (MAX_REGISTER_SIZE);
533
534       regcache_raw_read (regcache, gdbarch_tdep (gdbarch)->wb_regnum, buf);
535       regnum = arreg_number (gdbarch, regnum,
536                              extract_unsigned_integer (buf, 4));
537     }
538
539   /* We can always read non-pseudo registers.  */
540   if (regnum >= 0 && regnum < gdbarch_num_regs (gdbarch))
541     regcache_raw_read (regcache, regnum, buffer);
542
543
544   /* We have to find out how to deal with priveleged registers.
545      Let's treat them as pseudo-registers, but we cannot read/write them.  */
546      
547   else if (regnum < gdbarch_tdep (gdbarch)->a0_base)
548     {
549       buffer[0] = (gdb_byte)0;
550       buffer[1] = (gdb_byte)0;
551       buffer[2] = (gdb_byte)0;
552       buffer[3] = (gdb_byte)0;
553     }
554   /* Pseudo registers.  */
555   else if (regnum >= 0
556             && regnum < gdbarch_num_regs (gdbarch)
557                         + gdbarch_num_pseudo_regs (gdbarch))
558     {
559       xtensa_register_t *reg = &gdbarch_tdep (gdbarch)->regmap[regnum];
560       xtensa_register_type_t type = reg->type;
561       int flags = gdbarch_tdep (gdbarch)->target_flags;
562
563       /* We cannot read Unknown or Unmapped registers.  */
564       if (type == xtRegisterTypeUnmapped || type == xtRegisterTypeUnknown)
565         {
566           if ((flags & xtTargetFlagsNonVisibleRegs) == 0)
567             {
568               warning (_("cannot read register %s"),
569                        xtensa_register_name (gdbarch, regnum));
570               return;
571             }
572         }
573
574       /* Some targets cannot read TIE register files.  */
575       else if (type == xtRegisterTypeTieRegfile)
576         {
577           /* Use 'fetch' to get register?  */
578           if (flags & xtTargetFlagsUseFetchStore)
579             {
580               warning (_("cannot read register"));
581               return;
582             }
583
584           /* On some targets (esp. simulators), we can always read the reg.  */
585           else if ((flags & xtTargetFlagsNonVisibleRegs) == 0)
586             {
587               warning (_("cannot read register"));
588               return;
589             }
590         }
591
592       /* We can always read mapped registers.  */
593       else if (type == xtRegisterTypeMapped || type == xtRegisterTypeTieState)
594         {
595           xtensa_register_read_masked (regcache, reg, buffer);
596           return;
597         }
598
599       /* Assume that we can read the register.  */
600       regcache_raw_read (regcache, regnum, buffer);
601     }
602   else
603     internal_error (__FILE__, __LINE__,
604                     _("invalid register number %d"), regnum);
605 }
606
607
608 /* Write pseudo registers.  */
609
610 static void
611 xtensa_pseudo_register_write (struct gdbarch *gdbarch,
612                               struct regcache *regcache,
613                               int regnum,
614                               const gdb_byte *buffer)
615 {
616   DEBUGTRACE ("xtensa_pseudo_register_write (... regnum = %d (%s) ...)\n",
617               regnum, xtensa_register_name (gdbarch, regnum));
618
619   if (regnum == gdbarch_num_regs (gdbarch)
620                 + gdbarch_num_pseudo_regs (gdbarch) -1)
621      regnum = gdbarch_tdep (gdbarch)->a0_base + 1;
622
623   /* Renumber register, if aliase a0..a15 on Windowed ABI.  */
624   if (gdbarch_tdep (gdbarch)->isa_use_windowed_registers
625       && (regnum >= gdbarch_tdep (gdbarch)->a0_base)
626       && (regnum <= gdbarch_tdep (gdbarch)->a0_base + 15))
627     {
628       gdb_byte *buf = (gdb_byte *) alloca (MAX_REGISTER_SIZE);
629       unsigned int wb;
630
631       regcache_raw_read (regcache,
632                          gdbarch_tdep (gdbarch)->wb_regnum, buf);
633       regnum = arreg_number (gdbarch, regnum,
634                              extract_unsigned_integer (buf, 4));
635     }
636
637   /* We can always write 'core' registers.
638      Note: We might have converted Ax->ARy.  */
639   if (regnum >= 0 && regnum < gdbarch_num_regs (gdbarch))
640     regcache_raw_write (regcache, regnum, buffer);
641
642   /* We have to find out how to deal with priveleged registers.
643      Let's treat them as pseudo-registers, but we cannot read/write them.  */
644
645   else if (regnum < gdbarch_tdep (gdbarch)->a0_base)
646     {
647       return;
648     }
649   /* Pseudo registers.  */
650   else if (regnum >= 0
651            && regnum < gdbarch_num_regs (gdbarch)
652                        + gdbarch_num_pseudo_regs (gdbarch))
653     {
654       xtensa_register_t *reg = &gdbarch_tdep (gdbarch)->regmap[regnum];
655       xtensa_register_type_t type = reg->type;
656       int flags = gdbarch_tdep (gdbarch)->target_flags;
657
658       /* On most targets, we cannot write registers
659          of type "Unknown" or "Unmapped".  */
660       if (type == xtRegisterTypeUnmapped || type == xtRegisterTypeUnknown)
661         {
662           if ((flags & xtTargetFlagsNonVisibleRegs) == 0)
663             {
664               warning (_("cannot write register %s"),
665                        xtensa_register_name (gdbarch, regnum));
666               return;
667             }
668         }
669
670       /* Some targets cannot read TIE register files.  */
671       else if (type == xtRegisterTypeTieRegfile)
672         {
673           /* Use 'store' to get register?  */
674           if (flags & xtTargetFlagsUseFetchStore)
675             {
676               warning (_("cannot write register"));
677               return;
678             }
679
680           /* On some targets (esp. simulators), we can always write
681              the register.  */
682           else if ((flags & xtTargetFlagsNonVisibleRegs) == 0)
683             {
684               warning (_("cannot write register"));
685               return;
686             }
687         }
688
689       /* We can always write mapped registers.  */
690       else if (type == xtRegisterTypeMapped || type == xtRegisterTypeTieState)
691         {
692           xtensa_register_write_masked (regcache, reg, buffer);
693           return;
694         }
695
696       /* Assume that we can write the register.  */
697       regcache_raw_write (regcache, regnum, buffer);
698     }
699   else
700     internal_error (__FILE__, __LINE__,
701                     _("invalid register number %d"), regnum);
702 }
703
704 static struct reggroup *xtensa_ar_reggroup;
705 static struct reggroup *xtensa_user_reggroup;
706 static struct reggroup *xtensa_vectra_reggroup;
707 static struct reggroup *xtensa_cp[XTENSA_MAX_COPROCESSOR];
708
709 static void
710 xtensa_init_reggroups (void)
711 {
712   xtensa_ar_reggroup = reggroup_new ("ar", USER_REGGROUP);
713   xtensa_user_reggroup = reggroup_new ("user", USER_REGGROUP);
714   xtensa_vectra_reggroup = reggroup_new ("vectra", USER_REGGROUP);
715
716   xtensa_cp[0] = reggroup_new ("cp0", USER_REGGROUP);
717   xtensa_cp[1] = reggroup_new ("cp1", USER_REGGROUP);
718   xtensa_cp[2] = reggroup_new ("cp2", USER_REGGROUP);
719   xtensa_cp[3] = reggroup_new ("cp3", USER_REGGROUP);
720   xtensa_cp[4] = reggroup_new ("cp4", USER_REGGROUP);
721   xtensa_cp[5] = reggroup_new ("cp5", USER_REGGROUP);
722   xtensa_cp[6] = reggroup_new ("cp6", USER_REGGROUP);
723   xtensa_cp[7] = reggroup_new ("cp7", USER_REGGROUP);
724 }
725
726 static void
727 xtensa_add_reggroups (struct gdbarch *gdbarch)
728 {
729   int i;
730
731   /* Predefined groups.  */
732   reggroup_add (gdbarch, all_reggroup);
733   reggroup_add (gdbarch, save_reggroup);
734   reggroup_add (gdbarch, restore_reggroup);
735   reggroup_add (gdbarch, system_reggroup);
736   reggroup_add (gdbarch, vector_reggroup);
737   reggroup_add (gdbarch, general_reggroup);
738   reggroup_add (gdbarch, float_reggroup);
739
740   /* Xtensa-specific groups.  */
741   reggroup_add (gdbarch, xtensa_ar_reggroup);
742   reggroup_add (gdbarch, xtensa_user_reggroup);
743   reggroup_add (gdbarch, xtensa_vectra_reggroup);
744
745   for (i = 0; i < XTENSA_MAX_COPROCESSOR; i++)
746     reggroup_add (gdbarch, xtensa_cp[i]);
747 }
748
749 static int 
750 xtensa_coprocessor_register_group (struct reggroup *group)
751 {
752   int i;
753
754   for (i = 0; i < XTENSA_MAX_COPROCESSOR; i++)
755     if (group == xtensa_cp[i])
756       return i;
757
758   return -1;
759 }
760
761 #define SAVE_REST_FLAGS (XTENSA_REGISTER_FLAGS_READABLE \
762                         | XTENSA_REGISTER_FLAGS_WRITABLE \
763                         | XTENSA_REGISTER_FLAGS_VOLATILE)
764
765 #define SAVE_REST_VALID (XTENSA_REGISTER_FLAGS_READABLE \
766                         | XTENSA_REGISTER_FLAGS_WRITABLE)
767
768 static int
769 xtensa_register_reggroup_p (struct gdbarch *gdbarch,
770                             int regnum,
771                             struct reggroup *group)
772 {
773   xtensa_register_t* reg = &gdbarch_tdep (gdbarch)->regmap[regnum];
774   xtensa_register_type_t type = reg->type;
775   xtensa_register_group_t rg = reg->group;
776   int cp_number;
777
778   /* First, skip registers that are not visible to this target
779      (unknown and unmapped registers when not using ISS).  */
780
781   if (type == xtRegisterTypeUnmapped || type == xtRegisterTypeUnknown)
782     return 0;
783   if (group == all_reggroup)
784     return 1;
785   if (group == xtensa_ar_reggroup)
786     return rg & xtRegisterGroupAddrReg;
787   if (group == xtensa_user_reggroup)
788     return rg & xtRegisterGroupUser;
789   if (group == float_reggroup)
790     return rg & xtRegisterGroupFloat;
791   if (group == general_reggroup)
792     return rg & xtRegisterGroupGeneral;
793   if (group == float_reggroup)
794     return rg & xtRegisterGroupFloat;
795   if (group == system_reggroup)
796     return rg & xtRegisterGroupState;
797   if (group == vector_reggroup || group == xtensa_vectra_reggroup)
798     return rg & xtRegisterGroupVectra;
799   if (group == save_reggroup || group == restore_reggroup)
800     return (regnum < gdbarch_num_regs (gdbarch)
801             && (reg->flags & SAVE_REST_FLAGS) == SAVE_REST_VALID);
802   if ((cp_number = xtensa_coprocessor_register_group (group)) >= 0)
803     return rg & (xtRegisterGroupCP0 << cp_number);
804   else
805     return 1;
806 }
807
808
809 /* Supply register REGNUM from the buffer specified by GREGS and LEN
810    in the general-purpose register set REGSET to register cache
811    REGCACHE.  If REGNUM is -1 do this for all registers in REGSET.  */
812
813 static void
814 xtensa_supply_gregset (const struct regset *regset,
815                        struct regcache *rc,
816                        int regnum,
817                        const void *gregs,
818                        size_t len)
819 {
820   const xtensa_elf_gregset_t *regs = gregs;
821   struct gdbarch *gdbarch = get_regcache_arch (rc);
822   int i;
823
824   DEBUGTRACE ("xtensa_supply_gregset (..., regnum==%d, ...) \n", regnum);
825
826   if (regnum == gdbarch_pc_regnum (gdbarch) || regnum == -1)
827     regcache_raw_supply (rc, gdbarch_pc_regnum (gdbarch), (char *) &regs->pc);
828   if (regnum == gdbarch_ps_regnum (gdbarch) || regnum == -1)
829     regcache_raw_supply (rc, gdbarch_ps_regnum (gdbarch), (char *) &regs->ps);
830   if (regnum == gdbarch_tdep (gdbarch)->wb_regnum || regnum == -1)
831     regcache_raw_supply (rc, gdbarch_tdep (gdbarch)->wb_regnum,
832                          (char *) &regs->windowbase);
833   if (regnum == gdbarch_tdep (gdbarch)->ws_regnum || regnum == -1)
834     regcache_raw_supply (rc, gdbarch_tdep (gdbarch)->ws_regnum,
835                          (char *) &regs->windowstart);
836   if (regnum == gdbarch_tdep (gdbarch)->lbeg_regnum || regnum == -1)
837     regcache_raw_supply (rc, gdbarch_tdep (gdbarch)->lbeg_regnum,
838                          (char *) &regs->lbeg);
839   if (regnum == gdbarch_tdep (gdbarch)->lend_regnum || regnum == -1)
840     regcache_raw_supply (rc, gdbarch_tdep (gdbarch)->lend_regnum,
841                          (char *) &regs->lend);
842   if (regnum == gdbarch_tdep (gdbarch)->lcount_regnum || regnum == -1)
843     regcache_raw_supply (rc, gdbarch_tdep (gdbarch)->lcount_regnum,
844                          (char *) &regs->lcount);
845   if (regnum == gdbarch_tdep (gdbarch)->sar_regnum || regnum == -1)
846     regcache_raw_supply (rc, gdbarch_tdep (gdbarch)->sar_regnum,
847                          (char *) &regs->sar);
848   if (regnum >=gdbarch_tdep (gdbarch)->ar_base
849       && regnum < gdbarch_tdep (gdbarch)->ar_base
850                     + gdbarch_tdep (gdbarch)->num_aregs)
851     regcache_raw_supply (rc, regnum,
852                          (char *) &regs->ar[regnum - gdbarch_tdep
853                            (gdbarch)->ar_base]);
854   else if (regnum == -1)
855     {
856       for (i = 0; i < gdbarch_tdep (gdbarch)->num_aregs; ++i)
857         regcache_raw_supply (rc, gdbarch_tdep (gdbarch)->ar_base + i,
858                              (char *) &regs->ar[i]);
859     }
860 }
861
862
863 /* Xtensa register set.  */
864
865 static struct regset
866 xtensa_gregset =
867 {
868   NULL,
869   xtensa_supply_gregset
870 };
871
872
873 /* Return the appropriate register set for the core
874    section identified by SECT_NAME and SECT_SIZE.  */
875
876 static const struct regset *
877 xtensa_regset_from_core_section (struct gdbarch *core_arch,
878                                  const char *sect_name,
879                                  size_t sect_size)
880 {
881   DEBUGTRACE ("xtensa_regset_from_core_section "
882               "(..., sect_name==\"%s\", sect_size==%x) \n",
883               sect_name, (unsigned int) sect_size);
884
885   if (strcmp (sect_name, ".reg") == 0
886       && sect_size >= sizeof(xtensa_elf_gregset_t))
887     return &xtensa_gregset;
888
889   return NULL;
890 }
891
892
893 /* Handling frames.  */
894
895 /* Number of registers to save in case of Windowed ABI.  */
896 #define XTENSA_NUM_SAVED_AREGS          12
897
898 /* Frame cache part for Windowed ABI.  */
899 typedef struct xtensa_windowed_frame_cache
900 {
901   int wb;               /* WINDOWBASE of the previous frame.  */
902   int callsize;         /* Call size of this frame.  */
903   int ws;               /* WINDOWSTART of the previous frame.  It keeps track of
904                            life windows only.  If there is no bit set for the
905                            window, that means it had been already spilled
906                            because of window overflow.  */
907
908   /* Spilled A-registers from the previous frame.
909      AREGS[i] == -1, if corresponding AR is alive.  */
910   CORE_ADDR aregs[XTENSA_NUM_SAVED_AREGS];
911 } xtensa_windowed_frame_cache_t;
912
913 /* Call0 ABI Definitions.  */
914
915 #define C0_MAXOPDS  3   /* Maximum number of operands for prologue analysis.  */
916 #define C0_NREGS   16   /* Number of A-registers to track.  */
917 #define C0_CLESV   12   /* Callee-saved registers are here and up.  */
918 #define C0_SP       1   /* Register used as SP.  */
919 #define C0_FP      15   /* Register used as FP.  */
920 #define C0_RA       0   /* Register used as return address.  */
921 #define C0_ARGS     2   /* Register used as first arg/retval.  */
922 #define C0_NARGS    6   /* Number of A-regs for args/retvals.  */
923
924 /* Each element of xtensa_call0_frame_cache.c0_rt[] describes for each
925    A-register where the current content of the reg came from (in terms
926    of an original reg and a constant).  Negative values of c0_rt[n].fp_reg
927    mean that the orignal content of the register was saved to the stack.
928    c0_rt[n].fr.ofs is NOT the offset from the frame base because we don't 
929    know where SP will end up until the entire prologue has been analyzed.  */
930
931 #define C0_CONST   -1   /* fr_reg value if register contains a constant.  */
932 #define C0_INEXP   -2   /* fr_reg value if inexpressible as reg + offset.  */
933 #define C0_NOSTK   -1   /* to_stk value if register has not been stored.  */
934
935 extern xtensa_isa xtensa_default_isa;
936
937 typedef struct xtensa_c0reg
938 {
939     int     fr_reg;     /* original register from which register content
940                            is derived, or C0_CONST, or C0_INEXP.  */
941     int     fr_ofs;     /* constant offset from reg, or immediate value.  */
942     int     to_stk;     /* offset from original SP to register (4-byte aligned),
943                            or C0_NOSTK if register has not been saved.  */
944 } xtensa_c0reg_t;
945
946
947 /* Frame cache part for Call0 ABI.  */
948 typedef struct xtensa_call0_frame_cache
949 {
950   int c0_frmsz;                         /* Stack frame size.  */
951   int c0_hasfp;                         /* Current frame uses frame pointer.  */
952   int fp_regnum;                        /* A-register used as FP.  */
953   int c0_fp;                            /* Actual value of frame pointer.  */
954   xtensa_c0reg_t c0_rt[C0_NREGS];       /* Register tracking information.  */
955 } xtensa_call0_frame_cache_t;
956
957 typedef struct xtensa_frame_cache
958 {
959   CORE_ADDR base;       /* Stack pointer of this frame.  */
960   CORE_ADDR pc;         /* PC at the entry point to the function.  */
961   CORE_ADDR ra;         /* The raw return address (without CALLINC).  */
962   CORE_ADDR ps;         /* The PS register of the previous frame.  */
963   CORE_ADDR prev_sp;    /* Stack Pointer of the previous frame.  */
964   int call0;            /* It's a call0 framework (else windowed).  */
965   union
966     {
967       xtensa_windowed_frame_cache_t     wd;     /* call0 == false.  */
968       xtensa_call0_frame_cache_t        c0;     /* call0 == true.  */
969     };
970 } xtensa_frame_cache_t;
971
972
973 static struct xtensa_frame_cache *
974 xtensa_alloc_frame_cache (int windowed)
975 {
976   xtensa_frame_cache_t *cache;
977   int i;
978
979   DEBUGTRACE ("xtensa_alloc_frame_cache ()\n");
980
981   cache = FRAME_OBSTACK_ZALLOC (xtensa_frame_cache_t);
982
983   cache->base = 0;
984   cache->pc = 0;
985   cache->ra = 0;
986   cache->ps = 0;
987   cache->prev_sp = 0;
988   cache->call0 = !windowed;
989   if (cache->call0)
990     {
991       cache->c0.c0_frmsz  = -1;
992       cache->c0.c0_hasfp  =  0;
993       cache->c0.fp_regnum = -1;
994       cache->c0.c0_fp     = -1;
995
996       for (i = 0; i < C0_NREGS; i++)
997         {
998           cache->c0.c0_rt[i].fr_reg = i;
999           cache->c0.c0_rt[i].fr_ofs = 0;
1000           cache->c0.c0_rt[i].to_stk = C0_NOSTK;
1001         }
1002     }
1003   else
1004     {
1005       cache->wd.wb = 0;
1006       cache->wd.ws = 0;
1007       cache->wd.callsize = -1;
1008
1009       for (i = 0; i < XTENSA_NUM_SAVED_AREGS; i++)
1010         cache->wd.aregs[i] = -1;
1011     }
1012   return cache;
1013 }
1014
1015
1016 static CORE_ADDR
1017 xtensa_frame_align (struct gdbarch *gdbarch, CORE_ADDR address)
1018 {
1019   return address & ~15;
1020 }
1021
1022
1023 static CORE_ADDR
1024 xtensa_unwind_pc (struct gdbarch *gdbarch, struct frame_info *next_frame)
1025 {
1026   gdb_byte buf[8];
1027
1028   DEBUGTRACE ("xtensa_unwind_pc (next_frame = %p)\n", next_frame);
1029
1030   frame_unwind_register (next_frame, gdbarch_pc_regnum (gdbarch), buf);
1031
1032   DEBUGINFO ("[xtensa_unwind_pc] pc = 0x%08x\n", (unsigned int)
1033              extract_typed_address (buf, builtin_type_void_func_ptr));
1034
1035   return extract_typed_address (buf, builtin_type_void_func_ptr);
1036 }
1037
1038
1039 static struct frame_id
1040 xtensa_unwind_dummy_id (struct gdbarch *gdbarch, struct frame_info *next_frame)
1041 {
1042   CORE_ADDR pc, fp;
1043
1044   /* next_frame->prev is a dummy frame.  Return a frame ID of that frame.  */
1045
1046   DEBUGTRACE ("xtensa_unwind_dummy_id ()\n");
1047
1048   pc = frame_pc_unwind (next_frame);
1049   fp = frame_unwind_register_unsigned
1050          (next_frame, gdbarch_tdep (gdbarch)->a0_base + 1);
1051
1052   /* Make dummy frame ID unique by adding a constant.  */
1053   return frame_id_build (fp + SP_ALIGNMENT, pc);
1054 }
1055
1056 /* Returns the best guess about which register is a frame pointer
1057    for the function containing CURRENT_PC.  */
1058
1059 #define XTENSA_ISA_BSZ 32           /* Instruction buffer size.  */
1060
1061 static unsigned int
1062 xtensa_scan_prologue (struct gdbarch *gdbarch, CORE_ADDR current_pc)
1063 {
1064 #define RETURN_FP goto done
1065
1066   unsigned int fp_regnum = gdbarch_tdep (gdbarch)->a0_base + 1;
1067   CORE_ADDR start_addr;
1068   xtensa_isa isa;
1069   xtensa_insnbuf ins, slot;
1070   char ibuf[XTENSA_ISA_BSZ];
1071   CORE_ADDR ia, bt, ba;
1072   xtensa_format ifmt;
1073   int ilen, islots, is;
1074   xtensa_opcode opc;
1075   const char *opcname;
1076
1077   find_pc_partial_function (current_pc, NULL, &start_addr, NULL);
1078   if (start_addr == 0)
1079     return fp_regnum;
1080
1081   if (!xtensa_default_isa)
1082     xtensa_default_isa = xtensa_isa_init (0, 0);
1083   isa = xtensa_default_isa;
1084   gdb_assert (XTENSA_ISA_BSZ >= xtensa_isa_maxlength (isa));
1085   ins = xtensa_insnbuf_alloc (isa);
1086   slot = xtensa_insnbuf_alloc (isa);
1087   ba = 0;
1088
1089   for (ia = start_addr, bt = ia; ia < current_pc ; ia += ilen)
1090     {
1091       if (ia + xtensa_isa_maxlength (isa) > bt)
1092         {
1093           ba = ia;
1094           bt = (ba + XTENSA_ISA_BSZ) < current_pc
1095             ? ba + XTENSA_ISA_BSZ : current_pc;
1096           read_memory (ba, ibuf, bt - ba);
1097         }
1098
1099       xtensa_insnbuf_from_chars (isa, ins, &ibuf[ia-ba], 0);
1100       ifmt = xtensa_format_decode (isa, ins);
1101       if (ifmt == XTENSA_UNDEFINED)
1102         RETURN_FP;
1103       ilen = xtensa_format_length (isa, ifmt);
1104       if (ilen == XTENSA_UNDEFINED)
1105         RETURN_FP;
1106       islots = xtensa_format_num_slots (isa, ifmt);
1107       if (islots == XTENSA_UNDEFINED)
1108         RETURN_FP;
1109       
1110       for (is = 0; is < islots; ++is)
1111         {
1112           if (xtensa_format_get_slot (isa, ifmt, is, ins, slot))
1113             RETURN_FP;
1114           
1115           opc = xtensa_opcode_decode (isa, ifmt, is, slot);
1116           if (opc == XTENSA_UNDEFINED) 
1117             RETURN_FP;
1118           
1119           opcname = xtensa_opcode_name (isa, opc);
1120
1121           if (strcasecmp (opcname, "mov.n") == 0
1122               || strcasecmp (opcname, "or") == 0)
1123             {
1124               unsigned int register_operand;
1125
1126               /* Possible candidate for setting frame pointer
1127                  from A1. This is what we are looking for.  */
1128
1129               if (xtensa_operand_get_field (isa, opc, 1, ifmt, 
1130                                             is, slot, &register_operand) != 0)
1131                 RETURN_FP;
1132               if (xtensa_operand_decode (isa, opc, 1, &register_operand) != 0)
1133                 RETURN_FP;
1134               if (register_operand == 1)  /* Mov{.n} FP A1.  */
1135                 {
1136                   if (xtensa_operand_get_field (isa, opc, 0, ifmt, is, slot, 
1137                                                 &register_operand) != 0)
1138                     RETURN_FP;
1139                   if (xtensa_operand_decode (isa, opc, 0,
1140                                              &register_operand) != 0)
1141                     RETURN_FP;
1142
1143                   fp_regnum = gdbarch_tdep (gdbarch)->a0_base + register_operand;
1144                   RETURN_FP;
1145                 }
1146             }
1147
1148           if (
1149               /* We have problems decoding the memory.  */
1150               opcname == NULL 
1151               || strcasecmp (opcname, "ill") == 0
1152               || strcasecmp (opcname, "ill.n") == 0
1153               /* Hit planted breakpoint.  */
1154               || strcasecmp (opcname, "break") == 0
1155               || strcasecmp (opcname, "break.n") == 0
1156               /* Flow control instructions finish prologue.  */
1157               || xtensa_opcode_is_branch (isa, opc) > 0
1158               || xtensa_opcode_is_jump   (isa, opc) > 0
1159               || xtensa_opcode_is_loop   (isa, opc) > 0
1160               || xtensa_opcode_is_call   (isa, opc) > 0
1161               || strcasecmp (opcname, "simcall") == 0
1162               || strcasecmp (opcname, "syscall") == 0)
1163             /* Can not continue analysis.  */
1164             RETURN_FP;
1165         }
1166     }
1167 done:
1168   xtensa_insnbuf_free(isa, slot);
1169   xtensa_insnbuf_free(isa, ins);
1170   return fp_regnum;
1171 }
1172
1173 /* The key values to identify the frame using "cache" are 
1174
1175         cache->base    = SP (or best guess about FP) of this frame;
1176         cache->pc      = entry-PC (entry point of the frame function);
1177         cache->prev_sp = SP of the previous frame.
1178 */
1179
1180 static void
1181 call0_frame_cache (struct frame_info *next_frame,
1182                    xtensa_frame_cache_t *cache,
1183                    CORE_ADDR pc);
1184
1185 static struct xtensa_frame_cache *
1186 xtensa_frame_cache (struct frame_info *next_frame, void **this_cache)
1187 {
1188   xtensa_frame_cache_t *cache;
1189   CORE_ADDR ra, wb, ws, pc, sp, ps;
1190   struct gdbarch *gdbarch = get_frame_arch (next_frame);
1191   unsigned int ps_regnum = gdbarch_ps_regnum (gdbarch);
1192   unsigned int fp_regnum;
1193   char op1;
1194   int  windowed;
1195
1196   DEBUGTRACE ("xtensa_frame_cache (next_frame %p, *this_cache %p)\n",
1197               next_frame, this_cache ? *this_cache : (void*)0xdeadbeef);
1198
1199   if (*this_cache)
1200     return *this_cache;
1201
1202   windowed = windowing_enabled (xtensa_read_register (ps_regnum));
1203
1204   /* Get pristine xtensa-frame.  */
1205   cache = xtensa_alloc_frame_cache (windowed);
1206   *this_cache = cache;
1207
1208   pc = frame_unwind_register_unsigned (next_frame,
1209                                        gdbarch_pc_regnum (gdbarch));
1210
1211   if (windowed)
1212     {
1213       /* Get WINDOWBASE, WINDOWSTART, and PS registers.  */
1214       wb = frame_unwind_register_unsigned
1215              (next_frame, gdbarch_tdep (gdbarch)->wb_regnum);
1216       ws = frame_unwind_register_unsigned
1217              (next_frame, gdbarch_tdep (gdbarch)->ws_regnum);
1218       ps = frame_unwind_register_unsigned (next_frame, ps_regnum);
1219
1220       op1 = read_memory_integer (pc, 1);
1221       if (XTENSA_IS_ENTRY (gdbarch, op1))
1222         {
1223           int callinc = CALLINC (ps);
1224           ra = frame_unwind_register_unsigned
1225             (next_frame, gdbarch_tdep (gdbarch)->a0_base + callinc * 4);
1226           
1227           DEBUGINFO("[xtensa_frame_cache] 'entry' at 0x%08x\n (callinc = %d)",
1228                     (int)pc, callinc);
1229           
1230           /* ENTRY hasn't been executed yet, therefore callsize is still 0.  */
1231           cache->wd.callsize = 0;
1232           cache->wd.wb = wb;
1233           cache->wd.ws = ws;
1234           cache->prev_sp = frame_unwind_register_unsigned
1235                              (next_frame, gdbarch_tdep (gdbarch)->a0_base + 1);
1236
1237           /* This only can be the outermost frame since we are
1238              just about to execute ENTRY.  SP hasn't been set yet.
1239              We can assume any frame size, because it does not
1240              matter, and, let's fake frame base in cache.  */
1241           cache->base = cache->prev_sp + 16;
1242
1243           cache->pc = pc;
1244           cache->ra = (cache->pc & 0xc0000000) | (ra & 0x3fffffff);
1245           cache->ps = (ps & ~PS_CALLINC_MASK)
1246             | ((WINSIZE(ra)/4) << PS_CALLINC_SHIFT);
1247
1248           return cache;
1249         }
1250       else
1251         {
1252           fp_regnum = xtensa_scan_prologue (gdbarch, pc);
1253           ra = frame_unwind_register_unsigned
1254                  (next_frame, gdbarch_tdep (gdbarch)->a0_base);
1255           cache->wd.callsize = WINSIZE (ra);
1256           cache->wd.wb = (wb - cache->wd.callsize / 4)
1257                           & (gdbarch_tdep (gdbarch)->num_aregs / 4 - 1);
1258           cache->wd.ws = ws & ~(1 << wb);
1259
1260           cache->pc = frame_func_unwind (next_frame, NORMAL_FRAME);
1261           cache->ra = (cache->pc & 0xc0000000) | (ra & 0x3fffffff);
1262           cache->ps = (ps & ~PS_CALLINC_MASK)
1263             | ((WINSIZE(ra)/4) << PS_CALLINC_SHIFT);
1264         }
1265
1266       if (cache->wd.ws == 0)
1267         {
1268           int i;
1269
1270           /* Set A0...A3.  */
1271           sp = frame_unwind_register_unsigned
1272                  (next_frame, gdbarch_tdep (gdbarch)->a0_base + 1) - 16;
1273           
1274           for (i = 0; i < 4; i++, sp += 4)
1275             {
1276               cache->wd.aregs[i] = sp;
1277             }
1278
1279           if (cache->wd.callsize > 4)
1280             {
1281               /* Set A4...A7/A11.  */
1282               /* Get the SP of the frame previous to the previous one.
1283                  To achieve this, we have to dereference SP twice.  */
1284               sp = (CORE_ADDR) read_memory_integer (sp - 12, 4);
1285               sp = (CORE_ADDR) read_memory_integer (sp - 12, 4);
1286               sp -= cache->wd.callsize * 4;
1287
1288               for ( i = 4; i < cache->wd.callsize; i++, sp += 4)
1289                 {
1290                   cache->wd.aregs[i] = sp;
1291                 }
1292             }
1293         }
1294
1295       if ((cache->prev_sp == 0) && ( ra != 0 ))
1296         /* If RA is equal to 0 this frame is an outermost frame.  Leave
1297            cache->prev_sp unchanged marking the boundary of the frame stack.  */
1298         {
1299           if ((cache->wd.ws & (1 << cache->wd.wb)) == 0)
1300             {
1301               /* Register window overflow already happened.
1302                  We can read caller's SP from the proper spill loction.  */
1303               sp = frame_unwind_register_unsigned (next_frame,
1304                      gdbarch_tdep (gdbarch)->a0_base + 1);
1305               cache->prev_sp = read_memory_integer (sp - 12, 4); 
1306             }
1307           else
1308             {
1309               /* Read caller's frame SP directly from the previous window.  */
1310               int regnum = arreg_number
1311                              (gdbarch, gdbarch_tdep (gdbarch)->a0_base + 1,
1312                               cache->wd.wb);
1313
1314               cache->prev_sp = xtensa_read_register (regnum);
1315             }
1316         }
1317     }
1318   else  /* Call0 framework.  */
1319     {
1320       call0_frame_cache (next_frame, cache, pc);
1321       fp_regnum = cache->c0.fp_regnum;
1322     }
1323
1324   cache->base = frame_unwind_register_unsigned (next_frame, fp_regnum);
1325
1326   return cache;
1327 }
1328
1329 static void
1330 xtensa_frame_this_id (struct frame_info *next_frame,
1331                       void **this_cache,
1332                       struct frame_id *this_id)
1333 {
1334   struct xtensa_frame_cache *cache =
1335     xtensa_frame_cache (next_frame, this_cache);
1336   struct frame_id id;
1337
1338   DEBUGTRACE ("xtensa_frame_this_id (next 0x%lx, *this 0x%lx)\n",
1339               (unsigned long) next_frame, (unsigned long) *this_cache);
1340
1341   if (cache->prev_sp == 0)
1342     return;
1343
1344   id = frame_id_build (cache->prev_sp, cache->pc);
1345   if (frame_id_eq (id, get_frame_id(next_frame)))
1346     {
1347       warning(_("\
1348 Frame stack is corrupted. That could happen because of \
1349 setting register(s) from GDB or stopping execution \
1350 inside exception handler. Frame backtracing has stopped. \
1351 It can make some GDB commands work inappropriately.\n"));
1352       cache->prev_sp = 0;
1353       return;
1354     }
1355   (*this_id) = id;
1356 }
1357
1358 static int
1359 call0_frame_get_reg_at_entry (struct frame_info *next_frame,
1360                               struct xtensa_frame_cache *cache,
1361                               int regnum, 
1362                               CORE_ADDR *addrp,
1363                               enum lval_type *lval,
1364                               gdb_byte *valuep)
1365 {
1366   CORE_ADDR fp, spe;
1367   int stkofs;
1368   struct gdbarch *gdbarch = get_frame_arch (next_frame);
1369   int reg = (regnum >= gdbarch_tdep (gdbarch)->ar_base
1370             && regnum <= (gdbarch_tdep (gdbarch)->ar_base + C0_NREGS))
1371               ? regnum - gdbarch_tdep (gdbarch)->ar_base : regnum;
1372
1373   /* Determine stack pointer on entry to this function, based on FP.  */
1374   spe = cache->c0.c0_fp - cache->c0.c0_rt[cache->c0.fp_regnum].fr_ofs;
1375
1376   /* If register was saved to the stack frame in the prologue, retrieve it.  */
1377   stkofs = cache->c0.c0_rt[reg].to_stk;
1378   if (stkofs != C0_NOSTK)
1379     {
1380       *lval = lval_memory;
1381       *addrp = spe + stkofs;
1382
1383       if (valuep)
1384         read_memory (*addrp, valuep, register_size (gdbarch, regnum));
1385
1386       return 1;
1387     }
1388
1389   /* If not callee-saved or if known to have been overwritten, give up.  */
1390   if (reg < C0_CLESV 
1391       || cache->c0.c0_rt[reg].fr_reg != reg
1392       || cache->c0.c0_rt[reg].fr_ofs != 0)
1393     return 0;
1394
1395   if (get_frame_type (next_frame) != NORMAL_FRAME)
1396     /* TODO: Do we need a special case for DUMMY_FRAME here?  */
1397     return 0;
1398
1399   return call0_frame_get_reg_at_entry (get_next_frame(next_frame),
1400                                        cache, regnum, addrp, lval, valuep);
1401 }
1402
1403 static void
1404 xtensa_frame_prev_register (struct frame_info *next_frame,
1405                             void **this_cache,
1406                             int regnum,
1407                             int *optimizedp,
1408                             enum lval_type *lvalp,
1409                             CORE_ADDR *addrp,
1410                             int *realnump,
1411                             gdb_byte *valuep)
1412 {
1413   struct gdbarch *gdbarch = get_frame_arch (next_frame);
1414   struct xtensa_frame_cache *cache =
1415     xtensa_frame_cache (next_frame, this_cache);
1416   CORE_ADDR saved_reg = 0;
1417   int done = 1;
1418
1419   DEBUGTRACE ("xtensa_frame_prev_register (next 0x%lx, "
1420               "*this 0x%lx, regnum %d (%s), ...)\n",
1421               (unsigned long) next_frame,
1422               *this_cache ? (unsigned long) *this_cache : 0, regnum,
1423               xtensa_register_name (gdbarch, regnum));
1424
1425   if (regnum ==gdbarch_pc_regnum (gdbarch))
1426     saved_reg = cache->ra;
1427   else if (regnum == gdbarch_tdep (gdbarch)->a0_base + 1)
1428     saved_reg = cache->prev_sp;
1429   else if (!cache->call0)
1430     {
1431       if (regnum == gdbarch_tdep (gdbarch)->ws_regnum)
1432         saved_reg = cache->wd.ws;
1433       else if (regnum == gdbarch_tdep (gdbarch)->wb_regnum)
1434         saved_reg = cache->wd.wb;
1435       else if (regnum == gdbarch_ps_regnum (gdbarch))
1436         saved_reg = cache->ps;
1437       else
1438         done = 0;
1439     }
1440   else
1441     done = 0;
1442
1443   if (done)
1444     {
1445       *optimizedp = 0;
1446       *lvalp = not_lval;
1447       *addrp = 0;
1448       *realnump = -1;
1449       if (valuep)
1450         store_unsigned_integer (valuep, 4, saved_reg);
1451
1452       return;
1453     }
1454
1455   if (!cache->call0) /* Windowed ABI.  */
1456     {
1457       /* Convert A-register numbers to AR-register numbers,
1458          if we deal with A-register.  */
1459       if (regnum >= gdbarch_tdep (gdbarch)->a0_base
1460           && regnum <= gdbarch_tdep (gdbarch)->a0_base + 15)
1461         regnum = arreg_number (gdbarch, regnum, cache->wd.wb);
1462
1463       /* Check, if we deal with AR-register saved on stack.  */
1464       if (regnum >= gdbarch_tdep (gdbarch)->ar_base
1465           && regnum <= (gdbarch_tdep (gdbarch)->ar_base
1466                          + gdbarch_tdep (gdbarch)->num_aregs))
1467         {
1468           int areg = areg_number (gdbarch, regnum, cache->wd.wb);
1469
1470           if (areg >= 0
1471               && areg < XTENSA_NUM_SAVED_AREGS
1472               && cache->wd.aregs[areg] != -1)
1473             {
1474               *optimizedp = 0;
1475               *lvalp = lval_memory;
1476               *addrp = cache->wd.aregs[areg];
1477               *realnump = -1;
1478
1479               if (valuep)
1480                 read_memory (*addrp, valuep,
1481                              register_size (gdbarch, regnum));
1482
1483               DEBUGINFO ("[xtensa_frame_prev_register] register on stack\n");
1484               return;
1485             }
1486         }
1487     }
1488   else /* Call0 ABI.  */
1489     {
1490       int reg = (regnum >= gdbarch_tdep (gdbarch)->ar_base
1491                 && regnum <= (gdbarch_tdep (gdbarch)->ar_base
1492                                + C0_NREGS))
1493                   ? regnum - gdbarch_tdep (gdbarch)->ar_base : regnum;
1494
1495       if (reg < C0_NREGS)
1496         {
1497           CORE_ADDR spe;
1498           int stkofs;
1499
1500           /* If register was saved in the prologue, retrieve it.  */
1501           stkofs = cache->c0.c0_rt[reg].to_stk;
1502           if (stkofs != C0_NOSTK)
1503             {
1504               /* Determine SP on entry based on FP.  */
1505               spe = cache->c0.c0_fp
1506                 - cache->c0.c0_rt[cache->c0.fp_regnum].fr_ofs;
1507               *optimizedp = 0;
1508               *lvalp = lval_memory;
1509               *addrp = spe + stkofs;
1510               *realnump = -1;
1511           
1512               if (valuep)
1513                 read_memory (*addrp, valuep,
1514                              register_size (gdbarch, regnum));
1515           
1516               DEBUGINFO ("[xtensa_frame_prev_register] register on stack\n");
1517               return;
1518             }
1519         }
1520     }
1521
1522   /* All other registers have been either saved to
1523      the stack or are still alive in the processor.  */
1524
1525   *optimizedp = 0;
1526   *lvalp = lval_register;
1527   *addrp = 0;
1528   *realnump = regnum;
1529   if (valuep)
1530     frame_unwind_register (next_frame, (*realnump), valuep);
1531 }
1532
1533
1534 static const struct frame_unwind
1535 xtensa_frame_unwind =
1536 {
1537   NORMAL_FRAME,
1538   xtensa_frame_this_id,
1539   xtensa_frame_prev_register
1540 };
1541
1542 static const struct frame_unwind *
1543 xtensa_frame_sniffer (struct frame_info *next_frame)
1544 {
1545   return &xtensa_frame_unwind;
1546 }
1547
1548 static CORE_ADDR
1549 xtensa_frame_base_address (struct frame_info *next_frame, void **this_cache)
1550 {
1551   struct xtensa_frame_cache *cache =
1552     xtensa_frame_cache (next_frame, this_cache);
1553
1554   return cache->base;
1555 }
1556
1557 static const struct frame_base
1558 xtensa_frame_base =
1559 {
1560   &xtensa_frame_unwind,
1561   xtensa_frame_base_address,
1562   xtensa_frame_base_address,
1563   xtensa_frame_base_address
1564 };
1565
1566
1567 static void
1568 xtensa_extract_return_value (struct type *type,
1569                              struct regcache *regcache,
1570                              void *dst)
1571 {
1572   struct gdbarch *gdbarch = get_regcache_arch (regcache);
1573   bfd_byte *valbuf = dst;
1574   int len = TYPE_LENGTH (type);
1575   ULONGEST pc, wb;
1576   int callsize, areg;
1577   int offset = 0;
1578
1579   DEBUGTRACE ("xtensa_extract_return_value (...)\n");
1580
1581   gdb_assert(len > 0);
1582
1583   if (gdbarch_tdep (gdbarch)->call_abi != CallAbiCall0Only)
1584     {
1585       /* First, we have to find the caller window in the register file.  */
1586       regcache_raw_read_unsigned (regcache, gdbarch_pc_regnum (gdbarch), &pc);
1587       callsize = extract_call_winsize (gdbarch, pc);
1588
1589       /* On Xtensa, we can return up to 4 words (or 2 for call12).  */
1590       if (len > (callsize > 8 ? 8 : 16))
1591         internal_error (__FILE__, __LINE__,
1592                         _("cannot extract return value of %d bytes long"), len);
1593
1594       /* Get the register offset of the return
1595          register (A2) in the caller window.  */
1596       regcache_raw_read_unsigned
1597         (regcache, gdbarch_tdep (gdbarch)->wb_regnum, &wb);
1598       areg = arreg_number (gdbarch,
1599                           gdbarch_tdep (gdbarch)->a0_base + 2 + callsize, wb);
1600     }
1601   else
1602     {
1603       /* No windowing hardware - Call0 ABI.  */
1604       areg = gdbarch_tdep (gdbarch)->a0_base + C0_ARGS;
1605     }
1606
1607   DEBUGINFO ("[xtensa_extract_return_value] areg %d len %d\n", areg, len);
1608
1609   if (len < 4 && gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
1610     offset = 4 - len;
1611
1612   for (; len > 0; len -= 4, areg++, valbuf += 4)
1613     {
1614       if (len < 4)
1615         regcache_raw_read_part (regcache, areg, offset, len, valbuf);
1616       else
1617         regcache_raw_read (regcache, areg, valbuf);
1618     }
1619 }
1620
1621
1622 static void
1623 xtensa_store_return_value (struct type *type,
1624                            struct regcache *regcache,
1625                            const void *dst)
1626 {
1627   struct gdbarch *gdbarch = get_regcache_arch (regcache);
1628   const bfd_byte *valbuf = dst;
1629   unsigned int areg;
1630   ULONGEST pc, wb;
1631   int callsize;
1632   int len = TYPE_LENGTH (type);
1633   int offset = 0;
1634
1635   DEBUGTRACE ("xtensa_store_return_value (...)\n");
1636
1637   if (gdbarch_tdep (gdbarch)->call_abi != CallAbiCall0Only)
1638     {
1639       regcache_raw_read_unsigned 
1640         (regcache, gdbarch_tdep (gdbarch)->wb_regnum, &wb);
1641       regcache_raw_read_unsigned (regcache, gdbarch_pc_regnum (gdbarch), &pc);
1642       callsize = extract_call_winsize (gdbarch, pc);
1643
1644       if (len > (callsize > 8 ? 8 : 16))
1645         internal_error (__FILE__, __LINE__,
1646                         _("unimplemented for this length: %d"),
1647                         TYPE_LENGTH (type));
1648       areg = arreg_number (gdbarch,
1649                            gdbarch_tdep (gdbarch)->a0_base + 2 + callsize, wb);
1650
1651       DEBUGTRACE ("[xtensa_store_return_value] callsize %d wb %d\n",
1652               callsize, (int) wb);
1653     }
1654   else
1655     {
1656       areg = gdbarch_tdep (gdbarch)->a0_base + C0_ARGS;
1657     }
1658
1659   if (len < 4 && gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
1660     offset = 4 - len;
1661
1662   for (; len > 0; len -= 4, areg++, valbuf += 4)
1663     {
1664       if (len < 4)
1665         regcache_raw_write_part (regcache, areg, offset, len, valbuf);
1666       else
1667         regcache_raw_write (regcache, areg, valbuf);
1668     }
1669 }
1670
1671
1672 static enum return_value_convention
1673 xtensa_return_value (struct gdbarch *gdbarch,
1674                      struct type *func_type,
1675                      struct type *valtype,
1676                      struct regcache *regcache,
1677                      gdb_byte *readbuf,
1678                      const gdb_byte *writebuf)
1679 {
1680   /* Structures up to 16 bytes are returned in registers.  */
1681
1682   int struct_return = ((TYPE_CODE (valtype) == TYPE_CODE_STRUCT
1683                         || TYPE_CODE (valtype) == TYPE_CODE_UNION
1684                         || TYPE_CODE (valtype) == TYPE_CODE_ARRAY)
1685                        && TYPE_LENGTH (valtype) > 16);
1686
1687   if (struct_return)
1688     return RETURN_VALUE_STRUCT_CONVENTION;
1689
1690   DEBUGTRACE ("xtensa_return_value(...)\n");
1691
1692   if (writebuf != NULL)
1693     {
1694       xtensa_store_return_value (valtype, regcache, writebuf);
1695     }
1696
1697   if (readbuf != NULL)
1698     {
1699       gdb_assert (!struct_return);
1700       xtensa_extract_return_value (valtype, regcache, readbuf);
1701     }
1702   return RETURN_VALUE_REGISTER_CONVENTION;
1703 }
1704
1705
1706 /* DUMMY FRAME */
1707
1708 static CORE_ADDR
1709 xtensa_push_dummy_call (struct gdbarch *gdbarch,
1710                         struct value *function,
1711                         struct regcache *regcache,
1712                         CORE_ADDR bp_addr,
1713                         int nargs,
1714                         struct value **args,
1715                         CORE_ADDR sp,
1716                         int struct_return,
1717                         CORE_ADDR struct_addr)
1718 {
1719   int i;
1720   int size, onstack_size;
1721   gdb_byte *buf = (gdb_byte *) alloca (16);
1722   CORE_ADDR ra, ps;
1723   struct argument_info
1724   {
1725     const bfd_byte *contents;
1726     int length;
1727     int onstack;                /* onstack == 0 => in reg */
1728     int align;                  /* alignment */
1729     union
1730     {
1731       int offset;               /* stack offset if on stack */
1732       int regno;                /* regno if in register */
1733     } u;
1734   };
1735
1736   struct argument_info *arg_info =
1737     (struct argument_info *) alloca (nargs * sizeof (struct argument_info));
1738
1739   CORE_ADDR osp = sp;
1740
1741   DEBUGTRACE ("xtensa_push_dummy_call (...)\n");
1742
1743   if (xtensa_debug_level > 3)
1744     {
1745       int i;
1746       DEBUGINFO ("[xtensa_push_dummy_call] nargs = %d\n", nargs);
1747       DEBUGINFO ("[xtensa_push_dummy_call] sp=0x%x, struct_return=%d, "
1748                  "struct_addr=0x%x\n",
1749                  (int) sp, (int) struct_return, (int) struct_addr);
1750
1751       for (i = 0; i < nargs; i++)
1752         {
1753           struct value *arg = args[i];
1754           struct type *arg_type = check_typedef (value_type (arg));
1755           fprintf_unfiltered (gdb_stdlog, "%2d: 0x%lx %3d ",
1756                               i, (unsigned long) arg, TYPE_LENGTH (arg_type));
1757           switch (TYPE_CODE (arg_type))
1758             {
1759             case TYPE_CODE_INT:
1760               fprintf_unfiltered (gdb_stdlog, "int");
1761               break;
1762             case TYPE_CODE_STRUCT:
1763               fprintf_unfiltered (gdb_stdlog, "struct");
1764               break;
1765             default:
1766               fprintf_unfiltered (gdb_stdlog, "%3d", TYPE_CODE (arg_type));
1767               break;
1768             }
1769           fprintf_unfiltered (gdb_stdlog, " 0x%lx\n",
1770                               (unsigned long) value_contents (arg));
1771         }
1772     }
1773
1774   /* First loop: collect information.
1775      Cast into type_long.  (This shouldn't happen often for C because
1776      GDB already does this earlier.)  It's possible that GDB could
1777      do it all the time but it's harmless to leave this code here.  */
1778
1779   size = 0;
1780   onstack_size = 0;
1781   i = 0;
1782
1783   if (struct_return)
1784     size = REGISTER_SIZE;
1785
1786   for (i = 0; i < nargs; i++)
1787     {
1788       struct argument_info *info = &arg_info[i];
1789       struct value *arg = args[i];
1790       struct type *arg_type = check_typedef (value_type (arg));
1791
1792       switch (TYPE_CODE (arg_type))
1793         {
1794         case TYPE_CODE_INT:
1795         case TYPE_CODE_BOOL:
1796         case TYPE_CODE_CHAR:
1797         case TYPE_CODE_RANGE:
1798         case TYPE_CODE_ENUM:
1799
1800           /* Cast argument to long if necessary as the mask does it too.  */
1801           if (TYPE_LENGTH (arg_type) < TYPE_LENGTH (builtin_type_long))
1802             {
1803               arg_type = builtin_type_long;
1804               arg = value_cast (arg_type, arg);
1805             }
1806           /* Aligment is equal to the type length for the basic types.  */
1807           info->align = TYPE_LENGTH (arg_type);
1808           break;
1809
1810         case TYPE_CODE_FLT:
1811
1812           /* Align doubles correctly.  */
1813           if (TYPE_LENGTH (arg_type) == TYPE_LENGTH (builtin_type_double))
1814             info->align = TYPE_LENGTH (builtin_type_double);
1815           else
1816             info->align = TYPE_LENGTH (builtin_type_long);
1817           break;
1818
1819         case TYPE_CODE_STRUCT:
1820         default:
1821           info->align = TYPE_LENGTH (builtin_type_long);
1822           break;
1823         }
1824       info->length = TYPE_LENGTH (arg_type);
1825       info->contents = value_contents (arg);
1826
1827       /* Align size and onstack_size.  */
1828       size = (size + info->align - 1) & ~(info->align - 1);
1829       onstack_size = (onstack_size + info->align - 1) & ~(info->align - 1);
1830
1831       if (size + info->length > REGISTER_SIZE * ARG_NOF (gdbarch))
1832         {
1833           info->onstack = 1;
1834           info->u.offset = onstack_size;
1835           onstack_size += info->length;
1836         }
1837       else
1838         {
1839           info->onstack = 0;
1840           info->u.regno = ARG_1ST (gdbarch) + size / REGISTER_SIZE;
1841         }
1842       size += info->length;
1843     }
1844
1845   /* Adjust the stack pointer and align it.  */
1846   sp = align_down (sp - onstack_size, SP_ALIGNMENT);
1847
1848   /* Simulate MOVSP, if Windowed ABI.  */
1849   if ((gdbarch_tdep (gdbarch)->call_abi != CallAbiCall0Only)
1850       && (sp != osp))
1851     {
1852       read_memory (osp - 16, buf, 16);
1853       write_memory (sp - 16, buf, 16);
1854     }
1855
1856   /* Second Loop: Load arguments.  */
1857
1858   if (struct_return)
1859     {
1860       store_unsigned_integer (buf, REGISTER_SIZE, struct_addr);
1861       regcache_cooked_write (regcache, ARG_1ST (gdbarch), buf);
1862     }
1863
1864   for (i = 0; i < nargs; i++)
1865     {
1866       struct argument_info *info = &arg_info[i];
1867
1868       if (info->onstack)
1869         {
1870           int n = info->length;
1871           CORE_ADDR offset = sp + info->u.offset;
1872
1873           /* Odd-sized structs are aligned to the lower side of a memory
1874              word in big-endian mode and require a shift.  This only
1875              applies for structures smaller than one word.  */
1876
1877           if (n < REGISTER_SIZE
1878               && gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
1879             offset += (REGISTER_SIZE - n);
1880
1881           write_memory (offset, info->contents, info->length);
1882
1883         }
1884       else
1885         {
1886           int n = info->length;
1887           const bfd_byte *cp = info->contents;
1888           int r = info->u.regno;
1889
1890           /* Odd-sized structs are aligned to the lower side of registers in
1891              big-endian mode and require a shift.  The odd-sized leftover will
1892              be at the end.  Note that this is only true for structures smaller
1893              than REGISTER_SIZE; for larger odd-sized structures the excess
1894              will be left-aligned in the register on both endiannesses.  */
1895
1896           if (n < REGISTER_SIZE
1897               && gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
1898             {
1899               ULONGEST v = extract_unsigned_integer (cp, REGISTER_SIZE);
1900               v = v >> ((REGISTER_SIZE - n) * TARGET_CHAR_BIT);
1901
1902               store_unsigned_integer (buf, REGISTER_SIZE, v);
1903               regcache_cooked_write (regcache, r, buf);
1904
1905               cp += REGISTER_SIZE;
1906               n -= REGISTER_SIZE;
1907               r++;
1908             }
1909           else
1910             while (n > 0)
1911               {
1912                 regcache_cooked_write (regcache, r, cp);
1913
1914                 cp += REGISTER_SIZE;
1915                 n -= REGISTER_SIZE;
1916                 r++;
1917               }
1918         }
1919     }
1920
1921   /* Set the return address of dummy frame to the dummy address.
1922      The return address for the current function (in A0) is
1923      saved in the dummy frame, so we can savely overwrite A0 here.  */
1924
1925   if (gdbarch_tdep (gdbarch)->call_abi != CallAbiCall0Only)
1926     {
1927       ra = (bp_addr & 0x3fffffff) | 0x40000000;
1928       regcache_raw_read (regcache, gdbarch_ps_regnum (gdbarch), buf);
1929       ps = extract_unsigned_integer (buf, 4) & ~0x00030000;
1930       regcache_cooked_write_unsigned
1931         (regcache, gdbarch_tdep (gdbarch)->a0_base + 4, ra);
1932       regcache_cooked_write_unsigned (regcache,
1933                                       gdbarch_ps_regnum (gdbarch),
1934                                       ps | 0x00010000);
1935
1936       /* All the registers have been saved.  After executing
1937          dummy call, they all will be restored.  So it's safe
1938          to modify WINDOWSTART register to make it look like there
1939          is only one register window corresponding to WINDOWEBASE.  */
1940
1941       regcache_raw_read (regcache, gdbarch_tdep (gdbarch)->wb_regnum, buf);
1942       regcache_cooked_write_unsigned (regcache,
1943                                       gdbarch_tdep (gdbarch)->ws_regnum,
1944                                       1 << extract_unsigned_integer (buf, 4));
1945     }
1946   else
1947     {
1948       /* Simulate CALL0: write RA into A0 register.  */
1949       regcache_cooked_write_unsigned
1950         (regcache, gdbarch_tdep (gdbarch)->a0_base, bp_addr);
1951     }
1952
1953   /* Set new stack pointer and return it.  */
1954   regcache_cooked_write_unsigned (regcache,
1955                                   gdbarch_tdep (gdbarch)->a0_base + 1, sp);
1956   /* Make dummy frame ID unique by adding a constant.  */
1957   return sp + SP_ALIGNMENT;
1958 }
1959
1960
1961 /* Return a breakpoint for the current location of PC.  We always use
1962    the density version if we have density instructions (regardless of the
1963    current instruction at PC), and use regular instructions otherwise.  */
1964
1965 #define BIG_BREAKPOINT { 0x00, 0x04, 0x00 }
1966 #define LITTLE_BREAKPOINT { 0x00, 0x40, 0x00 }
1967 #define DENSITY_BIG_BREAKPOINT { 0xd2, 0x0f }
1968 #define DENSITY_LITTLE_BREAKPOINT { 0x2d, 0xf0 }
1969
1970 static const unsigned char *
1971 xtensa_breakpoint_from_pc (struct gdbarch *gdbarch, CORE_ADDR *pcptr,
1972                            int *lenptr)
1973 {
1974   static unsigned char big_breakpoint[] = BIG_BREAKPOINT;
1975   static unsigned char little_breakpoint[] = LITTLE_BREAKPOINT;
1976   static unsigned char density_big_breakpoint[] = DENSITY_BIG_BREAKPOINT;
1977   static unsigned char density_little_breakpoint[] = DENSITY_LITTLE_BREAKPOINT;
1978
1979   DEBUGTRACE ("xtensa_breakpoint_from_pc (pc = 0x%08x)\n", (int) *pcptr);
1980
1981   if (gdbarch_tdep (gdbarch)->isa_use_density_instructions)
1982     {
1983       if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
1984         {
1985           *lenptr = sizeof (density_big_breakpoint);
1986           return density_big_breakpoint;
1987         }
1988       else
1989         {
1990           *lenptr = sizeof (density_little_breakpoint);
1991           return density_little_breakpoint;
1992         }
1993     }
1994   else
1995     {
1996       if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
1997         {
1998           *lenptr = sizeof (big_breakpoint);
1999           return big_breakpoint;
2000         }
2001       else
2002         {
2003           *lenptr = sizeof (little_breakpoint);
2004           return little_breakpoint;
2005         }
2006     }
2007 }
2008
2009 /* Call0 ABI support routines.  */
2010
2011 /* Call0 opcode class.  Opcodes are preclassified according to what they
2012    mean for Call0 prologue analysis, and their number of significant operands.
2013    The purpose of this is to simplify prologue analysis by separating 
2014    instruction decoding (libisa) from the semantics of prologue analysis.  */
2015
2016 typedef enum {
2017   c0opc_illegal,       /* Unknown to libisa (invalid) or 'ill' opcode.  */
2018   c0opc_uninteresting, /* Not interesting for Call0 prologue analysis.  */
2019   c0opc_flow,          /* Flow control insn.  */
2020   c0opc_entry,         /* ENTRY indicates non-Call0 prologue.  */
2021   c0opc_break,         /* Debugger software breakpoints.  */
2022   c0opc_add,           /* Adding two registers.  */
2023   c0opc_addi,          /* Adding a register and an immediate.  */
2024   c0opc_sub,           /* Subtracting a register from a register.  */
2025   c0opc_mov,           /* Moving a register to a register.  */
2026   c0opc_movi,          /* Moving an immediate to a register.  */
2027   c0opc_l32r,          /* Loading a literal.  */
2028   c0opc_s32i,          /* Storing word at fixed offset from a base register.  */
2029   c0opc_NrOf           /* Number of opcode classifications.  */
2030 } xtensa_insn_kind;
2031
2032
2033 /* Classify an opcode based on what it means for Call0 prologue analysis.  */
2034
2035 static xtensa_insn_kind
2036 call0_classify_opcode (xtensa_isa isa, xtensa_opcode opc)
2037 {
2038   const char *opcname;
2039   xtensa_insn_kind opclass = c0opc_uninteresting;
2040
2041   DEBUGTRACE ("call0_classify_opcode (..., opc = %d)\n", opc);
2042
2043   /* Get opcode name and handle special classifications.  */
2044
2045   opcname = xtensa_opcode_name (isa, opc);
2046
2047   if (opcname == NULL 
2048       || strcasecmp (opcname, "ill") == 0
2049       || strcasecmp (opcname, "ill.n") == 0)
2050     opclass = c0opc_illegal;
2051   else if (strcasecmp (opcname, "break") == 0
2052            || strcasecmp (opcname, "break.n") == 0)
2053      opclass = c0opc_break;
2054   else if (strcasecmp (opcname, "entry") == 0)
2055     opclass = c0opc_entry;
2056   else if (xtensa_opcode_is_branch (isa, opc) > 0
2057            || xtensa_opcode_is_jump   (isa, opc) > 0
2058            || xtensa_opcode_is_loop   (isa, opc) > 0
2059            || xtensa_opcode_is_call   (isa, opc) > 0
2060            || strcasecmp (opcname, "simcall") == 0
2061            || strcasecmp (opcname, "syscall") == 0)
2062     opclass = c0opc_flow;
2063
2064   /* Also, classify specific opcodes that need to be tracked.  */
2065   else if (strcasecmp (opcname, "add") == 0 
2066            || strcasecmp (opcname, "add.n") == 0)
2067     opclass = c0opc_add;
2068   else if (strcasecmp (opcname, "addi") == 0 
2069            || strcasecmp (opcname, "addi.n") == 0
2070            || strcasecmp (opcname, "addmi") == 0)
2071     opclass = c0opc_addi;
2072   else if (strcasecmp (opcname, "sub") == 0)
2073     opclass = c0opc_sub;
2074   else if (strcasecmp (opcname, "mov.n") == 0
2075            || strcasecmp (opcname, "or") == 0) /* Could be 'mov' asm macro.  */
2076     opclass = c0opc_mov;
2077   else if (strcasecmp (opcname, "movi") == 0 
2078            || strcasecmp (opcname, "movi.n") == 0)
2079     opclass = c0opc_movi;
2080   else if (strcasecmp (opcname, "l32r") == 0)
2081     opclass = c0opc_l32r;
2082   else if (strcasecmp (opcname, "s32i") == 0 
2083            || strcasecmp (opcname, "s32i.n") == 0)
2084     opclass = c0opc_s32i;
2085
2086   return opclass;
2087 }
2088
2089 /* Tracks register movement/mutation for a given operation, which may
2090    be within a bundle.  Updates the destination register tracking info
2091    accordingly.  The pc is needed only for pc-relative load instructions
2092    (eg. l32r).  The SP register number is needed to identify stores to
2093    the stack frame.  */
2094
2095 static void
2096 call0_track_op (xtensa_c0reg_t dst[], xtensa_c0reg_t src[],
2097                 xtensa_insn_kind opclass, int nods, unsigned odv[],
2098                 CORE_ADDR pc, int spreg)
2099 {
2100   unsigned litbase, litaddr, litval;
2101
2102   switch (opclass)
2103     {
2104     case c0opc_addi:
2105       /* 3 operands: dst, src, imm.  */
2106       gdb_assert (nods == 3);
2107       dst[odv[0]].fr_reg = src[odv[1]].fr_reg;
2108       dst[odv[0]].fr_ofs = src[odv[1]].fr_ofs + odv[2];
2109       break;
2110     case c0opc_add:
2111       /* 3 operands: dst, src1, src2.  */
2112       gdb_assert (nods == 3);
2113       if      (src[odv[1]].fr_reg == C0_CONST)
2114         {
2115           dst[odv[0]].fr_reg = src[odv[2]].fr_reg;
2116           dst[odv[0]].fr_ofs = src[odv[2]].fr_ofs + src[odv[1]].fr_ofs;
2117         }
2118       else if (src[odv[2]].fr_reg == C0_CONST)
2119         {
2120           dst[odv[0]].fr_reg = src[odv[1]].fr_reg;
2121           dst[odv[0]].fr_ofs = src[odv[1]].fr_ofs + src[odv[2]].fr_ofs;
2122         }
2123       else dst[odv[0]].fr_reg = C0_INEXP;
2124       break;
2125     case c0opc_sub:
2126       /* 3 operands: dst, src1, src2.  */
2127       gdb_assert (nods == 3);
2128       if      (src[odv[2]].fr_reg == C0_CONST)
2129         {
2130           dst[odv[0]].fr_reg = src[odv[1]].fr_reg;
2131           dst[odv[0]].fr_ofs = src[odv[1]].fr_ofs - src[odv[2]].fr_ofs;
2132         }
2133       else dst[odv[0]].fr_reg = C0_INEXP;
2134       break;
2135     case c0opc_mov:
2136       /* 2 operands: dst, src [, src].  */
2137       gdb_assert (nods == 2);
2138       dst[odv[0]].fr_reg = src[odv[1]].fr_reg;
2139       dst[odv[0]].fr_ofs = src[odv[1]].fr_ofs;
2140       break;
2141     case c0opc_movi:
2142       /* 2 operands: dst, imm.  */
2143       gdb_assert (nods == 2);
2144       dst[odv[0]].fr_reg = C0_CONST;
2145       dst[odv[0]].fr_ofs = odv[1];
2146       break;
2147     case c0opc_l32r:
2148       /* 2 operands: dst, literal offset.  */
2149       gdb_assert (nods == 2);
2150       /* litbase = xtensa_get_litbase (pc); can be also used.  */
2151       litbase = (gdbarch_tdep (current_gdbarch)->litbase_regnum == -1)
2152         ? 0 : xtensa_read_register
2153                 (gdbarch_tdep (current_gdbarch)->litbase_regnum);
2154       litaddr = litbase & 1
2155                   ? (litbase & ~1) + (signed)odv[1]
2156                   : (pc + 3  + (signed)odv[1]) & ~3;
2157       litval = read_memory_integer(litaddr, 4);
2158       dst[odv[0]].fr_reg = C0_CONST;
2159       dst[odv[0]].fr_ofs = litval;
2160       break;
2161     case c0opc_s32i:
2162       /* 3 operands: value, base, offset.  */
2163       gdb_assert (nods == 3 && spreg >= 0 && spreg < C0_NREGS);
2164       if (src[odv[1]].fr_reg == spreg        /* Store to stack frame.  */
2165           && (src[odv[1]].fr_ofs & 3) == 0   /* Alignment preserved.  */
2166           &&  src[odv[0]].fr_reg >= 0        /* Value is from a register.  */
2167           &&  src[odv[0]].fr_ofs == 0        /* Value hasn't been modified.  */
2168           &&  src[src[odv[0]].fr_reg].to_stk == C0_NOSTK) /* First time.  */
2169         {
2170           /* ISA encoding guarantees alignment.  But, check it anyway.  */
2171           gdb_assert ((odv[2] & 3) == 0);
2172           dst[src[odv[0]].fr_reg].to_stk = src[odv[1]].fr_ofs + odv[2];
2173         }
2174       break;
2175     default:
2176         gdb_assert (0);
2177     }
2178 }
2179
2180 /* Analyze prologue of the function at start address to determine if it uses 
2181    the Call0 ABI, and if so track register moves and linear modifications
2182    in the prologue up to the PC or just beyond the prologue, whichever is first.
2183    An 'entry' instruction indicates non-Call0 ABI and the end of the prologue.
2184    The prologue may overlap non-prologue instructions but is guaranteed to end
2185    by the first flow-control instruction (jump, branch, call or return).
2186    Since an optimized function may move information around and change the
2187    stack frame arbitrarily during the prologue, the information is guaranteed
2188    valid only at the point in the function indicated by the PC.
2189    May be used to skip the prologue or identify the ABI, w/o tracking.
2190
2191    Returns:   Address of first instruction after prologue, or PC (whichever 
2192               is first), or 0, if decoding failed (in libisa).
2193    Input args:
2194       start   Start address of function/prologue.
2195       pc      Program counter to stop at.  Use 0 to continue to end of prologue.
2196               If 0, avoids infinite run-on in corrupt code memory by bounding
2197               the scan to the end of the function if that can be determined.
2198       nregs   Number of general registers to track (size of rt[] array).
2199    InOut args:
2200       rt[]    Array[nregs] of xtensa_c0reg structures for register tracking info.
2201               If NULL, registers are not tracked.
2202    Output args:
2203       call0   If != NULL, *call0 is set non-zero if Call0 ABI used, else 0
2204               (more accurately, non-zero until 'entry' insn is encountered).
2205
2206       Note that these may produce useful results even if decoding fails
2207       because they begin with default assumptions that analysis may change.  */
2208
2209 static CORE_ADDR
2210 call0_analyze_prologue (CORE_ADDR start, CORE_ADDR pc,
2211                         int nregs, xtensa_c0reg_t rt[], int *call0)
2212 {
2213   CORE_ADDR ia;             /* Current insn address in prologue.  */
2214   CORE_ADDR ba = 0;         /* Current address at base of insn buffer.  */
2215   CORE_ADDR bt;             /* Current address at top+1 of insn buffer.  */
2216   #define BSZ 32            /* Instruction buffer size.  */
2217   char ibuf[BSZ];           /* Instruction buffer for decoding prologue.  */
2218   xtensa_isa isa;           /* libisa ISA handle.  */
2219   xtensa_insnbuf ins, slot; /* libisa handle to decoded insn, slot.  */
2220   xtensa_format ifmt;       /* libisa instruction format.  */
2221   int ilen, islots, is;     /* Instruction length, nbr slots, current slot.  */
2222   xtensa_opcode opc;        /* Opcode in current slot.  */
2223   xtensa_insn_kind opclass; /* Opcode class for Call0 prologue analysis.  */
2224   int nods;                 /* Opcode number of operands.  */
2225   unsigned odv[C0_MAXOPDS]; /* Operand values in order provided by libisa.  */
2226   xtensa_c0reg_t *rtmp;     /* Register tracking info snapshot.  */
2227   int j;                    /* General loop counter.  */
2228   int fail = 0;             /* Set non-zero and exit, if decoding fails.  */
2229   CORE_ADDR body_pc;        /* The PC for the first non-prologue insn.  */
2230   CORE_ADDR end_pc;         /* The PC for the lust function insn.  */
2231
2232   struct symtab_and_line prologue_sal;
2233
2234   DEBUGTRACE ("call0_analyze_prologue (start = 0x%08x, pc = 0x%08x, ...)\n", 
2235               (int)start, (int)pc);
2236
2237   /* Try to limit the scan to the end of the function if a non-zero pc
2238      arg was not supplied to avoid probing beyond the end of valid memory.
2239      If memory is full of garbage that classifies as c0opc_uninteresting.
2240      If this fails (eg. if no symbols) pc ends up 0 as it was.
2241      Intialize the Call0 frame and register tracking info.
2242      Assume it's Call0 until an 'entry' instruction is encountered.
2243      Assume we may be in the prologue until we hit a flow control instr.  */
2244
2245   rtmp = NULL;
2246   body_pc = INT_MAX;
2247   end_pc = 0;
2248
2249   /* Find out, if we have an information about the prologue from DWARF.  */
2250   prologue_sal = find_pc_line (start, 0);
2251   if (prologue_sal.line != 0) /* Found debug info.  */
2252     body_pc = prologue_sal.end;
2253
2254   /* If we are going to analyze the prologue in general without knowing about
2255      the current PC, make the best assumtion for the end of the prologue.  */
2256   if (pc == 0)
2257     {
2258       find_pc_partial_function (start, 0, NULL, &end_pc);
2259       body_pc = min (end_pc, body_pc);
2260     }
2261   else
2262     body_pc = min (pc, body_pc);
2263
2264   if (call0 != NULL)
2265       *call0 = 1;
2266
2267   if (rt != NULL)
2268     {
2269       rtmp = (xtensa_c0reg_t*) alloca(nregs * sizeof(xtensa_c0reg_t));
2270       /* rt is already initialized in xtensa_alloc_frame_cache().  */
2271     }
2272   else nregs = 0;
2273
2274   if (!xtensa_default_isa)
2275     xtensa_default_isa = xtensa_isa_init (0, 0);
2276   isa = xtensa_default_isa;
2277   gdb_assert (BSZ >= xtensa_isa_maxlength (isa));
2278   ins = xtensa_insnbuf_alloc (isa);
2279   slot = xtensa_insnbuf_alloc (isa);
2280
2281   for (ia = start, bt = ia; ia < body_pc ; ia += ilen)
2282     {
2283       /* (Re)fill instruction buffer from memory if necessary, but do not
2284          read memory beyond PC to be sure we stay within text section
2285          (this protection only works if a non-zero pc is supplied).  */
2286
2287       if (ia + xtensa_isa_maxlength (isa) > bt)
2288         {
2289           ba = ia;
2290           bt = (ba + BSZ) < body_pc ? ba + BSZ : body_pc;
2291           read_memory (ba, ibuf, bt - ba);
2292         }
2293
2294       /* Decode format information.  */
2295
2296       xtensa_insnbuf_from_chars (isa, ins, &ibuf[ia-ba], 0);
2297       ifmt = xtensa_format_decode (isa, ins);
2298       if (ifmt == XTENSA_UNDEFINED)
2299         {
2300           fail = 1;
2301           goto done;
2302         }
2303       ilen = xtensa_format_length (isa, ifmt);
2304       if (ilen == XTENSA_UNDEFINED)
2305         {
2306           fail = 1;
2307           goto done;
2308         }
2309       islots = xtensa_format_num_slots (isa, ifmt);
2310       if (islots == XTENSA_UNDEFINED)
2311         {
2312           fail = 1;
2313           goto done;
2314         }
2315
2316       /* Analyze a bundle or a single instruction, using a snapshot of 
2317          the register tracking info as input for the entire bundle so that
2318          register changes do not take effect within this bundle.  */
2319
2320       for (j = 0; j < nregs; ++j)
2321         rtmp[j] = rt[j];
2322
2323       for (is = 0; is < islots; ++is)
2324         {
2325           /* Decode a slot and classify the opcode.  */
2326
2327           fail = xtensa_format_get_slot (isa, ifmt, is, ins, slot);
2328           if (fail)
2329             goto done;
2330
2331           opc = xtensa_opcode_decode (isa, ifmt, is, slot);
2332           DEBUGVERB ("[call0_analyze_prologue] instr addr = 0x%08x, opc = %d\n", 
2333                      (unsigned)ia, opc);
2334           if (opc == XTENSA_UNDEFINED) 
2335             opclass = c0opc_illegal;
2336           else
2337             opclass = call0_classify_opcode (isa, opc);
2338
2339           /* Decide whether to track this opcode, ignore it, or bail out.  */
2340
2341           switch (opclass)
2342             {
2343             case c0opc_illegal:
2344             case c0opc_break:
2345               fail = 1;
2346               goto done;
2347
2348             case c0opc_uninteresting:
2349               continue;
2350
2351             case c0opc_flow:
2352               goto done;
2353
2354             case c0opc_entry:
2355               if (call0 != NULL)
2356                 *call0 = 0;
2357               ia += ilen;               /* Skip over 'entry' insn.  */
2358               goto done;
2359
2360             default:
2361               if (call0 != NULL)
2362                 *call0 = 1;
2363             }
2364
2365           /* Only expected opcodes should get this far.  */
2366           if (rt == NULL)
2367             continue;
2368
2369           /* Extract and decode the operands.  */
2370           nods = xtensa_opcode_num_operands (isa, opc);
2371           if (nods == XTENSA_UNDEFINED)
2372             {
2373               fail = 1;
2374               goto done;
2375             }
2376
2377           for (j = 0; j < nods && j < C0_MAXOPDS; ++j)
2378             {
2379               fail = xtensa_operand_get_field (isa, opc, j, ifmt, 
2380                                                is, slot, &odv[j]);
2381               if (fail)
2382                 goto done;
2383
2384               fail = xtensa_operand_decode (isa, opc, j, &odv[j]);
2385               if (fail)
2386                 goto done;
2387             }
2388
2389           /* Check operands to verify use of 'mov' assembler macro.  */
2390           if (opclass == c0opc_mov && nods == 3)
2391             {
2392               if (odv[2] == odv[1])
2393                 nods = 2;
2394               else
2395                 {
2396                   opclass = c0opc_uninteresting;
2397                   continue;
2398                 }
2399             }
2400
2401           /* Track register movement and modification for this operation.  */
2402           call0_track_op (rt, rtmp, opclass, nods, odv, ia, 1);
2403         }
2404     }
2405 done:
2406   DEBUGVERB ("[call0_analyze_prologue] stopped at instr addr 0x%08x, %s\n",
2407              (unsigned)ia, fail ? "failed" : "succeeded");
2408   xtensa_insnbuf_free(isa, slot);
2409   xtensa_insnbuf_free(isa, ins);
2410   return fail ? 0 : ia;
2411 }
2412
2413 /* Initialize frame cache for the current frame.  The "next_frame" is the next
2414    one relative to current frame.  "cache" is the pointer to the data structure
2415    we have to initialize.  "pc" is curretnt PC.  */
2416
2417 static void
2418 call0_frame_cache (struct frame_info *next_frame,
2419                    xtensa_frame_cache_t *cache, CORE_ADDR pc)
2420 {
2421   struct gdbarch *gdbarch = get_frame_arch (next_frame);
2422   CORE_ADDR start_pc;           /* The beginning of the function.  */
2423   CORE_ADDR body_pc=UINT_MAX;   /* PC, where prologue analysis stopped.  */
2424   CORE_ADDR sp, fp, ra;
2425   int fp_regnum, c0_hasfp, c0_frmsz, prev_sp, to_stk;
2426  
2427   /* Find the beginning of the prologue of the function containing the PC
2428      and analyze it up to the PC or the end of the prologue.  */
2429
2430   if (find_pc_partial_function (pc, NULL, &start_pc, NULL))
2431     {
2432       body_pc = call0_analyze_prologue (start_pc, pc, C0_NREGS,
2433                                         &cache->c0.c0_rt[0],
2434                                         &cache->call0);
2435     }
2436   
2437   sp = frame_unwind_register_unsigned
2438          (next_frame, gdbarch_tdep (gdbarch)->a0_base + 1);
2439   fp = sp; /* Assume FP == SP until proven otherwise.  */
2440
2441   /* Get the frame information and FP (if used) at the current PC.
2442      If PC is in the prologue, the prologue analysis is more reliable
2443      than DWARF info.  We don't not know for sure if PC is in the prologue,
2444      but we know no calls have yet taken place, so we can almost
2445      certainly rely on the prologue analysis.  */
2446
2447   if (body_pc <= pc)
2448     {
2449       /* Prologue analysis was successful up to the PC.
2450          It includes the cases when PC == START_PC.  */
2451       c0_hasfp = cache->c0.c0_rt[C0_FP].fr_reg == C0_SP;
2452       /* c0_hasfp == true means there is a frame pointer because
2453          we analyzed the prologue and found that cache->c0.c0_rt[C0_FP]
2454          was derived from SP.  Otherwise, it would be C0_FP.  */
2455       fp_regnum = c0_hasfp ? C0_FP : C0_SP;
2456       c0_frmsz = - cache->c0.c0_rt[fp_regnum].fr_ofs;
2457       fp_regnum += gdbarch_tdep (gdbarch)->a0_base;
2458     }
2459   else  /* No data from the prologue analysis.  */
2460     {
2461       c0_hasfp = 0;
2462       fp_regnum = gdbarch_tdep (gdbarch)->a0_base + C0_SP;
2463       c0_frmsz = 0;
2464       start_pc = pc;
2465    }
2466
2467   prev_sp = fp + c0_frmsz;
2468
2469   /* Frame size from debug info or prologue tracking does not account for 
2470      alloca() and other dynamic allocations.  Adjust frame size by FP - SP.  */
2471   if (c0_hasfp)
2472     {
2473       fp = frame_unwind_register_unsigned (next_frame, fp_regnum);
2474
2475       /* Recalculate previous SP.  */
2476       prev_sp = fp + c0_frmsz;
2477       /* Update the stack frame size.  */
2478       c0_frmsz += fp - sp;
2479     }
2480
2481   /* Get the return address (RA) from the stack if saved,
2482      or try to get it from a register.  */
2483
2484   to_stk = cache->c0.c0_rt[C0_RA].to_stk;
2485   if (to_stk != C0_NOSTK)
2486     ra = (CORE_ADDR) 
2487       read_memory_integer (sp + c0_frmsz + cache->c0.c0_rt[C0_RA].to_stk, 4);
2488
2489   else if (cache->c0.c0_rt[C0_RA].fr_reg == C0_CONST
2490            && cache->c0.c0_rt[C0_RA].fr_ofs == 0)
2491     {
2492       /* Special case for terminating backtrace at a function that wants to
2493          be seen as the outermost.  Such a function will clear it's RA (A0)
2494          register to 0 in the prologue instead of saving its original value.  */
2495       ra = 0;
2496     }
2497   else
2498     {
2499       /* RA was copied to another register or (before any function call) may
2500          still be in the original RA register.  This is not always reliable:
2501          even in a leaf function, register tracking stops after prologue, and
2502          even in prologue, non-prologue instructions (not tracked) may overwrite
2503          RA or any register it was copied to.  If likely in prologue or before
2504          any call, use retracking info and hope for the best (compiler should
2505          have saved RA in stack if not in a leaf function).  If not in prologue,
2506          too bad.  */
2507
2508       int i;
2509       for (i = 0; 
2510            (i < C0_NREGS) &&
2511              (i == C0_RA || cache->c0.c0_rt[i].fr_reg != C0_RA);
2512            ++i);
2513       if (i >= C0_NREGS && cache->c0.c0_rt[C0_RA].fr_reg == C0_RA)
2514         i = C0_RA;
2515       if (i < C0_NREGS) /* Read from the next_frame.  */
2516         {
2517           ra = frame_unwind_register_unsigned
2518                  (next_frame,
2519                   gdbarch_tdep (gdbarch)->a0_base + cache->c0.c0_rt[i].fr_reg);
2520         }
2521       else ra = 0;
2522     }
2523   
2524   cache->pc = start_pc;
2525   cache->ra = ra;
2526   /* RA == 0 marks the outermost frame.  Do not go past it.  */
2527   cache->prev_sp = (ra != 0) ?  prev_sp : 0;
2528   cache->c0.fp_regnum = fp_regnum;
2529   cache->c0.c0_frmsz = c0_frmsz;
2530   cache->c0.c0_hasfp = c0_hasfp;
2531   cache->c0.c0_fp = fp;
2532 }
2533
2534
2535 /* Skip function prologue.
2536
2537    Return the pc of the first instruction after prologue.  GDB calls this to
2538    find the address of the first line of the function or (if there is no line
2539    number information) to skip the prologue for planting breakpoints on 
2540    function entries.  Use debug info (if present) or prologue analysis to skip 
2541    the prologue to achieve reliable debugging behavior.  For windowed ABI, 
2542    only the 'entry' instruction is skipped.  It is not strictly necessary to 
2543    skip the prologue (Call0) or 'entry' (Windowed) because xt-gdb knows how to
2544    backtrace at any point in the prologue, however certain potential hazards 
2545    are avoided and a more "normal" debugging experience is ensured by 
2546    skipping the prologue (can be disabled by defining DONT_SKIP_PROLOG).
2547    For example, if we don't skip the prologue:
2548    - Some args may not yet have been saved to the stack where the debug
2549      info expects to find them (true anyway when only 'entry' is skipped);
2550    - Software breakpoints ('break' instrs) may not have been unplanted 
2551      when the prologue analysis is done on initializing the frame cache, 
2552      and breaks in the prologue will throw off the analysis.
2553
2554    If we have debug info ( line-number info, in particular ) we simply skip
2555    the code associated with the first function line effectively skipping
2556    the prologue code.  It works even in cases like
2557
2558    int main()
2559    {    int local_var = 1;
2560         ....
2561    }
2562
2563    because, for this source code, both Xtensa compilers will generate two
2564    separate entries ( with the same line number ) in dwarf line-number
2565    section to make sure there is a boundary between the prologue code and
2566    the rest of the function.
2567
2568    If there is no debug info, we need to analyze the code.  */
2569
2570 /* #define DONT_SKIP_PROLOGUE  */
2571
2572 CORE_ADDR
2573 xtensa_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR start_pc)
2574 {
2575   struct symtab_and_line prologue_sal;
2576   CORE_ADDR body_pc;
2577
2578   DEBUGTRACE ("xtensa_skip_prologue (start_pc = 0x%08x)\n", (int) start_pc);
2579
2580 #if DONT_SKIP_PROLOGUE
2581   return start_pc;
2582 #endif
2583
2584  /* Try to find first body line from debug info.  */
2585
2586   prologue_sal = find_pc_line (start_pc, 0);
2587   if (prologue_sal.line != 0) /* Found debug info.  */
2588     {
2589       /* In Call0, it is possible to have a function with only one instruction
2590          ('ret') resulting from a 1-line optimized function that does nothing.
2591          In that case, prologue_sal.end may actually point to the start of the
2592          next function in the text section, causing a breakpoint to be set at
2593          the wrong place.  Check if the end address is in a different function,
2594          and if so return the start PC.  We know we have symbol info.  */
2595
2596       CORE_ADDR end_func;
2597
2598       find_pc_partial_function (prologue_sal.end, NULL, &end_func, NULL);
2599       if (end_func != start_pc)
2600         return start_pc;
2601
2602       return prologue_sal.end;
2603     }
2604
2605   /* No debug line info.  Analyze prologue for Call0 or simply skip ENTRY.  */
2606   body_pc = call0_analyze_prologue(start_pc, 0, 0, NULL, NULL);
2607   return body_pc != 0 ? body_pc : start_pc;
2608 }
2609
2610 /* Verify the current configuration.  */
2611 static void
2612 xtensa_verify_config (struct gdbarch *gdbarch)
2613 {
2614   struct ui_file *log;
2615   struct cleanup *cleanups;
2616   struct gdbarch_tdep *tdep;
2617   long dummy;
2618   char *buf;
2619
2620   tdep = gdbarch_tdep (gdbarch);
2621   log = mem_fileopen ();
2622   cleanups = make_cleanup_ui_file_delete (log);
2623
2624   /* Verify that we got a reasonable number of AREGS.  */
2625   if ((tdep->num_aregs & -tdep->num_aregs) != tdep->num_aregs)
2626     fprintf_unfiltered (log, _("\
2627 \n\tnum_aregs: Number of AR registers (%d) is not a power of two!"),
2628                         tdep->num_aregs);
2629
2630   /* Verify that certain registers exist.  */
2631
2632   if (tdep->pc_regnum == -1)
2633     fprintf_unfiltered (log, _("\n\tpc_regnum: No PC register"));
2634   if (tdep->isa_use_exceptions && tdep->ps_regnum == -1)
2635     fprintf_unfiltered (log, _("\n\tps_regnum: No PS register"));
2636
2637   if (tdep->isa_use_windowed_registers)
2638     {
2639       if (tdep->wb_regnum == -1)
2640         fprintf_unfiltered (log, _("\n\twb_regnum: No WB register"));
2641       if (tdep->ws_regnum == -1)
2642         fprintf_unfiltered (log, _("\n\tws_regnum: No WS register"));
2643       if (tdep->ar_base == -1)
2644         fprintf_unfiltered (log, _("\n\tar_base: No AR registers"));
2645     }
2646
2647   if (tdep->a0_base == -1)
2648     fprintf_unfiltered (log, _("\n\ta0_base: No Ax registers"));
2649
2650   buf = ui_file_xstrdup (log, &dummy);
2651   make_cleanup (xfree, buf);
2652   if (strlen (buf) > 0)
2653     internal_error (__FILE__, __LINE__,
2654                     _("the following are invalid: %s"), buf);
2655   do_cleanups (cleanups);
2656 }
2657
2658
2659 /* Derive specific register numbers from the array of registers.  */
2660
2661 void
2662 xtensa_derive_tdep (struct gdbarch_tdep *tdep)
2663 {
2664   xtensa_register_t* rmap;
2665   int n, max_size = 4;
2666
2667   tdep->num_regs = 0;
2668   tdep->num_nopriv_regs = 0;
2669
2670 /* Special registers 0..255 (core).  */
2671 #define XTENSA_DBREGN_SREG(n)  (0x0200+(n))
2672
2673   for (rmap = tdep->regmap, n = 0; rmap->target_number != -1; n++, rmap++)
2674     {
2675       if (rmap->target_number == 0x0020)
2676         tdep->pc_regnum = n;
2677       else if (rmap->target_number == 0x0100)
2678         tdep->ar_base = n;
2679       else if (rmap->target_number == 0x0000)
2680         tdep->a0_base = n;
2681       else if (rmap->target_number == XTENSA_DBREGN_SREG(72))
2682         tdep->wb_regnum = n;
2683       else if (rmap->target_number == XTENSA_DBREGN_SREG(73))
2684         tdep->ws_regnum = n;
2685       else if (rmap->target_number == XTENSA_DBREGN_SREG(233))
2686         tdep->debugcause_regnum = n;
2687       else if (rmap->target_number == XTENSA_DBREGN_SREG(232))
2688         tdep->exccause_regnum = n;
2689       else if (rmap->target_number == XTENSA_DBREGN_SREG(238))
2690         tdep->excvaddr_regnum = n;
2691       else if (rmap->target_number == XTENSA_DBREGN_SREG(0))
2692         tdep->lbeg_regnum = n;
2693       else if (rmap->target_number == XTENSA_DBREGN_SREG(1))
2694         tdep->lend_regnum = n;
2695       else if (rmap->target_number == XTENSA_DBREGN_SREG(2))
2696         tdep->lcount_regnum = n;
2697       else if (rmap->target_number == XTENSA_DBREGN_SREG(3))
2698         tdep->sar_regnum = n;
2699       else if (rmap->target_number == XTENSA_DBREGN_SREG(5))
2700         tdep->litbase_regnum = n;
2701       else if (rmap->target_number == XTENSA_DBREGN_SREG(230))
2702         tdep->ps_regnum = n;
2703 #if 0
2704       else if (rmap->target_number == XTENSA_DBREGN_SREG(226))
2705         tdep->interrupt_regnum = n;
2706       else if (rmap->target_number == XTENSA_DBREGN_SREG(227))
2707         tdep->interrupt2_regnum = n;
2708       else if (rmap->target_number == XTENSA_DBREGN_SREG(224))
2709         tdep->cpenable_regnum = n;
2710 #endif
2711
2712       if (rmap->byte_size > max_size)
2713         max_size = rmap->byte_size;
2714       if (rmap->mask != 0 && tdep->num_regs == 0)
2715         tdep->num_regs = n;
2716       /* Find out out how to deal with priveleged registers.
2717
2718          if ((rmap->flags & XTENSA_REGISTER_FLAGS_PRIVILEGED) != 0
2719               && tdep->num_nopriv_regs == 0)
2720            tdep->num_nopriv_regs = n;
2721       */
2722       if ((rmap->flags & XTENSA_REGISTER_FLAGS_PRIVILEGED) != 0
2723           && tdep->num_regs == 0)
2724         tdep->num_regs = n;
2725     }
2726
2727   /* Number of pseudo registers.  */
2728   tdep->num_pseudo_regs = n - tdep->num_regs;
2729
2730   /* Empirically determined maximum sizes.  */
2731   tdep->max_register_raw_size = max_size;
2732   tdep->max_register_virtual_size = max_size;
2733 }
2734
2735 /* Module "constructor" function.  */
2736
2737 extern struct gdbarch_tdep xtensa_tdep;
2738
2739 static struct gdbarch *
2740 xtensa_gdbarch_init (struct gdbarch_info info, struct gdbarch_list *arches)
2741 {
2742   struct gdbarch_tdep *tdep;
2743   struct gdbarch *gdbarch;
2744   struct xtensa_abi_handler *abi_handler;
2745
2746   DEBUGTRACE ("gdbarch_init()\n");
2747
2748   /* We have to set the byte order before we call gdbarch_alloc.  */
2749   info.byte_order = XCHAL_HAVE_BE ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
2750
2751   tdep = &xtensa_tdep;
2752   gdbarch = gdbarch_alloc (&info, tdep);
2753   xtensa_derive_tdep (tdep);
2754
2755   /* Verify our configuration.  */
2756   xtensa_verify_config (gdbarch);
2757
2758   /* Pseudo-Register read/write.  */
2759   set_gdbarch_pseudo_register_read (gdbarch, xtensa_pseudo_register_read);
2760   set_gdbarch_pseudo_register_write (gdbarch, xtensa_pseudo_register_write);
2761
2762   /* Set target information.  */
2763   set_gdbarch_num_regs (gdbarch, tdep->num_regs);
2764   set_gdbarch_num_pseudo_regs (gdbarch, tdep->num_pseudo_regs);
2765   set_gdbarch_sp_regnum (gdbarch, tdep->a0_base + 1);
2766   set_gdbarch_pc_regnum (gdbarch, tdep->pc_regnum);
2767   set_gdbarch_ps_regnum (gdbarch, tdep->ps_regnum);
2768
2769   /* Renumber registers for known formats (stab, dwarf, and dwarf2).  */
2770   set_gdbarch_stab_reg_to_regnum (gdbarch, xtensa_reg_to_regnum);
2771   set_gdbarch_dwarf_reg_to_regnum (gdbarch, xtensa_reg_to_regnum);
2772   set_gdbarch_dwarf2_reg_to_regnum (gdbarch, xtensa_reg_to_regnum);
2773
2774   /* We provide our own function to get register information.  */
2775   set_gdbarch_register_name (gdbarch, xtensa_register_name);
2776   set_gdbarch_register_type (gdbarch, xtensa_register_type);
2777
2778   /* To call functions from GDB using dummy frame */
2779   set_gdbarch_push_dummy_call (gdbarch, xtensa_push_dummy_call);
2780
2781   set_gdbarch_believe_pcc_promotion (gdbarch, 1);
2782
2783   set_gdbarch_return_value (gdbarch, xtensa_return_value);
2784
2785   /* Advance PC across any prologue instructions to reach "real" code.  */
2786   set_gdbarch_skip_prologue (gdbarch, xtensa_skip_prologue);
2787
2788   /* Stack grows downward.  */
2789   set_gdbarch_inner_than (gdbarch, core_addr_lessthan);
2790
2791   /* Set breakpoints.  */
2792   set_gdbarch_breakpoint_from_pc (gdbarch, xtensa_breakpoint_from_pc);
2793
2794   /* After breakpoint instruction or illegal instruction, pc still
2795      points at break instruction, so don't decrement.  */
2796   set_gdbarch_decr_pc_after_break (gdbarch, 0);
2797
2798   /* We don't skip args.  */
2799   set_gdbarch_frame_args_skip (gdbarch, 0);
2800
2801   set_gdbarch_unwind_pc (gdbarch, xtensa_unwind_pc);
2802
2803   set_gdbarch_frame_align (gdbarch, xtensa_frame_align);
2804
2805   set_gdbarch_unwind_dummy_id (gdbarch, xtensa_unwind_dummy_id);
2806
2807   /* Frame handling.  */
2808   frame_base_set_default (gdbarch, &xtensa_frame_base);
2809   frame_unwind_append_sniffer (gdbarch, xtensa_frame_sniffer);
2810
2811   set_gdbarch_print_insn (gdbarch, print_insn_xtensa);
2812
2813   set_gdbarch_have_nonsteppable_watchpoint (gdbarch, 1);
2814
2815   xtensa_add_reggroups (gdbarch);
2816   set_gdbarch_register_reggroup_p (gdbarch, xtensa_register_reggroup_p);
2817
2818   set_gdbarch_regset_from_core_section (gdbarch,
2819                                         xtensa_regset_from_core_section);
2820
2821   set_solib_svr4_fetch_link_map_offsets
2822     (gdbarch, svr4_ilp32_fetch_link_map_offsets);
2823
2824   return gdbarch;
2825 }
2826
2827 static void
2828 xtensa_dump_tdep (struct gdbarch *gdbarch, struct ui_file *file)
2829 {
2830   error (_("xtensa_dump_tdep(): not implemented"));
2831 }
2832
2833 void
2834 _initialize_xtensa_tdep (void)
2835 {
2836   struct cmd_list_element *c;
2837
2838   gdbarch_register (bfd_arch_xtensa, xtensa_gdbarch_init, xtensa_dump_tdep);
2839   xtensa_init_reggroups ();
2840
2841   add_setshow_zinteger_cmd ("xtensa",
2842                             class_maintenance,
2843                             &xtensa_debug_level, _("\
2844 Set Xtensa debugging."), _("\
2845 Show Xtensa debugging."), _("\
2846 When non-zero, Xtensa-specific debugging is enabled. \
2847 Can be 1, 2, 3, or 4 indicating the level of debugging."),
2848                             NULL,
2849                             NULL,
2850                             &setdebuglist, &showdebuglist);
2851 }