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