gdb/riscv: Handle passing variadic floating point arguments
[external/binutils.git] / gdb / riscv-tdep.c
1 /* Target-dependent code for the RISC-V architecture, for GDB.
2
3    Copyright (C) 2018 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 "inferior.h"
23 #include "symtab.h"
24 #include "value.h"
25 #include "gdbcmd.h"
26 #include "language.h"
27 #include "gdbcore.h"
28 #include "symfile.h"
29 #include "objfiles.h"
30 #include "gdbtypes.h"
31 #include "target.h"
32 #include "arch-utils.h"
33 #include "regcache.h"
34 #include "osabi.h"
35 #include "riscv-tdep.h"
36 #include "block.h"
37 #include "reggroups.h"
38 #include "opcode/riscv.h"
39 #include "elf/riscv.h"
40 #include "elf-bfd.h"
41 #include "symcat.h"
42 #include "dis-asm.h"
43 #include "frame-unwind.h"
44 #include "frame-base.h"
45 #include "trad-frame.h"
46 #include "infcall.h"
47 #include "floatformat.h"
48 #include "remote.h"
49 #include "target-descriptions.h"
50 #include "dwarf2-frame.h"
51 #include "user-regs.h"
52 #include "valprint.h"
53 #include "common-defs.h"
54 #include "opcode/riscv-opc.h"
55 #include "cli/cli-decode.h"
56 #include "observable.h"
57 #include "prologue-value.h"
58 #include "arch/riscv.h"
59
60 /* The stack must be 16-byte aligned.  */
61 #define SP_ALIGNMENT 16
62
63 /* The biggest alignment that the target supports.  */
64 #define BIGGEST_ALIGNMENT 16
65
66 /* Define a series of is_XXX_insn functions to check if the value INSN
67    is an instance of instruction XXX.  */
68 #define DECLARE_INSN(INSN_NAME, INSN_MATCH, INSN_MASK) \
69 static inline bool is_ ## INSN_NAME ## _insn (long insn) \
70 { \
71   return (insn & INSN_MASK) == INSN_MATCH; \
72 }
73 #include "opcode/riscv-opc.h"
74 #undef DECLARE_INSN
75
76 /* Cached information about a frame.  */
77
78 struct riscv_unwind_cache
79 {
80   /* The register from which we can calculate the frame base.  This is
81      usually $sp or $fp.  */
82   int frame_base_reg;
83
84   /* The offset from the current value in register FRAME_BASE_REG to the
85      actual frame base address.  */
86   int frame_base_offset;
87
88   /* Information about previous register values.  */
89   struct trad_frame_saved_reg *regs;
90
91   /* The id for this frame.  */
92   struct frame_id this_id;
93
94   /* The base (stack) address for this frame.  This is the stack pointer
95      value on entry to this frame before any adjustments are made.  */
96   CORE_ADDR frame_base;
97 };
98
99 /* RISC-V specific register group for CSRs.  */
100
101 static reggroup *csr_reggroup = NULL;
102
103 /* A set of registers that we expect to find in a tdesc_feature.  These
104    are use in RISCV_GDBARCH_INIT when processing the target description.  */
105
106 struct riscv_register_feature
107 {
108   /* Information for a single register.  */
109   struct register_info
110   {
111     /* The GDB register number for this register.  */
112     int regnum;
113
114     /* List of names for this register.  The first name in this list is the
115        preferred name, the name GDB should use when describing this
116        register.  */
117     std::vector <const char *> names;
118
119     /* When true this register is required in this feature set.  */
120     bool required_p;
121   };
122
123   /* The name for this feature.  This is the name used to find this feature
124      within the target description.  */
125   const char *name;
126
127   /* List of all the registers that we expect that we might find in this
128      register set.  */
129   std::vector <struct register_info> registers;
130 };
131
132 /* The general x-registers feature set.  */
133
134 static const struct riscv_register_feature riscv_xreg_feature =
135 {
136  "org.gnu.gdb.riscv.cpu",
137  {
138    { RISCV_ZERO_REGNUM + 0, { "zero", "x0" }, true },
139    { RISCV_ZERO_REGNUM + 1, { "ra", "x1" }, true },
140    { RISCV_ZERO_REGNUM + 2, { "sp", "x2" }, true },
141    { RISCV_ZERO_REGNUM + 3, { "gp", "x3" }, true },
142    { RISCV_ZERO_REGNUM + 4, { "tp", "x4" }, true },
143    { RISCV_ZERO_REGNUM + 5, { "t0", "x5" }, true },
144    { RISCV_ZERO_REGNUM + 6, { "t1", "x6" }, true },
145    { RISCV_ZERO_REGNUM + 7, { "t2", "x7" }, true },
146    { RISCV_ZERO_REGNUM + 8, { "fp", "x8", "s0" }, true },
147    { RISCV_ZERO_REGNUM + 9, { "s1", "x9" }, true },
148    { RISCV_ZERO_REGNUM + 10, { "a0", "x10" }, true },
149    { RISCV_ZERO_REGNUM + 11, { "a1", "x11" }, true },
150    { RISCV_ZERO_REGNUM + 12, { "a2", "x12" }, true },
151    { RISCV_ZERO_REGNUM + 13, { "a3", "x13" }, true },
152    { RISCV_ZERO_REGNUM + 14, { "a4", "x14" }, true },
153    { RISCV_ZERO_REGNUM + 15, { "a5", "x15" }, true },
154    { RISCV_ZERO_REGNUM + 16, { "a6", "x16" }, true },
155    { RISCV_ZERO_REGNUM + 17, { "a7", "x17" }, true },
156    { RISCV_ZERO_REGNUM + 18, { "s2", "x18" }, true },
157    { RISCV_ZERO_REGNUM + 19, { "s3", "x19" }, true },
158    { RISCV_ZERO_REGNUM + 20, { "s4", "x20" }, true },
159    { RISCV_ZERO_REGNUM + 21, { "s5", "x21" }, true },
160    { RISCV_ZERO_REGNUM + 22, { "s6", "x22" }, true },
161    { RISCV_ZERO_REGNUM + 23, { "s7", "x23" }, true },
162    { RISCV_ZERO_REGNUM + 24, { "s8", "x24" }, true },
163    { RISCV_ZERO_REGNUM + 25, { "s9", "x25" }, true },
164    { RISCV_ZERO_REGNUM + 26, { "s10", "x26" }, true },
165    { RISCV_ZERO_REGNUM + 27, { "s11", "x27" }, true },
166    { RISCV_ZERO_REGNUM + 28, { "t3", "x28" }, true },
167    { RISCV_ZERO_REGNUM + 29, { "t4", "x29" }, true },
168    { RISCV_ZERO_REGNUM + 30, { "t5", "x30" }, true },
169    { RISCV_ZERO_REGNUM + 31, { "t6", "x31" }, true },
170    { RISCV_ZERO_REGNUM + 32, { "pc" }, true }
171  }
172 };
173
174 /* The f-registers feature set.  */
175
176 static const struct riscv_register_feature riscv_freg_feature =
177 {
178  "org.gnu.gdb.riscv.fpu",
179  {
180    { RISCV_FIRST_FP_REGNUM + 0, { "ft0", "f0" }, true },
181    { RISCV_FIRST_FP_REGNUM + 1, { "ft1", "f1" }, true },
182    { RISCV_FIRST_FP_REGNUM + 2, { "ft2", "f2" }, true },
183    { RISCV_FIRST_FP_REGNUM + 3, { "ft3", "f3" }, true },
184    { RISCV_FIRST_FP_REGNUM + 4, { "ft4", "f4" }, true },
185    { RISCV_FIRST_FP_REGNUM + 5, { "ft5", "f5" }, true },
186    { RISCV_FIRST_FP_REGNUM + 6, { "ft6", "f6" }, true },
187    { RISCV_FIRST_FP_REGNUM + 7, { "ft7", "f7" }, true },
188    { RISCV_FIRST_FP_REGNUM + 8, { "fs0", "f8", "s0" }, true },
189    { RISCV_FIRST_FP_REGNUM + 9, { "fs1", "f9" }, true },
190    { RISCV_FIRST_FP_REGNUM + 10, { "fa0", "f10" }, true },
191    { RISCV_FIRST_FP_REGNUM + 11, { "fa1", "f11" }, true },
192    { RISCV_FIRST_FP_REGNUM + 12, { "fa2", "f12" }, true },
193    { RISCV_FIRST_FP_REGNUM + 13, { "fa3", "f13" }, true },
194    { RISCV_FIRST_FP_REGNUM + 14, { "fa4", "f14" }, true },
195    { RISCV_FIRST_FP_REGNUM + 15, { "fa5", "f15" }, true },
196    { RISCV_FIRST_FP_REGNUM + 16, { "fa6", "f16" }, true },
197    { RISCV_FIRST_FP_REGNUM + 17, { "fa7", "f17" }, true },
198    { RISCV_FIRST_FP_REGNUM + 18, { "fs2", "f18" }, true },
199    { RISCV_FIRST_FP_REGNUM + 19, { "fs3", "f19" }, true },
200    { RISCV_FIRST_FP_REGNUM + 20, { "fs4", "f20" }, true },
201    { RISCV_FIRST_FP_REGNUM + 21, { "fs5", "f21" }, true },
202    { RISCV_FIRST_FP_REGNUM + 22, { "fs6", "f22" }, true },
203    { RISCV_FIRST_FP_REGNUM + 23, { "fs7", "f23" }, true },
204    { RISCV_FIRST_FP_REGNUM + 24, { "fs8", "f24" }, true },
205    { RISCV_FIRST_FP_REGNUM + 25, { "fs9", "f25" }, true },
206    { RISCV_FIRST_FP_REGNUM + 26, { "fs10", "f26" }, true },
207    { RISCV_FIRST_FP_REGNUM + 27, { "fs11", "f27" }, true },
208    { RISCV_FIRST_FP_REGNUM + 28, { "ft8", "f28" }, true },
209    { RISCV_FIRST_FP_REGNUM + 29, { "ft9", "f29" }, true },
210    { RISCV_FIRST_FP_REGNUM + 30, { "ft10", "f30" }, true },
211    { RISCV_FIRST_FP_REGNUM + 31, { "ft11", "f31" }, true },
212
213    { RISCV_CSR_FFLAGS_REGNUM, { "fflags" }, true },
214    { RISCV_CSR_FRM_REGNUM, { "frm" }, true },
215    { RISCV_CSR_FCSR_REGNUM, { "fcsr" }, true },
216
217  }
218 };
219
220 /* Set of virtual registers.  These are not physical registers on the
221    hardware, but might be available from the target.  These are not pseudo
222    registers, reading these really does result in a register read from the
223    target, it is just that there might not be a physical register backing
224    the result.  */
225
226 static const struct riscv_register_feature riscv_virtual_feature =
227 {
228  "org.gnu.gdb.riscv.virtual",
229  {
230    { RISCV_PRIV_REGNUM, { "priv" }, false }
231  }
232 };
233
234 /* Feature set for CSRs.  This set is NOT constant as the register names
235    list for each register is not complete.  The aliases are computed
236    during RISCV_CREATE_CSR_ALIASES.  */
237
238 static struct riscv_register_feature riscv_csr_feature =
239 {
240  "org.gnu.gdb.riscv.csr",
241  {
242 #define DECLARE_CSR(NAME,VALUE) \
243   { RISCV_ ## VALUE ## _REGNUM, { # NAME }, false },
244 #include "opcode/riscv-opc.h"
245 #undef DECLARE_CSR
246  }
247 };
248
249 /* Complete RISCV_CSR_FEATURE, building the CSR alias names and adding them
250    to the name list for each register.  */
251
252 static void
253 riscv_create_csr_aliases ()
254 {
255   for (auto &reg : riscv_csr_feature.registers)
256     {
257       int csr_num = reg.regnum - RISCV_FIRST_CSR_REGNUM;
258       const char *alias = xstrprintf ("csr%d", csr_num);
259       reg.names.push_back (alias);
260     }
261 }
262
263 /* Controls whether we place compressed breakpoints or not.  When in auto
264    mode GDB tries to determine if the target supports compressed
265    breakpoints, and uses them if it does.  */
266
267 static enum auto_boolean use_compressed_breakpoints;
268
269 /* The show callback for 'show riscv use-compressed-breakpoints'.  */
270
271 static void
272 show_use_compressed_breakpoints (struct ui_file *file, int from_tty,
273                                  struct cmd_list_element *c,
274                                  const char *value)
275 {
276   fprintf_filtered (file,
277                     _("Debugger's use of compressed breakpoints is set "
278                       "to %s.\n"), value);
279 }
280
281 /* The set and show lists for 'set riscv' and 'show riscv' prefixes.  */
282
283 static struct cmd_list_element *setriscvcmdlist = NULL;
284 static struct cmd_list_element *showriscvcmdlist = NULL;
285
286 /* The show callback for the 'show riscv' prefix command.  */
287
288 static void
289 show_riscv_command (const char *args, int from_tty)
290 {
291   help_list (showriscvcmdlist, "show riscv ", all_commands, gdb_stdout);
292 }
293
294 /* The set callback for the 'set riscv' prefix command.  */
295
296 static void
297 set_riscv_command (const char *args, int from_tty)
298 {
299   printf_unfiltered
300     (_("\"set riscv\" must be followed by an appropriate subcommand.\n"));
301   help_list (setriscvcmdlist, "set riscv ", all_commands, gdb_stdout);
302 }
303
304 /* The set and show lists for 'set riscv' and 'show riscv' prefixes.  */
305
306 static struct cmd_list_element *setdebugriscvcmdlist = NULL;
307 static struct cmd_list_element *showdebugriscvcmdlist = NULL;
308
309 /* The show callback for the 'show debug riscv' prefix command.  */
310
311 static void
312 show_debug_riscv_command (const char *args, int from_tty)
313 {
314   help_list (showdebugriscvcmdlist, "show debug riscv ", all_commands, gdb_stdout);
315 }
316
317 /* The set callback for the 'set debug riscv' prefix command.  */
318
319 static void
320 set_debug_riscv_command (const char *args, int from_tty)
321 {
322   printf_unfiltered
323     (_("\"set debug riscv\" must be followed by an appropriate subcommand.\n"));
324   help_list (setdebugriscvcmdlist, "set debug riscv ", all_commands, gdb_stdout);
325 }
326
327 /* The show callback for all 'show debug riscv VARNAME' variables.  */
328
329 static void
330 show_riscv_debug_variable (struct ui_file *file, int from_tty,
331                            struct cmd_list_element *c,
332                            const char *value)
333 {
334   fprintf_filtered (file,
335                     _("RiscV debug variable `%s' is set to: %s\n"),
336                     c->name, value);
337 }
338
339 /* When this is set to non-zero debugging information about breakpoint
340    kinds will be printed.  */
341
342 static unsigned int riscv_debug_breakpoints = 0;
343
344 /* When this is set to non-zero debugging information about inferior calls
345    will be printed.  */
346
347 static unsigned int riscv_debug_infcall = 0;
348
349 /* When this is set to non-zero debugging information about stack unwinding
350    will be printed.  */
351
352 static unsigned int riscv_debug_unwinder = 0;
353
354 /* When this is set to non-zero debugging information about gdbarch
355    initialisation will be printed.  */
356
357 static unsigned int riscv_debug_gdbarch = 0;
358
359 /* See riscv-tdep.h.  */
360
361 int
362 riscv_isa_xlen (struct gdbarch *gdbarch)
363 {
364   return gdbarch_tdep (gdbarch)->features.xlen;
365 }
366
367 /* See riscv-tdep.h.  */
368
369 int
370 riscv_isa_flen (struct gdbarch *gdbarch)
371 {
372   return gdbarch_tdep (gdbarch)->features.flen;
373 }
374
375 /* Return true if the target for GDBARCH has floating point hardware.  */
376
377 static bool
378 riscv_has_fp_regs (struct gdbarch *gdbarch)
379 {
380   return (riscv_isa_flen (gdbarch) > 0);
381 }
382
383 /* Return true if GDBARCH is using any of the floating point hardware ABIs.  */
384
385 static bool
386 riscv_has_fp_abi (struct gdbarch *gdbarch)
387 {
388   return gdbarch_tdep (gdbarch)->features.hw_float_abi;
389 }
390
391 /* Return true if REGNO is a floating pointer register.  */
392
393 static bool
394 riscv_is_fp_regno_p (int regno)
395 {
396   return (regno >= RISCV_FIRST_FP_REGNUM
397           && regno <= RISCV_LAST_FP_REGNUM);
398 }
399
400 /* Implement the breakpoint_kind_from_pc gdbarch method.  */
401
402 static int
403 riscv_breakpoint_kind_from_pc (struct gdbarch *gdbarch, CORE_ADDR *pcptr)
404 {
405   if (use_compressed_breakpoints == AUTO_BOOLEAN_AUTO)
406     {
407       bool unaligned_p = false;
408       gdb_byte buf[1];
409
410       /* Some targets don't support unaligned reads.  The address can only
411          be unaligned if the C extension is supported.  So it is safe to
412          use a compressed breakpoint in this case.  */
413       if (*pcptr & 0x2)
414         unaligned_p = true;
415       else
416         {
417           /* Read the opcode byte to determine the instruction length.  */
418           read_code (*pcptr, buf, 1);
419         }
420
421       if (riscv_debug_breakpoints)
422         {
423           const char *bp = (unaligned_p || riscv_insn_length (buf[0]) == 2
424                             ? "C.EBREAK" : "EBREAK");
425
426           fprintf_unfiltered (gdb_stdlog, "Using %s for breakpoint at %s ",
427                               bp, paddress (gdbarch, *pcptr));
428           if (unaligned_p)
429             fprintf_unfiltered (gdb_stdlog, "(unaligned address)\n");
430           else
431             fprintf_unfiltered (gdb_stdlog, "(instruction length %d)\n",
432                                 riscv_insn_length (buf[0]));
433         }
434       if (unaligned_p || riscv_insn_length (buf[0]) == 2)
435         return 2;
436       else
437         return 4;
438     }
439   else if (use_compressed_breakpoints == AUTO_BOOLEAN_TRUE)
440     return 2;
441   else
442     return 4;
443 }
444
445 /* Implement the sw_breakpoint_from_kind gdbarch method.  */
446
447 static const gdb_byte *
448 riscv_sw_breakpoint_from_kind (struct gdbarch *gdbarch, int kind, int *size)
449 {
450   static const gdb_byte ebreak[] = { 0x73, 0x00, 0x10, 0x00, };
451   static const gdb_byte c_ebreak[] = { 0x02, 0x90 };
452
453   *size = kind;
454   switch (kind)
455     {
456     case 2:
457       return c_ebreak;
458     case 4:
459       return ebreak;
460     default:
461       gdb_assert_not_reached (_("unhandled breakpoint kind"));
462     }
463 }
464
465 /* Callback function for user_reg_add.  */
466
467 static struct value *
468 value_of_riscv_user_reg (struct frame_info *frame, const void *baton)
469 {
470   const int *reg_p = (const int *) baton;
471   return value_of_register (*reg_p, frame);
472 }
473
474 /* Implement the register_name gdbarch method.  This is used instead of
475    the function supplied by calling TDESC_USE_REGISTERS so that we can
476    ensure the preferred names are offered.  */
477
478 static const char *
479 riscv_register_name (struct gdbarch *gdbarch, int regnum)
480 {
481   /* Lookup the name through the target description.  If we get back NULL
482      then this is an unknown register.  If we do get a name back then we
483      look up the registers preferred name below.  */
484   const char *name = tdesc_register_name (gdbarch, regnum);
485   if (name == NULL || name[0] == '\0')
486     return NULL;
487
488   if (regnum >= RISCV_ZERO_REGNUM && regnum < RISCV_FIRST_FP_REGNUM)
489     {
490       gdb_assert (regnum < riscv_xreg_feature.registers.size ());
491       return riscv_xreg_feature.registers[regnum].names[0];
492     }
493
494   if (regnum >= RISCV_FIRST_FP_REGNUM && regnum <= RISCV_LAST_FP_REGNUM)
495     {
496       if (riscv_has_fp_regs (gdbarch))
497         {
498           regnum -= RISCV_FIRST_FP_REGNUM;
499           gdb_assert (regnum < riscv_freg_feature.registers.size ());
500           return riscv_freg_feature.registers[regnum].names[0];
501         }
502       else
503         return NULL;
504     }
505
506   /* Check that there's no gap between the set of registers handled above,
507      and the set of registers handled next.  */
508   gdb_assert ((RISCV_LAST_FP_REGNUM + 1) == RISCV_FIRST_CSR_REGNUM);
509
510   if (regnum >= RISCV_FIRST_CSR_REGNUM && regnum <= RISCV_LAST_CSR_REGNUM)
511     {
512 #define DECLARE_CSR(NAME,VALUE) \
513       case RISCV_ ## VALUE ## _REGNUM: return # NAME;
514
515       switch (regnum)
516         {
517 #include "opcode/riscv-opc.h"
518         }
519 #undef DECLARE_CSR
520     }
521
522   if (regnum == RISCV_PRIV_REGNUM)
523     return "priv";
524
525   /* It is possible that that the target provides some registers that GDB
526      is unaware of, in that case just return the NAME from the target
527      description.  */
528   return name;
529 }
530
531 /* Construct a type for 64-bit FP registers.  */
532
533 static struct type *
534 riscv_fpreg_d_type (struct gdbarch *gdbarch)
535 {
536   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
537
538   if (tdep->riscv_fpreg_d_type == nullptr)
539     {
540       const struct builtin_type *bt = builtin_type (gdbarch);
541
542       /* The type we're building is this: */
543 #if 0
544       union __gdb_builtin_type_fpreg_d
545       {
546         float f;
547         double d;
548       };
549 #endif
550
551       struct type *t;
552
553       t = arch_composite_type (gdbarch,
554                                "__gdb_builtin_type_fpreg_d", TYPE_CODE_UNION);
555       append_composite_type_field (t, "float", bt->builtin_float);
556       append_composite_type_field (t, "double", bt->builtin_double);
557       TYPE_VECTOR (t) = 1;
558       TYPE_NAME (t) = "builtin_type_fpreg_d";
559       tdep->riscv_fpreg_d_type = t;
560     }
561
562   return tdep->riscv_fpreg_d_type;
563 }
564
565 /* Implement the register_type gdbarch method.  This is installed as an
566    for the override setup by TDESC_USE_REGISTERS, for most registers we
567    delegate the type choice to the target description, but for a few
568    registers we try to improve the types if the target description has
569    taken a simplistic approach.  */
570
571 static struct type *
572 riscv_register_type (struct gdbarch *gdbarch, int regnum)
573 {
574   struct type *type = tdesc_register_type (gdbarch, regnum);
575   int xlen = riscv_isa_xlen (gdbarch);
576
577   /* We want to perform some specific type "fixes" in cases where we feel
578      that we really can do better than the target description.  For all
579      other cases we just return what the target description says.  */
580   if (riscv_is_fp_regno_p (regnum))
581     {
582       /* This spots the case for RV64 where the double is defined as
583          either 'ieee_double' or 'float' (which is the generic name that
584          converts to 'double' on 64-bit).  In these cases its better to
585          present the registers using a union type.  */
586       int flen = riscv_isa_flen (gdbarch);
587       if (flen == 8
588           && TYPE_CODE (type) == TYPE_CODE_FLT
589           && TYPE_LENGTH (type) == flen
590           && (strcmp (TYPE_NAME (type), "builtin_type_ieee_double") == 0
591               || strcmp (TYPE_NAME (type), "double") == 0))
592         type = riscv_fpreg_d_type (gdbarch);
593     }
594
595   if ((regnum == gdbarch_pc_regnum (gdbarch)
596        || regnum == RISCV_RA_REGNUM
597        || regnum == RISCV_FP_REGNUM
598        || regnum == RISCV_SP_REGNUM
599        || regnum == RISCV_GP_REGNUM
600        || regnum == RISCV_TP_REGNUM)
601       && TYPE_CODE (type) == TYPE_CODE_INT
602       && TYPE_LENGTH (type) == xlen)
603     {
604       /* This spots the case where some interesting registers are defined
605          as simple integers of the expected size, we force these registers
606          to be pointers as we believe that is more useful.  */
607       if (regnum == gdbarch_pc_regnum (gdbarch)
608           || regnum == RISCV_RA_REGNUM)
609         type = builtin_type (gdbarch)->builtin_func_ptr;
610       else if (regnum == RISCV_FP_REGNUM
611                || regnum == RISCV_SP_REGNUM
612                || regnum == RISCV_GP_REGNUM
613                || regnum == RISCV_TP_REGNUM)
614         type = builtin_type (gdbarch)->builtin_data_ptr;
615     }
616
617   return type;
618 }
619
620 /* Helper for riscv_print_registers_info, prints info for a single register
621    REGNUM.  */
622
623 static void
624 riscv_print_one_register_info (struct gdbarch *gdbarch,
625                                struct ui_file *file,
626                                struct frame_info *frame,
627                                int regnum)
628 {
629   const char *name = gdbarch_register_name (gdbarch, regnum);
630   struct value *val;
631   struct type *regtype;
632   int print_raw_format;
633   enum tab_stops { value_column_1 = 15 };
634
635   fputs_filtered (name, file);
636   print_spaces_filtered (value_column_1 - strlen (name), file);
637
638   TRY
639     {
640       val = value_of_register (regnum, frame);
641       regtype = value_type (val);
642     }
643   CATCH (ex, RETURN_MASK_ERROR)
644     {
645       /* Handle failure to read a register without interrupting the entire
646          'info registers' flow.  */
647       fprintf_filtered (file, "%s\n", ex.message);
648       return;
649     }
650   END_CATCH
651
652   print_raw_format = (value_entirely_available (val)
653                       && !value_optimized_out (val));
654
655   if (TYPE_CODE (regtype) == TYPE_CODE_FLT
656       || (TYPE_CODE (regtype) == TYPE_CODE_UNION
657           && TYPE_NFIELDS (regtype) == 2
658           && TYPE_CODE (TYPE_FIELD_TYPE (regtype, 0)) == TYPE_CODE_FLT
659           && TYPE_CODE (TYPE_FIELD_TYPE (regtype, 1)) == TYPE_CODE_FLT)
660       || (TYPE_CODE (regtype) == TYPE_CODE_UNION
661           && TYPE_NFIELDS (regtype) == 3
662           && TYPE_CODE (TYPE_FIELD_TYPE (regtype, 0)) == TYPE_CODE_FLT
663           && TYPE_CODE (TYPE_FIELD_TYPE (regtype, 1)) == TYPE_CODE_FLT
664           && TYPE_CODE (TYPE_FIELD_TYPE (regtype, 2)) == TYPE_CODE_FLT))
665     {
666       struct value_print_options opts;
667       const gdb_byte *valaddr = value_contents_for_printing (val);
668       enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (regtype));
669
670       get_user_print_options (&opts);
671       opts.deref_ref = 1;
672
673       val_print (regtype,
674                  value_embedded_offset (val), 0,
675                  file, 0, val, &opts, current_language);
676
677       if (print_raw_format)
678         {
679           fprintf_filtered (file, "\t(raw ");
680           print_hex_chars (file, valaddr, TYPE_LENGTH (regtype), byte_order,
681                            true);
682           fprintf_filtered (file, ")");
683         }
684     }
685   else
686     {
687       struct value_print_options opts;
688
689       /* Print the register in hex.  */
690       get_formatted_print_options (&opts, 'x');
691       opts.deref_ref = 1;
692       val_print (regtype,
693                  value_embedded_offset (val), 0,
694                  file, 0, val, &opts, current_language);
695
696       if (print_raw_format)
697         {
698           if (regnum == RISCV_CSR_MSTATUS_REGNUM)
699             {
700               LONGEST d;
701               int size = register_size (gdbarch, regnum);
702               unsigned xlen;
703
704               d = value_as_long (val);
705               xlen = size * 4;
706               fprintf_filtered (file,
707                                 "\tSD:%X VM:%02X MXR:%X PUM:%X MPRV:%X XS:%X "
708                                 "FS:%X MPP:%x HPP:%X SPP:%X MPIE:%X HPIE:%X "
709                                 "SPIE:%X UPIE:%X MIE:%X HIE:%X SIE:%X UIE:%X",
710                                 (int) ((d >> (xlen - 1)) & 0x1),
711                                 (int) ((d >> 24) & 0x1f),
712                                 (int) ((d >> 19) & 0x1),
713                                 (int) ((d >> 18) & 0x1),
714                                 (int) ((d >> 17) & 0x1),
715                                 (int) ((d >> 15) & 0x3),
716                                 (int) ((d >> 13) & 0x3),
717                                 (int) ((d >> 11) & 0x3),
718                                 (int) ((d >> 9) & 0x3),
719                                 (int) ((d >> 8) & 0x1),
720                                 (int) ((d >> 7) & 0x1),
721                                 (int) ((d >> 6) & 0x1),
722                                 (int) ((d >> 5) & 0x1),
723                                 (int) ((d >> 4) & 0x1),
724                                 (int) ((d >> 3) & 0x1),
725                                 (int) ((d >> 2) & 0x1),
726                                 (int) ((d >> 1) & 0x1),
727                                 (int) ((d >> 0) & 0x1));
728             }
729           else if (regnum == RISCV_CSR_MISA_REGNUM)
730             {
731               int base;
732               unsigned xlen, i;
733               LONGEST d;
734
735               d = value_as_long (val);
736               base = d >> 30;
737               xlen = 16;
738
739               for (; base > 0; base--)
740                 xlen *= 2;
741               fprintf_filtered (file, "\tRV%d", xlen);
742
743               for (i = 0; i < 26; i++)
744                 {
745                   if (d & (1 << i))
746                     fprintf_filtered (file, "%c", 'A' + i);
747                 }
748             }
749           else if (regnum == RISCV_CSR_FCSR_REGNUM
750                    || regnum == RISCV_CSR_FFLAGS_REGNUM
751                    || regnum == RISCV_CSR_FRM_REGNUM)
752             {
753               LONGEST d;
754
755               d = value_as_long (val);
756
757               fprintf_filtered (file, "\t");
758               if (regnum != RISCV_CSR_FRM_REGNUM)
759                 fprintf_filtered (file,
760                                   "RD:%01X NV:%d DZ:%d OF:%d UF:%d NX:%d",
761                                   (int) ((d >> 5) & 0x7),
762                                   (int) ((d >> 4) & 0x1),
763                                   (int) ((d >> 3) & 0x1),
764                                   (int) ((d >> 2) & 0x1),
765                                   (int) ((d >> 1) & 0x1),
766                                   (int) ((d >> 0) & 0x1));
767
768               if (regnum != RISCV_CSR_FFLAGS_REGNUM)
769                 {
770                   static const char * const sfrm[] =
771                     {
772                       "RNE (round to nearest; ties to even)",
773                       "RTZ (Round towards zero)",
774                       "RDN (Round down towards -INF)",
775                       "RUP (Round up towards +INF)",
776                       "RMM (Round to nearest; ties to max magnitude)",
777                       "INVALID[5]",
778                       "INVALID[6]",
779                       "dynamic rounding mode",
780                     };
781                   int frm = ((regnum == RISCV_CSR_FCSR_REGNUM)
782                              ? (d >> 5) : d) & 0x3;
783
784                   fprintf_filtered (file, "%sFRM:%i [%s]",
785                                     (regnum == RISCV_CSR_FCSR_REGNUM
786                                      ? " " : ""),
787                                     frm, sfrm[frm]);
788                 }
789             }
790           else if (regnum == RISCV_PRIV_REGNUM)
791             {
792               LONGEST d;
793               uint8_t priv;
794
795               d = value_as_long (val);
796               priv = d & 0xff;
797
798               if (priv < 4)
799                 {
800                   static const char * const sprv[] =
801                     {
802                       "User/Application",
803                       "Supervisor",
804                       "Hypervisor",
805                       "Machine"
806                     };
807                   fprintf_filtered (file, "\tprv:%d [%s]",
808                                     priv, sprv[priv]);
809                 }
810               else
811                 fprintf_filtered (file, "\tprv:%d [INVALID]", priv);
812             }
813           else
814             {
815               /* If not a vector register, print it also according to its
816                  natural format.  */
817               if (TYPE_VECTOR (regtype) == 0)
818                 {
819                   get_user_print_options (&opts);
820                   opts.deref_ref = 1;
821                   fprintf_filtered (file, "\t");
822                   val_print (regtype,
823                              value_embedded_offset (val), 0,
824                              file, 0, val, &opts, current_language);
825                 }
826             }
827         }
828     }
829   fprintf_filtered (file, "\n");
830 }
831
832 /* Return true if REGNUM is a valid CSR register.  The CSR register space
833    is sparsely populated, so not every number is a named CSR.  */
834
835 static bool
836 riscv_is_regnum_a_named_csr (int regnum)
837 {
838   gdb_assert (regnum >= RISCV_FIRST_CSR_REGNUM
839               && regnum <= RISCV_LAST_CSR_REGNUM);
840
841   switch (regnum)
842     {
843 #define DECLARE_CSR(name, num) case RISCV_ ## num ## _REGNUM:
844 #include "opcode/riscv-opc.h"
845 #undef DECLARE_CSR
846       return true;
847
848     default:
849       return false;
850     }
851 }
852
853 /* Implement the register_reggroup_p gdbarch method.  Is REGNUM a member
854    of REGGROUP?  */
855
856 static int
857 riscv_register_reggroup_p (struct gdbarch  *gdbarch, int regnum,
858                            struct reggroup *reggroup)
859 {
860   /* Used by 'info registers' and 'info registers <groupname>'.  */
861
862   if (gdbarch_register_name (gdbarch, regnum) == NULL
863       || gdbarch_register_name (gdbarch, regnum)[0] == '\0')
864     return 0;
865
866   if (regnum > RISCV_LAST_REGNUM)
867     {
868       int ret = tdesc_register_in_reggroup_p (gdbarch, regnum, reggroup);
869       if (ret != -1)
870         return ret;
871
872       return default_register_reggroup_p (gdbarch, regnum, reggroup);
873     }
874
875   if (reggroup == all_reggroup)
876     {
877       if (regnum < RISCV_FIRST_CSR_REGNUM || regnum == RISCV_PRIV_REGNUM)
878         return 1;
879       if (riscv_is_regnum_a_named_csr (regnum))
880         return 1;
881       return 0;
882     }
883   else if (reggroup == float_reggroup)
884     return (riscv_is_fp_regno_p (regnum)
885             || regnum == RISCV_CSR_FCSR_REGNUM
886             || regnum == RISCV_CSR_FFLAGS_REGNUM
887             || regnum == RISCV_CSR_FRM_REGNUM);
888   else if (reggroup == general_reggroup)
889     return regnum < RISCV_FIRST_FP_REGNUM;
890   else if (reggroup == restore_reggroup || reggroup == save_reggroup)
891     {
892       if (riscv_has_fp_regs (gdbarch))
893         return regnum <= RISCV_LAST_FP_REGNUM;
894       else
895         return regnum < RISCV_FIRST_FP_REGNUM;
896     }
897   else if (reggroup == system_reggroup || reggroup == csr_reggroup)
898     {
899       if (regnum == RISCV_PRIV_REGNUM)
900         return 1;
901       if (regnum < RISCV_FIRST_CSR_REGNUM || regnum > RISCV_LAST_CSR_REGNUM)
902         return 0;
903       if (riscv_is_regnum_a_named_csr (regnum))
904         return 1;
905       return 0;
906     }
907   else if (reggroup == vector_reggroup)
908     return 0;
909   else
910     return 0;
911 }
912
913 /* Implement the print_registers_info gdbarch method.  This is used by
914    'info registers' and 'info all-registers'.  */
915
916 static void
917 riscv_print_registers_info (struct gdbarch *gdbarch,
918                             struct ui_file *file,
919                             struct frame_info *frame,
920                             int regnum, int print_all)
921 {
922   if (regnum != -1)
923     {
924       /* Print one specified register.  */
925       if (gdbarch_register_name (gdbarch, regnum) == NULL
926           || *(gdbarch_register_name (gdbarch, regnum)) == '\0')
927         error (_("Not a valid register for the current processor type"));
928       riscv_print_one_register_info (gdbarch, file, frame, regnum);
929     }
930   else
931     {
932       struct reggroup *reggroup;
933
934       if (print_all)
935         reggroup = all_reggroup;
936       else
937         reggroup = general_reggroup;
938
939       for (regnum = 0; regnum <= RISCV_LAST_REGNUM; ++regnum)
940         {
941           /* Zero never changes, so might as well hide by default.  */
942           if (regnum == RISCV_ZERO_REGNUM && !print_all)
943             continue;
944
945           /* Registers with no name are not valid on this ISA.  */
946           if (gdbarch_register_name (gdbarch, regnum) == NULL
947               || *(gdbarch_register_name (gdbarch, regnum)) == '\0')
948             continue;
949
950           /* Is the register in the group we're interested in?  */
951           if (!gdbarch_register_reggroup_p (gdbarch, regnum, reggroup))
952             continue;
953
954           riscv_print_one_register_info (gdbarch, file, frame, regnum);
955         }
956     }
957 }
958
959 /* Class that handles one decoded RiscV instruction.  */
960
961 class riscv_insn
962 {
963 public:
964
965   /* Enum of all the opcodes that GDB cares about during the prologue scan.  */
966   enum opcode
967     {
968       /* Unknown value is used at initialisation time.  */
969       UNKNOWN = 0,
970
971       /* These instructions are all the ones we are interested in during the
972          prologue scan.  */
973       ADD,
974       ADDI,
975       ADDIW,
976       ADDW,
977       AUIPC,
978       LUI,
979       SD,
980       SW,
981       /* These are needed for software breakopint support.  */
982       JAL,
983       JALR,
984       BEQ,
985       BNE,
986       BLT,
987       BGE,
988       BLTU,
989       BGEU,
990       /* These are needed for stepping over atomic sequences.  */
991       LR,
992       SC,
993
994       /* Other instructions are not interesting during the prologue scan, and
995          are ignored.  */
996       OTHER
997     };
998
999   riscv_insn ()
1000     : m_length (0),
1001       m_opcode (OTHER),
1002       m_rd (0),
1003       m_rs1 (0),
1004       m_rs2 (0)
1005   {
1006     /* Nothing.  */
1007   }
1008
1009   void decode (struct gdbarch *gdbarch, CORE_ADDR pc);
1010
1011   /* Get the length of the instruction in bytes.  */
1012   int length () const
1013   { return m_length; }
1014
1015   /* Get the opcode for this instruction.  */
1016   enum opcode opcode () const
1017   { return m_opcode; }
1018
1019   /* Get destination register field for this instruction.  This is only
1020      valid if the OPCODE implies there is such a field for this
1021      instruction.  */
1022   int rd () const
1023   { return m_rd; }
1024
1025   /* Get the RS1 register field for this instruction.  This is only valid
1026      if the OPCODE implies there is such a field for this instruction.  */
1027   int rs1 () const
1028   { return m_rs1; }
1029
1030   /* Get the RS2 register field for this instruction.  This is only valid
1031      if the OPCODE implies there is such a field for this instruction.  */
1032   int rs2 () const
1033   { return m_rs2; }
1034
1035   /* Get the immediate for this instruction in signed form.  This is only
1036      valid if the OPCODE implies there is such a field for this
1037      instruction.  */
1038   int imm_signed () const
1039   { return m_imm.s; }
1040
1041 private:
1042
1043   /* Extract 5 bit register field at OFFSET from instruction OPCODE.  */
1044   int decode_register_index (unsigned long opcode, int offset)
1045   {
1046     return (opcode >> offset) & 0x1F;
1047   }
1048
1049   /* Extract 5 bit register field at OFFSET from instruction OPCODE.  */
1050   int decode_register_index_short (unsigned long opcode, int offset)
1051   {
1052     return ((opcode >> offset) & 0x7) + 8;
1053   }
1054
1055   /* Helper for DECODE, decode 32-bit R-type instruction.  */
1056   void decode_r_type_insn (enum opcode opcode, ULONGEST ival)
1057   {
1058     m_opcode = opcode;
1059     m_rd = decode_register_index (ival, OP_SH_RD);
1060     m_rs1 = decode_register_index (ival, OP_SH_RS1);
1061     m_rs2 = decode_register_index (ival, OP_SH_RS2);
1062   }
1063
1064   /* Helper for DECODE, decode 16-bit compressed R-type instruction.  */
1065   void decode_cr_type_insn (enum opcode opcode, ULONGEST ival)
1066   {
1067     m_opcode = opcode;
1068     m_rd = m_rs1 = decode_register_index (ival, OP_SH_CRS1S);
1069     m_rs2 = decode_register_index (ival, OP_SH_CRS2);
1070   }
1071
1072   /* Helper for DECODE, decode 32-bit I-type instruction.  */
1073   void decode_i_type_insn (enum opcode opcode, ULONGEST ival)
1074   {
1075     m_opcode = opcode;
1076     m_rd = decode_register_index (ival, OP_SH_RD);
1077     m_rs1 = decode_register_index (ival, OP_SH_RS1);
1078     m_imm.s = EXTRACT_ITYPE_IMM (ival);
1079   }
1080
1081   /* Helper for DECODE, decode 16-bit compressed I-type instruction.  */
1082   void decode_ci_type_insn (enum opcode opcode, ULONGEST ival)
1083   {
1084     m_opcode = opcode;
1085     m_rd = m_rs1 = decode_register_index (ival, OP_SH_CRS1S);
1086     m_imm.s = EXTRACT_RVC_IMM (ival);
1087   }
1088
1089   /* Helper for DECODE, decode 32-bit S-type instruction.  */
1090   void decode_s_type_insn (enum opcode opcode, ULONGEST ival)
1091   {
1092     m_opcode = opcode;
1093     m_rs1 = decode_register_index (ival, OP_SH_RS1);
1094     m_rs2 = decode_register_index (ival, OP_SH_RS2);
1095     m_imm.s = EXTRACT_STYPE_IMM (ival);
1096   }
1097
1098   /* Helper for DECODE, decode 16-bit CS-type instruction.  The immediate
1099      encoding is different for each CS format instruction, so extracting
1100      the immediate is left up to the caller, who should pass the extracted
1101      immediate value through in IMM.  */
1102   void decode_cs_type_insn (enum opcode opcode, ULONGEST ival, int imm)
1103   {
1104     m_opcode = opcode;
1105     m_imm.s = imm;
1106     m_rs1 = decode_register_index_short (ival, OP_SH_CRS1S);
1107     m_rs2 = decode_register_index_short (ival, OP_SH_CRS2S);
1108   }
1109
1110   /* Helper for DECODE, decode 16-bit CSS-type instruction.  The immediate
1111      encoding is different for each CSS format instruction, so extracting
1112      the immediate is left up to the caller, who should pass the extracted
1113      immediate value through in IMM.  */
1114   void decode_css_type_insn (enum opcode opcode, ULONGEST ival, int imm)
1115   {
1116     m_opcode = opcode;
1117     m_imm.s = imm;
1118     m_rs1 = RISCV_SP_REGNUM;
1119     /* Not a compressed register number in this case.  */
1120     m_rs2 = decode_register_index (ival, OP_SH_CRS2);
1121   }
1122
1123   /* Helper for DECODE, decode 32-bit U-type instruction.  */
1124   void decode_u_type_insn (enum opcode opcode, ULONGEST ival)
1125   {
1126     m_opcode = opcode;
1127     m_rd = decode_register_index (ival, OP_SH_RD);
1128     m_imm.s = EXTRACT_UTYPE_IMM (ival);
1129   }
1130
1131   /* Helper for DECODE, decode 32-bit J-type instruction.  */
1132   void decode_j_type_insn (enum opcode opcode, ULONGEST ival)
1133   {
1134     m_opcode = opcode;
1135     m_rd = decode_register_index (ival, OP_SH_RD);
1136     m_imm.s = EXTRACT_UJTYPE_IMM (ival);
1137   }
1138
1139   /* Helper for DECODE, decode 32-bit J-type instruction.  */
1140   void decode_cj_type_insn (enum opcode opcode, ULONGEST ival)
1141   {
1142     m_opcode = opcode;
1143     m_imm.s = EXTRACT_RVC_J_IMM (ival);
1144   }
1145
1146   void decode_b_type_insn (enum opcode opcode, ULONGEST ival)
1147   {
1148     m_opcode = opcode;
1149     m_rs1 = decode_register_index (ival, OP_SH_RS1);
1150     m_rs2 = decode_register_index (ival, OP_SH_RS2);
1151     m_imm.s = EXTRACT_SBTYPE_IMM (ival);
1152   }
1153
1154   void decode_cb_type_insn (enum opcode opcode, ULONGEST ival)
1155   {
1156     m_opcode = opcode;
1157     m_rs1 = decode_register_index_short (ival, OP_SH_CRS1S);
1158     m_imm.s = EXTRACT_RVC_B_IMM (ival);
1159   }
1160
1161   /* Fetch instruction from target memory at ADDR, return the content of
1162      the instruction, and update LEN with the instruction length.  */
1163   static ULONGEST fetch_instruction (struct gdbarch *gdbarch,
1164                                      CORE_ADDR addr, int *len);
1165
1166   /* The length of the instruction in bytes.  Should be 2 or 4.  */
1167   int m_length;
1168
1169   /* The instruction opcode.  */
1170   enum opcode m_opcode;
1171
1172   /* The three possible registers an instruction might reference.  Not
1173      every instruction fills in all of these registers.  Which fields are
1174      valid depends on the opcode.  The naming of these fields matches the
1175      naming in the riscv isa manual.  */
1176   int m_rd;
1177   int m_rs1;
1178   int m_rs2;
1179
1180   /* Possible instruction immediate.  This is only valid if the instruction
1181      format contains an immediate, not all instruction, whether this is
1182      valid depends on the opcode.  Despite only having one format for now
1183      the immediate is packed into a union, later instructions might require
1184      an unsigned formatted immediate, having the union in place now will
1185      reduce the need for code churn later.  */
1186   union riscv_insn_immediate
1187   {
1188     riscv_insn_immediate ()
1189       : s (0)
1190     {
1191       /* Nothing.  */
1192     }
1193
1194     int s;
1195   } m_imm;
1196 };
1197
1198 /* Fetch instruction from target memory at ADDR, return the content of the
1199    instruction, and update LEN with the instruction length.  */
1200
1201 ULONGEST
1202 riscv_insn::fetch_instruction (struct gdbarch *gdbarch,
1203                                CORE_ADDR addr, int *len)
1204 {
1205   enum bfd_endian byte_order = gdbarch_byte_order_for_code (gdbarch);
1206   gdb_byte buf[8];
1207   int instlen, status;
1208
1209   /* All insns are at least 16 bits.  */
1210   status = target_read_memory (addr, buf, 2);
1211   if (status)
1212     memory_error (TARGET_XFER_E_IO, addr);
1213
1214   /* If we need more, grab it now.  */
1215   instlen = riscv_insn_length (buf[0]);
1216   gdb_assert (instlen <= sizeof (buf));
1217   *len = instlen;
1218
1219   if (instlen > 2)
1220     {
1221       status = target_read_memory (addr + 2, buf + 2, instlen - 2);
1222       if (status)
1223         memory_error (TARGET_XFER_E_IO, addr + 2);
1224     }
1225
1226   return extract_unsigned_integer (buf, instlen, byte_order);
1227 }
1228
1229 /* Fetch from target memory an instruction at PC and decode it.  This can
1230    throw an error if the memory access fails, callers are responsible for
1231    handling this error if that is appropriate.  */
1232
1233 void
1234 riscv_insn::decode (struct gdbarch *gdbarch, CORE_ADDR pc)
1235 {
1236   ULONGEST ival;
1237
1238   /* Fetch the instruction, and the instructions length.  */
1239   ival = fetch_instruction (gdbarch, pc, &m_length);
1240
1241   if (m_length == 4)
1242     {
1243       if (is_add_insn (ival))
1244         decode_r_type_insn (ADD, ival);
1245       else if (is_addw_insn (ival))
1246         decode_r_type_insn (ADDW, ival);
1247       else if (is_addi_insn (ival))
1248         decode_i_type_insn (ADDI, ival);
1249       else if (is_addiw_insn (ival))
1250         decode_i_type_insn (ADDIW, ival);
1251       else if (is_auipc_insn (ival))
1252         decode_u_type_insn (AUIPC, ival);
1253       else if (is_lui_insn (ival))
1254         decode_u_type_insn (LUI, ival);
1255       else if (is_sd_insn (ival))
1256         decode_s_type_insn (SD, ival);
1257       else if (is_sw_insn (ival))
1258         decode_s_type_insn (SW, ival);
1259       else if (is_jal_insn (ival))
1260         decode_j_type_insn (JAL, ival);
1261       else if (is_jalr_insn (ival))
1262         decode_i_type_insn (JALR, ival);
1263       else if (is_beq_insn (ival))
1264         decode_b_type_insn (BEQ, ival);
1265       else if (is_bne_insn (ival))
1266         decode_b_type_insn (BNE, ival);
1267       else if (is_blt_insn (ival))
1268         decode_b_type_insn (BLT, ival);
1269       else if (is_bge_insn (ival))
1270         decode_b_type_insn (BGE, ival);
1271       else if (is_bltu_insn (ival))
1272         decode_b_type_insn (BLTU, ival);
1273       else if (is_bgeu_insn (ival))
1274         decode_b_type_insn (BGEU, ival);
1275       else if (is_lr_w_insn (ival))
1276         decode_r_type_insn (LR, ival);
1277       else if (is_lr_d_insn (ival))
1278         decode_r_type_insn (LR, ival);
1279       else if (is_sc_w_insn (ival))
1280         decode_r_type_insn (SC, ival);
1281       else if (is_sc_d_insn (ival))
1282         decode_r_type_insn (SC, ival);
1283       else
1284         /* None of the other fields are valid in this case.  */
1285         m_opcode = OTHER;
1286     }
1287   else if (m_length == 2)
1288     {
1289       int xlen = riscv_isa_xlen (gdbarch);
1290
1291       /* C_ADD and C_JALR have the same opcode.  If RS2 is 0, then this is a
1292          C_JALR.  So must try to match C_JALR first as it has more bits in
1293          mask.  */
1294       if (is_c_jalr_insn (ival))
1295         decode_cr_type_insn (JALR, ival);
1296       else if (is_c_add_insn (ival))
1297         decode_cr_type_insn (ADD, ival);
1298       /* C_ADDW is RV64 and RV128 only.  */
1299       else if (xlen != 4 && is_c_addw_insn (ival))
1300         decode_cr_type_insn (ADDW, ival);
1301       else if (is_c_addi_insn (ival))
1302         decode_ci_type_insn (ADDI, ival);
1303       /* C_ADDIW and C_JAL have the same opcode.  C_ADDIW is RV64 and RV128
1304          only and C_JAL is RV32 only.  */
1305       else if (xlen != 4 && is_c_addiw_insn (ival))
1306         decode_ci_type_insn (ADDIW, ival);
1307       else if (xlen == 4 && is_c_jal_insn (ival))
1308         decode_cj_type_insn (JAL, ival);
1309       /* C_ADDI16SP and C_LUI have the same opcode.  If RD is 2, then this is a
1310          C_ADDI16SP.  So must try to match C_ADDI16SP first as it has more bits
1311          in mask.  */
1312       else if (is_c_addi16sp_insn (ival))
1313         {
1314           m_opcode = ADDI;
1315           m_rd = m_rs1 = decode_register_index (ival, OP_SH_RD);
1316           m_imm.s = EXTRACT_RVC_ADDI16SP_IMM (ival);
1317         }
1318       else if (is_c_addi4spn_insn (ival))
1319         {
1320           m_opcode = ADDI;
1321           m_rd = decode_register_index_short (ival, OP_SH_CRS2S);
1322           m_rs1 = RISCV_SP_REGNUM;
1323           m_imm.s = EXTRACT_RVC_ADDI4SPN_IMM (ival);
1324         }
1325       else if (is_c_lui_insn (ival))
1326         {
1327           m_opcode = LUI;
1328           m_rd = decode_register_index (ival, OP_SH_CRS1S);
1329           m_imm.s = EXTRACT_RVC_LUI_IMM (ival);
1330         }
1331       /* C_SD and C_FSW have the same opcode.  C_SD is RV64 and RV128 only,
1332          and C_FSW is RV32 only.  */
1333       else if (xlen != 4 && is_c_sd_insn (ival))
1334         decode_cs_type_insn (SD, ival, EXTRACT_RVC_LD_IMM (ival));
1335       else if (is_c_sw_insn (ival))
1336         decode_cs_type_insn (SW, ival, EXTRACT_RVC_LW_IMM (ival));
1337       else if (is_c_swsp_insn (ival))
1338         decode_css_type_insn (SW, ival, EXTRACT_RVC_SWSP_IMM (ival));
1339       else if (xlen != 4 && is_c_sdsp_insn (ival))
1340         decode_css_type_insn (SW, ival, EXTRACT_RVC_SDSP_IMM (ival));
1341       /* C_JR and C_MV have the same opcode.  If RS2 is 0, then this is a C_JR.
1342          So must try to match C_JR first as it ahs more bits in mask.  */
1343       else if (is_c_jr_insn (ival))
1344         decode_cr_type_insn (JALR, ival);
1345       else if (is_c_j_insn (ival))
1346         decode_cj_type_insn (JAL, ival);
1347       else if (is_c_beqz_insn (ival))
1348         decode_cb_type_insn (BEQ, ival);
1349       else if (is_c_bnez_insn (ival))
1350         decode_cb_type_insn (BNE, ival);
1351       else
1352         /* None of the other fields of INSN are valid in this case.  */
1353         m_opcode = OTHER;
1354     }
1355   else
1356     internal_error (__FILE__, __LINE__,
1357                     _("unable to decode %d byte instructions in "
1358                       "prologue at %s"), m_length,
1359                     core_addr_to_string (pc));
1360 }
1361
1362 /* The prologue scanner.  This is currently only used for skipping the
1363    prologue of a function when the DWARF information is not sufficient.
1364    However, it is written with filling of the frame cache in mind, which
1365    is why different groups of stack setup instructions are split apart
1366    during the core of the inner loop.  In the future, the intention is to
1367    extend this function to fully support building up a frame cache that
1368    can unwind register values when there is no DWARF information.  */
1369
1370 static CORE_ADDR
1371 riscv_scan_prologue (struct gdbarch *gdbarch,
1372                      CORE_ADDR start_pc, CORE_ADDR end_pc,
1373                      struct riscv_unwind_cache *cache)
1374 {
1375   CORE_ADDR cur_pc, next_pc, after_prologue_pc;
1376   CORE_ADDR end_prologue_addr = 0;
1377
1378   /* Find an upper limit on the function prologue using the debug
1379      information.  If the debug information could not be used to provide
1380      that bound, then use an arbitrary large number as the upper bound.  */
1381   after_prologue_pc = skip_prologue_using_sal (gdbarch, start_pc);
1382   if (after_prologue_pc == 0)
1383     after_prologue_pc = start_pc + 100;   /* Arbitrary large number.  */
1384   if (after_prologue_pc < end_pc)
1385     end_pc = after_prologue_pc;
1386
1387   pv_t regs[RISCV_NUM_INTEGER_REGS]; /* Number of GPR.  */
1388   for (int regno = 0; regno < RISCV_NUM_INTEGER_REGS; regno++)
1389     regs[regno] = pv_register (regno, 0);
1390   pv_area stack (RISCV_SP_REGNUM, gdbarch_addr_bit (gdbarch));
1391
1392   if (riscv_debug_unwinder)
1393     fprintf_unfiltered
1394       (gdb_stdlog,
1395        "Prologue scan for function starting at %s (limit %s)\n",
1396        core_addr_to_string (start_pc),
1397        core_addr_to_string (end_pc));
1398
1399   for (next_pc = cur_pc = start_pc; cur_pc < end_pc; cur_pc = next_pc)
1400     {
1401       struct riscv_insn insn;
1402
1403       /* Decode the current instruction, and decide where the next
1404          instruction lives based on the size of this instruction.  */
1405       insn.decode (gdbarch, cur_pc);
1406       gdb_assert (insn.length () > 0);
1407       next_pc = cur_pc + insn.length ();
1408
1409       /* Look for common stack adjustment insns.  */
1410       if ((insn.opcode () == riscv_insn::ADDI
1411            || insn.opcode () == riscv_insn::ADDIW)
1412           && insn.rd () == RISCV_SP_REGNUM
1413           && insn.rs1 () == RISCV_SP_REGNUM)
1414         {
1415           /* Handle: addi sp, sp, -i
1416              or:     addiw sp, sp, -i  */
1417           gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1418           gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
1419           regs[insn.rd ()]
1420             = pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ());
1421         }
1422       else if ((insn.opcode () == riscv_insn::SW
1423                 || insn.opcode () == riscv_insn::SD)
1424                && (insn.rs1 () == RISCV_SP_REGNUM
1425                    || insn.rs1 () == RISCV_FP_REGNUM))
1426         {
1427           /* Handle: sw reg, offset(sp)
1428              or:     sd reg, offset(sp)
1429              or:     sw reg, offset(s0)
1430              or:     sd reg, offset(s0)  */
1431           /* Instruction storing a register onto the stack.  */
1432           gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
1433           gdb_assert (insn.rs2 () < RISCV_NUM_INTEGER_REGS);
1434           stack.store (pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ()),
1435                         (insn.opcode () == riscv_insn::SW ? 4 : 8),
1436                         regs[insn.rs2 ()]);
1437         }
1438       else if (insn.opcode () == riscv_insn::ADDI
1439                && insn.rd () == RISCV_FP_REGNUM
1440                && insn.rs1 () == RISCV_SP_REGNUM)
1441         {
1442           /* Handle: addi s0, sp, size  */
1443           /* Instructions setting up the frame pointer.  */
1444           gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1445           gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
1446           regs[insn.rd ()]
1447             = pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ());
1448         }
1449       else if ((insn.opcode () == riscv_insn::ADD
1450                 || insn.opcode () == riscv_insn::ADDW)
1451                && insn.rd () == RISCV_FP_REGNUM
1452                && insn.rs1 () == RISCV_SP_REGNUM
1453                && insn.rs2 () == RISCV_ZERO_REGNUM)
1454         {
1455           /* Handle: add s0, sp, 0
1456              or:     addw s0, sp, 0  */
1457           /* Instructions setting up the frame pointer.  */
1458           gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1459           gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
1460           regs[insn.rd ()] = pv_add_constant (regs[insn.rs1 ()], 0);
1461         }
1462       else if ((insn.opcode () == riscv_insn::ADDI
1463                 && insn.rd () == RISCV_ZERO_REGNUM
1464                 && insn.rs1 () == RISCV_ZERO_REGNUM
1465                 && insn.imm_signed () == 0))
1466         {
1467           /* Handle: add x0, x0, 0   (NOP)  */
1468         }
1469       else if (insn.opcode () == riscv_insn::AUIPC)
1470         {
1471           gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1472           regs[insn.rd ()] = pv_constant (cur_pc + insn.imm_signed ());
1473         }
1474       else if (insn.opcode () == riscv_insn::LUI)
1475         {
1476           /* Handle: lui REG, n
1477              Where REG is not gp register.  */
1478           gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1479           regs[insn.rd ()] = pv_constant (insn.imm_signed ());
1480         }
1481       else if (insn.opcode () == riscv_insn::ADDI)
1482         {
1483           /* Handle: addi REG1, REG2, IMM  */
1484           gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1485           gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
1486           regs[insn.rd ()]
1487             = pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ());
1488         }
1489       else if (insn.opcode () == riscv_insn::ADD)
1490         {
1491           /* Handle: addi REG1, REG2, IMM  */
1492           gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1493           gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
1494           gdb_assert (insn.rs2 () < RISCV_NUM_INTEGER_REGS);
1495           regs[insn.rd ()] = pv_add (regs[insn.rs1 ()], regs[insn.rs2 ()]);
1496         }
1497       else
1498         {
1499           end_prologue_addr = cur_pc;
1500           break;
1501         }
1502     }
1503
1504   if (end_prologue_addr == 0)
1505     end_prologue_addr = cur_pc;
1506
1507   if (riscv_debug_unwinder)
1508     fprintf_unfiltered (gdb_stdlog, "End of prologue at %s\n",
1509                         core_addr_to_string (end_prologue_addr));
1510
1511   if (cache != NULL)
1512     {
1513       /* Figure out if it is a frame pointer or just a stack pointer.  Also
1514          the offset held in the pv_t is from the original register value to
1515          the current value, which for a grows down stack means a negative
1516          value.  The FRAME_BASE_OFFSET is the negation of this, how to get
1517          from the current value to the original value.  */
1518       if (pv_is_register (regs[RISCV_FP_REGNUM], RISCV_SP_REGNUM))
1519         {
1520           cache->frame_base_reg = RISCV_FP_REGNUM;
1521           cache->frame_base_offset = -regs[RISCV_FP_REGNUM].k;
1522         }
1523       else
1524         {
1525           cache->frame_base_reg = RISCV_SP_REGNUM;
1526           cache->frame_base_offset = -regs[RISCV_SP_REGNUM].k;
1527         }
1528
1529       /* Assign offset from old SP to all saved registers.  As we don't
1530          have the previous value for the frame base register at this
1531          point, we store the offset as the address in the trad_frame, and
1532          then convert this to an actual address later.  */
1533       for (int i = 0; i <= RISCV_NUM_INTEGER_REGS; i++)
1534         {
1535           CORE_ADDR offset;
1536           if (stack.find_reg (gdbarch, i, &offset))
1537             {
1538               if (riscv_debug_unwinder)
1539                 fprintf_unfiltered (gdb_stdlog,
1540                                     "Register $%s at stack offset %ld\n",
1541                                     gdbarch_register_name (gdbarch, i),
1542                                     offset);
1543               trad_frame_set_addr (cache->regs, i, offset);
1544             }
1545         }
1546     }
1547
1548   return end_prologue_addr;
1549 }
1550
1551 /* Implement the riscv_skip_prologue gdbarch method.  */
1552
1553 static CORE_ADDR
1554 riscv_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR pc)
1555 {
1556   CORE_ADDR func_addr;
1557
1558   /* See if we can determine the end of the prologue via the symbol
1559      table.  If so, then return either PC, or the PC after the
1560      prologue, whichever is greater.  */
1561   if (find_pc_partial_function (pc, NULL, &func_addr, NULL))
1562     {
1563       CORE_ADDR post_prologue_pc
1564         = skip_prologue_using_sal (gdbarch, func_addr);
1565
1566       if (post_prologue_pc != 0)
1567         return std::max (pc, post_prologue_pc);
1568     }
1569
1570   /* Can't determine prologue from the symbol table, need to examine
1571      instructions.  Pass -1 for the end address to indicate the prologue
1572      scanner can scan as far as it needs to find the end of the prologue.  */
1573   return riscv_scan_prologue (gdbarch, pc, ((CORE_ADDR) -1), NULL);
1574 }
1575
1576 /* Implement the gdbarch push dummy code callback.  */
1577
1578 static CORE_ADDR
1579 riscv_push_dummy_code (struct gdbarch *gdbarch, CORE_ADDR sp,
1580                        CORE_ADDR funaddr, struct value **args, int nargs,
1581                        struct type *value_type, CORE_ADDR *real_pc,
1582                        CORE_ADDR *bp_addr, struct regcache *regcache)
1583 {
1584   /* Allocate space for a breakpoint, and keep the stack correctly
1585      aligned.  */
1586   sp -= 16;
1587   *bp_addr = sp;
1588   *real_pc = funaddr;
1589   return sp;
1590 }
1591
1592 /* Compute the alignment of the type T.  Used while setting up the
1593    arguments for a dummy call.  */
1594
1595 static int
1596 riscv_type_alignment (struct type *t)
1597 {
1598   t = check_typedef (t);
1599   switch (TYPE_CODE (t))
1600     {
1601     default:
1602       error (_("Could not compute alignment of type"));
1603
1604     case TYPE_CODE_RVALUE_REF:
1605     case TYPE_CODE_PTR:
1606     case TYPE_CODE_ENUM:
1607     case TYPE_CODE_INT:
1608     case TYPE_CODE_FLT:
1609     case TYPE_CODE_REF:
1610     case TYPE_CODE_CHAR:
1611     case TYPE_CODE_BOOL:
1612       return TYPE_LENGTH (t);
1613
1614     case TYPE_CODE_ARRAY:
1615       if (TYPE_VECTOR (t))
1616         return std::min (TYPE_LENGTH (t), (unsigned) BIGGEST_ALIGNMENT);
1617       /* FALLTHROUGH */
1618
1619     case TYPE_CODE_COMPLEX:
1620       return riscv_type_alignment (TYPE_TARGET_TYPE (t));
1621
1622     case TYPE_CODE_STRUCT:
1623     case TYPE_CODE_UNION:
1624       {
1625         int i;
1626         int align = 1;
1627
1628         for (i = 0; i < TYPE_NFIELDS (t); ++i)
1629           {
1630             if (TYPE_FIELD_LOC_KIND (t, i) == FIELD_LOC_KIND_BITPOS)
1631               {
1632                 int a = riscv_type_alignment (TYPE_FIELD_TYPE (t, i));
1633                 if (a > align)
1634                   align = a;
1635               }
1636           }
1637         return align;
1638       }
1639     }
1640 }
1641
1642 /* Holds information about a single argument either being passed to an
1643    inferior function, or returned from an inferior function.  This includes
1644    information about the size, type, etc of the argument, and also
1645    information about how the argument will be passed (or returned).  */
1646
1647 struct riscv_arg_info
1648 {
1649   /* Contents of the argument.  */
1650   const gdb_byte *contents;
1651
1652   /* Length of argument.  */
1653   int length;
1654
1655   /* Alignment required for an argument of this type.  */
1656   int align;
1657
1658   /* The type for this argument.  */
1659   struct type *type;
1660
1661   /* Each argument can have either 1 or 2 locations assigned to it.  Each
1662      location describes where part of the argument will be placed.  The
1663      second location is valid based on the LOC_TYPE and C_LENGTH fields
1664      of the first location (which is always valid).  */
1665   struct location
1666   {
1667     /* What type of location this is.  */
1668     enum location_type
1669       {
1670        /* Argument passed in a register.  */
1671        in_reg,
1672
1673        /* Argument passed as an on stack argument.  */
1674        on_stack,
1675
1676        /* Argument passed by reference.  The second location is always
1677           valid for a BY_REF argument, and describes where the address
1678           of the BY_REF argument should be placed.  */
1679        by_ref
1680       } loc_type;
1681
1682     /* Information that depends on the location type.  */
1683     union
1684     {
1685       /* Which register number to use.  */
1686       int regno;
1687
1688       /* The offset into the stack region.  */
1689       int offset;
1690     } loc_data;
1691
1692     /* The length of contents covered by this location.  If this is less
1693        than the total length of the argument, then the second location
1694        will be valid, and will describe where the rest of the argument
1695        will go.  */
1696     int c_length;
1697
1698     /* The offset within CONTENTS for this part of the argument.  Will
1699        always be 0 for the first part.  For the second part of the
1700        argument, this might be the C_LENGTH value of the first part,
1701        however, if we are passing a structure in two registers, and there's
1702        is padding between the first and second field, then this offset
1703        might be greater than the length of the first argument part.  When
1704        the second argument location is not holding part of the argument
1705        value, but is instead holding the address of a reference argument,
1706        then this offset will be set to 0.  */
1707     int c_offset;
1708   } argloc[2];
1709
1710   /* TRUE if this is an unnamed argument.  */
1711   bool is_unnamed;
1712 };
1713
1714 /* Information about a set of registers being used for passing arguments as
1715    part of a function call.  The register set must be numerically
1716    sequential from NEXT_REGNUM to LAST_REGNUM.  The register set can be
1717    disabled from use by setting NEXT_REGNUM greater than LAST_REGNUM.  */
1718
1719 struct riscv_arg_reg
1720 {
1721   riscv_arg_reg (int first, int last)
1722     : next_regnum (first),
1723       last_regnum (last)
1724   {
1725     /* Nothing.  */
1726   }
1727
1728   /* The GDB register number to use in this set.  */
1729   int next_regnum;
1730
1731   /* The last GDB register number to use in this set.  */
1732   int last_regnum;
1733 };
1734
1735 /* Arguments can be passed as on stack arguments, or by reference.  The
1736    on stack arguments must be in a continuous region starting from $sp,
1737    while the by reference arguments can be anywhere, but we'll put them
1738    on the stack after (at higher address) the on stack arguments.
1739
1740    This might not be the right approach to take.  The ABI is clear that
1741    an argument passed by reference can be modified by the callee, which
1742    us placing the argument (temporarily) onto the stack will not achieve
1743    (changes will be lost).  There's also the possibility that very large
1744    arguments could overflow the stack.
1745
1746    This struct is used to track offset into these two areas for where
1747    arguments are to be placed.  */
1748 struct riscv_memory_offsets
1749 {
1750   riscv_memory_offsets ()
1751     : arg_offset (0),
1752       ref_offset (0)
1753   {
1754     /* Nothing.  */
1755   }
1756
1757   /* Offset into on stack argument area.  */
1758   int arg_offset;
1759
1760   /* Offset into the pass by reference area.  */
1761   int ref_offset;
1762 };
1763
1764 /* Holds information about where arguments to a call will be placed.  This
1765    is updated as arguments are added onto the call, and can be used to
1766    figure out where the next argument should be placed.  */
1767
1768 struct riscv_call_info
1769 {
1770   riscv_call_info (struct gdbarch *gdbarch)
1771     : int_regs (RISCV_A0_REGNUM, RISCV_A0_REGNUM + 7),
1772       float_regs (RISCV_FA0_REGNUM, RISCV_FA0_REGNUM + 7)
1773   {
1774     xlen = riscv_isa_xlen (gdbarch);
1775     flen = riscv_isa_flen (gdbarch);
1776
1777     /* Disable use of floating point registers if needed.  */
1778     if (!riscv_has_fp_abi (gdbarch))
1779       float_regs.next_regnum = float_regs.last_regnum + 1;
1780   }
1781
1782   /* Track the memory areas used for holding in-memory arguments to a
1783      call.  */
1784   struct riscv_memory_offsets memory;
1785
1786   /* Holds information about the next integer register to use for passing
1787      an argument.  */
1788   struct riscv_arg_reg int_regs;
1789
1790   /* Holds information about the next floating point register to use for
1791      passing an argument.  */
1792   struct riscv_arg_reg float_regs;
1793
1794   /* The XLEN and FLEN are copied in to this structure for convenience, and
1795      are just the results of calling RISCV_ISA_XLEN and RISCV_ISA_FLEN.  */
1796   int xlen;
1797   int flen;
1798 };
1799
1800 /* Return the number of registers available for use as parameters in the
1801    register set REG.  Returned value can be 0 or more.  */
1802
1803 static int
1804 riscv_arg_regs_available (struct riscv_arg_reg *reg)
1805 {
1806   if (reg->next_regnum > reg->last_regnum)
1807     return 0;
1808
1809   return (reg->last_regnum - reg->next_regnum + 1);
1810 }
1811
1812 /* If there is at least one register available in the register set REG then
1813    the next register from REG is assigned to LOC and the length field of
1814    LOC is updated to LENGTH.  The register set REG is updated to indicate
1815    that the assigned register is no longer available and the function
1816    returns true.
1817
1818    If there are no registers available in REG then the function returns
1819    false, and LOC and REG are unchanged.  */
1820
1821 static bool
1822 riscv_assign_reg_location (struct riscv_arg_info::location *loc,
1823                            struct riscv_arg_reg *reg,
1824                            int length, int offset)
1825 {
1826   if (reg->next_regnum <= reg->last_regnum)
1827     {
1828       loc->loc_type = riscv_arg_info::location::in_reg;
1829       loc->loc_data.regno = reg->next_regnum;
1830       reg->next_regnum++;
1831       loc->c_length = length;
1832       loc->c_offset = offset;
1833       return true;
1834     }
1835
1836   return false;
1837 }
1838
1839 /* Assign LOC a location as the next stack parameter, and update MEMORY to
1840    record that an area of stack has been used to hold the parameter
1841    described by LOC.
1842
1843    The length field of LOC is updated to LENGTH, the length of the
1844    parameter being stored, and ALIGN is the alignment required by the
1845    parameter, which will affect how memory is allocated out of MEMORY.  */
1846
1847 static void
1848 riscv_assign_stack_location (struct riscv_arg_info::location *loc,
1849                              struct riscv_memory_offsets *memory,
1850                              int length, int align)
1851 {
1852   loc->loc_type = riscv_arg_info::location::on_stack;
1853   memory->arg_offset
1854     = align_up (memory->arg_offset, align);
1855   loc->loc_data.offset = memory->arg_offset;
1856   memory->arg_offset += length;
1857   loc->c_length = length;
1858
1859   /* Offset is always 0, either we're the first location part, in which
1860      case we're reading content from the start of the argument, or we're
1861      passing the address of a reference argument, so 0.  */
1862   loc->c_offset = 0;
1863 }
1864
1865 /* Update AINFO, which describes an argument that should be passed or
1866    returned using the integer ABI.  The argloc fields within AINFO are
1867    updated to describe the location in which the argument will be passed to
1868    a function, or returned from a function.
1869
1870    The CINFO structure contains the ongoing call information, the holds
1871    information such as which argument registers are remaining to be
1872    assigned to parameter, and how much memory has been used by parameters
1873    so far.
1874
1875    By examining the state of CINFO a suitable location can be selected,
1876    and assigned to AINFO.  */
1877
1878 static void
1879 riscv_call_arg_scalar_int (struct riscv_arg_info *ainfo,
1880                            struct riscv_call_info *cinfo)
1881 {
1882   if (ainfo->length > (2 * cinfo->xlen))
1883     {
1884       /* Argument is going to be passed by reference.  */
1885       ainfo->argloc[0].loc_type
1886         = riscv_arg_info::location::by_ref;
1887       cinfo->memory.ref_offset
1888         = align_up (cinfo->memory.ref_offset, ainfo->align);
1889       ainfo->argloc[0].loc_data.offset = cinfo->memory.ref_offset;
1890       cinfo->memory.ref_offset += ainfo->length;
1891       ainfo->argloc[0].c_length = ainfo->length;
1892
1893       /* The second location for this argument is given over to holding the
1894          address of the by-reference data.  Pass 0 for the offset as this
1895          is not part of the actual argument value.  */
1896       if (!riscv_assign_reg_location (&ainfo->argloc[1],
1897                                       &cinfo->int_regs,
1898                                       cinfo->xlen, 0))
1899         riscv_assign_stack_location (&ainfo->argloc[1],
1900                                      &cinfo->memory, cinfo->xlen,
1901                                      cinfo->xlen);
1902     }
1903   else
1904     {
1905       int len = std::min (ainfo->length, cinfo->xlen);
1906       int align = std::max (ainfo->align, cinfo->xlen);
1907
1908       /* Unnamed arguments in registers that require 2*XLEN alignment are
1909          passed in an aligned register pair.  */
1910       if (ainfo->is_unnamed && (align == cinfo->xlen * 2)
1911           && cinfo->int_regs.next_regnum & 1)
1912         cinfo->int_regs.next_regnum++;
1913
1914       if (!riscv_assign_reg_location (&ainfo->argloc[0],
1915                                       &cinfo->int_regs, len, 0))
1916         riscv_assign_stack_location (&ainfo->argloc[0],
1917                                      &cinfo->memory, len, align);
1918
1919       if (len < ainfo->length)
1920         {
1921           len = ainfo->length - len;
1922           if (!riscv_assign_reg_location (&ainfo->argloc[1],
1923                                           &cinfo->int_regs, len,
1924                                           cinfo->xlen))
1925             riscv_assign_stack_location (&ainfo->argloc[1],
1926                                          &cinfo->memory, len, cinfo->xlen);
1927         }
1928     }
1929 }
1930
1931 /* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
1932    is being passed with the floating point ABI.  */
1933
1934 static void
1935 riscv_call_arg_scalar_float (struct riscv_arg_info *ainfo,
1936                              struct riscv_call_info *cinfo)
1937 {
1938   if (ainfo->length > cinfo->flen || ainfo->is_unnamed)
1939     return riscv_call_arg_scalar_int (ainfo, cinfo);
1940   else
1941     {
1942       if (!riscv_assign_reg_location (&ainfo->argloc[0],
1943                                       &cinfo->float_regs,
1944                                       ainfo->length, 0))
1945         return riscv_call_arg_scalar_int (ainfo, cinfo);
1946     }
1947 }
1948
1949 /* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
1950    is a complex floating point argument, and is therefore handled
1951    differently to other argument types.  */
1952
1953 static void
1954 riscv_call_arg_complex_float (struct riscv_arg_info *ainfo,
1955                               struct riscv_call_info *cinfo)
1956 {
1957   if (ainfo->length <= (2 * cinfo->flen)
1958       && riscv_arg_regs_available (&cinfo->float_regs) >= 2
1959       && !ainfo->is_unnamed)
1960     {
1961       bool result;
1962       int len = ainfo->length / 2;
1963
1964       result = riscv_assign_reg_location (&ainfo->argloc[0],
1965                                           &cinfo->float_regs, len, len);
1966       gdb_assert (result);
1967
1968       result = riscv_assign_reg_location (&ainfo->argloc[1],
1969                                           &cinfo->float_regs, len, len);
1970       gdb_assert (result);
1971     }
1972   else
1973     return riscv_call_arg_scalar_int (ainfo, cinfo);
1974 }
1975
1976 /* A structure used for holding information about a structure type within
1977    the inferior program.  The RiscV ABI has special rules for handling some
1978    structures with a single field or with two fields.  The counting of
1979    fields here is done after flattening out all nested structures.  */
1980
1981 class riscv_struct_info
1982 {
1983 public:
1984   riscv_struct_info ()
1985     : m_number_of_fields (0),
1986       m_types { nullptr, nullptr }
1987   {
1988     /* Nothing.  */
1989   }
1990
1991   /* Analyse TYPE descending into nested structures, count the number of
1992      scalar fields and record the types of the first two fields found.  */
1993   void analyse (struct type *type);
1994
1995   /* The number of scalar fields found in the analysed type.  This is
1996      currently only accurate if the value returned is 0, 1, or 2 as the
1997      analysis stops counting when the number of fields is 3.  This is
1998      because the RiscV ABI only has special cases for 1 or 2 fields,
1999      anything else we just don't care about.  */
2000   int number_of_fields () const
2001   { return m_number_of_fields; }
2002
2003   /* Return the type for scalar field INDEX within the analysed type.  Will
2004      return nullptr if there is no field at that index.  Only INDEX values
2005      0 and 1 can be requested as the RiscV ABI only has special cases for
2006      structures with 1 or 2 fields.  */
2007   struct type *field_type (int index) const
2008   {
2009     gdb_assert (index < (sizeof (m_types) / sizeof (m_types[0])));
2010     return m_types[index];
2011   }
2012
2013 private:
2014   /* The number of scalar fields found within the structure after recursing
2015      into nested structures.  */
2016   int m_number_of_fields;
2017
2018   /* The types of the first two scalar fields found within the structure
2019      after recursing into nested structures.  */
2020   struct type *m_types[2];
2021 };
2022
2023 /* Analyse TYPE descending into nested structures, count the number of
2024    scalar fields and record the types of the first two fields found.  */
2025
2026 void
2027 riscv_struct_info::analyse (struct type *type)
2028 {
2029   unsigned int count = TYPE_NFIELDS (type);
2030   unsigned int i;
2031
2032   for (i = 0; i < count; ++i)
2033     {
2034       if (TYPE_FIELD_LOC_KIND (type, i) != FIELD_LOC_KIND_BITPOS)
2035         continue;
2036
2037       struct type *field_type = TYPE_FIELD_TYPE (type, i);
2038       field_type = check_typedef (field_type);
2039
2040       switch (TYPE_CODE (field_type))
2041         {
2042         case TYPE_CODE_STRUCT:
2043           analyse (field_type);
2044           break;
2045
2046         default:
2047           /* RiscV only flattens out structures.  Anything else does not
2048              need to be flattened, we just record the type, and when we
2049              look at the analysis results we'll realise this is not a
2050              structure we can special case, and pass the structure in
2051              memory.  */
2052           if (m_number_of_fields < 2)
2053             m_types[m_number_of_fields] = field_type;
2054           m_number_of_fields++;
2055           break;
2056         }
2057
2058       /* RiscV only has special handling for structures with 1 or 2 scalar
2059          fields, any more than that and the structure is just passed in
2060          memory.  We can safely drop out early when we find 3 or more
2061          fields then.  */
2062
2063       if (m_number_of_fields > 2)
2064         return;
2065     }
2066 }
2067
2068 /* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
2069    is a structure.  Small structures on RiscV have some special case
2070    handling in order that the structure might be passed in register.
2071    Larger structures are passed in memory.  After assigning location
2072    information to AINFO, CINFO will have been updated.  */
2073
2074 static void
2075 riscv_call_arg_struct (struct riscv_arg_info *ainfo,
2076                        struct riscv_call_info *cinfo)
2077 {
2078   if (riscv_arg_regs_available (&cinfo->float_regs) >= 1)
2079     {
2080       struct riscv_struct_info sinfo;
2081
2082       sinfo.analyse (ainfo->type);
2083       if (sinfo.number_of_fields () == 1
2084           && TYPE_CODE (sinfo.field_type (0)) == TYPE_CODE_COMPLEX)
2085         {
2086           gdb_assert (TYPE_LENGTH (ainfo->type)
2087                       == TYPE_LENGTH (sinfo.field_type (0)));
2088           return riscv_call_arg_complex_float (ainfo, cinfo);
2089         }
2090
2091       if (sinfo.number_of_fields () == 1
2092           && TYPE_CODE (sinfo.field_type (0)) == TYPE_CODE_FLT)
2093         {
2094           gdb_assert (TYPE_LENGTH (ainfo->type)
2095                       == TYPE_LENGTH (sinfo.field_type (0)));
2096           return riscv_call_arg_scalar_float (ainfo, cinfo);
2097         }
2098
2099       if (sinfo.number_of_fields () == 2
2100           && TYPE_CODE (sinfo.field_type (0)) == TYPE_CODE_FLT
2101           && TYPE_LENGTH (sinfo.field_type (0)) <= cinfo->flen
2102           && TYPE_CODE (sinfo.field_type (1)) == TYPE_CODE_FLT
2103           && TYPE_LENGTH (sinfo.field_type (1)) <= cinfo->flen
2104           && riscv_arg_regs_available (&cinfo->float_regs) >= 2)
2105         {
2106           int len0, len1, offset;
2107
2108           gdb_assert (TYPE_LENGTH (ainfo->type) <= (2 * cinfo->flen));
2109
2110           len0 = TYPE_LENGTH (sinfo.field_type (0));
2111           if (!riscv_assign_reg_location (&ainfo->argloc[0],
2112                                           &cinfo->float_regs, len0, 0))
2113             error (_("failed during argument setup"));
2114
2115           len1 = TYPE_LENGTH (sinfo.field_type (1));
2116           offset = align_up (len0, riscv_type_alignment (sinfo.field_type (1)));
2117           gdb_assert (len1 <= (TYPE_LENGTH (ainfo->type)
2118                                - TYPE_LENGTH (sinfo.field_type (0))));
2119
2120           if (!riscv_assign_reg_location (&ainfo->argloc[1],
2121                                           &cinfo->float_regs,
2122                                           len1, offset))
2123             error (_("failed during argument setup"));
2124           return;
2125         }
2126
2127       if (sinfo.number_of_fields () == 2
2128           && riscv_arg_regs_available (&cinfo->int_regs) >= 1
2129           && (TYPE_CODE (sinfo.field_type (0)) == TYPE_CODE_FLT
2130               && TYPE_LENGTH (sinfo.field_type (0)) <= cinfo->flen
2131               && is_integral_type (sinfo.field_type (1))
2132               && TYPE_LENGTH (sinfo.field_type (1)) <= cinfo->xlen))
2133         {
2134           int len0, len1, offset;
2135
2136           gdb_assert (TYPE_LENGTH (ainfo->type)
2137                       <= (cinfo->flen + cinfo->xlen));
2138
2139           len0 = TYPE_LENGTH (sinfo.field_type (0));
2140           if (!riscv_assign_reg_location (&ainfo->argloc[0],
2141                                           &cinfo->float_regs, len0, 0))
2142             error (_("failed during argument setup"));
2143
2144           len1 = TYPE_LENGTH (sinfo.field_type (1));
2145           offset = align_up (len0, riscv_type_alignment (sinfo.field_type (1)));
2146           gdb_assert (len1 <= cinfo->xlen);
2147           if (!riscv_assign_reg_location (&ainfo->argloc[1],
2148                                           &cinfo->int_regs, len1, offset))
2149             error (_("failed during argument setup"));
2150           return;
2151         }
2152
2153       if (sinfo.number_of_fields () == 2
2154           && riscv_arg_regs_available (&cinfo->int_regs) >= 1
2155           && (is_integral_type (sinfo.field_type (0))
2156               && TYPE_LENGTH (sinfo.field_type (0)) <= cinfo->xlen
2157               && TYPE_CODE (sinfo.field_type (1)) == TYPE_CODE_FLT
2158               && TYPE_LENGTH (sinfo.field_type (1)) <= cinfo->flen))
2159         {
2160           int len0, len1, offset;
2161
2162           gdb_assert (TYPE_LENGTH (ainfo->type)
2163                       <= (cinfo->flen + cinfo->xlen));
2164
2165           len0 = TYPE_LENGTH (sinfo.field_type (0));
2166           len1 = TYPE_LENGTH (sinfo.field_type (1));
2167           offset = align_up (len0, riscv_type_alignment (sinfo.field_type (1)));
2168
2169           gdb_assert (len0 <= cinfo->xlen);
2170           gdb_assert (len1 <= cinfo->flen);
2171
2172           if (!riscv_assign_reg_location (&ainfo->argloc[0],
2173                                           &cinfo->int_regs, len0, 0))
2174             error (_("failed during argument setup"));
2175
2176           if (!riscv_assign_reg_location (&ainfo->argloc[1],
2177                                           &cinfo->float_regs,
2178                                           len1, offset))
2179             error (_("failed during argument setup"));
2180
2181           return;
2182         }
2183     }
2184
2185   /* Non of the structure flattening cases apply, so we just pass using
2186      the integer ABI.  */
2187   ainfo->length = align_up (ainfo->length, cinfo->xlen);
2188   riscv_call_arg_scalar_int (ainfo, cinfo);
2189 }
2190
2191 /* Assign a location to call (or return) argument AINFO, the location is
2192    selected from CINFO which holds information about what call argument
2193    locations are available for use next.  The TYPE is the type of the
2194    argument being passed, this information is recorded into AINFO (along
2195    with some additional information derived from the type).  IS_UNNAMED
2196    is true if this is an unnamed (stdarg) argument, this info is also
2197    recorded into AINFO.
2198
2199    After assigning a location to AINFO, CINFO will have been updated.  */
2200
2201 static void
2202 riscv_arg_location (struct gdbarch *gdbarch,
2203                     struct riscv_arg_info *ainfo,
2204                     struct riscv_call_info *cinfo,
2205                     struct type *type, bool is_unnamed)
2206 {
2207   ainfo->type = type;
2208   ainfo->length = TYPE_LENGTH (ainfo->type);
2209   ainfo->align = riscv_type_alignment (ainfo->type);
2210   ainfo->is_unnamed = is_unnamed;
2211   ainfo->contents = nullptr;
2212
2213   switch (TYPE_CODE (ainfo->type))
2214     {
2215     case TYPE_CODE_INT:
2216     case TYPE_CODE_BOOL:
2217     case TYPE_CODE_CHAR:
2218     case TYPE_CODE_RANGE:
2219     case TYPE_CODE_ENUM:
2220     case TYPE_CODE_PTR:
2221       if (ainfo->length <= cinfo->xlen)
2222         {
2223           ainfo->type = builtin_type (gdbarch)->builtin_long;
2224           ainfo->length = cinfo->xlen;
2225         }
2226       else if (ainfo->length <= (2 * cinfo->xlen))
2227         {
2228           ainfo->type = builtin_type (gdbarch)->builtin_long_long;
2229           ainfo->length = 2 * cinfo->xlen;
2230         }
2231
2232       /* Recalculate the alignment requirement.  */
2233       ainfo->align = riscv_type_alignment (ainfo->type);
2234       riscv_call_arg_scalar_int (ainfo, cinfo);
2235       break;
2236
2237     case TYPE_CODE_FLT:
2238       riscv_call_arg_scalar_float (ainfo, cinfo);
2239       break;
2240
2241     case TYPE_CODE_COMPLEX:
2242       riscv_call_arg_complex_float (ainfo, cinfo);
2243       break;
2244
2245     case TYPE_CODE_STRUCT:
2246       riscv_call_arg_struct (ainfo, cinfo);
2247       break;
2248
2249     default:
2250       riscv_call_arg_scalar_int (ainfo, cinfo);
2251       break;
2252     }
2253 }
2254
2255 /* Used for printing debug information about the call argument location in
2256    INFO to STREAM.  The addresses in SP_REFS and SP_ARGS are the base
2257    addresses for the location of pass-by-reference and
2258    arguments-on-the-stack memory areas.  */
2259
2260 static void
2261 riscv_print_arg_location (ui_file *stream, struct gdbarch *gdbarch,
2262                           struct riscv_arg_info *info,
2263                           CORE_ADDR sp_refs, CORE_ADDR sp_args)
2264 {
2265   fprintf_unfiltered (stream, "type: '%s', length: 0x%x, alignment: 0x%x",
2266                       TYPE_SAFE_NAME (info->type), info->length, info->align);
2267   switch (info->argloc[0].loc_type)
2268     {
2269     case riscv_arg_info::location::in_reg:
2270       fprintf_unfiltered
2271         (stream, ", register %s",
2272          gdbarch_register_name (gdbarch, info->argloc[0].loc_data.regno));
2273       if (info->argloc[0].c_length < info->length)
2274         {
2275           switch (info->argloc[1].loc_type)
2276             {
2277             case riscv_arg_info::location::in_reg:
2278               fprintf_unfiltered
2279                 (stream, ", register %s",
2280                  gdbarch_register_name (gdbarch,
2281                                         info->argloc[1].loc_data.regno));
2282               break;
2283
2284             case riscv_arg_info::location::on_stack:
2285               fprintf_unfiltered (stream, ", on stack at offset 0x%x",
2286                                   info->argloc[1].loc_data.offset);
2287               break;
2288
2289             case riscv_arg_info::location::by_ref:
2290             default:
2291               /* The second location should never be a reference, any
2292                  argument being passed by reference just places its address
2293                  in the first location and is done.  */
2294               error (_("invalid argument location"));
2295               break;
2296             }
2297
2298           if (info->argloc[1].c_offset > info->argloc[0].c_length)
2299             fprintf_unfiltered (stream, " (offset 0x%x)",
2300                                 info->argloc[1].c_offset);
2301         }
2302       break;
2303
2304     case riscv_arg_info::location::on_stack:
2305       fprintf_unfiltered (stream, ", on stack at offset 0x%x",
2306                           info->argloc[0].loc_data.offset);
2307       break;
2308
2309     case riscv_arg_info::location::by_ref:
2310       fprintf_unfiltered
2311         (stream, ", by reference, data at offset 0x%x (%s)",
2312          info->argloc[0].loc_data.offset,
2313          core_addr_to_string (sp_refs + info->argloc[0].loc_data.offset));
2314       if (info->argloc[1].loc_type
2315           == riscv_arg_info::location::in_reg)
2316         fprintf_unfiltered
2317           (stream, ", address in register %s",
2318            gdbarch_register_name (gdbarch, info->argloc[1].loc_data.regno));
2319       else
2320         {
2321           gdb_assert (info->argloc[1].loc_type
2322                       == riscv_arg_info::location::on_stack);
2323           fprintf_unfiltered
2324             (stream, ", address on stack at offset 0x%x (%s)",
2325              info->argloc[1].loc_data.offset,
2326              core_addr_to_string (sp_args + info->argloc[1].loc_data.offset));
2327         }
2328       break;
2329
2330     default:
2331       gdb_assert_not_reached (_("unknown argument location type"));
2332     }
2333 }
2334
2335 /* Implement the push dummy call gdbarch callback.  */
2336
2337 static CORE_ADDR
2338 riscv_push_dummy_call (struct gdbarch *gdbarch,
2339                        struct value *function,
2340                        struct regcache *regcache,
2341                        CORE_ADDR bp_addr,
2342                        int nargs,
2343                        struct value **args,
2344                        CORE_ADDR sp,
2345                        function_call_return_method return_method,
2346                        CORE_ADDR struct_addr)
2347 {
2348   int i;
2349   CORE_ADDR sp_args, sp_refs;
2350   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2351
2352   struct riscv_arg_info *arg_info =
2353     (struct riscv_arg_info *) alloca (nargs * sizeof (struct riscv_arg_info));
2354
2355   struct riscv_call_info call_info (gdbarch);
2356
2357   CORE_ADDR osp = sp;
2358
2359   struct type *ftype = check_typedef (value_type (function));
2360
2361   if (TYPE_CODE (ftype) == TYPE_CODE_PTR)
2362     ftype = check_typedef (TYPE_TARGET_TYPE (ftype));
2363
2364   /* We'll use register $a0 if we're returning a struct.  */
2365   if (return_method == return_method_struct)
2366     ++call_info.int_regs.next_regnum;
2367
2368   for (i = 0; i < nargs; ++i)
2369     {
2370       struct value *arg_value;
2371       struct type *arg_type;
2372       struct riscv_arg_info *info = &arg_info[i];
2373
2374       arg_value = args[i];
2375       arg_type = check_typedef (value_type (arg_value));
2376
2377       riscv_arg_location (gdbarch, info, &call_info, arg_type,
2378                           TYPE_VARARGS (ftype) && i >= TYPE_NFIELDS (ftype));
2379
2380       if (info->type != arg_type)
2381         arg_value = value_cast (info->type, arg_value);
2382       info->contents = value_contents (arg_value);
2383     }
2384
2385   /* Adjust the stack pointer and align it.  */
2386   sp = sp_refs = align_down (sp - call_info.memory.ref_offset, SP_ALIGNMENT);
2387   sp = sp_args = align_down (sp - call_info.memory.arg_offset, SP_ALIGNMENT);
2388
2389   if (riscv_debug_infcall > 0)
2390     {
2391       fprintf_unfiltered (gdb_stdlog, "dummy call args:\n");
2392       fprintf_unfiltered (gdb_stdlog, ": floating point ABI %s in use\n",
2393                (riscv_has_fp_abi (gdbarch) ? "is" : "is not"));
2394       fprintf_unfiltered (gdb_stdlog, ": xlen: %d\n: flen: %d\n",
2395                call_info.xlen, call_info.flen);
2396       if (return_method == return_method_struct)
2397         fprintf_unfiltered (gdb_stdlog,
2398                             "[*] struct return pointer in register $A0\n");
2399       for (i = 0; i < nargs; ++i)
2400         {
2401           struct riscv_arg_info *info = &arg_info [i];
2402
2403           fprintf_unfiltered (gdb_stdlog, "[%2d] ", i);
2404           riscv_print_arg_location (gdb_stdlog, gdbarch, info, sp_refs, sp_args);
2405           fprintf_unfiltered (gdb_stdlog, "\n");
2406         }
2407       if (call_info.memory.arg_offset > 0
2408           || call_info.memory.ref_offset > 0)
2409         {
2410           fprintf_unfiltered (gdb_stdlog, "              Original sp: %s\n",
2411                               core_addr_to_string (osp));
2412           fprintf_unfiltered (gdb_stdlog, "Stack required (for args): 0x%x\n",
2413                               call_info.memory.arg_offset);
2414           fprintf_unfiltered (gdb_stdlog, "Stack required (for refs): 0x%x\n",
2415                               call_info.memory.ref_offset);
2416           fprintf_unfiltered (gdb_stdlog, "          Stack allocated: %s\n",
2417                               core_addr_to_string_nz (osp - sp));
2418         }
2419     }
2420
2421   /* Now load the argument into registers, or onto the stack.  */
2422
2423   if (return_method == return_method_struct)
2424     {
2425       gdb_byte buf[sizeof (LONGEST)];
2426
2427       store_unsigned_integer (buf, call_info.xlen, byte_order, struct_addr);
2428       regcache->cooked_write (RISCV_A0_REGNUM, buf);
2429     }
2430
2431   for (i = 0; i < nargs; ++i)
2432     {
2433       CORE_ADDR dst;
2434       int second_arg_length = 0;
2435       const gdb_byte *second_arg_data;
2436       struct riscv_arg_info *info = &arg_info [i];
2437
2438       gdb_assert (info->length > 0);
2439
2440       switch (info->argloc[0].loc_type)
2441         {
2442         case riscv_arg_info::location::in_reg:
2443           {
2444             gdb_byte tmp [sizeof (ULONGEST)];
2445
2446             gdb_assert (info->argloc[0].c_length <= info->length);
2447             /* FP values in FP registers must be NaN-boxed.  */
2448             if (riscv_is_fp_regno_p (info->argloc[0].loc_data.regno)
2449                 && info->argloc[0].c_length < call_info.flen)
2450               memset (tmp, -1, sizeof (tmp));
2451             else
2452               memset (tmp, 0, sizeof (tmp));
2453             memcpy (tmp, info->contents, info->argloc[0].c_length);
2454             regcache->cooked_write (info->argloc[0].loc_data.regno, tmp);
2455             second_arg_length =
2456               ((info->argloc[0].c_length < info->length)
2457                ? info->argloc[1].c_length : 0);
2458             second_arg_data = info->contents + info->argloc[1].c_offset;
2459           }
2460           break;
2461
2462         case riscv_arg_info::location::on_stack:
2463           dst = sp_args + info->argloc[0].loc_data.offset;
2464           write_memory (dst, info->contents, info->length);
2465           second_arg_length = 0;
2466           break;
2467
2468         case riscv_arg_info::location::by_ref:
2469           dst = sp_refs + info->argloc[0].loc_data.offset;
2470           write_memory (dst, info->contents, info->length);
2471
2472           second_arg_length = call_info.xlen;
2473           second_arg_data = (gdb_byte *) &dst;
2474           break;
2475
2476         default:
2477           gdb_assert_not_reached (_("unknown argument location type"));
2478         }
2479
2480       if (second_arg_length > 0)
2481         {
2482           switch (info->argloc[1].loc_type)
2483             {
2484             case riscv_arg_info::location::in_reg:
2485               {
2486                 gdb_byte tmp [sizeof (ULONGEST)];
2487
2488                 gdb_assert ((riscv_is_fp_regno_p (info->argloc[1].loc_data.regno)
2489                              && second_arg_length <= call_info.flen)
2490                             || second_arg_length <= call_info.xlen);
2491                 /* FP values in FP registers must be NaN-boxed.  */
2492                 if (riscv_is_fp_regno_p (info->argloc[1].loc_data.regno)
2493                     && second_arg_length < call_info.flen)
2494                   memset (tmp, -1, sizeof (tmp));
2495                 else
2496                   memset (tmp, 0, sizeof (tmp));
2497                 memcpy (tmp, second_arg_data, second_arg_length);
2498                 regcache->cooked_write (info->argloc[1].loc_data.regno, tmp);
2499               }
2500               break;
2501
2502             case riscv_arg_info::location::on_stack:
2503               {
2504                 CORE_ADDR arg_addr;
2505
2506                 arg_addr = sp_args + info->argloc[1].loc_data.offset;
2507                 write_memory (arg_addr, second_arg_data, second_arg_length);
2508                 break;
2509               }
2510
2511             case riscv_arg_info::location::by_ref:
2512             default:
2513               /* The second location should never be a reference, any
2514                  argument being passed by reference just places its address
2515                  in the first location and is done.  */
2516               error (_("invalid argument location"));
2517               break;
2518             }
2519         }
2520     }
2521
2522   /* Set the dummy return value to bp_addr.
2523      A dummy breakpoint will be setup to execute the call.  */
2524
2525   if (riscv_debug_infcall > 0)
2526     fprintf_unfiltered (gdb_stdlog, ": writing $ra = %s\n",
2527                         core_addr_to_string (bp_addr));
2528   regcache_cooked_write_unsigned (regcache, RISCV_RA_REGNUM, bp_addr);
2529
2530   /* Finally, update the stack pointer.  */
2531
2532   if (riscv_debug_infcall > 0)
2533     fprintf_unfiltered (gdb_stdlog, ": writing $sp = %s\n",
2534                         core_addr_to_string (sp));
2535   regcache_cooked_write_unsigned (regcache, RISCV_SP_REGNUM, sp);
2536
2537   return sp;
2538 }
2539
2540 /* Implement the return_value gdbarch method.  */
2541
2542 static enum return_value_convention
2543 riscv_return_value (struct gdbarch  *gdbarch,
2544                     struct value *function,
2545                     struct type *type,
2546                     struct regcache *regcache,
2547                     gdb_byte *readbuf,
2548                     const gdb_byte *writebuf)
2549 {
2550   struct riscv_call_info call_info (gdbarch);
2551   struct riscv_arg_info info;
2552   struct type *arg_type;
2553
2554   arg_type = check_typedef (type);
2555   riscv_arg_location (gdbarch, &info, &call_info, arg_type, false);
2556
2557   if (riscv_debug_infcall > 0)
2558     {
2559       fprintf_unfiltered (gdb_stdlog, "riscv return value:\n");
2560       fprintf_unfiltered (gdb_stdlog, "[R] ");
2561       riscv_print_arg_location (gdb_stdlog, gdbarch, &info, 0, 0);
2562       fprintf_unfiltered (gdb_stdlog, "\n");
2563     }
2564
2565   if (readbuf != nullptr || writebuf != nullptr)
2566     {
2567         int regnum;
2568
2569         switch (info.argloc[0].loc_type)
2570           {
2571             /* Return value in register(s).  */
2572           case riscv_arg_info::location::in_reg:
2573             {
2574               regnum = info.argloc[0].loc_data.regno;
2575
2576               if (readbuf)
2577                 regcache->cooked_read (regnum, readbuf);
2578
2579               if (writebuf)
2580                 regcache->cooked_write (regnum, writebuf);
2581
2582               /* A return value in register can have a second part in a
2583                  second register.  */
2584               if (info.argloc[0].c_length < info.length)
2585                 {
2586                   switch (info.argloc[1].loc_type)
2587                     {
2588                     case riscv_arg_info::location::in_reg:
2589                       regnum = info.argloc[1].loc_data.regno;
2590
2591                       if (readbuf)
2592                         {
2593                           readbuf += info.argloc[1].c_offset;
2594                           regcache->cooked_read (regnum, readbuf);
2595                         }
2596
2597                       if (writebuf)
2598                         {
2599                           writebuf += info.argloc[1].c_offset;
2600                           regcache->cooked_write (regnum, writebuf);
2601                         }
2602                       break;
2603
2604                     case riscv_arg_info::location::by_ref:
2605                     case riscv_arg_info::location::on_stack:
2606                     default:
2607                       error (_("invalid argument location"));
2608                       break;
2609                     }
2610                 }
2611             }
2612             break;
2613
2614             /* Return value by reference will have its address in A0.  */
2615           case riscv_arg_info::location::by_ref:
2616             {
2617               ULONGEST addr;
2618
2619               regcache_cooked_read_unsigned (regcache, RISCV_A0_REGNUM,
2620                                              &addr);
2621               if (readbuf != nullptr)
2622                 read_memory (addr, readbuf, info.length);
2623               if (writebuf != nullptr)
2624                 write_memory (addr, writebuf, info.length);
2625             }
2626             break;
2627
2628           case riscv_arg_info::location::on_stack:
2629           default:
2630             error (_("invalid argument location"));
2631             break;
2632           }
2633     }
2634
2635   switch (info.argloc[0].loc_type)
2636     {
2637     case riscv_arg_info::location::in_reg:
2638       return RETURN_VALUE_REGISTER_CONVENTION;
2639     case riscv_arg_info::location::by_ref:
2640       return RETURN_VALUE_ABI_RETURNS_ADDRESS;
2641     case riscv_arg_info::location::on_stack:
2642     default:
2643       error (_("invalid argument location"));
2644     }
2645 }
2646
2647 /* Implement the frame_align gdbarch method.  */
2648
2649 static CORE_ADDR
2650 riscv_frame_align (struct gdbarch *gdbarch, CORE_ADDR addr)
2651 {
2652   return align_down (addr, 16);
2653 }
2654
2655 /* Implement the unwind_pc gdbarch method.  */
2656
2657 static CORE_ADDR
2658 riscv_unwind_pc (struct gdbarch *gdbarch, struct frame_info *next_frame)
2659 {
2660   return frame_unwind_register_unsigned (next_frame, RISCV_PC_REGNUM);
2661 }
2662
2663 /* Implement the unwind_sp gdbarch method.  */
2664
2665 static CORE_ADDR
2666 riscv_unwind_sp (struct gdbarch *gdbarch, struct frame_info *next_frame)
2667 {
2668   return frame_unwind_register_unsigned (next_frame, RISCV_SP_REGNUM);
2669 }
2670
2671 /* Implement the dummy_id gdbarch method.  */
2672
2673 static struct frame_id
2674 riscv_dummy_id (struct gdbarch *gdbarch, struct frame_info *this_frame)
2675 {
2676   return frame_id_build (get_frame_register_signed (this_frame, RISCV_SP_REGNUM),
2677                          get_frame_pc (this_frame));
2678 }
2679
2680 /* Generate, or return the cached frame cache for the RiscV frame
2681    unwinder.  */
2682
2683 static struct riscv_unwind_cache *
2684 riscv_frame_cache (struct frame_info *this_frame, void **this_cache)
2685 {
2686   CORE_ADDR pc, start_addr;
2687   struct riscv_unwind_cache *cache;
2688   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2689   int numregs, regno;
2690
2691   if ((*this_cache) != NULL)
2692     return (struct riscv_unwind_cache *) *this_cache;
2693
2694   cache = FRAME_OBSTACK_ZALLOC (struct riscv_unwind_cache);
2695   cache->regs = trad_frame_alloc_saved_regs (this_frame);
2696   (*this_cache) = cache;
2697
2698   /* Scan the prologue, filling in the cache.  */
2699   start_addr = get_frame_func (this_frame);
2700   pc = get_frame_pc (this_frame);
2701   riscv_scan_prologue (gdbarch, start_addr, pc, cache);
2702
2703   /* We can now calculate the frame base address.  */
2704   cache->frame_base
2705     = (get_frame_register_signed (this_frame, cache->frame_base_reg)
2706        + cache->frame_base_offset);
2707   if (riscv_debug_unwinder)
2708     fprintf_unfiltered (gdb_stdlog, "Frame base is %s ($%s + 0x%x)\n",
2709                         core_addr_to_string (cache->frame_base),
2710                         gdbarch_register_name (gdbarch,
2711                                                cache->frame_base_reg),
2712                         cache->frame_base_offset);
2713
2714   /* The prologue scanner sets the address of registers stored to the stack
2715      as the offset of that register from the frame base.  The prologue
2716      scanner doesn't know the actual frame base value, and so is unable to
2717      compute the exact address.  We do now know the frame base value, so
2718      update the address of registers stored to the stack.  */
2719   numregs = gdbarch_num_regs (gdbarch) + gdbarch_num_pseudo_regs (gdbarch);
2720   for (regno = 0; regno < numregs; ++regno)
2721     {
2722       if (trad_frame_addr_p (cache->regs, regno))
2723         cache->regs[regno].addr += cache->frame_base;
2724     }
2725
2726   /* The previous $pc can be found wherever the $ra value can be found.
2727      The previous $ra value is gone, this would have been stored be the
2728      previous frame if required.  */
2729   cache->regs[gdbarch_pc_regnum (gdbarch)] = cache->regs[RISCV_RA_REGNUM];
2730   trad_frame_set_unknown (cache->regs, RISCV_RA_REGNUM);
2731
2732   /* Build the frame id.  */
2733   cache->this_id = frame_id_build (cache->frame_base, start_addr);
2734
2735   /* The previous $sp value is the frame base value.  */
2736   trad_frame_set_value (cache->regs, gdbarch_sp_regnum (gdbarch),
2737                         cache->frame_base);
2738
2739   return cache;
2740 }
2741
2742 /* Implement the this_id callback for RiscV frame unwinder.  */
2743
2744 static void
2745 riscv_frame_this_id (struct frame_info *this_frame,
2746                      void **prologue_cache,
2747                      struct frame_id *this_id)
2748 {
2749   struct riscv_unwind_cache *cache;
2750
2751   TRY
2752     {
2753       cache = riscv_frame_cache (this_frame, prologue_cache);
2754       *this_id = cache->this_id;
2755     }
2756   CATCH (ex, RETURN_MASK_ERROR)
2757     {
2758       /* Ignore errors, this leaves the frame id as the predefined outer
2759          frame id which terminates the backtrace at this point.  */
2760     }
2761   END_CATCH
2762 }
2763
2764 /* Implement the prev_register callback for RiscV frame unwinder.  */
2765
2766 static struct value *
2767 riscv_frame_prev_register (struct frame_info *this_frame,
2768                            void **prologue_cache,
2769                            int regnum)
2770 {
2771   struct riscv_unwind_cache *cache;
2772
2773   cache = riscv_frame_cache (this_frame, prologue_cache);
2774   return trad_frame_get_prev_register (this_frame, cache->regs, regnum);
2775 }
2776
2777 /* Structure defining the RiscV normal frame unwind functions.  Since we
2778    are the fallback unwinder (DWARF unwinder is used first), we use the
2779    default frame sniffer, which always accepts the frame.  */
2780
2781 static const struct frame_unwind riscv_frame_unwind =
2782 {
2783   /*.type          =*/ NORMAL_FRAME,
2784   /*.stop_reason   =*/ default_frame_unwind_stop_reason,
2785   /*.this_id       =*/ riscv_frame_this_id,
2786   /*.prev_register =*/ riscv_frame_prev_register,
2787   /*.unwind_data   =*/ NULL,
2788   /*.sniffer       =*/ default_frame_sniffer,
2789   /*.dealloc_cache =*/ NULL,
2790   /*.prev_arch     =*/ NULL,
2791 };
2792
2793 /* Extract a set of required target features out of INFO, specifically the
2794    bfd being executed is examined to see what target features it requires.
2795    IF there is no current bfd, or the bfd doesn't indicate any useful
2796    features then a RISCV_GDBARCH_FEATURES is returned in its default state.  */
2797
2798 static struct riscv_gdbarch_features
2799 riscv_features_from_gdbarch_info (const struct gdbarch_info info)
2800 {
2801   struct riscv_gdbarch_features features;
2802
2803   /* Now try to improve on the defaults by looking at the binary we are
2804      going to execute.  We assume the user knows what they are doing and
2805      that the target will match the binary.  Remember, this code path is
2806      only used at all if the target hasn't given us a description, so this
2807      is really a last ditched effort to do something sane before giving
2808      up.  */
2809   if (info.abfd != NULL
2810       && bfd_get_flavour (info.abfd) == bfd_target_elf_flavour)
2811     {
2812       unsigned char eclass = elf_elfheader (info.abfd)->e_ident[EI_CLASS];
2813       int e_flags = elf_elfheader (info.abfd)->e_flags;
2814
2815       if (eclass == ELFCLASS32)
2816         features.xlen = 4;
2817       else if (eclass == ELFCLASS64)
2818         features.xlen = 8;
2819       else
2820         internal_error (__FILE__, __LINE__,
2821                         _("unknown ELF header class %d"), eclass);
2822
2823       if (e_flags & EF_RISCV_FLOAT_ABI_DOUBLE)
2824         {
2825           features.flen = 8;
2826           features.hw_float_abi = true;
2827         }
2828       else if (e_flags & EF_RISCV_FLOAT_ABI_SINGLE)
2829         {
2830           features.flen = 4;
2831           features.hw_float_abi = true;
2832         }
2833     }
2834   else
2835     {
2836       const struct bfd_arch_info *binfo = info.bfd_arch_info;
2837
2838       if (binfo->bits_per_word == 32)
2839         features.xlen = 4;
2840       else if (binfo->bits_per_word == 64)
2841         features.xlen = 8;
2842       else
2843         internal_error (__FILE__, __LINE__, _("unknown bits_per_word %d"),
2844                         binfo->bits_per_word);
2845     }
2846
2847   return features;
2848 }
2849
2850 /* Find a suitable default target description.  Use the contents of INFO,
2851    specifically the bfd object being executed, to guide the selection of a
2852    suitable default target description.  */
2853
2854 static const struct target_desc *
2855 riscv_find_default_target_description (const struct gdbarch_info info)
2856 {
2857   /* Extract desired feature set from INFO.  */
2858   struct riscv_gdbarch_features features
2859     = riscv_features_from_gdbarch_info (info);
2860
2861   /* If the XLEN field is still 0 then we got nothing useful from INFO.  In
2862      this case we fall back to a minimal useful target, 8-byte x-registers,
2863      with no floating point.  */
2864   if (features.xlen == 0)
2865     features.xlen = 8;
2866
2867   /* Now build a target description based on the feature set.  */
2868   return riscv_create_target_description (features);
2869 }
2870
2871 /* All of the registers in REG_SET are checked for in FEATURE, TDESC_DATA
2872    is updated with the register numbers for each register as listed in
2873    REG_SET.  If any register marked as required in REG_SET is not found in
2874    FEATURE then this function returns false, otherwise, it returns true.  */
2875
2876 static bool
2877 riscv_check_tdesc_feature (struct tdesc_arch_data *tdesc_data,
2878                            const struct tdesc_feature *feature,
2879                            const struct riscv_register_feature *reg_set)
2880 {
2881   for (const auto &reg : reg_set->registers)
2882     {
2883       bool found = false;
2884
2885       for (const char *name : reg.names)
2886         {
2887           found =
2888             tdesc_numbered_register (feature, tdesc_data, reg.regnum, name);
2889
2890           if (found)
2891             break;
2892         }
2893
2894       if (!found && reg.required_p)
2895         return false;
2896     }
2897
2898   return true;
2899 }
2900
2901 /* Add all the expected register sets into GDBARCH.  */
2902
2903 static void
2904 riscv_add_reggroups (struct gdbarch *gdbarch)
2905 {
2906   /* Add predefined register groups.  */
2907   reggroup_add (gdbarch, all_reggroup);
2908   reggroup_add (gdbarch, save_reggroup);
2909   reggroup_add (gdbarch, restore_reggroup);
2910   reggroup_add (gdbarch, system_reggroup);
2911   reggroup_add (gdbarch, vector_reggroup);
2912   reggroup_add (gdbarch, general_reggroup);
2913   reggroup_add (gdbarch, float_reggroup);
2914
2915   /* Add RISC-V specific register groups.  */
2916   reggroup_add (gdbarch, csr_reggroup);
2917 }
2918
2919 /* Create register aliases for all the alternative names that exist for
2920    registers in REG_SET.  */
2921
2922 static void
2923 riscv_setup_register_aliases (struct gdbarch *gdbarch,
2924                               const struct riscv_register_feature *reg_set)
2925 {
2926   for (auto &reg : reg_set->registers)
2927     {
2928       /* The first item in the names list is the preferred name for the
2929          register, this is what RISCV_REGISTER_NAME returns, and so we
2930          don't need to create an alias with that name here.  */
2931       for (int i = 1; i < reg.names.size (); ++i)
2932         user_reg_add (gdbarch, reg.names[i], value_of_riscv_user_reg,
2933                       &reg.regnum);
2934     }
2935 }
2936
2937 /* Initialize the current architecture based on INFO.  If possible,
2938    re-use an architecture from ARCHES, which is a list of
2939    architectures already created during this debugging session.
2940
2941    Called e.g. at program startup, when reading a core file, and when
2942    reading a binary file.  */
2943
2944 static struct gdbarch *
2945 riscv_gdbarch_init (struct gdbarch_info info,
2946                     struct gdbarch_list *arches)
2947 {
2948   struct gdbarch *gdbarch;
2949   struct gdbarch_tdep *tdep;
2950   struct riscv_gdbarch_features features;
2951   const struct target_desc *tdesc = info.target_desc;
2952
2953   /* Ensure we always have a target description.  */
2954   if (!tdesc_has_registers (tdesc))
2955     tdesc = riscv_find_default_target_description (info);
2956   gdb_assert (tdesc);
2957
2958   if (riscv_debug_gdbarch)
2959     fprintf_unfiltered (gdb_stdlog, "Have got a target description\n");
2960
2961   const struct tdesc_feature *feature_cpu
2962     = tdesc_find_feature (tdesc, riscv_xreg_feature.name);
2963   const struct tdesc_feature *feature_fpu
2964     = tdesc_find_feature (tdesc, riscv_freg_feature.name);
2965   const struct tdesc_feature *feature_virtual
2966     = tdesc_find_feature (tdesc, riscv_virtual_feature.name);
2967   const struct tdesc_feature *feature_csr
2968     = tdesc_find_feature (tdesc, riscv_csr_feature.name);
2969
2970   if (feature_cpu == NULL)
2971     return NULL;
2972
2973   struct tdesc_arch_data *tdesc_data = tdesc_data_alloc ();
2974
2975   bool valid_p = riscv_check_tdesc_feature (tdesc_data,
2976                                             feature_cpu,
2977                                             &riscv_xreg_feature);
2978   if (valid_p)
2979     {
2980       /* Check that all of the core cpu registers have the same bitsize.  */
2981       int xlen_bitsize = tdesc_register_bitsize (feature_cpu, "pc");
2982
2983       for (auto &tdesc_reg : feature_cpu->registers)
2984         valid_p &= (tdesc_reg->bitsize == xlen_bitsize);
2985
2986       if (riscv_debug_gdbarch)
2987         fprintf_filtered
2988           (gdb_stdlog,
2989            "From target-description, xlen = %d\n", xlen_bitsize);
2990
2991       features.xlen = (xlen_bitsize / 8);
2992     }
2993
2994   if (feature_fpu != NULL)
2995     {
2996       valid_p &= riscv_check_tdesc_feature (tdesc_data, feature_fpu,
2997                                             &riscv_freg_feature);
2998
2999       int bitsize = tdesc_register_bitsize (feature_fpu, "ft0");
3000       features.flen = (bitsize / 8);
3001
3002       if (riscv_debug_gdbarch)
3003         fprintf_filtered
3004           (gdb_stdlog,
3005            "From target-description, flen = %d\n", bitsize);
3006     }
3007   else
3008     {
3009       features.flen = 0;
3010
3011       if (riscv_debug_gdbarch)
3012         fprintf_filtered
3013           (gdb_stdlog,
3014            "No FPU in target-description, assume soft-float ABI\n");
3015     }
3016
3017   if (feature_virtual)
3018     riscv_check_tdesc_feature (tdesc_data, feature_virtual,
3019                                &riscv_virtual_feature);
3020
3021   if (feature_csr)
3022     riscv_check_tdesc_feature (tdesc_data, feature_csr,
3023                                &riscv_csr_feature);
3024
3025   if (!valid_p)
3026     {
3027       if (riscv_debug_gdbarch)
3028         fprintf_unfiltered (gdb_stdlog, "Target description is not valid\n");
3029       tdesc_data_cleanup (tdesc_data);
3030       return NULL;
3031     }
3032
3033   /* Have a look at what the supplied (if any) bfd object requires of the
3034      target, then check that this matches with what the target is
3035      providing.  */
3036   struct riscv_gdbarch_features info_features
3037     = riscv_features_from_gdbarch_info (info);
3038   if (info_features.xlen != 0 && info_features.xlen != features.xlen)
3039     error (_("bfd requires xlen %d, but target has xlen %d"),
3040            info_features.xlen, features.xlen);
3041   if (info_features.flen != 0 && info_features.flen != features.flen)
3042     error (_("bfd requires flen %d, but target has flen %d"),
3043            info_features.flen, features.flen);
3044
3045   /* If the xlen from INFO_FEATURES is 0 then this indicates either there
3046      is no bfd object, or nothing useful could be extracted from it, in
3047      this case we enable hardware float abi if the target has floating
3048      point registers.
3049
3050      If the xlen from INFO_FEATURES is not 0, and the flen in
3051      INFO_FEATURES is also not 0, then this indicates that the supplied
3052      bfd does require hardware floating point abi.  */
3053   if (info_features.xlen == 0 || info_features.flen != 0)
3054     features.hw_float_abi = (features.flen > 0);
3055
3056   /* Find a candidate among the list of pre-declared architectures.  */
3057   for (arches = gdbarch_list_lookup_by_info (arches, &info);
3058        arches != NULL;
3059        arches = gdbarch_list_lookup_by_info (arches->next, &info))
3060     {
3061       /* Check that the feature set of the ARCHES matches the feature set
3062          we are looking for.  If it doesn't then we can't reuse this
3063          gdbarch.  */
3064       struct gdbarch_tdep *other_tdep = gdbarch_tdep (arches->gdbarch);
3065
3066       if (other_tdep->features != features)
3067         continue;
3068
3069       break;
3070     }
3071
3072   if (arches != NULL)
3073     {
3074       tdesc_data_cleanup (tdesc_data);
3075       return arches->gdbarch;
3076     }
3077
3078   /* None found, so create a new architecture from the information provided.  */
3079   tdep = new (struct gdbarch_tdep);
3080   gdbarch = gdbarch_alloc (&info, tdep);
3081   tdep->features = features;
3082
3083   /* Target data types.  */
3084   set_gdbarch_short_bit (gdbarch, 16);
3085   set_gdbarch_int_bit (gdbarch, 32);
3086   set_gdbarch_long_bit (gdbarch, riscv_isa_xlen (gdbarch) * 8);
3087   set_gdbarch_long_long_bit (gdbarch, 64);
3088   set_gdbarch_float_bit (gdbarch, 32);
3089   set_gdbarch_double_bit (gdbarch, 64);
3090   set_gdbarch_long_double_bit (gdbarch, 128);
3091   set_gdbarch_long_double_format (gdbarch, floatformats_ia64_quad);
3092   set_gdbarch_ptr_bit (gdbarch, riscv_isa_xlen (gdbarch) * 8);
3093   set_gdbarch_char_signed (gdbarch, 0);
3094
3095   /* Information about the target architecture.  */
3096   set_gdbarch_return_value (gdbarch, riscv_return_value);
3097   set_gdbarch_breakpoint_kind_from_pc (gdbarch, riscv_breakpoint_kind_from_pc);
3098   set_gdbarch_sw_breakpoint_from_kind (gdbarch, riscv_sw_breakpoint_from_kind);
3099   set_gdbarch_have_nonsteppable_watchpoint (gdbarch, 1);
3100
3101   /* Functions to analyze frames.  */
3102   set_gdbarch_skip_prologue (gdbarch, riscv_skip_prologue);
3103   set_gdbarch_inner_than (gdbarch, core_addr_lessthan);
3104   set_gdbarch_frame_align (gdbarch, riscv_frame_align);
3105
3106   /* Functions to access frame data.  */
3107   set_gdbarch_unwind_pc (gdbarch, riscv_unwind_pc);
3108   set_gdbarch_unwind_sp (gdbarch, riscv_unwind_sp);
3109
3110   /* Functions handling dummy frames.  */
3111   set_gdbarch_call_dummy_location (gdbarch, ON_STACK);
3112   set_gdbarch_push_dummy_code (gdbarch, riscv_push_dummy_code);
3113   set_gdbarch_push_dummy_call (gdbarch, riscv_push_dummy_call);
3114   set_gdbarch_dummy_id (gdbarch, riscv_dummy_id);
3115
3116   /* Frame unwinders.  Use DWARF debug info if available, otherwise use our own
3117      unwinder.  */
3118   dwarf2_append_unwinders (gdbarch);
3119   frame_unwind_append_unwinder (gdbarch, &riscv_frame_unwind);
3120
3121   /* Register architecture.  */
3122   riscv_add_reggroups (gdbarch);
3123
3124   /* We reserve all possible register numbers for the known registers.
3125      This means the target description mechanism will add any target
3126      specific registers after this number.  This helps make debugging GDB
3127      just a little easier.  */
3128   set_gdbarch_num_regs (gdbarch, RISCV_LAST_REGNUM + 1);
3129
3130   /* We don't have to provide the count of 0 here (its the default) but
3131      include this line to make it explicit that, right now, we don't have
3132      any pseudo registers on RISC-V.  */
3133   set_gdbarch_num_pseudo_regs (gdbarch, 0);
3134
3135   /* Some specific register numbers GDB likes to know about.  */
3136   set_gdbarch_sp_regnum (gdbarch, RISCV_SP_REGNUM);
3137   set_gdbarch_pc_regnum (gdbarch, RISCV_PC_REGNUM);
3138
3139   set_gdbarch_print_registers_info (gdbarch, riscv_print_registers_info);
3140
3141   /* Finalise the target description registers.  */
3142   tdesc_use_registers (gdbarch, tdesc, tdesc_data);
3143
3144   /* Override the register type callback setup by the target description
3145      mechanism.  This allows us to provide special type for floating point
3146      registers.  */
3147   set_gdbarch_register_type (gdbarch, riscv_register_type);
3148
3149   /* Override the register name callback setup by the target description
3150      mechanism.  This allows us to force our preferred names for the
3151      registers, no matter what the target description called them.  */
3152   set_gdbarch_register_name (gdbarch, riscv_register_name);
3153
3154   /* Override the register group callback setup by the target description
3155      mechanism.  This allows us to force registers into the groups we
3156      want, ignoring what the target tells us.  */
3157   set_gdbarch_register_reggroup_p (gdbarch, riscv_register_reggroup_p);
3158
3159   /* Create register aliases for alternative register names.  */
3160   riscv_setup_register_aliases (gdbarch, &riscv_xreg_feature);
3161   if (riscv_has_fp_regs (gdbarch))
3162     riscv_setup_register_aliases (gdbarch, &riscv_freg_feature);
3163   riscv_setup_register_aliases (gdbarch, &riscv_csr_feature);
3164
3165   /* Hook in OS ABI-specific overrides, if they have been registered.  */
3166   gdbarch_init_osabi (info, gdbarch);
3167
3168   return gdbarch;
3169 }
3170
3171 /* This decodes the current instruction and determines the address of the
3172    next instruction.  */
3173
3174 static CORE_ADDR
3175 riscv_next_pc (struct regcache *regcache, CORE_ADDR pc)
3176 {
3177   struct gdbarch *gdbarch = regcache->arch ();
3178   struct riscv_insn insn;
3179   CORE_ADDR next_pc;
3180
3181   insn.decode (gdbarch, pc);
3182   next_pc = pc + insn.length ();
3183
3184   if (insn.opcode () == riscv_insn::JAL)
3185     next_pc = pc + insn.imm_signed ();
3186   else if (insn.opcode () == riscv_insn::JALR)
3187     {
3188       LONGEST source;
3189       regcache->cooked_read (insn.rs1 (), &source);
3190       next_pc = (source + insn.imm_signed ()) & ~(CORE_ADDR) 0x1;
3191     }
3192   else if (insn.opcode () == riscv_insn::BEQ)
3193     {
3194       LONGEST src1, src2;
3195       regcache->cooked_read (insn.rs1 (), &src1);
3196       regcache->cooked_read (insn.rs2 (), &src2);
3197       if (src1 == src2)
3198         next_pc = pc + insn.imm_signed ();
3199     }
3200   else if (insn.opcode () == riscv_insn::BNE)
3201     {
3202       LONGEST src1, src2;
3203       regcache->cooked_read (insn.rs1 (), &src1);
3204       regcache->cooked_read (insn.rs2 (), &src2);
3205       if (src1 != src2)
3206         next_pc = pc + insn.imm_signed ();
3207     }
3208   else if (insn.opcode () == riscv_insn::BLT)
3209     {
3210       LONGEST src1, src2;
3211       regcache->cooked_read (insn.rs1 (), &src1);
3212       regcache->cooked_read (insn.rs2 (), &src2);
3213       if (src1 < src2)
3214         next_pc = pc + insn.imm_signed ();
3215     }
3216   else if (insn.opcode () == riscv_insn::BGE)
3217     {
3218       LONGEST src1, src2;
3219       regcache->cooked_read (insn.rs1 (), &src1);
3220       regcache->cooked_read (insn.rs2 (), &src2);
3221       if (src1 >= src2)
3222         next_pc = pc + insn.imm_signed ();
3223     }
3224   else if (insn.opcode () == riscv_insn::BLTU)
3225     {
3226       ULONGEST src1, src2;
3227       regcache->cooked_read (insn.rs1 (), &src1);
3228       regcache->cooked_read (insn.rs2 (), &src2);
3229       if (src1 < src2)
3230         next_pc = pc + insn.imm_signed ();
3231     }
3232   else if (insn.opcode () == riscv_insn::BGEU)
3233     {
3234       ULONGEST src1, src2;
3235       regcache->cooked_read (insn.rs1 (), &src1);
3236       regcache->cooked_read (insn.rs2 (), &src2);
3237       if (src1 >= src2)
3238         next_pc = pc + insn.imm_signed ();
3239     }
3240
3241   return next_pc;
3242 }
3243
3244 /* We can't put a breakpoint in the middle of a lr/sc atomic sequence, so look
3245    for the end of the sequence and put the breakpoint there.  */
3246
3247 static bool
3248 riscv_next_pc_atomic_sequence (struct regcache *regcache, CORE_ADDR pc,
3249                                CORE_ADDR *next_pc)
3250 {
3251   struct gdbarch *gdbarch = regcache->arch ();
3252   struct riscv_insn insn;
3253   CORE_ADDR cur_step_pc = pc;
3254   CORE_ADDR last_addr = 0;
3255
3256   /* First instruction has to be a load reserved.  */
3257   insn.decode (gdbarch, cur_step_pc);
3258   if (insn.opcode () != riscv_insn::LR)
3259     return false;
3260   cur_step_pc = cur_step_pc + insn.length ();
3261
3262   /* Next instruction should be branch to exit.  */
3263   insn.decode (gdbarch, cur_step_pc);
3264   if (insn.opcode () != riscv_insn::BNE)
3265     return false;
3266   last_addr = cur_step_pc + insn.imm_signed ();
3267   cur_step_pc = cur_step_pc + insn.length ();
3268
3269   /* Next instruction should be store conditional.  */
3270   insn.decode (gdbarch, cur_step_pc);
3271   if (insn.opcode () != riscv_insn::SC)
3272     return false;
3273   cur_step_pc = cur_step_pc + insn.length ();
3274
3275   /* Next instruction should be branch to start.  */
3276   insn.decode (gdbarch, cur_step_pc);
3277   if (insn.opcode () != riscv_insn::BNE)
3278     return false;
3279   if (pc != (cur_step_pc + insn.imm_signed ()))
3280     return false;
3281   cur_step_pc = cur_step_pc + insn.length ();
3282
3283   /* We should now be at the end of the sequence.  */
3284   if (cur_step_pc != last_addr)
3285     return false;
3286
3287   *next_pc = cur_step_pc;
3288   return true;
3289 }
3290
3291 /* This is called just before we want to resume the inferior, if we want to
3292    single-step it but there is no hardware or kernel single-step support.  We
3293    find the target of the coming instruction and breakpoint it.  */
3294
3295 std::vector<CORE_ADDR>
3296 riscv_software_single_step (struct regcache *regcache)
3297 {
3298   CORE_ADDR pc, next_pc;
3299
3300   pc = regcache_read_pc (regcache);
3301
3302   if (riscv_next_pc_atomic_sequence (regcache, pc, &next_pc))
3303     return {next_pc};
3304
3305   next_pc = riscv_next_pc (regcache, pc);
3306
3307   return {next_pc};
3308 }
3309
3310 /* Create RISC-V specific reggroups.  */
3311
3312 static void
3313 riscv_init_reggroups ()
3314 {
3315   csr_reggroup = reggroup_new ("csr", USER_REGGROUP);
3316 }
3317
3318 void
3319 _initialize_riscv_tdep (void)
3320 {
3321   riscv_create_csr_aliases ();
3322   riscv_init_reggroups ();
3323
3324   gdbarch_register (bfd_arch_riscv, riscv_gdbarch_init, NULL);
3325
3326   /* Add root prefix command for all "set debug riscv" and "show debug
3327      riscv" commands.  */
3328   add_prefix_cmd ("riscv", no_class, set_debug_riscv_command,
3329                   _("RISC-V specific debug commands."),
3330                   &setdebugriscvcmdlist, "set debug riscv ", 0,
3331                   &setdebuglist);
3332
3333   add_prefix_cmd ("riscv", no_class, show_debug_riscv_command,
3334                   _("RISC-V specific debug commands."),
3335                   &showdebugriscvcmdlist, "show debug riscv ", 0,
3336                   &showdebuglist);
3337
3338   add_setshow_zuinteger_cmd ("breakpoints", class_maintenance,
3339                              &riscv_debug_breakpoints,  _("\
3340 Set riscv breakpoint debugging."), _("\
3341 Show riscv breakpoint debugging."), _("\
3342 When non-zero, print debugging information for the riscv specific parts\n\
3343 of the breakpoint mechanism."),
3344                              NULL,
3345                              show_riscv_debug_variable,
3346                              &setdebugriscvcmdlist, &showdebugriscvcmdlist);
3347
3348   add_setshow_zuinteger_cmd ("infcall", class_maintenance,
3349                              &riscv_debug_infcall,  _("\
3350 Set riscv inferior call debugging."), _("\
3351 Show riscv inferior call debugging."), _("\
3352 When non-zero, print debugging information for the riscv specific parts\n\
3353 of the inferior call mechanism."),
3354                              NULL,
3355                              show_riscv_debug_variable,
3356                              &setdebugriscvcmdlist, &showdebugriscvcmdlist);
3357
3358   add_setshow_zuinteger_cmd ("unwinder", class_maintenance,
3359                              &riscv_debug_unwinder,  _("\
3360 Set riscv stack unwinding debugging."), _("\
3361 Show riscv stack unwinding debugging."), _("\
3362 When non-zero, print debugging information for the riscv specific parts\n\
3363 of the stack unwinding mechanism."),
3364                              NULL,
3365                              show_riscv_debug_variable,
3366                              &setdebugriscvcmdlist, &showdebugriscvcmdlist);
3367
3368   add_setshow_zuinteger_cmd ("gdbarch", class_maintenance,
3369                              &riscv_debug_gdbarch,  _("\
3370 Set riscv gdbarch initialisation debugging."), _("\
3371 Show riscv gdbarch initialisation debugging."), _("\
3372 When non-zero, print debugging information for the riscv gdbarch\n\
3373 initialisation process."),
3374                              NULL,
3375                              show_riscv_debug_variable,
3376                              &setdebugriscvcmdlist, &showdebugriscvcmdlist);
3377
3378   /* Add root prefix command for all "set riscv" and "show riscv" commands.  */
3379   add_prefix_cmd ("riscv", no_class, set_riscv_command,
3380                   _("RISC-V specific commands."),
3381                   &setriscvcmdlist, "set riscv ", 0, &setlist);
3382
3383   add_prefix_cmd ("riscv", no_class, show_riscv_command,
3384                   _("RISC-V specific commands."),
3385                   &showriscvcmdlist, "show riscv ", 0, &showlist);
3386
3387
3388   use_compressed_breakpoints = AUTO_BOOLEAN_AUTO;
3389   add_setshow_auto_boolean_cmd ("use-compressed-breakpoints", no_class,
3390                                 &use_compressed_breakpoints,
3391                                 _("\
3392 Set debugger's use of compressed breakpoints."), _("    \
3393 Show debugger's use of compressed breakpoints."), _("\
3394 Debugging compressed code requires compressed breakpoints to be used. If\n\
3395 left to 'auto' then gdb will use them if the existing instruction is a\n\
3396 compressed instruction. If that doesn't give the correct behavior, then\n\
3397 this option can be used."),
3398                                 NULL,
3399                                 show_use_compressed_breakpoints,
3400                                 &setriscvcmdlist,
3401                                 &showriscvcmdlist);
3402 }