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