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