Regenerate configure and pot files with updated binutils version number.
[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
58 /* The stack must be 16-byte aligned.  */
59 #define SP_ALIGNMENT 16
60
61 /* Forward declarations.  */
62 static bool riscv_has_feature (struct gdbarch *gdbarch, char feature);
63 struct riscv_inferior_data;
64 struct riscv_inferior_data * riscv_inferior_data (struct inferior *const inf);
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 /* Per inferior information for RiscV.  */
77
78 struct riscv_inferior_data
79 {
80   /* True when MISA_VALUE is valid, otherwise false.  */
81   bool misa_read;
82
83   /* If MISA_READ is true then MISA_VALUE holds the value of the MISA
84      register read from the target.  */
85   uint32_t misa_value;
86 };
87
88 /* Key created when the RiscV per-inferior data is registered.  */
89
90 static const struct inferior_data *riscv_inferior_data_reg;
91
92 /* Architectural name for core registers.  */
93
94 static const char * const riscv_gdb_reg_names[RISCV_LAST_FP_REGNUM + 1] =
95 {
96   "x0",  "x1",  "x2",  "x3",  "x4",  "x5",  "x6",  "x7",
97   "x8",  "x9",  "x10", "x11", "x12", "x13", "x14", "x15",
98   "x16", "x17", "x18", "x19", "x20", "x21", "x22", "x23",
99   "x24", "x25", "x26", "x27", "x28", "x29", "x30", "x31",
100   "pc",
101   "f0",  "f1",  "f2",  "f3",  "f4",  "f5",  "f6",  "f7",
102   "f8",  "f9",  "f10", "f11", "f12", "f13", "f14", "f15",
103   "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23",
104   "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31",
105 };
106
107 /* Maps "pretty" register names onto their GDB register number.  */
108
109 struct register_alias
110 {
111   /* The register alias.  Usually more descriptive than the
112      architectural name of the register.  */
113   const char *name;
114
115   /* The GDB register number.  */
116   int regnum;
117 };
118
119 /* Table of register aliases.  */
120
121 static const struct register_alias riscv_register_aliases[] =
122 {
123   { "zero", 0 },
124   { "ra", 1 },
125   { "sp", 2 },
126   { "gp", 3 },
127   { "tp", 4 },
128   { "t0", 5 },
129   { "t1", 6 },
130   { "t2", 7 },
131   { "fp", 8 },
132   { "s0", 8 },
133   { "s1", 9 },
134   { "a0", 10 },
135   { "a1", 11 },
136   { "a2", 12 },
137   { "a3", 13 },
138   { "a4", 14 },
139   { "a5", 15 },
140   { "a6", 16 },
141   { "a7", 17 },
142   { "s2", 18 },
143   { "s3", 19 },
144   { "s4", 20 },
145   { "s5", 21 },
146   { "s6", 22 },
147   { "s7", 23 },
148   { "s8", 24 },
149   { "s9", 25 },
150   { "s10", 26 },
151   { "s11", 27 },
152   { "t3", 28 },
153   { "t4", 29 },
154   { "t5", 30 },
155   { "t6", 31 },
156   /* pc is 32.  */
157   { "ft0", 33 },
158   { "ft1", 34 },
159   { "ft2", 35 },
160   { "ft3", 36 },
161   { "ft4", 37 },
162   { "ft5", 38 },
163   { "ft6", 39 },
164   { "ft7", 40 },
165   { "fs0", 41 },
166   { "fs1", 42 },
167   { "fa0", 43 },
168   { "fa1", 44 },
169   { "fa2", 45 },
170   { "fa3", 46 },
171   { "fa4", 47 },
172   { "fa5", 48 },
173   { "fa6", 49 },
174   { "fa7", 50 },
175   { "fs2", 51 },
176   { "fs3", 52 },
177   { "fs4", 53 },
178   { "fs5", 54 },
179   { "fs6", 55 },
180   { "fs7", 56 },
181   { "fs8", 57 },
182   { "fs9", 58 },
183   { "fs10", 59 },
184   { "fs11", 60 },
185   { "ft8", 61 },
186   { "ft9", 62 },
187   { "ft10", 63 },
188   { "ft11", 64 },
189 #define DECLARE_CSR(name, num) { #name, (num) + 65 },
190 #include "opcode/riscv-opc.h"
191 #undef DECLARE_CSR
192 };
193
194 /* Controls whether we place compressed breakpoints or not.  When in auto
195    mode GDB tries to determine if the target supports compressed
196    breakpoints, and uses them if it does.  */
197
198 static enum auto_boolean use_compressed_breakpoints;
199
200 /* The show callback for 'show riscv use-compressed-breakpoints'.  */
201
202 static void
203 show_use_compressed_breakpoints (struct ui_file *file, int from_tty,
204                                  struct cmd_list_element *c,
205                                  const char *value)
206 {
207   const char *additional_info;
208   struct gdbarch *gdbarch = target_gdbarch ();
209
210   if (use_compressed_breakpoints == AUTO_BOOLEAN_AUTO)
211     if (riscv_has_feature (gdbarch, 'C'))
212       additional_info = _(" (currently on)");
213     else
214       additional_info = _(" (currently off)");
215   else
216     additional_info = "";
217
218   fprintf_filtered (file,
219                     _("Debugger's use of compressed breakpoints is set "
220                       "to %s%s.\n"), value, additional_info);
221 }
222
223 /* The set and show lists for 'set riscv' and 'show riscv' prefixes.  */
224
225 static struct cmd_list_element *setriscvcmdlist = NULL;
226 static struct cmd_list_element *showriscvcmdlist = NULL;
227
228 /* The show callback for the 'show riscv' prefix command.  */
229
230 static void
231 show_riscv_command (const char *args, int from_tty)
232 {
233   help_list (showriscvcmdlist, "show riscv ", all_commands, gdb_stdout);
234 }
235
236 /* The set callback for the 'set riscv' prefix command.  */
237
238 static void
239 set_riscv_command (const char *args, int from_tty)
240 {
241   printf_unfiltered
242     (_("\"set riscv\" must be followed by an appropriate subcommand.\n"));
243   help_list (setriscvcmdlist, "set riscv ", all_commands, gdb_stdout);
244 }
245
246 /* The set and show lists for 'set riscv' and 'show riscv' prefixes.  */
247
248 static struct cmd_list_element *setdebugriscvcmdlist = NULL;
249 static struct cmd_list_element *showdebugriscvcmdlist = NULL;
250
251 /* The show callback for the 'show debug riscv' prefix command.  */
252
253 static void
254 show_debug_riscv_command (const char *args, int from_tty)
255 {
256   help_list (showdebugriscvcmdlist, "show debug riscv ", all_commands, gdb_stdout);
257 }
258
259 /* The set callback for the 'set debug riscv' prefix command.  */
260
261 static void
262 set_debug_riscv_command (const char *args, int from_tty)
263 {
264   printf_unfiltered
265     (_("\"set debug riscv\" must be followed by an appropriate subcommand.\n"));
266   help_list (setdebugriscvcmdlist, "set debug riscv ", all_commands, gdb_stdout);
267 }
268
269 /* The show callback for all 'show debug riscv VARNAME' variables.  */
270
271 static void
272 show_riscv_debug_variable (struct ui_file *file, int from_tty,
273                            struct cmd_list_element *c,
274                            const char *value)
275 {
276   fprintf_filtered (file,
277                     _("RiscV debug variable `%s' is set to: %s\n"),
278                     c->name, value);
279 }
280
281 /* When this is set to non-zero debugging information about inferior calls
282    will be printed.  */
283
284 static unsigned int riscv_debug_infcall = 0;
285
286 /* Read the MISA register from the target.  The register will only be read
287    once, and the value read will be cached.  If the register can't be read
288    from the target then a default value (0) will be returned.  If the
289    pointer READ_P is not null, then the bool pointed to is updated  to
290    indicate if the value returned was read from the target (true) or is the
291    default (false).  */
292
293 static uint32_t
294 riscv_read_misa_reg (bool *read_p)
295 {
296   struct riscv_inferior_data *inf_data
297     = riscv_inferior_data (current_inferior ());
298
299   if (!inf_data->misa_read && target_has_registers)
300     {
301       uint32_t value = 0;
302       struct frame_info *frame = get_current_frame ();
303
304       TRY
305         {
306           value = get_frame_register_unsigned (frame, RISCV_CSR_MISA_REGNUM);
307         }
308       CATCH (ex, RETURN_MASK_ERROR)
309         {
310           /* Old cores might have MISA located at a different offset.  */
311           value = get_frame_register_unsigned (frame,
312                                                RISCV_CSR_LEGACY_MISA_REGNUM);
313         }
314       END_CATCH
315
316       inf_data->misa_read = true;
317       inf_data->misa_value = value;
318     }
319
320   if (read_p != nullptr)
321     *read_p = inf_data->misa_read;
322
323   return inf_data->misa_value;
324 }
325
326 /* Return true if FEATURE is available for the architecture GDBARCH.  The
327    FEATURE should be one of the single character feature codes described in
328    the RiscV ISA manual, these are between 'A' and 'Z'.  */
329
330 static bool
331 riscv_has_feature (struct gdbarch *gdbarch, char feature)
332 {
333   bool have_read_misa = false;
334   uint32_t misa;
335
336   gdb_assert (feature >= 'A' && feature <= 'Z');
337
338   /* It would be nice to always check with the real target where possible,
339      however, for compressed instructions this is a bad idea.
340
341      The call to `set_gdbarch_decr_pc_after_break' is made just once per
342      GDBARCH and we decide at that point if we should decrement by 2 or 4
343      bytes based on whether the BFD has compressed instruction support or
344      not.
345
346      If the BFD was not compiled with compressed instruction support, but we
347      are running on a target with compressed instructions then we might
348      place a 4-byte breakpoint, then decrement the $pc by 2 bytes leading to
349      confusion.
350
351      It's safer if we just make decisions about compressed instruction
352      support based on the BFD.  */
353   if (feature != 'C')
354     misa = riscv_read_misa_reg (&have_read_misa);
355   if (!have_read_misa || misa == 0)
356     misa = gdbarch_tdep (gdbarch)->core_features;
357
358   return (misa & (1 << (feature - 'A'))) != 0;
359 }
360
361 /* Return the width in bytes  of the general purpose registers for GDBARCH.
362    Possible return values are 4, 8, or 16 for RiscV variants RV32, RV64, or
363    RV128.  */
364
365 static int
366 riscv_isa_xlen (struct gdbarch *gdbarch)
367 {
368   switch (gdbarch_tdep (gdbarch)->abi.fields.base_len)
369     {
370     default:
371       warning (_("unknown xlen size, assuming 4 bytes"));
372       /* Fall through.  */
373     case 1:
374       return 4;
375     case 2:
376       return 8;
377     case 3:
378       return 16;
379     }
380 }
381
382 /* Return the width in bytes of the floating point registers for GDBARCH.
383    If this architecture has no floating point registers, then return 0.
384    Possible values are 4, 8, or 16 for depending on which of single, double
385    or quad floating point support is available.  */
386
387 static int
388 riscv_isa_flen (struct gdbarch *gdbarch)
389 {
390   if (riscv_has_feature (gdbarch, 'Q'))
391     return 16;
392   else if (riscv_has_feature (gdbarch, 'D'))
393     return 8;
394   else if (riscv_has_feature (gdbarch, 'F'))
395     return 4;
396
397   return 0;
398 }
399
400 /* Return true if the target for GDBARCH has floating point hardware.  */
401
402 static bool
403 riscv_has_fp_regs (struct gdbarch *gdbarch)
404 {
405   return (riscv_isa_flen (gdbarch) > 0);
406 }
407
408 /* Return true if GDBARCH is using any of the floating point hardware ABIs.  */
409
410 static bool
411 riscv_has_fp_abi (struct gdbarch *gdbarch)
412 {
413   return (gdbarch_tdep (gdbarch)->abi.fields.float_abi != 0);
414 }
415
416 /* Implement the breakpoint_kind_from_pc gdbarch method.  */
417
418 static int
419 riscv_breakpoint_kind_from_pc (struct gdbarch *gdbarch, CORE_ADDR *pcptr)
420 {
421   if (use_compressed_breakpoints == AUTO_BOOLEAN_AUTO)
422     {
423       if (riscv_has_feature (gdbarch, 'C'))
424         return 2;
425       else
426         return 4;
427     }
428   else if (use_compressed_breakpoints == AUTO_BOOLEAN_TRUE)
429     return 2;
430   else
431     return 4;
432 }
433
434 /* Implement the sw_breakpoint_from_kind gdbarch method.  */
435
436 static const gdb_byte *
437 riscv_sw_breakpoint_from_kind (struct gdbarch *gdbarch, int kind, int *size)
438 {
439   static const gdb_byte ebreak[] = { 0x73, 0x00, 0x10, 0x00, };
440   static const gdb_byte c_ebreak[] = { 0x02, 0x90 };
441
442   *size = kind;
443   switch (kind)
444     {
445     case 2:
446       return c_ebreak;
447     case 4:
448       return ebreak;
449     default:
450       gdb_assert_not_reached (_("unhandled breakpoint kind"));
451     }
452 }
453
454 /* Callback function for user_reg_add.  */
455
456 static struct value *
457 value_of_riscv_user_reg (struct frame_info *frame, const void *baton)
458 {
459   const int *reg_p = (const int *) baton;
460   return value_of_register (*reg_p, frame);
461 }
462
463 /* Implement the register_name gdbarch method.  */
464
465 static const char *
466 riscv_register_name (struct gdbarch *gdbarch, int regnum)
467 {
468   /* Prefer to use the alias. */
469   if (regnum >= RISCV_ZERO_REGNUM && regnum <= RISCV_LAST_REGNUM)
470     {
471       int i;
472
473       for (i = 0; i < ARRAY_SIZE (riscv_register_aliases); ++i)
474         if (regnum == riscv_register_aliases[i].regnum)
475           return riscv_register_aliases[i].name;
476     }
477
478   if (regnum >= RISCV_ZERO_REGNUM && regnum <= RISCV_LAST_FP_REGNUM)
479     return riscv_gdb_reg_names[regnum];
480
481   if (regnum >= RISCV_FIRST_CSR_REGNUM && regnum <= RISCV_LAST_CSR_REGNUM)
482     {
483       static char buf[20];
484
485       xsnprintf (buf, sizeof (buf), "csr%d",
486                  regnum - RISCV_FIRST_CSR_REGNUM);
487       return buf;
488     }
489
490   if (regnum == RISCV_PRIV_REGNUM)
491     return "priv";
492
493   return NULL;
494 }
495
496 /* Implement the register_type gdbarch method.  */
497
498 static struct type *
499 riscv_register_type (struct gdbarch *gdbarch, int regnum)
500 {
501   int regsize;
502
503   if (regnum < RISCV_FIRST_FP_REGNUM)
504     {
505       if (regnum == gdbarch_pc_regnum (gdbarch)
506           || regnum == RISCV_RA_REGNUM)
507         return builtin_type (gdbarch)->builtin_func_ptr;
508
509       if (regnum == RISCV_FP_REGNUM
510           || regnum == RISCV_SP_REGNUM
511           || regnum == RISCV_GP_REGNUM
512           || regnum == RISCV_TP_REGNUM)
513         return builtin_type (gdbarch)->builtin_data_ptr;
514
515       /* Remaining GPRs vary in size based on the current ISA.  */
516       regsize = riscv_isa_xlen (gdbarch);
517       switch (regsize)
518         {
519         case 4:
520           return builtin_type (gdbarch)->builtin_uint32;
521         case 8:
522           return builtin_type (gdbarch)->builtin_uint64;
523         case 16:
524           return builtin_type (gdbarch)->builtin_uint128;
525         default:
526           internal_error (__FILE__, __LINE__,
527                           _("unknown isa regsize %i"), regsize);
528         }
529     }
530   else if (regnum <= RISCV_LAST_FP_REGNUM)
531     {
532       regsize = riscv_isa_xlen (gdbarch);
533       switch (regsize)
534         {
535         case 4:
536           return builtin_type (gdbarch)->builtin_float;
537         case 8:
538           return builtin_type (gdbarch)->builtin_double;
539         case 16:
540           return builtin_type (gdbarch)->builtin_long_double;
541         default:
542           internal_error (__FILE__, __LINE__,
543                           _("unknown isa regsize %i"), regsize);
544         }
545     }
546   else if (regnum == RISCV_PRIV_REGNUM)
547     return builtin_type (gdbarch)->builtin_int8;
548   else
549     {
550       if (regnum == RISCV_CSR_FFLAGS_REGNUM
551           || regnum == RISCV_CSR_FRM_REGNUM
552           || regnum == RISCV_CSR_FCSR_REGNUM)
553         return builtin_type (gdbarch)->builtin_int32;
554
555       regsize = riscv_isa_xlen (gdbarch);
556       switch (regsize)
557         {
558         case 4:
559           return builtin_type (gdbarch)->builtin_int32;
560         case 8:
561           return builtin_type (gdbarch)->builtin_int64;
562         case 16:
563           return builtin_type (gdbarch)->builtin_int128;
564         default:
565           internal_error (__FILE__, __LINE__,
566                           _("unknown isa regsize %i"), regsize);
567         }
568     }
569 }
570
571 /* Helper for riscv_print_registers_info, prints info for a single register
572    REGNUM.  */
573
574 static void
575 riscv_print_one_register_info (struct gdbarch *gdbarch,
576                                struct ui_file *file,
577                                struct frame_info *frame,
578                                int regnum)
579 {
580   const char *name = gdbarch_register_name (gdbarch, regnum);
581   struct value *val = value_of_register (regnum, frame);
582   struct type *regtype = value_type (val);
583   int print_raw_format;
584   enum tab_stops { value_column_1 = 15 };
585
586   fputs_filtered (name, file);
587   print_spaces_filtered (value_column_1 - strlen (name), file);
588
589   print_raw_format = (value_entirely_available (val)
590                       && !value_optimized_out (val));
591
592   if (TYPE_CODE (regtype) == TYPE_CODE_FLT)
593     {
594       struct value_print_options opts;
595       const gdb_byte *valaddr = value_contents_for_printing (val);
596       enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (regtype));
597
598       get_user_print_options (&opts);
599       opts.deref_ref = 1;
600
601       val_print (regtype,
602                  value_embedded_offset (val), 0,
603                  file, 0, val, &opts, current_language);
604
605       if (print_raw_format)
606         {
607           fprintf_filtered (file, "\t(raw ");
608           print_hex_chars (file, valaddr, TYPE_LENGTH (regtype), byte_order,
609                            true);
610           fprintf_filtered (file, ")");
611         }
612     }
613   else
614     {
615       struct value_print_options opts;
616
617       /* Print the register in hex.  */
618       get_formatted_print_options (&opts, 'x');
619       opts.deref_ref = 1;
620       val_print (regtype,
621                  value_embedded_offset (val), 0,
622                  file, 0, val, &opts, current_language);
623
624       if (print_raw_format)
625         {
626           if (regnum == RISCV_CSR_MSTATUS_REGNUM)
627             {
628               LONGEST d;
629               int size = register_size (gdbarch, regnum);
630               unsigned xlen;
631
632               d = value_as_long (val);
633               xlen = size * 4;
634               fprintf_filtered (file,
635                                 "\tSD:%X VM:%02X MXR:%X PUM:%X MPRV:%X XS:%X "
636                                 "FS:%X MPP:%x HPP:%X SPP:%X MPIE:%X HPIE:%X "
637                                 "SPIE:%X UPIE:%X MIE:%X HIE:%X SIE:%X UIE:%X",
638                                 (int) ((d >> (xlen - 1)) & 0x1),
639                                 (int) ((d >> 24) & 0x1f),
640                                 (int) ((d >> 19) & 0x1),
641                                 (int) ((d >> 18) & 0x1),
642                                 (int) ((d >> 17) & 0x1),
643                                 (int) ((d >> 15) & 0x3),
644                                 (int) ((d >> 13) & 0x3),
645                                 (int) ((d >> 11) & 0x3),
646                                 (int) ((d >> 9) & 0x3),
647                                 (int) ((d >> 8) & 0x1),
648                                 (int) ((d >> 7) & 0x1),
649                                 (int) ((d >> 6) & 0x1),
650                                 (int) ((d >> 5) & 0x1),
651                                 (int) ((d >> 4) & 0x1),
652                                 (int) ((d >> 3) & 0x1),
653                                 (int) ((d >> 2) & 0x1),
654                                 (int) ((d >> 1) & 0x1),
655                                 (int) ((d >> 0) & 0x1));
656             }
657           else if (regnum == RISCV_CSR_MISA_REGNUM)
658             {
659               int base;
660               unsigned xlen, i;
661               LONGEST d;
662
663               d = value_as_long (val);
664               base = d >> 30;
665               xlen = 16;
666
667               for (; base > 0; base--)
668                 xlen *= 2;
669               fprintf_filtered (file, "\tRV%d", xlen);
670
671               for (i = 0; i < 26; i++)
672                 {
673                   if (d & (1 << i))
674                     fprintf_filtered (file, "%c", 'A' + i);
675                 }
676             }
677           else if (regnum == RISCV_CSR_FCSR_REGNUM
678                    || regnum == RISCV_CSR_FFLAGS_REGNUM
679                    || regnum == RISCV_CSR_FRM_REGNUM)
680             {
681               LONGEST d;
682
683               d = value_as_long (val);
684
685               fprintf_filtered (file, "\t");
686               if (regnum != RISCV_CSR_FRM_REGNUM)
687                 fprintf_filtered (file,
688                                   "RD:%01X NV:%d DZ:%d OF:%d UF:%d NX:%d",
689                                   (int) ((d >> 5) & 0x7),
690                                   (int) ((d >> 4) & 0x1),
691                                   (int) ((d >> 3) & 0x1),
692                                   (int) ((d >> 2) & 0x1),
693                                   (int) ((d >> 1) & 0x1),
694                                   (int) ((d >> 0) & 0x1));
695
696               if (regnum != RISCV_CSR_FFLAGS_REGNUM)
697                 {
698                   static const char * const sfrm[] =
699                     {
700                       "RNE (round to nearest; ties to even)",
701                       "RTZ (Round towards zero)",
702                       "RDN (Round down towards -INF)",
703                       "RUP (Round up towards +INF)",
704                       "RMM (Round to nearest; ties to max magnitude)",
705                       "INVALID[5]",
706                       "INVALID[6]",
707                       "dynamic rounding mode",
708                     };
709                   int frm = ((regnum == RISCV_CSR_FCSR_REGNUM)
710                              ? (d >> 5) : d) & 0x3;
711
712                   fprintf_filtered (file, "%sFRM:%i [%s]",
713                                     (regnum == RISCV_CSR_FCSR_REGNUM
714                                      ? " " : ""),
715                                     frm, sfrm[frm]);
716                 }
717             }
718           else if (regnum == RISCV_PRIV_REGNUM)
719             {
720               LONGEST d;
721               uint8_t priv;
722
723               d = value_as_long (val);
724               priv = d & 0xff;
725
726               if (priv < 4)
727                 {
728                   static const char * const sprv[] =
729                     {
730                       "User/Application",
731                       "Supervisor",
732                       "Hypervisor",
733                       "Machine"
734                     };
735                   fprintf_filtered (file, "\tprv:%d [%s]",
736                                     priv, sprv[priv]);
737                 }
738               else
739                 fprintf_filtered (file, "\tprv:%d [INVALID]", priv);
740             }
741           else
742             {
743               /* If not a vector register, print it also according to its
744                  natural format.  */
745               if (TYPE_VECTOR (regtype) == 0)
746                 {
747                   get_user_print_options (&opts);
748                   opts.deref_ref = 1;
749                   fprintf_filtered (file, "\t");
750                   val_print (regtype,
751                              value_embedded_offset (val), 0,
752                              file, 0, val, &opts, current_language);
753                 }
754             }
755         }
756     }
757   fprintf_filtered (file, "\n");
758 }
759
760 /* Implement the register_reggroup_p gdbarch method.  Is REGNUM a member
761    of REGGROUP?  */
762
763 static int
764 riscv_register_reggroup_p (struct gdbarch  *gdbarch, int regnum,
765                            struct reggroup *reggroup)
766 {
767   int float_p;
768   int raw_p;
769   unsigned int i;
770
771   /* Used by 'info registers' and 'info registers <groupname>'.  */
772
773   if (gdbarch_register_name (gdbarch, regnum) == NULL
774       || gdbarch_register_name (gdbarch, regnum)[0] == '\0')
775     return 0;
776
777   if (reggroup == all_reggroup)
778     {
779       if (regnum < RISCV_FIRST_CSR_REGNUM || regnum == RISCV_PRIV_REGNUM)
780         return 1;
781       /* Only include CSRs that have aliases.  */
782       for (i = 0; i < ARRAY_SIZE (riscv_register_aliases); ++i)
783         {
784           if (regnum == riscv_register_aliases[i].regnum)
785             return 1;
786         }
787       return 0;
788     }
789   else if (reggroup == float_reggroup)
790     return ((regnum >= RISCV_FIRST_FP_REGNUM && regnum <= RISCV_LAST_FP_REGNUM)
791             || (regnum == RISCV_CSR_FCSR_REGNUM
792                 || regnum == RISCV_CSR_FFLAGS_REGNUM
793                 || regnum == RISCV_CSR_FRM_REGNUM));
794   else if (reggroup == general_reggroup)
795     return regnum < RISCV_FIRST_FP_REGNUM;
796   else if (reggroup == restore_reggroup || reggroup == save_reggroup)
797     {
798       if (riscv_has_fp_regs (gdbarch))
799         return regnum <= RISCV_LAST_FP_REGNUM;
800       else
801         return regnum < RISCV_FIRST_FP_REGNUM;
802     }
803   else if (reggroup == system_reggroup)
804     {
805       if (regnum == RISCV_PRIV_REGNUM)
806         return 1;
807       if (regnum < RISCV_FIRST_CSR_REGNUM || regnum > RISCV_LAST_CSR_REGNUM)
808         return 0;
809       /* Only include CSRs that have aliases.  */
810       for (i = 0; i < ARRAY_SIZE (riscv_register_aliases); ++i)
811         {
812           if (regnum == riscv_register_aliases[i].regnum)
813             return 1;
814         }
815       return 0;
816     }
817   else if (reggroup == vector_reggroup)
818     return 0;
819   else
820     return 0;
821 }
822
823 /* Implement the print_registers_info gdbarch method.  This is used by
824    'info registers' and 'info all-registers'.  */
825
826 static void
827 riscv_print_registers_info (struct gdbarch *gdbarch,
828                             struct ui_file *file,
829                             struct frame_info *frame,
830                             int regnum, int print_all)
831 {
832   if (regnum != -1)
833     {
834       /* Print one specified register.  */
835       gdb_assert (regnum <= RISCV_LAST_REGNUM);
836       if (gdbarch_register_name (gdbarch, regnum) == NULL
837           || *(gdbarch_register_name (gdbarch, regnum)) == '\0')
838         error (_("Not a valid register for the current processor type"));
839       riscv_print_one_register_info (gdbarch, file, frame, regnum);
840     }
841   else
842     {
843       struct reggroup *reggroup;
844
845       if (print_all)
846         reggroup = all_reggroup;
847       else
848         reggroup = general_reggroup;
849
850       for (regnum = 0; regnum <= RISCV_LAST_REGNUM; ++regnum)
851         {
852           /* Zero never changes, so might as well hide by default.  */
853           if (regnum == RISCV_ZERO_REGNUM && !print_all)
854             continue;
855
856           /* Registers with no name are not valid on this ISA.  */
857           if (gdbarch_register_name (gdbarch, regnum) == NULL
858               || *(gdbarch_register_name (gdbarch, regnum)) == '\0')
859             continue;
860
861           /* Is the register in the group we're interested in?  */
862           if (!riscv_register_reggroup_p (gdbarch, regnum, reggroup))
863             continue;
864
865           riscv_print_one_register_info (gdbarch, file, frame, regnum);
866         }
867     }
868 }
869
870 /* Class that handles one decoded RiscV instruction.  */
871
872 class riscv_insn
873 {
874 public:
875
876   /* Enum of all the opcodes that GDB cares about during the prologue scan.  */
877   enum opcode
878     {
879       /* Unknown value is used at initialisation time.  */
880       UNKNOWN = 0,
881
882       /* These instructions are all the ones we are interested in during the
883          prologue scan.  */
884       ADD,
885       ADDI,
886       ADDIW,
887       ADDW,
888       AUIPC,
889       LUI,
890       SD,
891       SW,
892
893       /* Other instructions are not interesting during the prologue scan, and
894          are ignored.  */
895       OTHER
896     };
897
898   riscv_insn ()
899     : m_length (0),
900       m_opcode (OTHER),
901       m_rd (0),
902       m_rs1 (0),
903       m_rs2 (0)
904   {
905     /* Nothing.  */
906   }
907
908   void decode (struct gdbarch *gdbarch, CORE_ADDR pc);
909
910   /* Get the length of the instruction in bytes.  */
911   int length () const
912   { return m_length; }
913
914   /* Get the opcode for this instruction.  */
915   enum opcode opcode () const
916   { return m_opcode; }
917
918   /* Get destination register field for this instruction.  This is only
919      valid if the OPCODE implies there is such a field for this
920      instruction.  */
921   int rd () const
922   { return m_rd; }
923
924   /* Get the RS1 register field for this instruction.  This is only valid
925      if the OPCODE implies there is such a field for this instruction.  */
926   int rs1 () const
927   { return m_rs1; }
928
929   /* Get the RS2 register field for this instruction.  This is only valid
930      if the OPCODE implies there is such a field for this instruction.  */
931   int rs2 () const
932   { return m_rs2; }
933
934   /* Get the immediate for this instruction in signed form.  This is only
935      valid if the OPCODE implies there is such a field for this
936      instruction.  */
937   int imm_signed () const
938   { return m_imm.s; }
939
940 private:
941
942   /* Extract 5 bit register field at OFFSET from instruction OPCODE.  */
943   int decode_register_index (unsigned long opcode, int offset)
944   {
945     return (opcode >> offset) & 0x1F;
946   }
947
948   /* Helper for DECODE, decode 32-bit R-type instruction.  */
949   void decode_r_type_insn (enum opcode opcode, ULONGEST ival)
950   {
951     m_opcode = opcode;
952     m_rd = decode_register_index (ival, OP_SH_RD);
953     m_rs1 = decode_register_index (ival, OP_SH_RS1);
954     m_rs2 = decode_register_index (ival, OP_SH_RS2);
955   }
956
957   /* Helper for DECODE, decode 16-bit compressed R-type instruction.  */
958   void decode_cr_type_insn (enum opcode opcode, ULONGEST ival)
959   {
960     m_opcode = opcode;
961     m_rd = m_rs1 = decode_register_index (ival, OP_SH_CRS1S);
962     m_rs2 = decode_register_index (ival, OP_SH_CRS2);
963   }
964
965   /* Helper for DECODE, decode 32-bit I-type instruction.  */
966   void decode_i_type_insn (enum opcode opcode, ULONGEST ival)
967   {
968     m_opcode = opcode;
969     m_rd = decode_register_index (ival, OP_SH_RD);
970     m_rs1 = decode_register_index (ival, OP_SH_RS1);
971     m_imm.s = EXTRACT_ITYPE_IMM (ival);
972   }
973
974   /* Helper for DECODE, decode 16-bit compressed I-type instruction.  */
975   void decode_ci_type_insn (enum opcode opcode, ULONGEST ival)
976   {
977     m_opcode = opcode;
978     m_rd = m_rs1 = decode_register_index (ival, OP_SH_CRS1S);
979     m_imm.s = EXTRACT_RVC_IMM (ival);
980   }
981
982   /* Helper for DECODE, decode 32-bit S-type instruction.  */
983   void decode_s_type_insn (enum opcode opcode, ULONGEST ival)
984   {
985     m_opcode = opcode;
986     m_rs1 = decode_register_index (ival, OP_SH_RS1);
987     m_rs2 = decode_register_index (ival, OP_SH_RS2);
988     m_imm.s = EXTRACT_STYPE_IMM (ival);
989   }
990
991   /* Helper for DECODE, decode 32-bit U-type instruction.  */
992   void decode_u_type_insn (enum opcode opcode, ULONGEST ival)
993   {
994     m_opcode = opcode;
995     m_rd = decode_register_index (ival, OP_SH_RD);
996     m_imm.s = EXTRACT_UTYPE_IMM (ival);
997   }
998
999   /* Fetch instruction from target memory at ADDR, return the content of
1000      the instruction, and update LEN with the instruction length.  */
1001   static ULONGEST fetch_instruction (struct gdbarch *gdbarch,
1002                                      CORE_ADDR addr, int *len);
1003
1004   /* The length of the instruction in bytes.  Should be 2 or 4.  */
1005   int m_length;
1006
1007   /* The instruction opcode.  */
1008   enum opcode m_opcode;
1009
1010   /* The three possible registers an instruction might reference.  Not
1011      every instruction fills in all of these registers.  Which fields are
1012      valid depends on the opcode.  The naming of these fields matches the
1013      naming in the riscv isa manual.  */
1014   int m_rd;
1015   int m_rs1;
1016   int m_rs2;
1017
1018   /* Possible instruction immediate.  This is only valid if the instruction
1019      format contains an immediate, not all instruction, whether this is
1020      valid depends on the opcode.  Despite only having one format for now
1021      the immediate is packed into a union, later instructions might require
1022      an unsigned formatted immediate, having the union in place now will
1023      reduce the need for code churn later.  */
1024   union riscv_insn_immediate
1025   {
1026     riscv_insn_immediate ()
1027       : s (0)
1028     {
1029       /* Nothing.  */
1030     }
1031
1032     int s;
1033   } m_imm;
1034 };
1035
1036 /* Fetch instruction from target memory at ADDR, return the content of the
1037    instruction, and update LEN with the instruction length.  */
1038
1039 ULONGEST
1040 riscv_insn::fetch_instruction (struct gdbarch *gdbarch,
1041                                CORE_ADDR addr, int *len)
1042 {
1043   enum bfd_endian byte_order = gdbarch_byte_order_for_code (gdbarch);
1044   gdb_byte buf[8];
1045   int instlen, status;
1046
1047   /* All insns are at least 16 bits.  */
1048   status = target_read_memory (addr, buf, 2);
1049   if (status)
1050     memory_error (TARGET_XFER_E_IO, addr);
1051
1052   /* If we need more, grab it now.  */
1053   instlen = riscv_insn_length (buf[0]);
1054   gdb_assert (instlen <= sizeof (buf));
1055   *len = instlen;
1056
1057   if (instlen > 2)
1058     {
1059       status = target_read_memory (addr + 2, buf + 2, instlen - 2);
1060       if (status)
1061         memory_error (TARGET_XFER_E_IO, addr + 2);
1062     }
1063
1064   return extract_unsigned_integer (buf, instlen, byte_order);
1065 }
1066
1067 /* Fetch from target memory an instruction at PC and decode it.  */
1068
1069 void
1070 riscv_insn::decode (struct gdbarch *gdbarch, CORE_ADDR pc)
1071 {
1072   ULONGEST ival;
1073
1074   /* Fetch the instruction, and the instructions length.  */
1075   ival = fetch_instruction (gdbarch, pc, &m_length);
1076
1077   if (m_length == 4)
1078     {
1079       if (is_add_insn (ival))
1080         decode_r_type_insn (ADD, ival);
1081       else if (is_addw_insn (ival))
1082         decode_r_type_insn (ADDW, ival);
1083       else if (is_addi_insn (ival))
1084         decode_i_type_insn (ADDI, ival);
1085       else if (is_addiw_insn (ival))
1086         decode_i_type_insn (ADDIW, ival);
1087       else if (is_auipc_insn (ival))
1088         decode_u_type_insn (AUIPC, ival);
1089       else if (is_lui_insn (ival))
1090         decode_u_type_insn (LUI, ival);
1091       else if (is_sd_insn (ival))
1092         decode_s_type_insn (SD, ival);
1093       else if (is_sw_insn (ival))
1094         decode_s_type_insn (SW, ival);
1095       else
1096         /* None of the other fields are valid in this case.  */
1097         m_opcode = OTHER;
1098     }
1099   else if (m_length == 2)
1100     {
1101       if (is_c_add_insn (ival))
1102         decode_cr_type_insn (ADD, ival);
1103       else if (is_c_addw_insn (ival))
1104         decode_cr_type_insn (ADDW, ival);
1105       else if (is_c_addi_insn (ival))
1106         decode_ci_type_insn (ADDI, ival);
1107       else if (is_c_addiw_insn (ival))
1108         decode_ci_type_insn (ADDIW, ival);
1109       else if (is_c_addi16sp_insn (ival))
1110         {
1111           m_opcode = ADDI;
1112           m_rd = m_rs1 = decode_register_index (ival, OP_SH_RD);
1113           m_imm.s = EXTRACT_RVC_ADDI16SP_IMM (ival);
1114         }
1115       else if (is_lui_insn (ival))
1116         m_opcode = OTHER;
1117       else if (is_c_sd_insn (ival))
1118         m_opcode = OTHER;
1119       else if (is_sw_insn (ival))
1120         m_opcode = OTHER;
1121       else
1122         /* None of the other fields of INSN are valid in this case.  */
1123         m_opcode = OTHER;
1124     }
1125   else
1126     internal_error (__FILE__, __LINE__,
1127                     _("unable to decode %d byte instructions in "
1128                       "prologue at %s"), m_length,
1129                     core_addr_to_string (pc));
1130 }
1131
1132 /* The prologue scanner.  This is currently only used for skipping the
1133    prologue of a function when the DWARF information is not sufficient.
1134    However, it is written with filling of the frame cache in mind, which
1135    is why different groups of stack setup instructions are split apart
1136    during the core of the inner loop.  In the future, the intention is to
1137    extend this function to fully support building up a frame cache that
1138    can unwind register values when there is no DWARF information.  */
1139
1140 static CORE_ADDR
1141 riscv_scan_prologue (struct gdbarch *gdbarch,
1142                      CORE_ADDR start_pc, CORE_ADDR limit_pc)
1143 {
1144   CORE_ADDR cur_pc, next_pc;
1145   long frame_offset = 0;
1146   CORE_ADDR end_prologue_addr = 0;
1147
1148   if (limit_pc > start_pc + 200)
1149     limit_pc = start_pc + 200;
1150
1151   for (next_pc = cur_pc = start_pc; cur_pc < limit_pc; cur_pc = next_pc)
1152     {
1153       struct riscv_insn insn;
1154
1155       /* Decode the current instruction, and decide where the next
1156          instruction lives based on the size of this instruction.  */
1157       insn.decode (gdbarch, cur_pc);
1158       gdb_assert (insn.length () > 0);
1159       next_pc = cur_pc + insn.length ();
1160
1161       /* Look for common stack adjustment insns.  */
1162       if ((insn.opcode () == riscv_insn::ADDI
1163            || insn.opcode () == riscv_insn::ADDIW)
1164           && insn.rd () == RISCV_SP_REGNUM
1165           && insn.rs1 () == RISCV_SP_REGNUM)
1166         {
1167           /* Handle: addi sp, sp, -i
1168              or:     addiw sp, sp, -i  */
1169           if (insn.imm_signed () < 0)
1170             frame_offset += insn.imm_signed ();
1171           else
1172             break;
1173         }
1174       else if ((insn.opcode () == riscv_insn::SW
1175                 || insn.opcode () == riscv_insn::SD)
1176                && (insn.rs1 () == RISCV_SP_REGNUM
1177                    || insn.rs1 () == RISCV_FP_REGNUM))
1178         {
1179           /* Handle: sw reg, offset(sp)
1180              or:     sd reg, offset(sp)
1181              or:     sw reg, offset(s0)
1182              or:     sd reg, offset(s0)  */
1183           /* Instruction storing a register onto the stack.  */
1184         }
1185       else if (insn.opcode () == riscv_insn::ADDI
1186                && insn.rd () == RISCV_FP_REGNUM
1187                && insn.rs1 () == RISCV_SP_REGNUM)
1188         {
1189           /* Handle: addi s0, sp, size  */
1190           /* Instructions setting up the frame pointer.  */
1191         }
1192       else if ((insn.opcode () == riscv_insn::ADD
1193                 || insn.opcode () == riscv_insn::ADDW)
1194                && insn.rd () == RISCV_FP_REGNUM
1195                && insn.rs1 () == RISCV_SP_REGNUM
1196                && insn.rs2 () == RISCV_ZERO_REGNUM)
1197         {
1198           /* Handle: add s0, sp, 0
1199              or:     addw s0, sp, 0  */
1200           /* Instructions setting up the frame pointer.  */
1201         }
1202       else if ((insn.rd () == RISCV_GP_REGNUM
1203                 && (insn.opcode () == riscv_insn::AUIPC
1204                     || insn.opcode () == riscv_insn::LUI
1205                     || (insn.opcode () == riscv_insn::ADDI
1206                         && insn.rs1 () == RISCV_GP_REGNUM)
1207                     || (insn.opcode () == riscv_insn::ADD
1208                         && (insn.rs1 () == RISCV_GP_REGNUM
1209                             || insn.rs2 () == RISCV_GP_REGNUM))))
1210                || (insn.opcode () == riscv_insn::ADDI
1211                    && insn.rd () == RISCV_ZERO_REGNUM
1212                    && insn.rs1 () == RISCV_ZERO_REGNUM
1213                    && insn.imm_signed () == 0))
1214         {
1215           /* Handle: auipc gp, n
1216              or:     addi gp, gp, n
1217              or:     add gp, gp, reg
1218              or:     add gp, reg, gp
1219              or:     lui gp, n
1220              or:     add x0, x0, 0   (NOP)  */
1221           /* These instructions are part of the prologue, but we don't need
1222              to do anything special to handle them.  */
1223         }
1224       else
1225         {
1226           if (end_prologue_addr == 0)
1227             end_prologue_addr = cur_pc;
1228         }
1229     }
1230
1231   if (end_prologue_addr == 0)
1232     end_prologue_addr = cur_pc;
1233
1234   return end_prologue_addr;
1235 }
1236
1237 /* Implement the riscv_skip_prologue gdbarch method.  */
1238
1239 static CORE_ADDR
1240 riscv_skip_prologue (struct gdbarch *gdbarch,
1241                      CORE_ADDR       pc)
1242 {
1243   CORE_ADDR limit_pc;
1244   CORE_ADDR func_addr;
1245
1246   /* See if we can determine the end of the prologue via the symbol
1247      table.  If so, then return either PC, or the PC after the
1248      prologue, whichever is greater.  */
1249   if (find_pc_partial_function (pc, NULL, &func_addr, NULL))
1250     {
1251       CORE_ADDR post_prologue_pc
1252         = skip_prologue_using_sal (gdbarch, func_addr);
1253
1254       if (post_prologue_pc != 0)
1255         return std::max (pc, post_prologue_pc);
1256     }
1257
1258   /* Can't determine prologue from the symbol table, need to examine
1259      instructions.  */
1260
1261   /* Find an upper limit on the function prologue using the debug
1262      information.  If the debug information could not be used to provide
1263      that bound, then use an arbitrary large number as the upper bound.  */
1264   limit_pc = skip_prologue_using_sal (gdbarch, pc);
1265   if (limit_pc == 0)
1266     limit_pc = pc + 100;   /* MAGIC! */
1267
1268   return riscv_scan_prologue (gdbarch, pc, limit_pc);
1269 }
1270
1271 /* Implement the gdbarch push dummy code callback.  */
1272
1273 static CORE_ADDR
1274 riscv_push_dummy_code (struct gdbarch *gdbarch, CORE_ADDR sp,
1275                        CORE_ADDR funaddr, struct value **args, int nargs,
1276                        struct type *value_type, CORE_ADDR *real_pc,
1277                        CORE_ADDR *bp_addr, struct regcache *regcache)
1278 {
1279   /* Allocate space for a breakpoint, and keep the stack correctly
1280      aligned.  */
1281   sp -= 16;
1282   *bp_addr = sp;
1283   *real_pc = funaddr;
1284   return sp;
1285 }
1286
1287 /* Compute the alignment of the type T.  Used while setting up the
1288    arguments for a dummy call.  */
1289
1290 static int
1291 riscv_type_alignment (struct type *t)
1292 {
1293   t = check_typedef (t);
1294   switch (TYPE_CODE (t))
1295     {
1296     default:
1297       error (_("Could not compute alignment of type"));
1298
1299     case TYPE_CODE_RVALUE_REF:
1300     case TYPE_CODE_PTR:
1301     case TYPE_CODE_ENUM:
1302     case TYPE_CODE_INT:
1303     case TYPE_CODE_FLT:
1304     case TYPE_CODE_REF:
1305     case TYPE_CODE_CHAR:
1306     case TYPE_CODE_BOOL:
1307       return TYPE_LENGTH (t);
1308
1309     case TYPE_CODE_ARRAY:
1310     case TYPE_CODE_COMPLEX:
1311       return riscv_type_alignment (TYPE_TARGET_TYPE (t));
1312
1313     case TYPE_CODE_STRUCT:
1314     case TYPE_CODE_UNION:
1315       {
1316         int i;
1317         int align = 1;
1318
1319         for (i = 0; i < TYPE_NFIELDS (t); ++i)
1320           {
1321             if (TYPE_FIELD_LOC_KIND (t, i) == FIELD_LOC_KIND_BITPOS)
1322               {
1323                 int a = riscv_type_alignment (TYPE_FIELD_TYPE (t, i));
1324                 if (a > align)
1325                   align = a;
1326               }
1327           }
1328         return align;
1329       }
1330     }
1331 }
1332
1333 /* Holds information about a single argument either being passed to an
1334    inferior function, or returned from an inferior function.  This includes
1335    information about the size, type, etc of the argument, and also
1336    information about how the argument will be passed (or returned).  */
1337
1338 struct riscv_arg_info
1339 {
1340   /* Contents of the argument.  */
1341   const gdb_byte *contents;
1342
1343   /* Length of argument.  */
1344   int length;
1345
1346   /* Alignment required for an argument of this type.  */
1347   int align;
1348
1349   /* The type for this argument.  */
1350   struct type *type;
1351
1352   /* Each argument can have either 1 or 2 locations assigned to it.  Each
1353      location describes where part of the argument will be placed.  The
1354      second location is valid based on the LOC_TYPE and C_LENGTH fields
1355      of the first location (which is always valid).  */
1356   struct location
1357   {
1358     /* What type of location this is.  */
1359     enum location_type
1360       {
1361        /* Argument passed in a register.  */
1362        in_reg,
1363
1364        /* Argument passed as an on stack argument.  */
1365        on_stack,
1366
1367        /* Argument passed by reference.  The second location is always
1368           valid for a BY_REF argument, and describes where the address
1369           of the BY_REF argument should be placed.  */
1370        by_ref
1371       } loc_type;
1372
1373     /* Information that depends on the location type.  */
1374     union
1375     {
1376       /* Which register number to use.  */
1377       int regno;
1378
1379       /* The offset into the stack region.  */
1380       int offset;
1381     } loc_data;
1382
1383     /* The length of contents covered by this location.  If this is less
1384        than the total length of the argument, then the second location
1385        will be valid, and will describe where the rest of the argument
1386        will go.  */
1387     int c_length;
1388
1389     /* The offset within CONTENTS for this part of the argument.  Will
1390        always be 0 for the first part.  For the second part of the
1391        argument, this might be the C_LENGTH value of the first part,
1392        however, if we are passing a structure in two registers, and there's
1393        is padding between the first and second field, then this offset
1394        might be greater than the length of the first argument part.  When
1395        the second argument location is not holding part of the argument
1396        value, but is instead holding the address of a reference argument,
1397        then this offset will be set to 0.  */
1398     int c_offset;
1399   } argloc[2];
1400 };
1401
1402 /* Information about a set of registers being used for passing arguments as
1403    part of a function call.  The register set must be numerically
1404    sequential from NEXT_REGNUM to LAST_REGNUM.  The register set can be
1405    disabled from use by setting NEXT_REGNUM greater than LAST_REGNUM.  */
1406
1407 struct riscv_arg_reg
1408 {
1409   riscv_arg_reg (int first, int last)
1410     : next_regnum (first),
1411       last_regnum (last)
1412   {
1413     /* Nothing.  */
1414   }
1415
1416   /* The GDB register number to use in this set.  */
1417   int next_regnum;
1418
1419   /* The last GDB register number to use in this set.  */
1420   int last_regnum;
1421 };
1422
1423 /* Arguments can be passed as on stack arguments, or by reference.  The
1424    on stack arguments must be in a continuous region starting from $sp,
1425    while the by reference arguments can be anywhere, but we'll put them
1426    on the stack after (at higher address) the on stack arguments.
1427
1428    This might not be the right approach to take.  The ABI is clear that
1429    an argument passed by reference can be modified by the callee, which
1430    us placing the argument (temporarily) onto the stack will not achieve
1431    (changes will be lost).  There's also the possibility that very large
1432    arguments could overflow the stack.
1433
1434    This struct is used to track offset into these two areas for where
1435    arguments are to be placed.  */
1436 struct riscv_memory_offsets
1437 {
1438   riscv_memory_offsets ()
1439     : arg_offset (0),
1440       ref_offset (0)
1441   {
1442     /* Nothing.  */
1443   }
1444
1445   /* Offset into on stack argument area.  */
1446   int arg_offset;
1447
1448   /* Offset into the pass by reference area.  */
1449   int ref_offset;
1450 };
1451
1452 /* Holds information about where arguments to a call will be placed.  This
1453    is updated as arguments are added onto the call, and can be used to
1454    figure out where the next argument should be placed.  */
1455
1456 struct riscv_call_info
1457 {
1458   riscv_call_info (struct gdbarch *gdbarch)
1459     : int_regs (RISCV_A0_REGNUM, RISCV_A0_REGNUM + 7),
1460       float_regs (RISCV_FA0_REGNUM, RISCV_FA0_REGNUM + 7)
1461   {
1462     xlen = riscv_isa_xlen (gdbarch);
1463     flen = riscv_isa_flen (gdbarch);
1464
1465     /* Disable use of floating point registers if needed.  */
1466     if (!riscv_has_fp_abi (gdbarch))
1467       float_regs.next_regnum = float_regs.last_regnum + 1;
1468   }
1469
1470   /* Track the memory areas used for holding in-memory arguments to a
1471      call.  */
1472   struct riscv_memory_offsets memory;
1473
1474   /* Holds information about the next integer register to use for passing
1475      an argument.  */
1476   struct riscv_arg_reg int_regs;
1477
1478   /* Holds information about the next floating point register to use for
1479      passing an argument.  */
1480   struct riscv_arg_reg float_regs;
1481
1482   /* The XLEN and FLEN are copied in to this structure for convenience, and
1483      are just the results of calling RISCV_ISA_XLEN and RISCV_ISA_FLEN.  */
1484   int xlen;
1485   int flen;
1486 };
1487
1488 /* Return the number of registers available for use as parameters in the
1489    register set REG.  Returned value can be 0 or more.  */
1490
1491 static int
1492 riscv_arg_regs_available (struct riscv_arg_reg *reg)
1493 {
1494   if (reg->next_regnum > reg->last_regnum)
1495     return 0;
1496
1497   return (reg->last_regnum - reg->next_regnum + 1);
1498 }
1499
1500 /* If there is at least one register available in the register set REG then
1501    the next register from REG is assigned to LOC and the length field of
1502    LOC is updated to LENGTH.  The register set REG is updated to indicate
1503    that the assigned register is no longer available and the function
1504    returns true.
1505
1506    If there are no registers available in REG then the function returns
1507    false, and LOC and REG are unchanged.  */
1508
1509 static bool
1510 riscv_assign_reg_location (struct riscv_arg_info::location *loc,
1511                            struct riscv_arg_reg *reg,
1512                            int length, int offset)
1513 {
1514   if (reg->next_regnum <= reg->last_regnum)
1515     {
1516       loc->loc_type = riscv_arg_info::location::in_reg;
1517       loc->loc_data.regno = reg->next_regnum;
1518       reg->next_regnum++;
1519       loc->c_length = length;
1520       loc->c_offset = offset;
1521       return true;
1522     }
1523
1524   return false;
1525 }
1526
1527 /* Assign LOC a location as the next stack parameter, and update MEMORY to
1528    record that an area of stack has been used to hold the parameter
1529    described by LOC.
1530
1531    The length field of LOC is updated to LENGTH, the length of the
1532    parameter being stored, and ALIGN is the alignment required by the
1533    parameter, which will affect how memory is allocated out of MEMORY.  */
1534
1535 static void
1536 riscv_assign_stack_location (struct riscv_arg_info::location *loc,
1537                              struct riscv_memory_offsets *memory,
1538                              int length, int align)
1539 {
1540   loc->loc_type = riscv_arg_info::location::on_stack;
1541   memory->arg_offset
1542     = align_up (memory->arg_offset, align);
1543   loc->loc_data.offset = memory->arg_offset;
1544   memory->arg_offset += length;
1545   loc->c_length = length;
1546
1547   /* Offset is always 0, either we're the first location part, in which
1548      case we're reading content from the start of the argument, or we're
1549      passing the address of a reference argument, so 0.  */
1550   loc->c_offset = 0;
1551 }
1552
1553 /* Update AINFO, which describes an argument that should be passed or
1554    returned using the integer ABI.  The argloc fields within AINFO are
1555    updated to describe the location in which the argument will be passed to
1556    a function, or returned from a function.
1557
1558    The CINFO structure contains the ongoing call information, the holds
1559    information such as which argument registers are remaining to be
1560    assigned to parameter, and how much memory has been used by parameters
1561    so far.
1562
1563    By examining the state of CINFO a suitable location can be selected,
1564    and assigned to AINFO.  */
1565
1566 static void
1567 riscv_call_arg_scalar_int (struct riscv_arg_info *ainfo,
1568                            struct riscv_call_info *cinfo)
1569 {
1570   if (ainfo->length > (2 * cinfo->xlen))
1571     {
1572       /* Argument is going to be passed by reference.  */
1573       ainfo->argloc[0].loc_type
1574         = riscv_arg_info::location::by_ref;
1575       cinfo->memory.ref_offset
1576         = align_up (cinfo->memory.ref_offset, ainfo->align);
1577       ainfo->argloc[0].loc_data.offset = cinfo->memory.ref_offset;
1578       cinfo->memory.ref_offset += ainfo->length;
1579       ainfo->argloc[0].c_length = ainfo->length;
1580
1581       /* The second location for this argument is given over to holding the
1582          address of the by-reference data.  Pass 0 for the offset as this
1583          is not part of the actual argument value.  */
1584       if (!riscv_assign_reg_location (&ainfo->argloc[1],
1585                                       &cinfo->int_regs,
1586                                       cinfo->xlen, 0))
1587         riscv_assign_stack_location (&ainfo->argloc[1],
1588                                      &cinfo->memory, cinfo->xlen,
1589                                      cinfo->xlen);
1590     }
1591   else
1592     {
1593       int len = (ainfo->length > cinfo->xlen) ? cinfo->xlen : ainfo->length;
1594
1595       if (!riscv_assign_reg_location (&ainfo->argloc[0],
1596                                       &cinfo->int_regs, len, 0))
1597         riscv_assign_stack_location (&ainfo->argloc[0],
1598                                      &cinfo->memory, len, ainfo->align);
1599
1600       if (len < ainfo->length)
1601         {
1602           len = ainfo->length - len;
1603           if (!riscv_assign_reg_location (&ainfo->argloc[1],
1604                                           &cinfo->int_regs, len,
1605                                           cinfo->xlen))
1606             riscv_assign_stack_location (&ainfo->argloc[1],
1607                                          &cinfo->memory, len, cinfo->xlen);
1608         }
1609     }
1610 }
1611
1612 /* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
1613    is being passed with the floating point ABI.  */
1614
1615 static void
1616 riscv_call_arg_scalar_float (struct riscv_arg_info *ainfo,
1617                              struct riscv_call_info *cinfo)
1618 {
1619   if (ainfo->length > cinfo->flen)
1620     return riscv_call_arg_scalar_int (ainfo, cinfo);
1621   else
1622     {
1623       if (!riscv_assign_reg_location (&ainfo->argloc[0],
1624                                       &cinfo->float_regs,
1625                                       ainfo->length, 0))
1626         return riscv_call_arg_scalar_int (ainfo, cinfo);
1627     }
1628 }
1629
1630 /* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
1631    is a complex floating point argument, and is therefore handled
1632    differently to other argument types.  */
1633
1634 static void
1635 riscv_call_arg_complex_float (struct riscv_arg_info *ainfo,
1636                               struct riscv_call_info *cinfo)
1637 {
1638   if (ainfo->length <= (2 * cinfo->flen)
1639       && riscv_arg_regs_available (&cinfo->float_regs) >= 2)
1640     {
1641       bool result;
1642       int len = ainfo->length / 2;
1643
1644       result = riscv_assign_reg_location (&ainfo->argloc[0],
1645                                           &cinfo->float_regs, len, len);
1646       gdb_assert (result);
1647
1648       result = riscv_assign_reg_location (&ainfo->argloc[1],
1649                                           &cinfo->float_regs, len, len);
1650       gdb_assert (result);
1651     }
1652   else
1653     return riscv_call_arg_scalar_int (ainfo, cinfo);
1654 }
1655
1656 /* A structure used for holding information about a structure type within
1657    the inferior program.  The RiscV ABI has special rules for handling some
1658    structures with a single field or with two fields.  The counting of
1659    fields here is done after flattening out all nested structures.  */
1660
1661 class riscv_struct_info
1662 {
1663 public:
1664   riscv_struct_info ()
1665     : m_number_of_fields (0),
1666       m_types { nullptr, nullptr }
1667   {
1668     /* Nothing.  */
1669   }
1670
1671   /* Analyse TYPE descending into nested structures, count the number of
1672      scalar fields and record the types of the first two fields found.  */
1673   void analyse (struct type *type);
1674
1675   /* The number of scalar fields found in the analysed type.  This is
1676      currently only accurate if the value returned is 0, 1, or 2 as the
1677      analysis stops counting when the number of fields is 3.  This is
1678      because the RiscV ABI only has special cases for 1 or 2 fields,
1679      anything else we just don't care about.  */
1680   int number_of_fields () const
1681   { return m_number_of_fields; }
1682
1683   /* Return the type for scalar field INDEX within the analysed type.  Will
1684      return nullptr if there is no field at that index.  Only INDEX values
1685      0 and 1 can be requested as the RiscV ABI only has special cases for
1686      structures with 1 or 2 fields.  */
1687   struct type *field_type (int index) const
1688   {
1689     gdb_assert (index < (sizeof (m_types) / sizeof (m_types[0])));
1690     return m_types[index];
1691   }
1692
1693 private:
1694   /* The number of scalar fields found within the structure after recursing
1695      into nested structures.  */
1696   int m_number_of_fields;
1697
1698   /* The types of the first two scalar fields found within the structure
1699      after recursing into nested structures.  */
1700   struct type *m_types[2];
1701 };
1702
1703 /* Analyse TYPE descending into nested structures, count the number of
1704    scalar fields and record the types of the first two fields found.  */
1705
1706 void
1707 riscv_struct_info::analyse (struct type *type)
1708 {
1709   unsigned int count = TYPE_NFIELDS (type);
1710   unsigned int i;
1711
1712   for (i = 0; i < count; ++i)
1713     {
1714       if (TYPE_FIELD_LOC_KIND (type, i) != FIELD_LOC_KIND_BITPOS)
1715         continue;
1716
1717       struct type *field_type = TYPE_FIELD_TYPE (type, i);
1718       field_type = check_typedef (field_type);
1719
1720       switch (TYPE_CODE (field_type))
1721         {
1722         case TYPE_CODE_STRUCT:
1723           analyse (field_type);
1724           break;
1725
1726         default:
1727           /* RiscV only flattens out structures.  Anything else does not
1728              need to be flattened, we just record the type, and when we
1729              look at the analysis results we'll realise this is not a
1730              structure we can special case, and pass the structure in
1731              memory.  */
1732           if (m_number_of_fields < 2)
1733             m_types[m_number_of_fields] = field_type;
1734           m_number_of_fields++;
1735           break;
1736         }
1737
1738       /* RiscV only has special handling for structures with 1 or 2 scalar
1739          fields, any more than that and the structure is just passed in
1740          memory.  We can safely drop out early when we find 3 or more
1741          fields then.  */
1742
1743       if (m_number_of_fields > 2)
1744         return;
1745     }
1746 }
1747
1748 /* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
1749    is a structure.  Small structures on RiscV have some special case
1750    handling in order that the structure might be passed in register.
1751    Larger structures are passed in memory.  After assigning location
1752    information to AINFO, CINFO will have been updated.  */
1753
1754 static void
1755 riscv_call_arg_struct (struct riscv_arg_info *ainfo,
1756                        struct riscv_call_info *cinfo)
1757 {
1758   if (riscv_arg_regs_available (&cinfo->float_regs) >= 1)
1759     {
1760       struct riscv_struct_info sinfo;
1761
1762       sinfo.analyse (ainfo->type);
1763       if (sinfo.number_of_fields () == 1
1764           && TYPE_CODE (sinfo.field_type (0)) == TYPE_CODE_COMPLEX)
1765         {
1766           gdb_assert (TYPE_LENGTH (ainfo->type)
1767                       == TYPE_LENGTH (sinfo.field_type (0)));
1768           return riscv_call_arg_complex_float (ainfo, cinfo);
1769         }
1770
1771       if (sinfo.number_of_fields () == 1
1772           && TYPE_CODE (sinfo.field_type (0)) == TYPE_CODE_FLT)
1773         {
1774           gdb_assert (TYPE_LENGTH (ainfo->type)
1775                       == TYPE_LENGTH (sinfo.field_type (0)));
1776           return riscv_call_arg_scalar_float (ainfo, cinfo);
1777         }
1778
1779       if (sinfo.number_of_fields () == 2
1780           && TYPE_CODE (sinfo.field_type (0)) == TYPE_CODE_FLT
1781           && TYPE_LENGTH (sinfo.field_type (0)) <= cinfo->flen
1782           && TYPE_CODE (sinfo.field_type (1)) == TYPE_CODE_FLT
1783           && TYPE_LENGTH (sinfo.field_type (1)) <= cinfo->flen
1784           && riscv_arg_regs_available (&cinfo->float_regs) >= 2)
1785         {
1786           int len0, len1, offset;
1787
1788           gdb_assert (TYPE_LENGTH (ainfo->type) <= (2 * cinfo->flen));
1789
1790           len0 = TYPE_LENGTH (sinfo.field_type (0));
1791           if (!riscv_assign_reg_location (&ainfo->argloc[0],
1792                                           &cinfo->float_regs, len0, 0))
1793             error (_("failed during argument setup"));
1794
1795           len1 = TYPE_LENGTH (sinfo.field_type (1));
1796           offset = align_up (len0, riscv_type_alignment (sinfo.field_type (1)));
1797           gdb_assert (len1 <= (TYPE_LENGTH (ainfo->type)
1798                                - TYPE_LENGTH (sinfo.field_type (0))));
1799
1800           if (!riscv_assign_reg_location (&ainfo->argloc[1],
1801                                           &cinfo->float_regs,
1802                                           len1, offset))
1803             error (_("failed during argument setup"));
1804           return;
1805         }
1806
1807       if (sinfo.number_of_fields () == 2
1808           && riscv_arg_regs_available (&cinfo->int_regs) >= 1
1809           && (TYPE_CODE (sinfo.field_type (0)) == TYPE_CODE_FLT
1810               && TYPE_LENGTH (sinfo.field_type (0)) <= cinfo->flen
1811               && is_integral_type (sinfo.field_type (1))
1812               && TYPE_LENGTH (sinfo.field_type (1)) <= cinfo->xlen))
1813         {
1814           int len0, len1, offset;
1815
1816           gdb_assert (TYPE_LENGTH (ainfo->type)
1817                       <= (cinfo->flen + cinfo->xlen));
1818
1819           len0 = TYPE_LENGTH (sinfo.field_type (0));
1820           if (!riscv_assign_reg_location (&ainfo->argloc[0],
1821                                           &cinfo->float_regs, len0, 0))
1822             error (_("failed during argument setup"));
1823
1824           len1 = TYPE_LENGTH (sinfo.field_type (1));
1825           offset = align_up (len0, riscv_type_alignment (sinfo.field_type (1)));
1826           gdb_assert (len1 <= cinfo->xlen);
1827           if (!riscv_assign_reg_location (&ainfo->argloc[1],
1828                                           &cinfo->int_regs, len1, offset))
1829             error (_("failed during argument setup"));
1830           return;
1831         }
1832
1833       if (sinfo.number_of_fields () == 2
1834           && riscv_arg_regs_available (&cinfo->int_regs) >= 1
1835           && (is_integral_type (sinfo.field_type (0))
1836               && TYPE_LENGTH (sinfo.field_type (0)) <= cinfo->xlen
1837               && TYPE_CODE (sinfo.field_type (1)) == TYPE_CODE_FLT
1838               && TYPE_LENGTH (sinfo.field_type (1)) <= cinfo->flen))
1839         {
1840           int len0, len1, offset;
1841
1842           gdb_assert (TYPE_LENGTH (ainfo->type)
1843                       <= (cinfo->flen + cinfo->xlen));
1844
1845           len0 = TYPE_LENGTH (sinfo.field_type (0));
1846           len1 = TYPE_LENGTH (sinfo.field_type (1));
1847           offset = align_up (len0, riscv_type_alignment (sinfo.field_type (1)));
1848
1849           gdb_assert (len0 <= cinfo->xlen);
1850           gdb_assert (len1 <= cinfo->flen);
1851
1852           if (!riscv_assign_reg_location (&ainfo->argloc[0],
1853                                           &cinfo->int_regs, len0, 0))
1854             error (_("failed during argument setup"));
1855
1856           if (!riscv_assign_reg_location (&ainfo->argloc[1],
1857                                           &cinfo->float_regs,
1858                                           len1, offset))
1859             error (_("failed during argument setup"));
1860
1861           return;
1862         }
1863     }
1864
1865   /* Non of the structure flattening cases apply, so we just pass using
1866      the integer ABI.  */
1867   ainfo->length = align_up (ainfo->length, cinfo->xlen);
1868   riscv_call_arg_scalar_int (ainfo, cinfo);
1869 }
1870
1871 /* Assign a location to call (or return) argument AINFO, the location is
1872    selected from CINFO which holds information about what call argument
1873    locations are available for use next.  The TYPE is the type of the
1874    argument being passed, this information is recorded into AINFO (along
1875    with some additional information derived from the type).
1876
1877    After assigning a location to AINFO, CINFO will have been updated.  */
1878
1879 static void
1880 riscv_arg_location (struct gdbarch *gdbarch,
1881                     struct riscv_arg_info *ainfo,
1882                     struct riscv_call_info *cinfo,
1883                     struct type *type)
1884 {
1885   ainfo->type = type;
1886   ainfo->length = TYPE_LENGTH (ainfo->type);
1887   ainfo->align = riscv_type_alignment (ainfo->type);
1888   ainfo->contents = nullptr;
1889
1890   switch (TYPE_CODE (ainfo->type))
1891     {
1892     case TYPE_CODE_INT:
1893     case TYPE_CODE_BOOL:
1894     case TYPE_CODE_CHAR:
1895     case TYPE_CODE_RANGE:
1896     case TYPE_CODE_ENUM:
1897     case TYPE_CODE_PTR:
1898       if (ainfo->length <= cinfo->xlen)
1899         {
1900           ainfo->type = builtin_type (gdbarch)->builtin_long;
1901           ainfo->length = cinfo->xlen;
1902         }
1903       else if (ainfo->length <= (2 * cinfo->xlen))
1904         {
1905           ainfo->type = builtin_type (gdbarch)->builtin_long_long;
1906           ainfo->length = 2 * cinfo->xlen;
1907         }
1908
1909       /* Recalculate the alignment requirement.  */
1910       ainfo->align = riscv_type_alignment (ainfo->type);
1911       riscv_call_arg_scalar_int (ainfo, cinfo);
1912       break;
1913
1914     case TYPE_CODE_FLT:
1915       riscv_call_arg_scalar_float (ainfo, cinfo);
1916       break;
1917
1918     case TYPE_CODE_COMPLEX:
1919       riscv_call_arg_complex_float (ainfo, cinfo);
1920       break;
1921
1922     case TYPE_CODE_STRUCT:
1923       riscv_call_arg_struct (ainfo, cinfo);
1924       break;
1925
1926     default:
1927       riscv_call_arg_scalar_int (ainfo, cinfo);
1928       break;
1929     }
1930 }
1931
1932 /* Used for printing debug information about the call argument location in
1933    INFO to STREAM.  The addresses in SP_REFS and SP_ARGS are the base
1934    addresses for the location of pass-by-reference and
1935    arguments-on-the-stack memory areas.  */
1936
1937 static void
1938 riscv_print_arg_location (ui_file *stream, struct gdbarch *gdbarch,
1939                           struct riscv_arg_info *info,
1940                           CORE_ADDR sp_refs, CORE_ADDR sp_args)
1941 {
1942   const char* type_name = TYPE_NAME (info->type);
1943   if (type_name == nullptr)
1944     type_name = "???";
1945
1946   fprintf_unfiltered (stream, "type: '%s', length: 0x%x, alignment: 0x%x",
1947                       type_name, info->length, info->align);
1948   switch (info->argloc[0].loc_type)
1949     {
1950     case riscv_arg_info::location::in_reg:
1951       fprintf_unfiltered
1952         (stream, ", register %s",
1953          gdbarch_register_name (gdbarch, info->argloc[0].loc_data.regno));
1954       if (info->argloc[0].c_length < info->length)
1955         {
1956           switch (info->argloc[1].loc_type)
1957             {
1958             case riscv_arg_info::location::in_reg:
1959               fprintf_unfiltered
1960                 (stream, ", register %s",
1961                  gdbarch_register_name (gdbarch,
1962                                         info->argloc[1].loc_data.regno));
1963               break;
1964
1965             case riscv_arg_info::location::on_stack:
1966               fprintf_unfiltered (stream, ", on stack at offset 0x%x",
1967                                   info->argloc[1].loc_data.offset);
1968               break;
1969
1970             case riscv_arg_info::location::by_ref:
1971             default:
1972               /* The second location should never be a reference, any
1973                  argument being passed by reference just places its address
1974                  in the first location and is done.  */
1975               error (_("invalid argument location"));
1976               break;
1977             }
1978
1979           if (info->argloc[1].c_offset > info->argloc[0].c_length)
1980             fprintf_unfiltered (stream, " (offset 0x%x)",
1981                                 info->argloc[1].c_offset);
1982         }
1983       break;
1984
1985     case riscv_arg_info::location::on_stack:
1986       fprintf_unfiltered (stream, ", on stack at offset 0x%x",
1987                           info->argloc[0].loc_data.offset);
1988       break;
1989
1990     case riscv_arg_info::location::by_ref:
1991       fprintf_unfiltered
1992         (stream, ", by reference, data at offset 0x%x (%s)",
1993          info->argloc[0].loc_data.offset,
1994          core_addr_to_string (sp_refs + info->argloc[0].loc_data.offset));
1995       if (info->argloc[1].loc_type
1996           == riscv_arg_info::location::in_reg)
1997         fprintf_unfiltered
1998           (stream, ", address in register %s",
1999            gdbarch_register_name (gdbarch, info->argloc[1].loc_data.regno));
2000       else
2001         {
2002           gdb_assert (info->argloc[1].loc_type
2003                       == riscv_arg_info::location::on_stack);
2004           fprintf_unfiltered
2005             (stream, ", address on stack at offset 0x%x (%s)",
2006              info->argloc[1].loc_data.offset,
2007              core_addr_to_string (sp_args + info->argloc[1].loc_data.offset));
2008         }
2009       break;
2010
2011     default:
2012       gdb_assert_not_reached (_("unknown argument location type"));
2013     }
2014 }
2015
2016 /* Implement the push dummy call gdbarch callback.  */
2017
2018 static CORE_ADDR
2019 riscv_push_dummy_call (struct gdbarch *gdbarch,
2020                        struct value *function,
2021                        struct regcache *regcache,
2022                        CORE_ADDR bp_addr,
2023                        int nargs,
2024                        struct value **args,
2025                        CORE_ADDR sp,
2026                        int struct_return,
2027                        CORE_ADDR struct_addr)
2028 {
2029   int i;
2030   CORE_ADDR sp_args, sp_refs;
2031   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2032   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
2033
2034   struct riscv_arg_info *arg_info =
2035     (struct riscv_arg_info *) alloca (nargs * sizeof (struct riscv_arg_info));
2036   struct riscv_arg_info *info;
2037
2038   struct riscv_call_info call_info (gdbarch);
2039
2040   CORE_ADDR osp = sp;
2041
2042   /* We'll use register $a0 if we're returning a struct.  */
2043   if (struct_return)
2044     ++call_info.int_regs.next_regnum;
2045
2046   for (i = 0, info = &arg_info[0];
2047        i < nargs;
2048        ++i, ++info)
2049     {
2050       struct value *arg_value;
2051       struct type *arg_type;
2052
2053       arg_value = args[i];
2054       arg_type = check_typedef (value_type (arg_value));
2055
2056       riscv_arg_location (gdbarch, info, &call_info, arg_type);
2057
2058       if (info->type != arg_type)
2059         arg_value = value_cast (info->type, arg_value);
2060       info->contents = value_contents (arg_value);
2061     }
2062
2063   /* Adjust the stack pointer and align it.  */
2064   sp = sp_refs = align_down (sp - call_info.memory.ref_offset, SP_ALIGNMENT);
2065   sp = sp_args = align_down (sp - call_info.memory.arg_offset, SP_ALIGNMENT);
2066
2067   if (riscv_debug_infcall > 0)
2068     {
2069       fprintf_unfiltered (gdb_stdlog, "dummy call args:\n");
2070       fprintf_unfiltered (gdb_stdlog, ": floating point ABI %s in use\n",
2071                (riscv_has_fp_abi (gdbarch) ? "is" : "is not"));
2072       fprintf_unfiltered (gdb_stdlog, ": xlen: %d\n: flen: %d\n",
2073                call_info.xlen, call_info.flen);
2074       if (struct_return)
2075         fprintf_unfiltered (gdb_stdlog,
2076                             "[*] struct return pointer in register $A0\n");
2077       for (i = 0; i < nargs; ++i)
2078         {
2079           struct riscv_arg_info *info = &arg_info [i];
2080
2081           fprintf_unfiltered (gdb_stdlog, "[%2d] ", i);
2082           riscv_print_arg_location (gdb_stdlog, gdbarch, info, sp_refs, sp_args);
2083           fprintf_unfiltered (gdb_stdlog, "\n");
2084         }
2085       if (call_info.memory.arg_offset > 0
2086           || call_info.memory.ref_offset > 0)
2087         {
2088           fprintf_unfiltered (gdb_stdlog, "              Original sp: %s\n",
2089                               core_addr_to_string (osp));
2090           fprintf_unfiltered (gdb_stdlog, "Stack required (for args): 0x%x\n",
2091                               call_info.memory.arg_offset);
2092           fprintf_unfiltered (gdb_stdlog, "Stack required (for refs): 0x%x\n",
2093                               call_info.memory.ref_offset);
2094           fprintf_unfiltered (gdb_stdlog, "          Stack allocated: %s\n",
2095                               core_addr_to_string_nz (osp - sp));
2096         }
2097     }
2098
2099   /* Now load the argument into registers, or onto the stack.  */
2100
2101   if (struct_return)
2102     {
2103       gdb_byte buf[sizeof (LONGEST)];
2104
2105       store_unsigned_integer (buf, call_info.xlen, byte_order, struct_addr);
2106       regcache->cooked_write (RISCV_A0_REGNUM, buf);
2107     }
2108
2109   for (i = 0; i < nargs; ++i)
2110     {
2111       CORE_ADDR dst;
2112       int second_arg_length = 0;
2113       const gdb_byte *second_arg_data;
2114       struct riscv_arg_info *info = &arg_info [i];
2115
2116       gdb_assert (info->length > 0);
2117
2118       switch (info->argloc[0].loc_type)
2119         {
2120         case riscv_arg_info::location::in_reg:
2121           {
2122             gdb_byte tmp [sizeof (ULONGEST)];
2123
2124             gdb_assert (info->argloc[0].c_length <= info->length);
2125             memset (tmp, 0, sizeof (tmp));
2126             memcpy (tmp, info->contents, info->argloc[0].c_length);
2127             regcache->cooked_write (info->argloc[0].loc_data.regno, tmp);
2128             second_arg_length =
2129               ((info->argloc[0].c_length < info->length)
2130                ? info->argloc[1].c_length : 0);
2131             second_arg_data = info->contents + info->argloc[1].c_offset;
2132           }
2133           break;
2134
2135         case riscv_arg_info::location::on_stack:
2136           dst = sp_args + info->argloc[0].loc_data.offset;
2137           write_memory (dst, info->contents, info->length);
2138           second_arg_length = 0;
2139           break;
2140
2141         case riscv_arg_info::location::by_ref:
2142           dst = sp_refs + info->argloc[0].loc_data.offset;
2143           write_memory (dst, info->contents, info->length);
2144
2145           second_arg_length = call_info.xlen;
2146           second_arg_data = (gdb_byte *) &dst;
2147           break;
2148
2149         default:
2150           gdb_assert_not_reached (_("unknown argument location type"));
2151         }
2152
2153       if (second_arg_length > 0)
2154         {
2155           switch (info->argloc[1].loc_type)
2156             {
2157             case riscv_arg_info::location::in_reg:
2158               {
2159                 gdb_byte tmp [sizeof (ULONGEST)];
2160
2161                 gdb_assert (second_arg_length <= call_info.xlen);
2162                 memset (tmp, 0, sizeof (tmp));
2163                 memcpy (tmp, second_arg_data, second_arg_length);
2164                 regcache->cooked_write (info->argloc[1].loc_data.regno, tmp);
2165               }
2166               break;
2167
2168             case riscv_arg_info::location::on_stack:
2169               {
2170                 CORE_ADDR arg_addr;
2171
2172                 arg_addr = sp_args + info->argloc[1].loc_data.offset;
2173                 write_memory (arg_addr, second_arg_data, second_arg_length);
2174                 break;
2175               }
2176
2177             case riscv_arg_info::location::by_ref:
2178             default:
2179               /* The second location should never be a reference, any
2180                  argument being passed by reference just places its address
2181                  in the first location and is done.  */
2182               error (_("invalid argument location"));
2183               break;
2184             }
2185         }
2186     }
2187
2188   /* Set the dummy return value to bp_addr.
2189      A dummy breakpoint will be setup to execute the call.  */
2190
2191   if (riscv_debug_infcall > 0)
2192     fprintf_unfiltered (gdb_stdlog, ": writing $ra = %s\n",
2193                         core_addr_to_string (bp_addr));
2194   regcache_cooked_write_unsigned (regcache, RISCV_RA_REGNUM, bp_addr);
2195
2196   /* Finally, update the stack pointer.  */
2197
2198   if (riscv_debug_infcall > 0)
2199     fprintf_unfiltered (gdb_stdlog, ": writing $sp = %s\n",
2200                         core_addr_to_string (sp));
2201   regcache_cooked_write_unsigned (regcache, RISCV_SP_REGNUM, sp);
2202
2203   return sp;
2204 }
2205
2206 /* Implement the return_value gdbarch method.  */
2207
2208 static enum return_value_convention
2209 riscv_return_value (struct gdbarch  *gdbarch,
2210                     struct value *function,
2211                     struct type *type,
2212                     struct regcache *regcache,
2213                     gdb_byte *readbuf,
2214                     const gdb_byte *writebuf)
2215 {
2216   enum type_code rv_type = TYPE_CODE (type);
2217   unsigned int rv_size = TYPE_LENGTH (type);
2218   int fp, regnum, flen;
2219   ULONGEST tmp;
2220   struct riscv_call_info call_info (gdbarch);
2221   struct riscv_arg_info info;
2222   struct type *arg_type;
2223
2224   arg_type = check_typedef (type);
2225   riscv_arg_location (gdbarch, &info, &call_info, arg_type);
2226
2227   if (riscv_debug_infcall > 0)
2228     {
2229       fprintf_unfiltered (gdb_stdlog, "riscv return value:\n");
2230       fprintf_unfiltered (gdb_stdlog, "[R] ");
2231       riscv_print_arg_location (gdb_stdlog, gdbarch, &info, 0, 0);
2232       fprintf_unfiltered (gdb_stdlog, "\n");
2233     }
2234
2235   if (readbuf != nullptr || writebuf != nullptr)
2236     {
2237         int regnum;
2238
2239         switch (info.argloc[0].loc_type)
2240           {
2241             /* Return value in register(s).  */
2242           case riscv_arg_info::location::in_reg:
2243             {
2244               regnum = info.argloc[0].loc_data.regno;
2245
2246               if (readbuf)
2247                 regcache->cooked_read (regnum, readbuf);
2248
2249               if (writebuf)
2250                 regcache->cooked_write (regnum, writebuf);
2251
2252               /* A return value in register can have a second part in a
2253                  second register.  */
2254               if (info.argloc[0].c_length < info.length)
2255                 {
2256                   switch (info.argloc[1].loc_type)
2257                     {
2258                     case riscv_arg_info::location::in_reg:
2259                       regnum = info.argloc[1].loc_data.regno;
2260
2261                       if (readbuf)
2262                         {
2263                           readbuf += info.argloc[1].c_offset;
2264                           regcache->cooked_read (regnum, readbuf);
2265                         }
2266
2267                       if (writebuf)
2268                         {
2269                           writebuf += info.argloc[1].c_offset;
2270                           regcache->cooked_write (regnum, writebuf);
2271                         }
2272                       break;
2273
2274                     case riscv_arg_info::location::by_ref:
2275                     case riscv_arg_info::location::on_stack:
2276                     default:
2277                       error (_("invalid argument location"));
2278                       break;
2279                     }
2280                 }
2281             }
2282             break;
2283
2284             /* Return value by reference will have its address in A0.  */
2285           case riscv_arg_info::location::by_ref:
2286             {
2287               ULONGEST addr;
2288
2289               regcache_cooked_read_unsigned (regcache, RISCV_A0_REGNUM,
2290                                              &addr);
2291               if (readbuf != nullptr)
2292                 read_memory (addr, readbuf, info.length);
2293               if (writebuf != nullptr)
2294                 write_memory (addr, writebuf, info.length);
2295             }
2296             break;
2297
2298           case riscv_arg_info::location::on_stack:
2299           default:
2300             error (_("invalid argument location"));
2301             break;
2302           }
2303     }
2304
2305   switch (info.argloc[0].loc_type)
2306     {
2307     case riscv_arg_info::location::in_reg:
2308       return RETURN_VALUE_REGISTER_CONVENTION;
2309     case riscv_arg_info::location::by_ref:
2310       return RETURN_VALUE_ABI_RETURNS_ADDRESS;
2311     case riscv_arg_info::location::on_stack:
2312     default:
2313       error (_("invalid argument location"));
2314     }
2315 }
2316
2317 /* Implement the frame_align gdbarch method.  */
2318
2319 static CORE_ADDR
2320 riscv_frame_align (struct gdbarch *gdbarch, CORE_ADDR addr)
2321 {
2322   return align_down (addr, 16);
2323 }
2324
2325 /* Implement the unwind_pc gdbarch method.  */
2326
2327 static CORE_ADDR
2328 riscv_unwind_pc (struct gdbarch *gdbarch, struct frame_info *next_frame)
2329 {
2330   return frame_unwind_register_unsigned (next_frame, RISCV_PC_REGNUM);
2331 }
2332
2333 /* Implement the unwind_sp gdbarch method.  */
2334
2335 static CORE_ADDR
2336 riscv_unwind_sp (struct gdbarch *gdbarch, struct frame_info *next_frame)
2337 {
2338   return frame_unwind_register_unsigned (next_frame, RISCV_SP_REGNUM);
2339 }
2340
2341 /* Implement the dummy_id gdbarch method.  */
2342
2343 static struct frame_id
2344 riscv_dummy_id (struct gdbarch *gdbarch, struct frame_info *this_frame)
2345 {
2346   return frame_id_build (get_frame_register_signed (this_frame, RISCV_SP_REGNUM),
2347                          get_frame_pc (this_frame));
2348 }
2349
2350 /* Generate, or return the cached frame cache for the RiscV frame
2351    unwinder.  */
2352
2353 static struct trad_frame_cache *
2354 riscv_frame_cache (struct frame_info *this_frame, void **this_cache)
2355 {
2356   CORE_ADDR pc;
2357   CORE_ADDR start_addr;
2358   CORE_ADDR stack_addr;
2359   struct trad_frame_cache *this_trad_cache;
2360   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2361
2362   if ((*this_cache) != NULL)
2363     return (struct trad_frame_cache *) *this_cache;
2364   this_trad_cache = trad_frame_cache_zalloc (this_frame);
2365   (*this_cache) = this_trad_cache;
2366
2367   trad_frame_set_reg_realreg (this_trad_cache, gdbarch_pc_regnum (gdbarch),
2368                               RISCV_RA_REGNUM);
2369
2370   pc = get_frame_pc (this_frame);
2371   find_pc_partial_function (pc, NULL, &start_addr, NULL);
2372   stack_addr = get_frame_register_signed (this_frame, RISCV_SP_REGNUM);
2373   trad_frame_set_id (this_trad_cache, frame_id_build (stack_addr, start_addr));
2374
2375   trad_frame_set_this_base (this_trad_cache, stack_addr);
2376
2377   return this_trad_cache;
2378 }
2379
2380 /* Implement the this_id callback for RiscV frame unwinder.  */
2381
2382 static void
2383 riscv_frame_this_id (struct frame_info *this_frame,
2384                      void **prologue_cache,
2385                      struct frame_id *this_id)
2386 {
2387   struct trad_frame_cache *info;
2388
2389   info = riscv_frame_cache (this_frame, prologue_cache);
2390   trad_frame_get_id (info, this_id);
2391 }
2392
2393 /* Implement the prev_register callback for RiscV frame unwinder.  */
2394
2395 static struct value *
2396 riscv_frame_prev_register (struct frame_info *this_frame,
2397                            void **prologue_cache,
2398                            int regnum)
2399 {
2400   struct trad_frame_cache *info;
2401
2402   info = riscv_frame_cache (this_frame, prologue_cache);
2403   return trad_frame_get_register (info, this_frame, regnum);
2404 }
2405
2406 /* Structure defining the RiscV normal frame unwind functions.  Since we
2407    are the fallback unwinder (DWARF unwinder is used first), we use the
2408    default frame sniffer, which always accepts the frame.  */
2409
2410 static const struct frame_unwind riscv_frame_unwind =
2411 {
2412   /*.type          =*/ NORMAL_FRAME,
2413   /*.stop_reason   =*/ default_frame_unwind_stop_reason,
2414   /*.this_id       =*/ riscv_frame_this_id,
2415   /*.prev_register =*/ riscv_frame_prev_register,
2416   /*.unwind_data   =*/ NULL,
2417   /*.sniffer       =*/ default_frame_sniffer,
2418   /*.dealloc_cache =*/ NULL,
2419   /*.prev_arch     =*/ NULL,
2420 };
2421
2422 /* Initialize the current architecture based on INFO.  If possible,
2423    re-use an architecture from ARCHES, which is a list of
2424    architectures already created during this debugging session.
2425
2426    Called e.g. at program startup, when reading a core file, and when
2427    reading a binary file.  */
2428
2429 static struct gdbarch *
2430 riscv_gdbarch_init (struct gdbarch_info info,
2431                     struct gdbarch_list *arches)
2432 {
2433   struct gdbarch *gdbarch;
2434   struct gdbarch_tdep *tdep;
2435   struct gdbarch_tdep tmp_tdep;
2436   bool has_compressed_isa = false;
2437   int i;
2438
2439   /* Ideally, we'd like to get as much information from the target for
2440      things like register size, and whether the target has floating point
2441      hardware.  However, there are some things that the target can't tell
2442      us, like, what ABI is being used.
2443
2444      So, for now, we take as much information as possible from the ELF,
2445      including things like register size, and FP hardware support, along
2446      with information about the ABI.
2447
2448      Information about this target is built up in TMP_TDEP, and then we
2449      look for an existing gdbarch in ARCHES that matches TMP_TDEP.  If no
2450      match is found we'll create a new gdbarch and copy TMP_TDEP over.  */
2451   memset (&tmp_tdep, 0, sizeof (tmp_tdep));
2452
2453   if (info.abfd != NULL
2454       && bfd_get_flavour (info.abfd) == bfd_target_elf_flavour)
2455     {
2456       unsigned char eclass = elf_elfheader (info.abfd)->e_ident[EI_CLASS];
2457       int e_flags = elf_elfheader (info.abfd)->e_flags;
2458
2459       if (eclass == ELFCLASS32)
2460         tmp_tdep.abi.fields.base_len = 1;
2461       else if (eclass == ELFCLASS64)
2462         tmp_tdep.abi.fields.base_len = 2;
2463       else
2464         internal_error (__FILE__, __LINE__,
2465                         _("unknown ELF header class %d"), eclass);
2466
2467       if (e_flags & EF_RISCV_RVC)
2468         {
2469           has_compressed_isa = true;
2470           tmp_tdep.core_features |= (1 << ('C' - 'A'));
2471         }
2472
2473       if (e_flags & EF_RISCV_FLOAT_ABI_DOUBLE)
2474         {
2475           tmp_tdep.abi.fields.float_abi = 2;
2476           tmp_tdep.core_features |= (1 << ('D' - 'A'));
2477           tmp_tdep.core_features |= (1 << ('F' - 'A'));
2478         }
2479       else if (e_flags & EF_RISCV_FLOAT_ABI_SINGLE)
2480         {
2481           tmp_tdep.abi.fields.float_abi = 1;
2482           tmp_tdep.core_features |= (1 << ('F' - 'A'));
2483         }
2484     }
2485   else
2486     {
2487       const struct bfd_arch_info *binfo = info.bfd_arch_info;
2488
2489       if (binfo->bits_per_word == 32)
2490         tmp_tdep.abi.fields.base_len = 1;
2491       else if (binfo->bits_per_word == 64)
2492         tmp_tdep.abi.fields.base_len = 2;
2493       else
2494         internal_error (__FILE__, __LINE__, _("unknown bits_per_word %d"),
2495                         binfo->bits_per_word);
2496     }
2497
2498   /* Find a candidate among the list of pre-declared architectures.  */
2499   for (arches = gdbarch_list_lookup_by_info (arches, &info);
2500        arches != NULL;
2501        arches = gdbarch_list_lookup_by_info (arches->next, &info))
2502     if (gdbarch_tdep (arches->gdbarch)->abi.value == tmp_tdep.abi.value)
2503       return arches->gdbarch;
2504
2505   /* None found, so create a new architecture from the information provided.  */
2506   tdep = (struct gdbarch_tdep *) xmalloc (sizeof *tdep);
2507   gdbarch = gdbarch_alloc (&info, tdep);
2508   memcpy (tdep, &tmp_tdep, sizeof (tmp_tdep));
2509
2510   /* Target data types.  */
2511   set_gdbarch_short_bit (gdbarch, 16);
2512   set_gdbarch_int_bit (gdbarch, 32);
2513   set_gdbarch_long_bit (gdbarch, riscv_isa_xlen (gdbarch) * 8);
2514   set_gdbarch_long_long_bit (gdbarch, 64);
2515   set_gdbarch_float_bit (gdbarch, 32);
2516   set_gdbarch_double_bit (gdbarch, 64);
2517   set_gdbarch_long_double_bit (gdbarch, 128);
2518   set_gdbarch_long_double_format (gdbarch, floatformats_ia64_quad);
2519   set_gdbarch_ptr_bit (gdbarch, riscv_isa_xlen (gdbarch) * 8);
2520   set_gdbarch_char_signed (gdbarch, 0);
2521
2522   /* Information about the target architecture.  */
2523   set_gdbarch_return_value (gdbarch, riscv_return_value);
2524   set_gdbarch_breakpoint_kind_from_pc (gdbarch, riscv_breakpoint_kind_from_pc);
2525   set_gdbarch_sw_breakpoint_from_kind (gdbarch, riscv_sw_breakpoint_from_kind);
2526
2527   /* Register architecture.  */
2528   set_gdbarch_num_regs (gdbarch, RISCV_LAST_REGNUM + 1);
2529   set_gdbarch_sp_regnum (gdbarch, RISCV_SP_REGNUM);
2530   set_gdbarch_pc_regnum (gdbarch, RISCV_PC_REGNUM);
2531   set_gdbarch_ps_regnum (gdbarch, RISCV_FP_REGNUM);
2532   set_gdbarch_deprecated_fp_regnum (gdbarch, RISCV_FP_REGNUM);
2533
2534   /* Functions to supply register information.  */
2535   set_gdbarch_register_name (gdbarch, riscv_register_name);
2536   set_gdbarch_register_type (gdbarch, riscv_register_type);
2537   set_gdbarch_print_registers_info (gdbarch, riscv_print_registers_info);
2538   set_gdbarch_register_reggroup_p (gdbarch, riscv_register_reggroup_p);
2539
2540   /* Functions to analyze frames.  */
2541   set_gdbarch_decr_pc_after_break (gdbarch, (has_compressed_isa ? 2 : 4));
2542   set_gdbarch_skip_prologue (gdbarch, riscv_skip_prologue);
2543   set_gdbarch_inner_than (gdbarch, core_addr_lessthan);
2544   set_gdbarch_frame_align (gdbarch, riscv_frame_align);
2545
2546   /* Functions to access frame data.  */
2547   set_gdbarch_unwind_pc (gdbarch, riscv_unwind_pc);
2548   set_gdbarch_unwind_sp (gdbarch, riscv_unwind_sp);
2549
2550   /* Functions handling dummy frames.  */
2551   set_gdbarch_call_dummy_location (gdbarch, ON_STACK);
2552   set_gdbarch_push_dummy_code (gdbarch, riscv_push_dummy_code);
2553   set_gdbarch_push_dummy_call (gdbarch, riscv_push_dummy_call);
2554   set_gdbarch_dummy_id (gdbarch, riscv_dummy_id);
2555
2556   /* Frame unwinders.  Use DWARF debug info if available, otherwise use our own
2557      unwinder.  */
2558   dwarf2_append_unwinders (gdbarch);
2559   frame_unwind_append_unwinder (gdbarch, &riscv_frame_unwind);
2560
2561   for (i = 0; i < ARRAY_SIZE (riscv_register_aliases); ++i)
2562     user_reg_add (gdbarch, riscv_register_aliases[i].name,
2563                   value_of_riscv_user_reg, &riscv_register_aliases[i].regnum);
2564
2565   return gdbarch;
2566 }
2567
2568
2569 /* Allocate new riscv_inferior_data object.  */
2570
2571 static struct riscv_inferior_data *
2572 riscv_new_inferior_data (void)
2573 {
2574   struct riscv_inferior_data *inf_data
2575     = new (struct riscv_inferior_data);
2576   inf_data->misa_read = false;
2577   return inf_data;
2578 }
2579
2580 /* Free inferior data.  */
2581
2582 static void
2583 riscv_inferior_data_cleanup (struct inferior *inf, void *data)
2584 {
2585   struct riscv_inferior_data *inf_data =
2586     static_cast <struct riscv_inferior_data *> (data);
2587   delete (inf_data);
2588 }
2589
2590 /* Return riscv_inferior_data for the given INFERIOR.  If not yet created,
2591    construct it.  */
2592
2593 struct riscv_inferior_data *
2594 riscv_inferior_data (struct inferior *const inf)
2595 {
2596   struct riscv_inferior_data *inf_data;
2597
2598   gdb_assert (inf != NULL);
2599
2600   inf_data
2601     = (struct riscv_inferior_data *) inferior_data (inf, riscv_inferior_data_reg);
2602   if (inf_data == NULL)
2603     {
2604       inf_data = riscv_new_inferior_data ();
2605       set_inferior_data (inf, riscv_inferior_data_reg, inf_data);
2606     }
2607
2608   return inf_data;
2609 }
2610
2611 /* Free the inferior data when an inferior exits.  */
2612
2613 static void
2614 riscv_invalidate_inferior_data (struct inferior *inf)
2615 {
2616   struct riscv_inferior_data *inf_data;
2617
2618   gdb_assert (inf != NULL);
2619
2620   /* Don't call RISCV_INFERIOR_DATA as we don't want to create the data if
2621      we've not already created it by this point.  */
2622   inf_data
2623     = (struct riscv_inferior_data *) inferior_data (inf, riscv_inferior_data_reg);
2624   if (inf_data != NULL)
2625     {
2626       delete (inf_data);
2627       set_inferior_data (inf, riscv_inferior_data_reg, NULL);
2628     }
2629 }
2630
2631 void
2632 _initialize_riscv_tdep (void)
2633 {
2634   gdbarch_register (bfd_arch_riscv, riscv_gdbarch_init, NULL);
2635
2636   /* Register per-inferior data.  */
2637   riscv_inferior_data_reg
2638     = register_inferior_data_with_cleanup (NULL, riscv_inferior_data_cleanup);
2639
2640   /* Observers used to invalidate the inferior data when needed.  */
2641   gdb::observers::inferior_exit.attach (riscv_invalidate_inferior_data);
2642   gdb::observers::inferior_appeared.attach (riscv_invalidate_inferior_data);
2643
2644   /* Add root prefix command for all "set debug riscv" and "show debug
2645      riscv" commands.  */
2646   add_prefix_cmd ("riscv", no_class, set_debug_riscv_command,
2647                   _("RISC-V specific debug commands."),
2648                   &setdebugriscvcmdlist, "set debug riscv ", 0,
2649                   &setdebuglist);
2650
2651   add_prefix_cmd ("riscv", no_class, show_debug_riscv_command,
2652                   _("RISC-V specific debug commands."),
2653                   &showdebugriscvcmdlist, "show debug riscv ", 0,
2654                   &showdebuglist);
2655
2656   add_setshow_zuinteger_cmd ("infcall", class_maintenance,
2657                              &riscv_debug_infcall,  _("\
2658 Set riscv inferior call debugging."), _("\
2659 Show riscv inferior call debugging."), _("\
2660 When non-zero, print debugging information for the riscv specific parts\n\
2661 of the inferior call mechanism."),
2662                              NULL,
2663                              show_riscv_debug_variable,
2664                              &setdebugriscvcmdlist, &showdebugriscvcmdlist);
2665
2666   /* Add root prefix command for all "set riscv" and "show riscv" commands.  */
2667   add_prefix_cmd ("riscv", no_class, set_riscv_command,
2668                   _("RISC-V specific commands."),
2669                   &setriscvcmdlist, "set riscv ", 0, &setlist);
2670
2671   add_prefix_cmd ("riscv", no_class, show_riscv_command,
2672                   _("RISC-V specific commands."),
2673                   &showriscvcmdlist, "show riscv ", 0, &showlist);
2674
2675
2676   use_compressed_breakpoints = AUTO_BOOLEAN_AUTO;
2677   add_setshow_auto_boolean_cmd ("use-compressed-breakpoints", no_class,
2678                                 &use_compressed_breakpoints,
2679                                 _("\
2680 Set debugger's use of compressed breakpoints."), _("    \
2681 Show debugger's use of compressed breakpoints."), _("\
2682 Debugging compressed code requires compressed breakpoints to be used. If\n \
2683 left to 'auto' then gdb will use them if $misa indicates the C extension\n \
2684 is supported. If that doesn't give the correct behavior, then this option\n\
2685 can be used."),
2686                                 NULL,
2687                                 show_use_compressed_breakpoints,
2688                                 &setriscvcmdlist,
2689                                 &showriscvcmdlist);
2690 }