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