]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/riscv-tdep.c
Automatic date update in version.in
[thirdparty/binutils-gdb.git] / gdb / riscv-tdep.c
CommitLineData
dbbb1059
AB
1/* Target-dependent code for the RISC-V architecture, for GDB.
2
d01e8234 3 Copyright (C) 2018-2025 Free Software Foundation, Inc.
dbbb1059 4
dbbb1059
AB
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
ec452525 20#include "extract-store-integer.h"
dbbb1059
AB
21#include "frame.h"
22#include "inferior.h"
23#include "symtab.h"
24#include "value.h"
5b9707eb 25#include "cli/cli-cmds.h"
dbbb1059
AB
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"
dbbb1059
AB
36#include "reggroups.h"
37#include "opcode/riscv.h"
38#include "elf/riscv.h"
39#include "elf-bfd.h"
40#include "symcat.h"
41#include "dis-asm.h"
42#include "frame-unwind.h"
43#include "frame-base.h"
44#include "trad-frame.h"
45#include "infcall.h"
46#include "floatformat.h"
47#include "remote.h"
48#include "target-descriptions.h"
82ca8957 49#include "dwarf2/frame.h"
dbbb1059
AB
50#include "user-regs.h"
51#include "valprint.h"
dbbb1059
AB
52#include "opcode/riscv-opc.h"
53#include "cli/cli-decode.h"
76727919 54#include "observable.h"
78a3b0fa 55#include "prologue-value.h"
b5ffee31 56#include "arch/riscv.h"
b9c7eed0 57#include "record-full.h"
db3ad2f0 58#include "riscv-ravenscar-thread.h"
e0f4b3ec 59#include "gdbsupport/gdb-safe-ctype.h"
dbbb1059 60
b9c7eed0
T
61#include <vector>
62
dbbb1059
AB
63/* The stack must be 16-byte aligned. */
64#define SP_ALIGNMENT 16
65
ef2de9e7
JW
66/* The biggest alignment that the target supports. */
67#define BIGGEST_ALIGNMENT 16
68
dbbb1059
AB
69/* Define a series of is_XXX_insn functions to check if the value INSN
70 is an instance of instruction XXX. */
71#define DECLARE_INSN(INSN_NAME, INSN_MATCH, INSN_MASK) \
72static inline bool is_ ## INSN_NAME ## _insn (long insn) \
73{ \
74 return (insn & INSN_MASK) == INSN_MATCH; \
75}
76#include "opcode/riscv-opc.h"
77#undef DECLARE_INSN
78
4f6e0c44
AB
79/* When this is true debugging information about breakpoint kinds will be
80 printed. */
25428040 81
4f6e0c44 82static bool riscv_debug_breakpoints = false;
25428040 83
4f6e0c44
AB
84/* Print a "riscv-breakpoints" debug statement. */
85
86#define riscv_breakpoints_debug_printf(fmt, ...) \
87 debug_prefixed_printf_cond (riscv_debug_breakpoints, \
88 "riscv-breakpoints", \
89 fmt, ##__VA_ARGS__)
90
91/* When this is true debugging information about inferior calls will be
92 printed. */
93
94static bool riscv_debug_infcall = false;
95
96/* Print a "riscv-infcall" debug statement. */
97
98#define riscv_infcall_debug_printf(fmt, ...) \
99 debug_prefixed_printf_cond (riscv_debug_infcall, "riscv-infcall", \
100 fmt, ##__VA_ARGS__)
101
102/* Print "riscv-infcall" start/end debug statements. */
25428040 103
4f6e0c44
AB
104#define RISCV_INFCALL_SCOPED_DEBUG_START_END(fmt, ...) \
105 scoped_debug_start_end (riscv_debug_infcall, "riscv-infcall", \
106 fmt, ##__VA_ARGS__)
25428040 107
4f6e0c44
AB
108/* When this is true debugging information about stack unwinding will be
109 printed. */
110
111static bool riscv_debug_unwinder = false;
112
113/* Print a "riscv-unwinder" debug statement. */
114
115#define riscv_unwinder_debug_printf(fmt, ...) \
116 debug_prefixed_printf_cond (riscv_debug_unwinder, "riscv-unwinder", \
117 fmt, ##__VA_ARGS__)
118
119/* When this is true debugging information about gdbarch initialisation
25428040
AB
120 will be printed. */
121
4f6e0c44 122static bool riscv_debug_gdbarch = false;
25428040 123
4f6e0c44 124/* Print a "riscv-gdbarch" debug statement. */
25428040 125
4f6e0c44
AB
126#define riscv_gdbarch_debug_printf(fmt, ...) \
127 debug_prefixed_printf_cond (riscv_debug_gdbarch, "riscv-gdbarch", \
128 fmt, ##__VA_ARGS__)
25428040 129
d782d24b
AB
130/* The names of the RISC-V target description features. */
131const char *riscv_feature_name_csr = "org.gnu.gdb.riscv.csr";
132static const char *riscv_feature_name_cpu = "org.gnu.gdb.riscv.cpu";
133static const char *riscv_feature_name_fpu = "org.gnu.gdb.riscv.fpu";
134static const char *riscv_feature_name_virtual = "org.gnu.gdb.riscv.virtual";
96f842cb 135static const char *riscv_feature_name_vector = "org.gnu.gdb.riscv.vector";
d782d24b 136
61a5375b 137/* The current set of options to be passed to the disassembler. */
c05dd511 138static std::string riscv_disassembler_options;
61a5375b 139
2047479c
CW
140/* When true, prefer to show register names in their numeric form (eg. x28).
141 When false, show them in their abi form (eg. t3). */
142
143static bool numeric_register_names = false;
144
78a3b0fa
AB
145/* Cached information about a frame. */
146
147struct riscv_unwind_cache
148{
149 /* The register from which we can calculate the frame base. This is
150 usually $sp or $fp. */
151 int frame_base_reg;
152
153 /* The offset from the current value in register FRAME_BASE_REG to the
154 actual frame base address. */
155 int frame_base_offset;
156
157 /* Information about previous register values. */
098caef4 158 trad_frame_saved_reg *regs;
78a3b0fa
AB
159
160 /* The id for this frame. */
161 struct frame_id this_id;
162
163 /* The base (stack) address for this frame. This is the stack pointer
164 value on entry to this frame before any adjustments are made. */
165 CORE_ADDR frame_base;
166};
167
b5ffee31 168/* RISC-V specific register group for CSRs. */
dbbb1059 169
e7fe1011 170static const reggroup *csr_reggroup = nullptr;
dbbb1059 171
3b9fce96
AB
172/* Callback function for user_reg_add. */
173
174static struct value *
8480a37e 175value_of_riscv_user_reg (const frame_info_ptr &frame, const void *baton)
3b9fce96
AB
176{
177 const int *reg_p = (const int *) baton;
a7952927 178 return value_of_register (*reg_p, get_next_frame_sentinel_okay (frame));
3b9fce96
AB
179}
180
181/* Information about a register alias that needs to be set up for this
182 target. These are collected when the target's XML description is
183 analysed, and then processed later, once the gdbarch has been created. */
184
185class riscv_pending_register_alias
186{
187public:
188 /* Constructor. */
189
190 riscv_pending_register_alias (const char *name, const void *baton)
191 : m_name (name),
192 m_baton (baton)
193 { /* Nothing. */ }
194
195 /* Convert this into a user register for GDBARCH. */
196
197 void create (struct gdbarch *gdbarch) const
198 {
199 user_reg_add (gdbarch, m_name, value_of_riscv_user_reg, m_baton);
200 }
201
202private:
203 /* The name for this alias. */
204 const char *m_name;
205
206 /* The baton value for passing to user_reg_add. This must point to some
207 data that will live for at least as long as the gdbarch object to
208 which the user register is attached. */
209 const void *m_baton;
210};
211
b5ffee31
AB
212/* A set of registers that we expect to find in a tdesc_feature. These
213 are use in RISCV_GDBARCH_INIT when processing the target description. */
dbbb1059 214
b5ffee31 215struct riscv_register_feature
dbbb1059 216{
25428040
AB
217 explicit riscv_register_feature (const char *feature_name)
218 : m_feature_name (feature_name)
219 { /* Delete. */ }
220
221 riscv_register_feature () = delete;
222 DISABLE_COPY_AND_ASSIGN (riscv_register_feature);
223
b5ffee31
AB
224 /* Information for a single register. */
225 struct register_info
226 {
227 /* The GDB register number for this register. */
228 int regnum;
229
230 /* List of names for this register. The first name in this list is the
231 preferred name, the name GDB should use when describing this
232 register. */
4445e8f5 233 std::vector<const char *> names;
b5ffee31 234
3b9fce96
AB
235 /* Look in FEATURE for a register with a name from this classes names
236 list. If the register is found then register its number with
2047479c 237 TDESC_DATA and add all its aliases to the ALIASES list. */
3b9fce96
AB
238 bool check (struct tdesc_arch_data *tdesc_data,
239 const struct tdesc_feature *feature,
3b9fce96 240 std::vector<riscv_pending_register_alias> *aliases) const;
b5ffee31
AB
241 };
242
25428040
AB
243 /* Return the name of this feature. */
244 const char *name () const
245 { return m_feature_name; }
dbbb1059 246
25428040 247protected:
ed69cbc8 248
25428040
AB
249 /* Return a target description feature extracted from TDESC for this
250 register feature. Will return nullptr if there is no feature in TDESC
251 with the name M_FEATURE_NAME. */
252 const struct tdesc_feature *tdesc_feature (const struct target_desc *tdesc) const
253 {
254 return tdesc_find_feature (tdesc, name ());
255 }
ed69cbc8 256
b5ffee31
AB
257 /* List of all the registers that we expect that we might find in this
258 register set. */
25428040
AB
259 std::vector<struct register_info> m_registers;
260
261private:
262
263 /* The name for this feature. This is the name used to find this feature
264 within the target description. */
265 const char *m_feature_name;
b5ffee31
AB
266};
267
3b9fce96
AB
268/* See description in the class declaration above. */
269
270bool
271riscv_register_feature::register_info::check
272 (struct tdesc_arch_data *tdesc_data,
273 const struct tdesc_feature *feature,
3b9fce96
AB
274 std::vector<riscv_pending_register_alias> *aliases) const
275{
276 for (const char *name : this->names)
277 {
278 bool found = tdesc_numbered_register (feature, tdesc_data,
279 this->regnum, name);
280 if (found)
281 {
282 /* We know that the target description mentions this
283 register. In RISCV_REGISTER_NAME we ensure that GDB
2047479c
CW
284 always refers to the register by its user-configured name.
285 Here, we add aliases for all possible names, so that
286 the user can refer to the register by any of them. */
287 for (const char *alias : this->names)
288 aliases->emplace_back (alias, (void *) &this->regnum);
3b9fce96
AB
289 return true;
290 }
291 }
292 return false;
293}
294
25428040
AB
295/* Class representing the x-registers feature set. */
296
297struct riscv_xreg_feature : public riscv_register_feature
298{
299 riscv_xreg_feature ()
d782d24b 300 : riscv_register_feature (riscv_feature_name_cpu)
25428040
AB
301 {
302 m_registers = {
303 { RISCV_ZERO_REGNUM + 0, { "zero", "x0" } },
304 { RISCV_ZERO_REGNUM + 1, { "ra", "x1" } },
305 { RISCV_ZERO_REGNUM + 2, { "sp", "x2" } },
306 { RISCV_ZERO_REGNUM + 3, { "gp", "x3" } },
307 { RISCV_ZERO_REGNUM + 4, { "tp", "x4" } },
308 { RISCV_ZERO_REGNUM + 5, { "t0", "x5" } },
309 { RISCV_ZERO_REGNUM + 6, { "t1", "x6" } },
310 { RISCV_ZERO_REGNUM + 7, { "t2", "x7" } },
311 { RISCV_ZERO_REGNUM + 8, { "fp", "x8", "s0" } },
312 { RISCV_ZERO_REGNUM + 9, { "s1", "x9" } },
313 { RISCV_ZERO_REGNUM + 10, { "a0", "x10" } },
314 { RISCV_ZERO_REGNUM + 11, { "a1", "x11" } },
315 { RISCV_ZERO_REGNUM + 12, { "a2", "x12" } },
316 { RISCV_ZERO_REGNUM + 13, { "a3", "x13" } },
317 { RISCV_ZERO_REGNUM + 14, { "a4", "x14" } },
318 { RISCV_ZERO_REGNUM + 15, { "a5", "x15" } },
319 { RISCV_ZERO_REGNUM + 16, { "a6", "x16" } },
320 { RISCV_ZERO_REGNUM + 17, { "a7", "x17" } },
321 { RISCV_ZERO_REGNUM + 18, { "s2", "x18" } },
322 { RISCV_ZERO_REGNUM + 19, { "s3", "x19" } },
323 { RISCV_ZERO_REGNUM + 20, { "s4", "x20" } },
324 { RISCV_ZERO_REGNUM + 21, { "s5", "x21" } },
325 { RISCV_ZERO_REGNUM + 22, { "s6", "x22" } },
326 { RISCV_ZERO_REGNUM + 23, { "s7", "x23" } },
327 { RISCV_ZERO_REGNUM + 24, { "s8", "x24" } },
328 { RISCV_ZERO_REGNUM + 25, { "s9", "x25" } },
329 { RISCV_ZERO_REGNUM + 26, { "s10", "x26" } },
330 { RISCV_ZERO_REGNUM + 27, { "s11", "x27" } },
331 { RISCV_ZERO_REGNUM + 28, { "t3", "x28" } },
332 { RISCV_ZERO_REGNUM + 29, { "t4", "x29" } },
333 { RISCV_ZERO_REGNUM + 30, { "t5", "x30" } },
334 { RISCV_ZERO_REGNUM + 31, { "t6", "x31" } },
335 { RISCV_ZERO_REGNUM + 32, { "pc" } }
336 };
337 }
338
339 /* Return the preferred name for the register with gdb register number
340 REGNUM, which must be in the inclusive range RISCV_ZERO_REGNUM to
341 RISCV_PC_REGNUM. */
342 const char *register_name (int regnum) const
343 {
344 gdb_assert (regnum >= RISCV_ZERO_REGNUM && regnum <= m_registers.size ());
2047479c
CW
345 if (numeric_register_names && (regnum <= RISCV_ZERO_REGNUM + 31))
346 return m_registers[regnum].names[1];
25428040
AB
347 return m_registers[regnum].names[0];
348 }
349
350 /* Check this feature within TDESC, record the registers from this
351 feature into TDESC_DATA and update ALIASES and FEATURES. */
352 bool check (const struct target_desc *tdesc,
353 struct tdesc_arch_data *tdesc_data,
354 std::vector<riscv_pending_register_alias> *aliases,
355 struct riscv_gdbarch_features *features) const
356 {
357 const struct tdesc_feature *feature_cpu = tdesc_feature (tdesc);
358
359 if (feature_cpu == nullptr)
360 return false;
361
362 bool seen_an_optional_reg_p = false;
363 for (const auto &reg : m_registers)
364 {
2047479c 365 bool found = reg.check (tdesc_data, feature_cpu, aliases);
25428040
AB
366
367 bool is_optional_reg_p = (reg.regnum >= RISCV_ZERO_REGNUM + 16
368 && reg.regnum < RISCV_ZERO_REGNUM + 32);
369
370 if (!found && (!is_optional_reg_p || seen_an_optional_reg_p))
371 return false;
372 else if (found && is_optional_reg_p)
373 seen_an_optional_reg_p = true;
374 }
375
376 /* Check that all of the core cpu registers have the same bitsize. */
377 int xlen_bitsize = tdesc_register_bitsize (feature_cpu, "pc");
378
379 bool valid_p = true;
380 for (auto &tdesc_reg : feature_cpu->registers)
381 valid_p &= (tdesc_reg->bitsize == xlen_bitsize);
382
383 features->xlen = (xlen_bitsize / 8);
384 features->embedded = !seen_an_optional_reg_p;
385
386 return valid_p;
387 }
b5ffee31
AB
388};
389
25428040
AB
390/* An instance of the x-register feature set. */
391
392static const struct riscv_xreg_feature riscv_xreg_feature;
393
394/* Class representing the f-registers feature set. */
395
396struct riscv_freg_feature : public riscv_register_feature
397{
398 riscv_freg_feature ()
d782d24b 399 : riscv_register_feature (riscv_feature_name_fpu)
25428040
AB
400 {
401 m_registers = {
402 { RISCV_FIRST_FP_REGNUM + 0, { "ft0", "f0" } },
403 { RISCV_FIRST_FP_REGNUM + 1, { "ft1", "f1" } },
404 { RISCV_FIRST_FP_REGNUM + 2, { "ft2", "f2" } },
405 { RISCV_FIRST_FP_REGNUM + 3, { "ft3", "f3" } },
406 { RISCV_FIRST_FP_REGNUM + 4, { "ft4", "f4" } },
407 { RISCV_FIRST_FP_REGNUM + 5, { "ft5", "f5" } },
408 { RISCV_FIRST_FP_REGNUM + 6, { "ft6", "f6" } },
409 { RISCV_FIRST_FP_REGNUM + 7, { "ft7", "f7" } },
410 { RISCV_FIRST_FP_REGNUM + 8, { "fs0", "f8" } },
411 { RISCV_FIRST_FP_REGNUM + 9, { "fs1", "f9" } },
412 { RISCV_FIRST_FP_REGNUM + 10, { "fa0", "f10" } },
413 { RISCV_FIRST_FP_REGNUM + 11, { "fa1", "f11" } },
414 { RISCV_FIRST_FP_REGNUM + 12, { "fa2", "f12" } },
415 { RISCV_FIRST_FP_REGNUM + 13, { "fa3", "f13" } },
416 { RISCV_FIRST_FP_REGNUM + 14, { "fa4", "f14" } },
417 { RISCV_FIRST_FP_REGNUM + 15, { "fa5", "f15" } },
418 { RISCV_FIRST_FP_REGNUM + 16, { "fa6", "f16" } },
419 { RISCV_FIRST_FP_REGNUM + 17, { "fa7", "f17" } },
420 { RISCV_FIRST_FP_REGNUM + 18, { "fs2", "f18" } },
421 { RISCV_FIRST_FP_REGNUM + 19, { "fs3", "f19" } },
422 { RISCV_FIRST_FP_REGNUM + 20, { "fs4", "f20" } },
423 { RISCV_FIRST_FP_REGNUM + 21, { "fs5", "f21" } },
424 { RISCV_FIRST_FP_REGNUM + 22, { "fs6", "f22" } },
425 { RISCV_FIRST_FP_REGNUM + 23, { "fs7", "f23" } },
426 { RISCV_FIRST_FP_REGNUM + 24, { "fs8", "f24" } },
427 { RISCV_FIRST_FP_REGNUM + 25, { "fs9", "f25" } },
428 { RISCV_FIRST_FP_REGNUM + 26, { "fs10", "f26" } },
429 { RISCV_FIRST_FP_REGNUM + 27, { "fs11", "f27" } },
430 { RISCV_FIRST_FP_REGNUM + 28, { "ft8", "f28" } },
431 { RISCV_FIRST_FP_REGNUM + 29, { "ft9", "f29" } },
432 { RISCV_FIRST_FP_REGNUM + 30, { "ft10", "f30" } },
433 { RISCV_FIRST_FP_REGNUM + 31, { "ft11", "f31" } },
434 { RISCV_CSR_FFLAGS_REGNUM, { "fflags", "csr1" } },
435 { RISCV_CSR_FRM_REGNUM, { "frm", "csr2" } },
436 { RISCV_CSR_FCSR_REGNUM, { "fcsr", "csr3" } },
437 };
438 }
439
440 /* Return the preferred name for the register with gdb register number
441 REGNUM, which must be in the inclusive range RISCV_FIRST_FP_REGNUM to
442 RISCV_LAST_FP_REGNUM. */
443 const char *register_name (int regnum) const
444 {
69f6730d 445 static_assert (RISCV_LAST_FP_REGNUM == RISCV_FIRST_FP_REGNUM + 31);
25428040
AB
446 gdb_assert (regnum >= RISCV_FIRST_FP_REGNUM
447 && regnum <= RISCV_LAST_FP_REGNUM);
448 regnum -= RISCV_FIRST_FP_REGNUM;
2047479c
CW
449 if (numeric_register_names && (regnum <= 31))
450 return m_registers[regnum].names[1];
25428040
AB
451 return m_registers[regnum].names[0];
452 }
453
454 /* Check this feature within TDESC, record the registers from this
455 feature into TDESC_DATA and update ALIASES and FEATURES. */
456 bool check (const struct target_desc *tdesc,
457 struct tdesc_arch_data *tdesc_data,
458 std::vector<riscv_pending_register_alias> *aliases,
459 struct riscv_gdbarch_features *features) const
460 {
461 const struct tdesc_feature *feature_fpu = tdesc_feature (tdesc);
462
463 /* It's fine if this feature is missing. Update the architecture
464 feature set and return. */
465 if (feature_fpu == nullptr)
466 {
467 features->flen = 0;
468 return true;
469 }
470
471 /* Check all of the floating pointer registers are present. We also
472 check that the floating point CSRs are present too, though if these
473 are missing this is not fatal. */
474 for (const auto &reg : m_registers)
475 {
2047479c 476 bool found = reg.check (tdesc_data, feature_fpu, aliases);
25428040
AB
477
478 bool is_ctrl_reg_p = reg.regnum > RISCV_LAST_FP_REGNUM;
479
480 if (!found && !is_ctrl_reg_p)
481 return false;
482 }
483
484 /* Look through all of the floating point registers (not the FP CSRs
485 though), and check they all have the same bitsize. Use this bitsize
486 to update the feature set for this gdbarch. */
487 int fp_bitsize = -1;
488 for (const auto &reg : m_registers)
489 {
490 /* Stop once we get to the CSRs which are at the end of the
491 M_REGISTERS list. */
492 if (reg.regnum > RISCV_LAST_FP_REGNUM)
493 break;
494
495 int reg_bitsize = -1;
496 for (const char *name : reg.names)
497 {
498 if (tdesc_unnumbered_register (feature_fpu, name))
499 {
500 reg_bitsize = tdesc_register_bitsize (feature_fpu, name);
501 break;
502 }
503 }
504 gdb_assert (reg_bitsize != -1);
505 if (fp_bitsize == -1)
506 fp_bitsize = reg_bitsize;
507 else if (fp_bitsize != reg_bitsize)
508 return false;
509 }
510
511 features->flen = (fp_bitsize / 8);
512 return true;
513 }
b5ffee31
AB
514};
515
25428040
AB
516/* An instance of the f-register feature set. */
517
518static const struct riscv_freg_feature riscv_freg_feature;
519
520/* Class representing the virtual registers. These are not physical
521 registers on the hardware, but might be available from the target.
522 These are not pseudo registers, reading these really does result in a
523 register read from the target, it is just that there might not be a
524 physical register backing the result. */
b5ffee31 525
25428040 526struct riscv_virtual_feature : public riscv_register_feature
b5ffee31 527{
25428040 528 riscv_virtual_feature ()
d782d24b 529 : riscv_register_feature (riscv_feature_name_virtual)
25428040
AB
530 {
531 m_registers = {
532 { RISCV_PRIV_REGNUM, { "priv" } }
533 };
534 }
535
536 bool check (const struct target_desc *tdesc,
537 struct tdesc_arch_data *tdesc_data,
538 std::vector<riscv_pending_register_alias> *aliases,
539 struct riscv_gdbarch_features *features) const
540 {
541 const struct tdesc_feature *feature_virtual = tdesc_feature (tdesc);
542
543 /* It's fine if this feature is missing. */
544 if (feature_virtual == nullptr)
545 return true;
546
547 /* We don't check the return value from the call to check here, all the
548 registers in this feature are optional. */
549 for (const auto &reg : m_registers)
2047479c 550 reg.check (tdesc_data, feature_virtual, aliases);
25428040
AB
551
552 return true;
553 }
dbbb1059
AB
554};
555
25428040 556/* An instance of the virtual register feature. */
b5ffee31 557
25428040
AB
558static const struct riscv_virtual_feature riscv_virtual_feature;
559
560/* Class representing the CSR feature. */
561
562struct riscv_csr_feature : public riscv_register_feature
b5ffee31 563{
25428040 564 riscv_csr_feature ()
d782d24b 565 : riscv_register_feature (riscv_feature_name_csr)
25428040
AB
566 {
567 m_registers = {
568#define DECLARE_CSR(NAME,VALUE,CLASS,DEFINE_VER,ABORT_VER) \
569 { RISCV_ ## VALUE ## _REGNUM, { # NAME } },
b5ffee31
AB
570#include "opcode/riscv-opc.h"
571#undef DECLARE_CSR
25428040
AB
572 };
573 riscv_create_csr_aliases ();
574 }
575
576 bool check (const struct target_desc *tdesc,
577 struct tdesc_arch_data *tdesc_data,
578 std::vector<riscv_pending_register_alias> *aliases,
579 struct riscv_gdbarch_features *features) const
580 {
581 const struct tdesc_feature *feature_csr = tdesc_feature (tdesc);
582
583 /* It's fine if this feature is missing. */
584 if (feature_csr == nullptr)
585 return true;
586
587 /* We don't check the return value from the call to check here, all the
588 registers in this feature are optional. */
589 for (const auto &reg : m_registers)
2047479c 590 reg.check (tdesc_data, feature_csr, aliases);
25428040
AB
591
592 return true;
593 }
594
595private:
596
597 /* Complete RISCV_CSR_FEATURE, building the CSR alias names and adding them
598 to the name list for each register. */
599
600 void
601 riscv_create_csr_aliases ()
602 {
603 for (auto &reg : m_registers)
604 {
605 int csr_num = reg.regnum - RISCV_FIRST_CSR_REGNUM;
8579fd13
AB
606 gdb::unique_xmalloc_ptr<char> alias = xstrprintf ("csr%d", csr_num);
607 reg.names.push_back (alias.release ());
25428040
AB
608 }
609 }
dbbb1059
AB
610};
611
25428040 612/* An instance of the csr register feature. */
b5ffee31 613
25428040 614static const struct riscv_csr_feature riscv_csr_feature;
b5ffee31 615
96f842cb
AB
616/* Class representing the v-registers feature set. */
617
618struct riscv_vector_feature : public riscv_register_feature
619{
620 riscv_vector_feature ()
621 : riscv_register_feature (riscv_feature_name_vector)
622 {
623 m_registers = {
624 { RISCV_V0_REGNUM + 0, { "v0" } },
625 { RISCV_V0_REGNUM + 1, { "v1" } },
626 { RISCV_V0_REGNUM + 2, { "v2" } },
627 { RISCV_V0_REGNUM + 3, { "v3" } },
628 { RISCV_V0_REGNUM + 4, { "v4" } },
629 { RISCV_V0_REGNUM + 5, { "v5" } },
630 { RISCV_V0_REGNUM + 6, { "v6" } },
631 { RISCV_V0_REGNUM + 7, { "v7" } },
632 { RISCV_V0_REGNUM + 8, { "v8" } },
633 { RISCV_V0_REGNUM + 9, { "v9" } },
634 { RISCV_V0_REGNUM + 10, { "v10" } },
635 { RISCV_V0_REGNUM + 11, { "v11" } },
636 { RISCV_V0_REGNUM + 12, { "v12" } },
637 { RISCV_V0_REGNUM + 13, { "v13" } },
638 { RISCV_V0_REGNUM + 14, { "v14" } },
639 { RISCV_V0_REGNUM + 15, { "v15" } },
640 { RISCV_V0_REGNUM + 16, { "v16" } },
641 { RISCV_V0_REGNUM + 17, { "v17" } },
642 { RISCV_V0_REGNUM + 18, { "v18" } },
643 { RISCV_V0_REGNUM + 19, { "v19" } },
644 { RISCV_V0_REGNUM + 20, { "v20" } },
645 { RISCV_V0_REGNUM + 21, { "v21" } },
646 { RISCV_V0_REGNUM + 22, { "v22" } },
647 { RISCV_V0_REGNUM + 23, { "v23" } },
648 { RISCV_V0_REGNUM + 24, { "v24" } },
649 { RISCV_V0_REGNUM + 25, { "v25" } },
650 { RISCV_V0_REGNUM + 26, { "v26" } },
651 { RISCV_V0_REGNUM + 27, { "v27" } },
652 { RISCV_V0_REGNUM + 28, { "v28" } },
653 { RISCV_V0_REGNUM + 29, { "v29" } },
654 { RISCV_V0_REGNUM + 30, { "v30" } },
655 { RISCV_V0_REGNUM + 31, { "v31" } },
656 };
657 }
658
659 /* Return the preferred name for the register with gdb register number
660 REGNUM, which must be in the inclusive range RISCV_V0_REGNUM to
661 RISCV_V0_REGNUM + 31. */
662 const char *register_name (int regnum) const
663 {
664 gdb_assert (regnum >= RISCV_V0_REGNUM
665 && regnum <= RISCV_V0_REGNUM + 31);
666 regnum -= RISCV_V0_REGNUM;
667 return m_registers[regnum].names[0];
668 }
669
670 /* Check this feature within TDESC, record the registers from this
671 feature into TDESC_DATA and update ALIASES and FEATURES. */
672 bool check (const struct target_desc *tdesc,
673 struct tdesc_arch_data *tdesc_data,
674 std::vector<riscv_pending_register_alias> *aliases,
675 struct riscv_gdbarch_features *features) const
676 {
677 const struct tdesc_feature *feature_vector = tdesc_feature (tdesc);
678
679 /* It's fine if this feature is missing. Update the architecture
680 feature set and return. */
681 if (feature_vector == nullptr)
682 {
683 features->vlen = 0;
684 return true;
685 }
686
687 /* Check all of the vector registers are present. */
688 for (const auto &reg : m_registers)
689 {
2047479c 690 if (!reg.check (tdesc_data, feature_vector, aliases))
96f842cb
AB
691 return false;
692 }
693
694 /* Look through all of the vector registers and check they all have the
695 same bitsize. Use this bitsize to update the feature set for this
696 gdbarch. */
697 int vector_bitsize = -1;
698 for (const auto &reg : m_registers)
699 {
700 int reg_bitsize = -1;
701 for (const char *name : reg.names)
702 {
703 if (tdesc_unnumbered_register (feature_vector, name))
704 {
705 reg_bitsize = tdesc_register_bitsize (feature_vector, name);
706 break;
707 }
708 }
709 gdb_assert (reg_bitsize != -1);
710 if (vector_bitsize == -1)
711 vector_bitsize = reg_bitsize;
712 else if (vector_bitsize != reg_bitsize)
713 return false;
714 }
715
716 features->vlen = (vector_bitsize / 8);
717 return true;
718 }
719};
720
721/* An instance of the v-register feature set. */
722
723static const struct riscv_vector_feature riscv_vector_feature;
724
dbbb1059
AB
725/* Controls whether we place compressed breakpoints or not. When in auto
726 mode GDB tries to determine if the target supports compressed
727 breakpoints, and uses them if it does. */
728
729static enum auto_boolean use_compressed_breakpoints;
730
731/* The show callback for 'show riscv use-compressed-breakpoints'. */
732
733static void
734show_use_compressed_breakpoints (struct ui_file *file, int from_tty,
735 struct cmd_list_element *c,
736 const char *value)
737{
6cb06a8c
TT
738 gdb_printf (file,
739 _("Debugger's use of compressed breakpoints is set "
740 "to %s.\n"), value);
dbbb1059
AB
741}
742
2047479c
CW
743/* The show callback for 'show riscv numeric-register-names'. */
744
745static void
746show_numeric_register_names (struct ui_file *file, int from_tty,
747 struct cmd_list_element *c,
748 const char *value)
749{
750 gdb_printf (file,
751 _("Displaying registers with their numeric names is %s.\n"),
752 value);
753}
754
dbbb1059
AB
755/* The set and show lists for 'set riscv' and 'show riscv' prefixes. */
756
757static struct cmd_list_element *setriscvcmdlist = NULL;
758static struct cmd_list_element *showriscvcmdlist = NULL;
759
dbbb1059
AB
760/* The set and show lists for 'set riscv' and 'show riscv' prefixes. */
761
762static struct cmd_list_element *setdebugriscvcmdlist = NULL;
763static struct cmd_list_element *showdebugriscvcmdlist = NULL;
764
dbbb1059
AB
765/* The show callback for all 'show debug riscv VARNAME' variables. */
766
767static void
768show_riscv_debug_variable (struct ui_file *file, int from_tty,
769 struct cmd_list_element *c,
770 const char *value)
771{
6cb06a8c
TT
772 gdb_printf (file,
773 _("RiscV debug variable `%s' is set to: %s\n"),
774 c->name, value);
dbbb1059
AB
775}
776
8a613826 777/* See riscv-tdep.h. */
dbbb1059 778
411baa47 779int
dbbb1059
AB
780riscv_isa_xlen (struct gdbarch *gdbarch)
781{
08106042 782 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
345bd07c 783 return tdep->isa_features.xlen;
113b7b81
AB
784}
785
786/* See riscv-tdep.h. */
787
788int
789riscv_abi_xlen (struct gdbarch *gdbarch)
790{
08106042 791 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
345bd07c 792 return tdep->abi_features.xlen;
dbbb1059
AB
793}
794
8a613826 795/* See riscv-tdep.h. */
dbbb1059 796
8a613826 797int
dbbb1059
AB
798riscv_isa_flen (struct gdbarch *gdbarch)
799{
08106042 800 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
345bd07c 801 return tdep->isa_features.flen;
113b7b81
AB
802}
803
804/* See riscv-tdep.h. */
805
806int
807riscv_abi_flen (struct gdbarch *gdbarch)
808{
08106042 809 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
345bd07c 810 return tdep->abi_features.flen;
dbbb1059
AB
811}
812
25428040
AB
813/* See riscv-tdep.h. */
814
815bool
816riscv_abi_embedded (struct gdbarch *gdbarch)
817{
08106042 818 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
345bd07c 819 return tdep->abi_features.embedded;
25428040
AB
820}
821
dbbb1059
AB
822/* Return true if the target for GDBARCH has floating point hardware. */
823
824static bool
825riscv_has_fp_regs (struct gdbarch *gdbarch)
826{
827 return (riscv_isa_flen (gdbarch) > 0);
828}
829
830/* Return true if GDBARCH is using any of the floating point hardware ABIs. */
831
832static bool
833riscv_has_fp_abi (struct gdbarch *gdbarch)
834{
08106042 835 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
345bd07c 836 return tdep->abi_features.flen > 0;
dbbb1059
AB
837}
838
8c49aa89
AB
839/* Return true if REGNO is a floating pointer register. */
840
841static bool
842riscv_is_fp_regno_p (int regno)
843{
844 return (regno >= RISCV_FIRST_FP_REGNUM
845 && regno <= RISCV_LAST_FP_REGNUM);
846}
847
dbbb1059
AB
848/* Implement the breakpoint_kind_from_pc gdbarch method. */
849
850static int
851riscv_breakpoint_kind_from_pc (struct gdbarch *gdbarch, CORE_ADDR *pcptr)
852{
853 if (use_compressed_breakpoints == AUTO_BOOLEAN_AUTO)
854 {
3ba2ee38 855 bool unaligned_p = false;
f37bc8b1
JB
856 gdb_byte buf[1];
857
3ba2ee38
JW
858 /* Some targets don't support unaligned reads. The address can only
859 be unaligned if the C extension is supported. So it is safe to
860 use a compressed breakpoint in this case. */
861 if (*pcptr & 0x2)
862 unaligned_p = true;
863 else
864 {
c01660c6
AB
865 /* Read the opcode byte to determine the instruction length. If
866 the read fails this may be because we tried to set the
867 breakpoint at an invalid address, in this case we provide a
868 fake result which will give a breakpoint length of 4.
869 Hopefully when we try to actually insert the breakpoint we
870 will see a failure then too which will be reported to the
871 user. */
872 if (target_read_code (*pcptr, buf, 1) == -1)
873 buf[0] = 0;
3ba2ee38 874 }
f37bc8b1
JB
875
876 if (riscv_debug_breakpoints)
3ba2ee38
JW
877 {
878 const char *bp = (unaligned_p || riscv_insn_length (buf[0]) == 2
879 ? "C.EBREAK" : "EBREAK");
880
4f6e0c44 881 std::string suffix;
3ba2ee38 882 if (unaligned_p)
4f6e0c44 883 suffix = "(unaligned address)";
3ba2ee38 884 else
4f6e0c44
AB
885 suffix = string_printf ("(instruction length %d)",
886 riscv_insn_length (buf[0]));
887 riscv_breakpoints_debug_printf ("Using %s for breakpoint at %s %s",
888 bp, paddress (gdbarch, *pcptr),
889 suffix.c_str ());
3ba2ee38
JW
890 }
891 if (unaligned_p || riscv_insn_length (buf[0]) == 2)
dbbb1059
AB
892 return 2;
893 else
894 return 4;
895 }
896 else if (use_compressed_breakpoints == AUTO_BOOLEAN_TRUE)
897 return 2;
898 else
899 return 4;
900}
901
902/* Implement the sw_breakpoint_from_kind gdbarch method. */
903
904static const gdb_byte *
905riscv_sw_breakpoint_from_kind (struct gdbarch *gdbarch, int kind, int *size)
906{
907 static const gdb_byte ebreak[] = { 0x73, 0x00, 0x10, 0x00, };
908 static const gdb_byte c_ebreak[] = { 0x02, 0x90 };
909
910 *size = kind;
911 switch (kind)
912 {
913 case 2:
914 return c_ebreak;
915 case 4:
916 return ebreak;
917 default:
557b4d76 918 gdb_assert_not_reached ("unhandled breakpoint kind");
dbbb1059
AB
919 }
920}
921
b5ffee31
AB
922/* Implement the register_name gdbarch method. This is used instead of
923 the function supplied by calling TDESC_USE_REGISTERS so that we can
ed69cbc8 924 ensure the preferred names are offered for x-regs and f-regs. */
dbbb1059
AB
925
926static const char *
927riscv_register_name (struct gdbarch *gdbarch, int regnum)
928{
b5ffee31
AB
929 /* Lookup the name through the target description. If we get back NULL
930 then this is an unknown register. If we do get a name back then we
931 look up the registers preferred name below. */
932 const char *name = tdesc_register_name (gdbarch, regnum);
bd93abe8
AB
933 gdb_assert (name != nullptr);
934 if (name[0] == '\0')
935 return name;
b5ffee31 936
2047479c
CW
937 /* We want GDB to use the user-configured names for registers even
938 if the target gives us a target description with something different.
939 For example, we want to see 'ra' if numeric_register_names is false,
940 or 'x1' if numeric_register_names is true - regardless of what the
941 target description called it. */
b5ffee31 942 if (regnum >= RISCV_ZERO_REGNUM && regnum < RISCV_FIRST_FP_REGNUM)
25428040 943 return riscv_xreg_feature.register_name (regnum);
b5ffee31 944
2047479c
CW
945 /* Like with the x-regs we refer to the user configuration for the
946 floating point register names. If the target doesn't have floating
947 point registers then the tdesc_register_name call above should have
948 returned an empty string. */
b5ffee31 949 if (regnum >= RISCV_FIRST_FP_REGNUM && regnum <= RISCV_LAST_FP_REGNUM)
dbbb1059 950 {
bd93abe8
AB
951 gdb_assert (riscv_has_fp_regs (gdbarch));
952 return riscv_freg_feature.register_name (regnum);
dbbb1059
AB
953 }
954
2e52d038
AB
955 /* Some targets (QEMU) are reporting these three registers twice, once
956 in the FPU feature, and once in the CSR feature. Both of these read
957 the same underlying state inside the target, but naming the register
958 twice in the target description results in GDB having two registers
959 with the same name, only one of which can ever be accessed, but both
960 will show up in 'info register all'. Unless, we identify the
961 duplicate copies of these registers (in riscv_tdesc_unknown_reg) and
962 then hide the registers here by giving them no name. */
08106042 963 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
bd93abe8
AB
964 if (tdep->duplicate_fflags_regnum == regnum
965 || tdep->duplicate_frm_regnum == regnum
966 || tdep->duplicate_fcsr_regnum == regnum)
967 return "";
2e52d038 968
ed69cbc8
AB
969 /* The remaining registers are different. For all other registers on the
970 machine we prefer to see the names that the target description
971 provides. This is particularly important for CSRs which might be
972 renamed over time. If GDB keeps track of the "latest" name, but a
973 particular target provides an older name then we don't want to force
974 users to see the newer name in register output.
dbbb1059 975
ed69cbc8
AB
976 The other case that reaches here are any registers that the target
977 provided that GDB is completely unaware of. For these we have no
978 choice but to accept the target description name.
dbbb1059 979
ed69cbc8 980 Just accept whatever name TDESC_REGISTER_NAME returned. */
b5ffee31 981 return name;
dbbb1059
AB
982}
983
4749b84b
AB
984/* Implement gdbarch_pseudo_register_read. Read pseudo-register REGNUM
985 from REGCACHE and place the register value into BUF. BUF is sized
986 based on the type of register REGNUM, all of BUF should be written too,
987 the result should be sign or zero extended as appropriate. */
988
989static enum register_status
990riscv_pseudo_register_read (struct gdbarch *gdbarch,
991 readable_regcache *regcache,
992 int regnum, gdb_byte *buf)
993{
994 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
995
996 if (regnum == tdep->fflags_regnum || regnum == tdep->frm_regnum)
997 {
998 /* Clear BUF. */
999 memset (buf, 0, register_size (gdbarch, regnum));
1000
1001 /* Read the first byte of the fcsr register, this contains both frm
1002 and fflags. */
1003 enum register_status status
1004 = regcache->raw_read_part (RISCV_CSR_FCSR_REGNUM, 0, 1, buf);
1005
1006 if (status != REG_VALID)
1007 return status;
1008
1009 /* Extract the appropriate parts. */
1010 if (regnum == tdep->fflags_regnum)
1011 buf[0] &= 0x1f;
1012 else if (regnum == tdep->frm_regnum)
1013 buf[0] = (buf[0] >> 5) & 0x7;
1014
1015 return REG_VALID;
1016 }
1017
1018 return REG_UNKNOWN;
1019}
1020
7f0f3b0f
SM
1021/* Implement gdbarch_deprecated_pseudo_register_write. Write the contents of
1022 BUF into pseudo-register REGNUM in REGCACHE. BUF is sized based on the type
1023 of register REGNUM. */
4749b84b
AB
1024
1025static void
1026riscv_pseudo_register_write (struct gdbarch *gdbarch,
1027 struct regcache *regcache, int regnum,
1028 const gdb_byte *buf)
1029{
1030 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
1031
1032 if (regnum == tdep->fflags_regnum || regnum == tdep->frm_regnum)
1033 {
1034 int fcsr_regnum = RISCV_CSR_FCSR_REGNUM;
d724d71a 1035 gdb::byte_vector raw_buf (register_size (gdbarch, fcsr_regnum));
4749b84b
AB
1036
1037 regcache->raw_read (fcsr_regnum, raw_buf);
1038
1039 if (regnum == tdep->fflags_regnum)
1040 raw_buf[0] = (raw_buf[0] & ~0x1f) | (buf[0] & 0x1f);
1041 else if (regnum == tdep->frm_regnum)
1042 raw_buf[0] = (raw_buf[0] & ~(0x7 << 5)) | ((buf[0] & 0x7) << 5);
1043
1044 regcache->raw_write (fcsr_regnum, raw_buf);
1045 }
1046 else
1047 gdb_assert_not_reached ("unknown pseudo register %d", regnum);
1048}
1049
f8053219 1050/* Implement the cannot_store_register gdbarch method. The zero register
1051 (x0) is read-only on RISC-V. */
1052
1053static int
1054riscv_cannot_store_register (struct gdbarch *gdbarch, int regnum)
1055{
1056 return regnum == RISCV_ZERO_REGNUM;
1057}
1058
270b9329
JW
1059/* Construct a type for 64-bit FP registers. */
1060
1061static struct type *
1062riscv_fpreg_d_type (struct gdbarch *gdbarch)
1063{
08106042 1064 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
270b9329
JW
1065
1066 if (tdep->riscv_fpreg_d_type == nullptr)
1067 {
1068 const struct builtin_type *bt = builtin_type (gdbarch);
1069
1070 /* The type we're building is this: */
1071#if 0
1072 union __gdb_builtin_type_fpreg_d
1073 {
1074 float f;
1075 double d;
1076 };
1077#endif
1078
1079 struct type *t;
1080
1081 t = arch_composite_type (gdbarch,
1082 "__gdb_builtin_type_fpreg_d", TYPE_CODE_UNION);
1083 append_composite_type_field (t, "float", bt->builtin_float);
1084 append_composite_type_field (t, "double", bt->builtin_double);
2062087b 1085 t->set_is_vector (true);
d0e39ea2 1086 t->set_name ("builtin_type_fpreg_d");
270b9329
JW
1087 tdep->riscv_fpreg_d_type = t;
1088 }
1089
1090 return tdep->riscv_fpreg_d_type;
1091}
1092
b5ffee31
AB
1093/* Implement the register_type gdbarch method. This is installed as an
1094 for the override setup by TDESC_USE_REGISTERS, for most registers we
1095 delegate the type choice to the target description, but for a few
1096 registers we try to improve the types if the target description has
1097 taken a simplistic approach. */
270b9329
JW
1098
1099static struct type *
b5ffee31 1100riscv_register_type (struct gdbarch *gdbarch, int regnum)
270b9329 1101{
b5ffee31
AB
1102 struct type *type = tdesc_register_type (gdbarch, regnum);
1103 int xlen = riscv_isa_xlen (gdbarch);
270b9329 1104
b5ffee31
AB
1105 /* We want to perform some specific type "fixes" in cases where we feel
1106 that we really can do better than the target description. For all
1107 other cases we just return what the target description says. */
1108 if (riscv_is_fp_regno_p (regnum))
270b9329 1109 {
b5ffee31 1110 /* This spots the case for RV64 where the double is defined as
dda83cd7
SM
1111 either 'ieee_double' or 'float' (which is the generic name that
1112 converts to 'double' on 64-bit). In these cases its better to
1113 present the registers using a union type. */
b5ffee31
AB
1114 int flen = riscv_isa_flen (gdbarch);
1115 if (flen == 8
dda83cd7 1116 && type->code () == TYPE_CODE_FLT
df86565b 1117 && type->length () == flen
dda83cd7
SM
1118 && (strcmp (type->name (), "builtin_type_ieee_double") == 0
1119 || strcmp (type->name (), "double") == 0))
1120 type = riscv_fpreg_d_type (gdbarch);
270b9329
JW
1121 }
1122
b5ffee31
AB
1123 if ((regnum == gdbarch_pc_regnum (gdbarch)
1124 || regnum == RISCV_RA_REGNUM
1125 || regnum == RISCV_FP_REGNUM
1126 || regnum == RISCV_SP_REGNUM
1127 || regnum == RISCV_GP_REGNUM
1128 || regnum == RISCV_TP_REGNUM)
78134374 1129 && type->code () == TYPE_CODE_INT
df86565b 1130 && type->length () == xlen)
dbbb1059 1131 {
b5ffee31 1132 /* This spots the case where some interesting registers are defined
dda83cd7
SM
1133 as simple integers of the expected size, we force these registers
1134 to be pointers as we believe that is more useful. */
dbbb1059 1135 if (regnum == gdbarch_pc_regnum (gdbarch)
dda83cd7
SM
1136 || regnum == RISCV_RA_REGNUM)
1137 type = builtin_type (gdbarch)->builtin_func_ptr;
b5ffee31 1138 else if (regnum == RISCV_FP_REGNUM
dda83cd7
SM
1139 || regnum == RISCV_SP_REGNUM
1140 || regnum == RISCV_GP_REGNUM
1141 || regnum == RISCV_TP_REGNUM)
b5ffee31 1142 type = builtin_type (gdbarch)->builtin_data_ptr;
dbbb1059 1143 }
dbbb1059 1144
b5ffee31 1145 return type;
dbbb1059
AB
1146}
1147
1148/* Helper for riscv_print_registers_info, prints info for a single register
1149 REGNUM. */
1150
1151static void
1152riscv_print_one_register_info (struct gdbarch *gdbarch,
1153 struct ui_file *file,
8480a37e 1154 const frame_info_ptr &frame,
dbbb1059
AB
1155 int regnum)
1156{
1157 const char *name = gdbarch_register_name (gdbarch, regnum);
b5ffee31
AB
1158 struct value *val;
1159 struct type *regtype;
dbbb1059
AB
1160 int print_raw_format;
1161 enum tab_stops { value_column_1 = 15 };
1162
0426ad51 1163 gdb_puts (name, file);
5cd2b85e 1164 print_spaces (std::max<int> (1, value_column_1 - strlen (name)), file);
dbbb1059 1165
a70b8144 1166 try
b5ffee31 1167 {
a7952927 1168 val = value_of_register (regnum, get_next_frame_sentinel_okay (frame));
d0c97917 1169 regtype = val->type ();
b5ffee31 1170 }
230d2906 1171 catch (const gdb_exception_error &ex)
b5ffee31
AB
1172 {
1173 /* Handle failure to read a register without interrupting the entire
dda83cd7 1174 'info registers' flow. */
6cb06a8c 1175 gdb_printf (file, "%s\n", ex.what ());
b5ffee31
AB
1176 return;
1177 }
b5ffee31 1178
d00664db
TT
1179 print_raw_format = (val->entirely_available ()
1180 && !val->optimized_out ());
dbbb1059 1181
78134374
SM
1182 if (regtype->code () == TYPE_CODE_FLT
1183 || (regtype->code () == TYPE_CODE_UNION
1f704f76 1184 && regtype->num_fields () == 2
940da03e
SM
1185 && regtype->field (0).type ()->code () == TYPE_CODE_FLT
1186 && regtype->field (1).type ()->code () == TYPE_CODE_FLT)
78134374 1187 || (regtype->code () == TYPE_CODE_UNION
1f704f76 1188 && regtype->num_fields () == 3
940da03e
SM
1189 && regtype->field (0).type ()->code () == TYPE_CODE_FLT
1190 && regtype->field (1).type ()->code () == TYPE_CODE_FLT
1191 && regtype->field (2).type ()->code () == TYPE_CODE_FLT))
dbbb1059
AB
1192 {
1193 struct value_print_options opts;
efaf1ae0 1194 const gdb_byte *valaddr = val->contents_for_printing ().data ();
34877895 1195 enum bfd_endian byte_order = type_byte_order (regtype);
dbbb1059
AB
1196
1197 get_user_print_options (&opts);
dad6b350 1198 opts.deref_ref = true;
dbbb1059 1199
040f66bd 1200 common_val_print (val, file, 0, &opts, current_language);
dbbb1059
AB
1201
1202 if (print_raw_format)
1203 {
6cb06a8c 1204 gdb_printf (file, "\t(raw ");
df86565b 1205 print_hex_chars (file, valaddr, regtype->length (), byte_order,
dbbb1059 1206 true);
6cb06a8c 1207 gdb_printf (file, ")");
dbbb1059
AB
1208 }
1209 }
1210 else
1211 {
1212 struct value_print_options opts;
4749b84b 1213 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
dbbb1059
AB
1214
1215 /* Print the register in hex. */
1216 get_formatted_print_options (&opts, 'x');
dad6b350 1217 opts.deref_ref = true;
040f66bd 1218 common_val_print (val, file, 0, &opts, current_language);
dbbb1059
AB
1219
1220 if (print_raw_format)
1221 {
1222 if (regnum == RISCV_CSR_MSTATUS_REGNUM)
1223 {
1224 LONGEST d;
1225 int size = register_size (gdbarch, regnum);
1226 unsigned xlen;
1227
b7c8601a
JW
1228 /* The SD field is always in the upper bit of MSTATUS, regardless
1229 of the number of bits in MSTATUS. */
dbbb1059 1230 d = value_as_long (val);
b7c8601a 1231 xlen = size * 8;
6cb06a8c
TT
1232 gdb_printf (file,
1233 "\tSD:%X VM:%02X MXR:%X PUM:%X MPRV:%X XS:%X "
1234 "FS:%X MPP:%x HPP:%X SPP:%X MPIE:%X HPIE:%X "
1235 "SPIE:%X UPIE:%X MIE:%X HIE:%X SIE:%X UIE:%X",
1236 (int) ((d >> (xlen - 1)) & 0x1),
1237 (int) ((d >> 24) & 0x1f),
1238 (int) ((d >> 19) & 0x1),
1239 (int) ((d >> 18) & 0x1),
1240 (int) ((d >> 17) & 0x1),
1241 (int) ((d >> 15) & 0x3),
1242 (int) ((d >> 13) & 0x3),
1243 (int) ((d >> 11) & 0x3),
1244 (int) ((d >> 9) & 0x3),
1245 (int) ((d >> 8) & 0x1),
1246 (int) ((d >> 7) & 0x1),
1247 (int) ((d >> 6) & 0x1),
1248 (int) ((d >> 5) & 0x1),
1249 (int) ((d >> 4) & 0x1),
1250 (int) ((d >> 3) & 0x1),
1251 (int) ((d >> 2) & 0x1),
1252 (int) ((d >> 1) & 0x1),
1253 (int) ((d >> 0) & 0x1));
dbbb1059
AB
1254 }
1255 else if (regnum == RISCV_CSR_MISA_REGNUM)
1256 {
1257 int base;
1258 unsigned xlen, i;
1259 LONGEST d;
b7c8601a 1260 int size = register_size (gdbarch, regnum);
dbbb1059 1261
b7c8601a
JW
1262 /* The MXL field is always in the upper two bits of MISA,
1263 regardless of the number of bits in MISA. Mask out other
1264 bits to ensure we have a positive value. */
dbbb1059 1265 d = value_as_long (val);
b7c8601a 1266 base = (d >> ((size * 8) - 2)) & 0x3;
dbbb1059
AB
1267 xlen = 16;
1268
1269 for (; base > 0; base--)
1270 xlen *= 2;
6cb06a8c 1271 gdb_printf (file, "\tRV%d", xlen);
dbbb1059
AB
1272
1273 for (i = 0; i < 26; i++)
1274 {
1275 if (d & (1 << i))
6cb06a8c 1276 gdb_printf (file, "%c", 'A' + i);
dbbb1059
AB
1277 }
1278 }
1279 else if (regnum == RISCV_CSR_FCSR_REGNUM
4749b84b
AB
1280 || regnum == tdep->fflags_regnum
1281 || regnum == tdep->frm_regnum)
dbbb1059 1282 {
4749b84b 1283 LONGEST d = value_as_long (val);
dbbb1059 1284
6cb06a8c 1285 gdb_printf (file, "\t");
4749b84b 1286 if (regnum != tdep->frm_regnum)
6cb06a8c 1287 gdb_printf (file,
3095d926 1288 "NV:%d DZ:%d OF:%d UF:%d NX:%d",
6cb06a8c
TT
1289 (int) ((d >> 4) & 0x1),
1290 (int) ((d >> 3) & 0x1),
1291 (int) ((d >> 2) & 0x1),
1292 (int) ((d >> 1) & 0x1),
1293 (int) ((d >> 0) & 0x1));
dbbb1059 1294
4749b84b 1295 if (regnum != tdep->fflags_regnum)
dbbb1059
AB
1296 {
1297 static const char * const sfrm[] =
1298 {
3095d926
AB
1299 _("RNE (round to nearest; ties to even)"),
1300 _("RTZ (Round towards zero)"),
1301 _("RDN (Round down towards -INF)"),
1302 _("RUP (Round up towards +INF)"),
1303 _("RMM (Round to nearest; ties to max magnitude)"),
1304 _("INVALID[5]"),
1305 _("INVALID[6]"),
1306 /* A value of 0x7 indicates dynamic rounding mode when
1307 used within an instructions rounding-mode field, but
1308 is invalid within the FRM register. */
1309 _("INVALID[7] (Dynamic rounding mode)"),
dbbb1059
AB
1310 };
1311 int frm = ((regnum == RISCV_CSR_FCSR_REGNUM)
3095d926 1312 ? (d >> 5) : d) & 0x7;
dbbb1059 1313
6cb06a8c
TT
1314 gdb_printf (file, "%sFRM:%i [%s]",
1315 (regnum == RISCV_CSR_FCSR_REGNUM
1316 ? " " : ""),
1317 frm, sfrm[frm]);
dbbb1059
AB
1318 }
1319 }
1320 else if (regnum == RISCV_PRIV_REGNUM)
1321 {
1322 LONGEST d;
1323 uint8_t priv;
1324
1325 d = value_as_long (val);
1326 priv = d & 0xff;
1327
1328 if (priv < 4)
1329 {
1330 static const char * const sprv[] =
1331 {
1332 "User/Application",
1333 "Supervisor",
1334 "Hypervisor",
1335 "Machine"
1336 };
6cb06a8c
TT
1337 gdb_printf (file, "\tprv:%d [%s]",
1338 priv, sprv[priv]);
dbbb1059
AB
1339 }
1340 else
6cb06a8c 1341 gdb_printf (file, "\tprv:%d [INVALID]", priv);
dbbb1059
AB
1342 }
1343 else
1344 {
1345 /* If not a vector register, print it also according to its
1346 natural format. */
bd63c870 1347 if (regtype->is_vector () == 0)
dbbb1059
AB
1348 {
1349 get_user_print_options (&opts);
dad6b350 1350 opts.deref_ref = true;
6cb06a8c 1351 gdb_printf (file, "\t");
040f66bd 1352 common_val_print (val, file, 0, &opts, current_language);
dbbb1059
AB
1353 }
1354 }
1355 }
1356 }
6cb06a8c 1357 gdb_printf (file, "\n");
dbbb1059
AB
1358}
1359
0dbfcfff
AB
1360/* Return true if REGNUM is a valid CSR register. The CSR register space
1361 is sparsely populated, so not every number is a named CSR. */
1362
1363static bool
1364riscv_is_regnum_a_named_csr (int regnum)
1365{
1366 gdb_assert (regnum >= RISCV_FIRST_CSR_REGNUM
1367 && regnum <= RISCV_LAST_CSR_REGNUM);
1368
1369 switch (regnum)
1370 {
8f595e9b 1371#define DECLARE_CSR(name, num, class, define_ver, abort_ver) case RISCV_ ## num ## _REGNUM:
0dbfcfff
AB
1372#include "opcode/riscv-opc.h"
1373#undef DECLARE_CSR
1374 return true;
1375
1376 default:
1377 return false;
1378 }
1379}
1380
e4502042
AB
1381/* Return true if REGNUM is an unknown CSR identified in
1382 riscv_tdesc_unknown_reg for GDBARCH. */
1383
1384static bool
1385riscv_is_unknown_csr (struct gdbarch *gdbarch, int regnum)
1386{
08106042 1387 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
e4502042
AB
1388 return (regnum >= tdep->unknown_csrs_first_regnum
1389 && regnum < (tdep->unknown_csrs_first_regnum
1390 + tdep->unknown_csrs_count));
1391}
1392
dbbb1059
AB
1393/* Implement the register_reggroup_p gdbarch method. Is REGNUM a member
1394 of REGGROUP? */
1395
1396static int
1397riscv_register_reggroup_p (struct gdbarch *gdbarch, int regnum,
dbf5d61b 1398 const struct reggroup *reggroup)
dbbb1059 1399{
4749b84b
AB
1400 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
1401
dbbb1059
AB
1402 /* Used by 'info registers' and 'info registers <groupname>'. */
1403
637b2f86 1404 if (gdbarch_register_name (gdbarch, regnum)[0] == '\0')
dbbb1059
AB
1405 return 0;
1406
4749b84b 1407 if (regnum > RISCV_LAST_REGNUM && regnum < gdbarch_num_regs (gdbarch))
b5ffee31 1408 {
2e52d038
AB
1409 /* Any extra registers from the CSR tdesc_feature (identified in
1410 riscv_tdesc_unknown_reg) are removed from the save/restore groups
e4502042
AB
1411 as some targets (QEMU) report CSRs which then can't be read and
1412 having unreadable registers in the save/restore group breaks
1413 things like inferior calls.
1414
1415 The unknown CSRs are also removed from the general group, and
1416 added into both the csr and system group. This is inline with the
1417 known CSRs (see below). */
1418 if (riscv_is_unknown_csr (gdbarch, regnum))
1419 {
1420 if (reggroup == restore_reggroup || reggroup == save_reggroup
1421 || reggroup == general_reggroup)
1422 return 0;
1423 else if (reggroup == system_reggroup || reggroup == csr_reggroup)
1424 return 1;
1425 }
2e52d038
AB
1426
1427 /* This is some other unknown register from the target description.
1428 In this case we trust whatever the target description says about
1429 which groups this register should be in. */
b5ffee31
AB
1430 int ret = tdesc_register_in_reggroup_p (gdbarch, regnum, reggroup);
1431 if (ret != -1)
dda83cd7 1432 return ret;
b5ffee31
AB
1433
1434 return default_register_reggroup_p (gdbarch, regnum, reggroup);
1435 }
1436
dbbb1059
AB
1437 if (reggroup == all_reggroup)
1438 {
96f842cb 1439 if (regnum < RISCV_FIRST_CSR_REGNUM || regnum >= RISCV_PRIV_REGNUM)
dbbb1059 1440 return 1;
0dbfcfff 1441 if (riscv_is_regnum_a_named_csr (regnum))
dda83cd7 1442 return 1;
dbbb1059
AB
1443 return 0;
1444 }
1445 else if (reggroup == float_reggroup)
8c49aa89
AB
1446 return (riscv_is_fp_regno_p (regnum)
1447 || regnum == RISCV_CSR_FCSR_REGNUM
4749b84b
AB
1448 || regnum == tdep->fflags_regnum
1449 || regnum == tdep->frm_regnum);
dbbb1059
AB
1450 else if (reggroup == general_reggroup)
1451 return regnum < RISCV_FIRST_FP_REGNUM;
1452 else if (reggroup == restore_reggroup || reggroup == save_reggroup)
1453 {
1454 if (riscv_has_fp_regs (gdbarch))
ecc82c05
AB
1455 return (regnum <= RISCV_LAST_FP_REGNUM
1456 || regnum == RISCV_CSR_FCSR_REGNUM
4749b84b
AB
1457 || regnum == tdep->fflags_regnum
1458 || regnum == tdep->frm_regnum);
dbbb1059
AB
1459 else
1460 return regnum < RISCV_FIRST_FP_REGNUM;
1461 }
b5ffee31 1462 else if (reggroup == system_reggroup || reggroup == csr_reggroup)
dbbb1059
AB
1463 {
1464 if (regnum == RISCV_PRIV_REGNUM)
1465 return 1;
1466 if (regnum < RISCV_FIRST_CSR_REGNUM || regnum > RISCV_LAST_CSR_REGNUM)
1467 return 0;
0dbfcfff 1468 if (riscv_is_regnum_a_named_csr (regnum))
dda83cd7 1469 return 1;
dbbb1059
AB
1470 return 0;
1471 }
1472 else if (reggroup == vector_reggroup)
96f842cb 1473 return (regnum >= RISCV_V0_REGNUM && regnum <= RISCV_V31_REGNUM);
dbbb1059
AB
1474 else
1475 return 0;
1476}
1477
4749b84b
AB
1478/* Return the name for pseudo-register REGNUM for GDBARCH. */
1479
1480static const char *
1481riscv_pseudo_register_name (struct gdbarch *gdbarch, int regnum)
1482{
1483 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
1484
1485 if (regnum == tdep->fflags_regnum)
1486 return "fflags";
1487 else if (regnum == tdep->frm_regnum)
1488 return "frm";
1489 else
1490 gdb_assert_not_reached ("unknown pseudo register number %d", regnum);
1491}
1492
1493/* Return the type for pseudo-register REGNUM for GDBARCH. */
1494
1495static struct type *
1496riscv_pseudo_register_type (struct gdbarch *gdbarch, int regnum)
1497{
1498 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
1499
1500 if (regnum == tdep->fflags_regnum || regnum == tdep->frm_regnum)
1501 return builtin_type (gdbarch)->builtin_int32;
1502 else
1503 gdb_assert_not_reached ("unknown pseudo register number %d", regnum);
1504}
1505
1506/* Return true (non-zero) if pseudo-register REGNUM from GDBARCH is a
1507 member of REGGROUP, otherwise return false (zero). */
1508
1509static int
1510riscv_pseudo_register_reggroup_p (struct gdbarch *gdbarch, int regnum,
1511 const struct reggroup *reggroup)
1512{
1513 /* The standard function will also work for pseudo-registers. */
1514 return riscv_register_reggroup_p (gdbarch, regnum, reggroup);
1515}
1516
dbbb1059
AB
1517/* Implement the print_registers_info gdbarch method. This is used by
1518 'info registers' and 'info all-registers'. */
1519
1520static void
1521riscv_print_registers_info (struct gdbarch *gdbarch,
1522 struct ui_file *file,
8480a37e 1523 const frame_info_ptr &frame,
dbbb1059
AB
1524 int regnum, int print_all)
1525{
1526 if (regnum != -1)
1527 {
1528 /* Print one specified register. */
637b2f86 1529 if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
dda83cd7 1530 error (_("Not a valid register for the current processor type"));
dbbb1059
AB
1531 riscv_print_one_register_info (gdbarch, file, frame, regnum);
1532 }
1533 else
1534 {
3a471c03 1535 const struct reggroup *reggroup;
dbbb1059
AB
1536
1537 if (print_all)
1538 reggroup = all_reggroup;
1539 else
1540 reggroup = general_reggroup;
1541
6d74da72 1542 for (regnum = 0; regnum < gdbarch_num_cooked_regs (gdbarch); ++regnum)
dbbb1059
AB
1543 {
1544 /* Zero never changes, so might as well hide by default. */
1545 if (regnum == RISCV_ZERO_REGNUM && !print_all)
1546 continue;
1547
1548 /* Registers with no name are not valid on this ISA. */
637b2f86 1549 if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
dbbb1059
AB
1550 continue;
1551
1552 /* Is the register in the group we're interested in? */
b5ffee31 1553 if (!gdbarch_register_reggroup_p (gdbarch, regnum, reggroup))
dbbb1059
AB
1554 continue;
1555
1556 riscv_print_one_register_info (gdbarch, file, frame, regnum);
1557 }
1558 }
1559}
1560
1561/* Class that handles one decoded RiscV instruction. */
1562
1563class riscv_insn
1564{
1565public:
1566
1567 /* Enum of all the opcodes that GDB cares about during the prologue scan. */
1568 enum opcode
1569 {
1570 /* Unknown value is used at initialisation time. */
1571 UNKNOWN = 0,
1572
1573 /* These instructions are all the ones we are interested in during the
1574 prologue scan. */
1575 ADD,
1576 ADDI,
1577 ADDIW,
1578 ADDW,
1579 AUIPC,
1580 LUI,
6abf2eef 1581 LI,
dbbb1059
AB
1582 SD,
1583 SW,
a35606d9
LS
1584 LD,
1585 LW,
2b014cc5 1586 MV,
405feb71 1587 /* These are needed for software breakpoint support. */
5c720ed8
JW
1588 JAL,
1589 JALR,
1590 BEQ,
1591 BNE,
1592 BLT,
1593 BGE,
1594 BLTU,
1595 BGEU,
1596 /* These are needed for stepping over atomic sequences. */
b273287f
YL
1597 SLTI,
1598 SLTIU,
1599 XORI,
1600 ORI,
1601 ANDI,
1602 SLLI,
1603 SLLIW,
1604 SRLI,
1605 SRLIW,
1606 SRAI,
1607 SRAIW,
1608 SUB,
1609 SUBW,
1610 SLL,
1611 SLLW,
1612 SLT,
1613 SLTU,
1614 XOR,
1615 SRL,
1616 SRLW,
1617 SRA,
1618 SRAW,
1619 OR,
1620 AND,
1621 LR_W,
1622 LR_D,
1623 SC_W,
1624 SC_D,
e843807b
LS
1625 /* This instruction is used to do a syscall. */
1626 ECALL,
dbbb1059
AB
1627
1628 /* Other instructions are not interesting during the prologue scan, and
1629 are ignored. */
1630 OTHER
1631 };
1632
1633 riscv_insn ()
1634 : m_length (0),
1635 m_opcode (OTHER),
1636 m_rd (0),
1637 m_rs1 (0),
1638 m_rs2 (0)
1639 {
1640 /* Nothing. */
1641 }
1642
1643 void decode (struct gdbarch *gdbarch, CORE_ADDR pc);
1644
1645 /* Get the length of the instruction in bytes. */
1646 int length () const
1647 { return m_length; }
1648
1649 /* Get the opcode for this instruction. */
1650 enum opcode opcode () const
1651 { return m_opcode; }
1652
1653 /* Get destination register field for this instruction. This is only
1654 valid if the OPCODE implies there is such a field for this
1655 instruction. */
1656 int rd () const
1657 { return m_rd; }
1658
1659 /* Get the RS1 register field for this instruction. This is only valid
1660 if the OPCODE implies there is such a field for this instruction. */
1661 int rs1 () const
1662 { return m_rs1; }
1663
1664 /* Get the RS2 register field for this instruction. This is only valid
1665 if the OPCODE implies there is such a field for this instruction. */
1666 int rs2 () const
1667 { return m_rs2; }
1668
1669 /* Get the immediate for this instruction in signed form. This is only
1670 valid if the OPCODE implies there is such a field for this
1671 instruction. */
1672 int imm_signed () const
1673 { return m_imm.s; }
1674
b9c7eed0
T
1675 /* Fetch instruction from target memory at ADDR, return the content of
1676 the instruction, and update LEN with the instruction length. */
1677 static ULONGEST fetch_instruction (struct gdbarch *gdbarch,
1678 CORE_ADDR addr, int *len);
1679
dbbb1059
AB
1680private:
1681
1682 /* Extract 5 bit register field at OFFSET from instruction OPCODE. */
1683 int decode_register_index (unsigned long opcode, int offset)
1684 {
1685 return (opcode >> offset) & 0x1F;
1686 }
1687
5c720ed8
JW
1688 /* Extract 5 bit register field at OFFSET from instruction OPCODE. */
1689 int decode_register_index_short (unsigned long opcode, int offset)
1690 {
1691 return ((opcode >> offset) & 0x7) + 8;
1692 }
1693
dbbb1059
AB
1694 /* Helper for DECODE, decode 32-bit R-type instruction. */
1695 void decode_r_type_insn (enum opcode opcode, ULONGEST ival)
1696 {
1697 m_opcode = opcode;
1698 m_rd = decode_register_index (ival, OP_SH_RD);
1699 m_rs1 = decode_register_index (ival, OP_SH_RS1);
1700 m_rs2 = decode_register_index (ival, OP_SH_RS2);
1701 }
1702
1703 /* Helper for DECODE, decode 16-bit compressed R-type instruction. */
1704 void decode_cr_type_insn (enum opcode opcode, ULONGEST ival)
1705 {
1706 m_opcode = opcode;
1707 m_rd = m_rs1 = decode_register_index (ival, OP_SH_CRS1S);
1708 m_rs2 = decode_register_index (ival, OP_SH_CRS2);
1709 }
1710
1711 /* Helper for DECODE, decode 32-bit I-type instruction. */
1712 void decode_i_type_insn (enum opcode opcode, ULONGEST ival)
1713 {
1714 m_opcode = opcode;
1715 m_rd = decode_register_index (ival, OP_SH_RD);
1716 m_rs1 = decode_register_index (ival, OP_SH_RS1);
1717 m_imm.s = EXTRACT_ITYPE_IMM (ival);
1718 }
1719
3ad6e510
AB
1720 /* Helper for DECODE, decode 16-bit compressed I-type instruction. Some
1721 of the CI instruction have a hard-coded rs1 register, while others
1722 just use rd for both the source and destination. RS1_REGNUM, if
1723 passed, is the value to place in rs1, otherwise rd is duplicated into
1724 rs1. */
1725 void decode_ci_type_insn (enum opcode opcode, ULONGEST ival,
6b09f134 1726 std::optional<int> rs1_regnum = {})
dbbb1059
AB
1727 {
1728 m_opcode = opcode;
3ad6e510
AB
1729 m_rd = decode_register_index (ival, OP_SH_CRS1S);
1730 if (rs1_regnum.has_value ())
1731 m_rs1 = *rs1_regnum;
1732 else
1733 m_rs1 = m_rd;
5a9f5403 1734 m_imm.s = EXTRACT_CITYPE_IMM (ival);
dbbb1059
AB
1735 }
1736
a35606d9
LS
1737 /* Helper for DECODE, decode 16-bit compressed CL-type instruction. */
1738 void decode_cl_type_insn (enum opcode opcode, ULONGEST ival)
1739 {
1740 m_opcode = opcode;
1741 m_rd = decode_register_index_short (ival, OP_SH_CRS2S);
1742 m_rs1 = decode_register_index_short (ival, OP_SH_CRS1S);
1743 m_imm.s = EXTRACT_CLTYPE_IMM (ival);
1744 }
1745
dbbb1059
AB
1746 /* Helper for DECODE, decode 32-bit S-type instruction. */
1747 void decode_s_type_insn (enum opcode opcode, ULONGEST ival)
1748 {
1749 m_opcode = opcode;
1750 m_rs1 = decode_register_index (ival, OP_SH_RS1);
1751 m_rs2 = decode_register_index (ival, OP_SH_RS2);
1752 m_imm.s = EXTRACT_STYPE_IMM (ival);
1753 }
1754
ff3a05b3
AB
1755 /* Helper for DECODE, decode 16-bit CS-type instruction. The immediate
1756 encoding is different for each CS format instruction, so extracting
1757 the immediate is left up to the caller, who should pass the extracted
1758 immediate value through in IMM. */
1759 void decode_cs_type_insn (enum opcode opcode, ULONGEST ival, int imm)
1760 {
1761 m_opcode = opcode;
1762 m_imm.s = imm;
1763 m_rs1 = decode_register_index_short (ival, OP_SH_CRS1S);
1764 m_rs2 = decode_register_index_short (ival, OP_SH_CRS2S);
1765 }
1766
1767 /* Helper for DECODE, decode 16-bit CSS-type instruction. The immediate
1768 encoding is different for each CSS format instruction, so extracting
1769 the immediate is left up to the caller, who should pass the extracted
1770 immediate value through in IMM. */
1771 void decode_css_type_insn (enum opcode opcode, ULONGEST ival, int imm)
1772 {
1773 m_opcode = opcode;
1774 m_imm.s = imm;
1775 m_rs1 = RISCV_SP_REGNUM;
1776 /* Not a compressed register number in this case. */
1777 m_rs2 = decode_register_index (ival, OP_SH_CRS2);
1778 }
1779
dbbb1059
AB
1780 /* Helper for DECODE, decode 32-bit U-type instruction. */
1781 void decode_u_type_insn (enum opcode opcode, ULONGEST ival)
1782 {
1783 m_opcode = opcode;
1784 m_rd = decode_register_index (ival, OP_SH_RD);
1785 m_imm.s = EXTRACT_UTYPE_IMM (ival);
1786 }
1787
5c720ed8
JW
1788 /* Helper for DECODE, decode 32-bit J-type instruction. */
1789 void decode_j_type_insn (enum opcode opcode, ULONGEST ival)
1790 {
1791 m_opcode = opcode;
1792 m_rd = decode_register_index (ival, OP_SH_RD);
5a9f5403 1793 m_imm.s = EXTRACT_JTYPE_IMM (ival);
5c720ed8
JW
1794 }
1795
1796 /* Helper for DECODE, decode 32-bit J-type instruction. */
1797 void decode_cj_type_insn (enum opcode opcode, ULONGEST ival)
1798 {
1799 m_opcode = opcode;
5a9f5403 1800 m_imm.s = EXTRACT_CJTYPE_IMM (ival);
5c720ed8
JW
1801 }
1802
1803 void decode_b_type_insn (enum opcode opcode, ULONGEST ival)
1804 {
1805 m_opcode = opcode;
1806 m_rs1 = decode_register_index (ival, OP_SH_RS1);
1807 m_rs2 = decode_register_index (ival, OP_SH_RS2);
5a9f5403 1808 m_imm.s = EXTRACT_BTYPE_IMM (ival);
5c720ed8
JW
1809 }
1810
1811 void decode_cb_type_insn (enum opcode opcode, ULONGEST ival)
1812 {
1813 m_opcode = opcode;
1814 m_rs1 = decode_register_index_short (ival, OP_SH_CRS1S);
5a9f5403 1815 m_imm.s = EXTRACT_CBTYPE_IMM (ival);
5c720ed8
JW
1816 }
1817
b273287f
YL
1818 void decode_ca_type_insn (enum opcode opcode, ULONGEST ival)
1819 {
1820 m_opcode = opcode;
1821 m_rs1 = decode_register_index_short (ival, OP_SH_CRS1S);
1822 m_rs2 = decode_register_index_short (ival, OP_SH_CRS2S);
1823 }
1824
dbbb1059
AB
1825 /* The length of the instruction in bytes. Should be 2 or 4. */
1826 int m_length;
1827
1828 /* The instruction opcode. */
1829 enum opcode m_opcode;
1830
1831 /* The three possible registers an instruction might reference. Not
1832 every instruction fills in all of these registers. Which fields are
1833 valid depends on the opcode. The naming of these fields matches the
1834 naming in the riscv isa manual. */
1835 int m_rd;
1836 int m_rs1;
1837 int m_rs2;
1838
1839 /* Possible instruction immediate. This is only valid if the instruction
1840 format contains an immediate, not all instruction, whether this is
1841 valid depends on the opcode. Despite only having one format for now
1842 the immediate is packed into a union, later instructions might require
1843 an unsigned formatted immediate, having the union in place now will
1844 reduce the need for code churn later. */
1845 union riscv_insn_immediate
1846 {
1847 riscv_insn_immediate ()
1848 : s (0)
1849 {
1850 /* Nothing. */
1851 }
1852
1853 int s;
1854 } m_imm;
1855};
1856
1857/* Fetch instruction from target memory at ADDR, return the content of the
1858 instruction, and update LEN with the instruction length. */
1859
1860ULONGEST
1861riscv_insn::fetch_instruction (struct gdbarch *gdbarch,
1862 CORE_ADDR addr, int *len)
1863{
436a7b5e 1864 gdb_byte buf[RISCV_MAX_INSN_LEN];
dbbb1059
AB
1865 int instlen, status;
1866
1867 /* All insns are at least 16 bits. */
1868 status = target_read_memory (addr, buf, 2);
1869 if (status)
1870 memory_error (TARGET_XFER_E_IO, addr);
1871
1872 /* If we need more, grab it now. */
1873 instlen = riscv_insn_length (buf[0]);
89a3b63e 1874 gdb_assert (instlen <= sizeof (buf));
dbbb1059 1875 *len = instlen;
89a3b63e
AB
1876
1877 if (instlen > 2)
dbbb1059
AB
1878 {
1879 status = target_read_memory (addr + 2, buf + 2, instlen - 2);
1880 if (status)
1881 memory_error (TARGET_XFER_E_IO, addr + 2);
1882 }
1883
c0c3bb70
BB
1884 /* RISC-V Specification states instructions are always little endian */
1885 return extract_unsigned_integer (buf, instlen, BFD_ENDIAN_LITTLE);
dbbb1059
AB
1886}
1887
17cf2897
AB
1888/* Fetch from target memory an instruction at PC and decode it. This can
1889 throw an error if the memory access fails, callers are responsible for
1890 handling this error if that is appropriate. */
dbbb1059
AB
1891
1892void
1893riscv_insn::decode (struct gdbarch *gdbarch, CORE_ADDR pc)
1894{
1895 ULONGEST ival;
1896
1897 /* Fetch the instruction, and the instructions length. */
1898 ival = fetch_instruction (gdbarch, pc, &m_length);
1899
1900 if (m_length == 4)
1901 {
1902 if (is_add_insn (ival))
1903 decode_r_type_insn (ADD, ival);
1904 else if (is_addw_insn (ival))
1905 decode_r_type_insn (ADDW, ival);
1906 else if (is_addi_insn (ival))
1907 decode_i_type_insn (ADDI, ival);
1908 else if (is_addiw_insn (ival))
1909 decode_i_type_insn (ADDIW, ival);
1910 else if (is_auipc_insn (ival))
1911 decode_u_type_insn (AUIPC, ival);
1912 else if (is_lui_insn (ival))
1913 decode_u_type_insn (LUI, ival);
1914 else if (is_sd_insn (ival))
1915 decode_s_type_insn (SD, ival);
1916 else if (is_sw_insn (ival))
1917 decode_s_type_insn (SW, ival);
5c720ed8
JW
1918 else if (is_jal_insn (ival))
1919 decode_j_type_insn (JAL, ival);
1920 else if (is_jalr_insn (ival))
1921 decode_i_type_insn (JALR, ival);
1922 else if (is_beq_insn (ival))
1923 decode_b_type_insn (BEQ, ival);
1924 else if (is_bne_insn (ival))
1925 decode_b_type_insn (BNE, ival);
1926 else if (is_blt_insn (ival))
1927 decode_b_type_insn (BLT, ival);
1928 else if (is_bge_insn (ival))
1929 decode_b_type_insn (BGE, ival);
1930 else if (is_bltu_insn (ival))
1931 decode_b_type_insn (BLTU, ival);
1932 else if (is_bgeu_insn (ival))
1933 decode_b_type_insn (BGEU, ival);
b273287f
YL
1934 else if (is_slti_insn(ival))
1935 decode_i_type_insn (SLTI, ival);
1936 else if (is_sltiu_insn(ival))
1937 decode_i_type_insn (SLTIU, ival);
1938 else if (is_xori_insn(ival))
1939 decode_i_type_insn (XORI, ival);
1940 else if (is_ori_insn(ival))
1941 decode_i_type_insn (ORI, ival);
1942 else if (is_andi_insn(ival))
1943 decode_i_type_insn (ANDI, ival);
1944 else if (is_slli_insn(ival))
1945 decode_i_type_insn (SLLI, ival);
1946 else if (is_slliw_insn(ival))
1947 decode_i_type_insn (SLLIW, ival);
1948 else if (is_srli_insn(ival))
1949 decode_i_type_insn (SRLI, ival);
1950 else if (is_srliw_insn(ival))
1951 decode_i_type_insn (SRLIW, ival);
1952 else if (is_srai_insn(ival))
1953 decode_i_type_insn (SRAI, ival);
1954 else if (is_sraiw_insn(ival))
1955 decode_i_type_insn (SRAIW, ival);
1956 else if (is_sub_insn(ival))
1957 decode_r_type_insn (SUB, ival);
1958 else if (is_subw_insn(ival))
1959 decode_r_type_insn (SUBW, ival);
1960 else if (is_sll_insn(ival))
1961 decode_r_type_insn (SLL, ival);
1962 else if (is_sllw_insn(ival))
1963 decode_r_type_insn (SLLW, ival);
1964 else if (is_slt_insn(ival))
1965 decode_r_type_insn (SLT, ival);
1966 else if (is_sltu_insn(ival))
1967 decode_r_type_insn (SLTU, ival);
1968 else if (is_xor_insn(ival))
1969 decode_r_type_insn (XOR, ival);
1970 else if (is_srl_insn(ival))
1971 decode_r_type_insn (SRL, ival);
1972 else if (is_srlw_insn(ival))
1973 decode_r_type_insn (SRLW, ival);
1974 else if (is_sra_insn(ival))
1975 decode_r_type_insn (SRA, ival);
1976 else if (is_sraw_insn(ival))
1977 decode_r_type_insn (SRAW, ival);
1978 else if (is_or_insn(ival))
1979 decode_r_type_insn (OR, ival);
1980 else if (is_and_insn(ival))
1981 decode_r_type_insn (AND, ival);
5c720ed8 1982 else if (is_lr_w_insn (ival))
b273287f 1983 decode_r_type_insn (LR_W, ival);
5c720ed8 1984 else if (is_lr_d_insn (ival))
b273287f 1985 decode_r_type_insn (LR_D, ival);
5c720ed8 1986 else if (is_sc_w_insn (ival))
b273287f 1987 decode_r_type_insn (SC_W, ival);
5c720ed8 1988 else if (is_sc_d_insn (ival))
b273287f 1989 decode_r_type_insn (SC_D, ival);
e843807b
LS
1990 else if (is_ecall_insn (ival))
1991 decode_i_type_insn (ECALL, ival);
a35606d9
LS
1992 else if (is_ld_insn (ival))
1993 decode_i_type_insn (LD, ival);
1994 else if (is_lw_insn (ival))
1995 decode_i_type_insn (LW, ival);
dbbb1059
AB
1996 else
1997 /* None of the other fields are valid in this case. */
1998 m_opcode = OTHER;
1999 }
2000 else if (m_length == 2)
2001 {
5c720ed8
JW
2002 int xlen = riscv_isa_xlen (gdbarch);
2003
2004 /* C_ADD and C_JALR have the same opcode. If RS2 is 0, then this is a
2005 C_JALR. So must try to match C_JALR first as it has more bits in
2006 mask. */
2007 if (is_c_jalr_insn (ival))
2008 decode_cr_type_insn (JALR, ival);
2009 else if (is_c_add_insn (ival))
dbbb1059 2010 decode_cr_type_insn (ADD, ival);
5c720ed8
JW
2011 /* C_ADDW is RV64 and RV128 only. */
2012 else if (xlen != 4 && is_c_addw_insn (ival))
dbbb1059
AB
2013 decode_cr_type_insn (ADDW, ival);
2014 else if (is_c_addi_insn (ival))
2015 decode_ci_type_insn (ADDI, ival);
5c720ed8
JW
2016 /* C_ADDIW and C_JAL have the same opcode. C_ADDIW is RV64 and RV128
2017 only and C_JAL is RV32 only. */
2018 else if (xlen != 4 && is_c_addiw_insn (ival))
dbbb1059 2019 decode_ci_type_insn (ADDIW, ival);
5c720ed8
JW
2020 else if (xlen == 4 && is_c_jal_insn (ival))
2021 decode_cj_type_insn (JAL, ival);
2022 /* C_ADDI16SP and C_LUI have the same opcode. If RD is 2, then this is a
2023 C_ADDI16SP. So must try to match C_ADDI16SP first as it has more bits
2024 in mask. */
dbbb1059
AB
2025 else if (is_c_addi16sp_insn (ival))
2026 {
2027 m_opcode = ADDI;
2028 m_rd = m_rs1 = decode_register_index (ival, OP_SH_RD);
5a9f5403 2029 m_imm.s = EXTRACT_CITYPE_ADDI16SP_IMM (ival);
dbbb1059 2030 }
ff3a05b3
AB
2031 else if (is_c_addi4spn_insn (ival))
2032 {
2033 m_opcode = ADDI;
2034 m_rd = decode_register_index_short (ival, OP_SH_CRS2S);
2035 m_rs1 = RISCV_SP_REGNUM;
5a9f5403 2036 m_imm.s = EXTRACT_CIWTYPE_ADDI4SPN_IMM (ival);
ff3a05b3 2037 }
5c720ed8 2038 else if (is_c_lui_insn (ival))
dda83cd7
SM
2039 {
2040 m_opcode = LUI;
2041 m_rd = decode_register_index (ival, OP_SH_CRS1S);
5a9f5403 2042 m_imm.s = EXTRACT_CITYPE_LUI_IMM (ival);
dda83cd7 2043 }
b273287f
YL
2044 else if (is_c_srli_insn (ival))
2045 decode_cb_type_insn (SRLI, ival);
2046 else if (is_c_srai_insn (ival))
2047 decode_cb_type_insn (SRAI, ival);
2048 else if (is_c_andi_insn (ival))
2049 decode_cb_type_insn (ANDI, ival);
2050 else if (is_c_sub_insn (ival))
2051 decode_ca_type_insn (SUB, ival);
2052 else if (is_c_xor_insn (ival))
2053 decode_ca_type_insn (XOR, ival);
2054 else if (is_c_or_insn (ival))
2055 decode_ca_type_insn (OR, ival);
2056 else if (is_c_and_insn (ival))
2057 decode_ca_type_insn (AND, ival);
2058 else if (is_c_subw_insn (ival))
2059 decode_ca_type_insn (SUBW, ival);
2060 else if (is_c_addw_insn (ival))
2061 decode_ca_type_insn (ADDW, ival);
6abf2eef
AB
2062 else if (is_c_li_insn (ival))
2063 decode_ci_type_insn (LI, ival);
5c720ed8
JW
2064 /* C_SD and C_FSW have the same opcode. C_SD is RV64 and RV128 only,
2065 and C_FSW is RV32 only. */
2066 else if (xlen != 4 && is_c_sd_insn (ival))
5a9f5403 2067 decode_cs_type_insn (SD, ival, EXTRACT_CLTYPE_LD_IMM (ival));
5c720ed8 2068 else if (is_c_sw_insn (ival))
5a9f5403 2069 decode_cs_type_insn (SW, ival, EXTRACT_CLTYPE_LW_IMM (ival));
ff3a05b3 2070 else if (is_c_swsp_insn (ival))
5a9f5403 2071 decode_css_type_insn (SW, ival, EXTRACT_CSSTYPE_SWSP_IMM (ival));
ff3a05b3 2072 else if (xlen != 4 && is_c_sdsp_insn (ival))
5a9f5403 2073 decode_css_type_insn (SD, ival, EXTRACT_CSSTYPE_SDSP_IMM (ival));
5c720ed8 2074 /* C_JR and C_MV have the same opcode. If RS2 is 0, then this is a C_JR.
2b014cc5 2075 So must try to match C_JR first as it has more bits in mask. */
5c720ed8
JW
2076 else if (is_c_jr_insn (ival))
2077 decode_cr_type_insn (JALR, ival);
2b014cc5
LS
2078 else if (is_c_mv_insn (ival))
2079 decode_cr_type_insn (MV, ival);
5c720ed8
JW
2080 else if (is_c_j_insn (ival))
2081 decode_cj_type_insn (JAL, ival);
2082 else if (is_c_beqz_insn (ival))
2083 decode_cb_type_insn (BEQ, ival);
2084 else if (is_c_bnez_insn (ival))
2085 decode_cb_type_insn (BNE, ival);
a35606d9
LS
2086 else if (is_c_ld_insn (ival))
2087 decode_cl_type_insn (LD, ival);
2088 else if (is_c_lw_insn (ival))
2089 decode_cl_type_insn (LW, ival);
3ad6e510
AB
2090 else if (is_c_ldsp_insn (ival))
2091 decode_ci_type_insn (LD, ival, RISCV_SP_REGNUM);
2092 else if (is_c_lwsp_insn (ival))
2093 decode_ci_type_insn (LW, ival, RISCV_SP_REGNUM);
dbbb1059
AB
2094 else
2095 /* None of the other fields of INSN are valid in this case. */
2096 m_opcode = OTHER;
2097 }
2098 else
312617a3 2099 {
436a7b5e
TO
2100 /* 6 bytes or more. If the instruction is longer than 8 bytes, we don't
2101 have full instruction bits in ival. At least, such long instructions
2102 are not defined yet, so just ignore it. */
2103 gdb_assert (m_length > 0 && m_length % 2 == 0);
312617a3
AB
2104 m_opcode = OTHER;
2105 }
dbbb1059
AB
2106}
2107
29caf118
AB
2108/* Return true if INSN represents an instruction something like:
2109
2110 ld fp,IMMEDIATE(sp)
2111
2112 That is, a load from stack-pointer plus some immediate offset, with the
2113 result stored into the frame pointer. We also accept 'lw' as well as
2114 'ld'. */
2115
2116static bool
2117is_insn_load_of_fp_from_sp (const struct riscv_insn &insn)
2118{
2119 return ((insn.opcode () == riscv_insn::LD
2120 || insn.opcode () == riscv_insn::LW)
2121 && insn.rd () == RISCV_FP_REGNUM
2122 && insn.rs1 () == RISCV_SP_REGNUM);
2123}
2124
2125/* Return true if INSN represents an instruction something like:
2126
2127 add sp,sp,IMMEDIATE
2128
2129 That is, an add of an immediate to the value in the stack pointer
2130 register, with the result stored back to the stack pointer register. */
2131
2132static bool
2133is_insn_addi_of_sp_to_sp (const struct riscv_insn &insn)
2134{
2135 return ((insn.opcode () == riscv_insn::ADDI
2136 || insn.opcode () == riscv_insn::ADDIW)
2137 && insn.rd () == RISCV_SP_REGNUM
2138 && insn.rs1 () == RISCV_SP_REGNUM);
2139}
2140
2141/* Is the instruction in code memory prior to address PC a load from stack
2142 instruction? Return true if it is, otherwise, return false.
2143
2144 This is a best effort that is used as part of the function prologue
2145 scanning logic. With compressed instructions and arbitrary control
2146 flow in the inferior, we can never be certain what the instruction
2147 prior to PC is.
2148
2149 This function first looks for a compressed instruction, then looks for
2150 a 32-bit non-compressed instruction. */
2151
2152static bool
2153previous_insn_is_load_fp_from_stack (struct gdbarch *gdbarch, CORE_ADDR pc)
2154{
2155 struct riscv_insn insn;
2156 insn.decode (gdbarch, pc - 2);
2157 gdb_assert (insn.length () > 0);
2158
2159 if (insn.length () != 2 || !is_insn_load_of_fp_from_sp (insn))
2160 {
2161 insn.decode (gdbarch, pc - 4);
2162 gdb_assert (insn.length () > 0);
2163
2164 if (insn.length () != 4 || !is_insn_load_of_fp_from_sp (insn))
2165 return false;
2166 }
2167
2168 riscv_unwinder_debug_printf
2169 ("previous instruction at %s (length %d) was 'ld'",
2170 core_addr_to_string (pc - insn.length ()), insn.length ());
2171 return true;
2172}
2173
2174/* Is the instruction in code memory prior to address PC an add of an
2175 immediate to the stack pointer, with the result being written back into
2176 the stack pointer? Return true and set *PREV_PC to the address of the
2177 previous instruction if we believe the previous instruction is such an
2178 add, otherwise return false and *PREV_PC is undefined.
2179
2180 This is a best effort that is used as part of the function prologue
2181 scanning logic. With compressed instructions and arbitrary control
2182 flow in the inferior, we can never be certain what the instruction
2183 prior to PC is.
2184
2185 This function first looks for a compressed instruction, then looks for
2186 a 32-bit non-compressed instruction. */
2187
2188static bool
2189previous_insn_is_add_imm_to_sp (struct gdbarch *gdbarch, CORE_ADDR pc,
2190 CORE_ADDR *prev_pc)
2191{
2192 struct riscv_insn insn;
2193 insn.decode (gdbarch, pc - 2);
2194 gdb_assert (insn.length () > 0);
2195
2196 if (insn.length () != 2 || !is_insn_addi_of_sp_to_sp (insn))
2197 {
2198 insn.decode (gdbarch, pc - 4);
2199 gdb_assert (insn.length () > 0);
2200
2201 if (insn.length () != 4 || !is_insn_addi_of_sp_to_sp (insn))
2202 return false;
2203 }
2204
2205 riscv_unwinder_debug_printf
2206 ("previous instruction at %s (length %d) was 'add'",
2207 core_addr_to_string (pc - insn.length ()), insn.length ());
2208 *prev_pc = pc - insn.length ();
2209 return true;
2210}
2211
2212/* Try to spot when PC is located in an exit sequence for a particular
2213 function. Detecting an exit sequence involves a limited amount of
2214 scanning backwards through the disassembly, and so, when considering
2215 compressed instructions, we can never be certain that we have
2216 disassembled the preceding instructions correctly. On top of that, we
2217 can't be certain that the inferior arrived at PC by passing through the
2218 preceding instructions.
2219
2220 With all that said, we know that using prologue scanning to figure a
2221 functions unwind information starts to fail when we consider returns
2222 from an instruction -- we must pass through some instructions that
2223 restore the previous state prior to the final return instruction, and
2224 with state partially restored, our prologue derived unwind information
2225 is no longer valid.
2226
2227 This function then, aims to spot instruction sequences like this:
2228
2229 ld fp, IMM_1(sp)
2230 add sp, sp, IMM_2
2231 ret
2232
2233 The first instruction restores the previous frame-pointer value, the
2234 second restores the previous stack pointer value, and the final
2235 instruction is the actual return.
2236
2237 We need to consider that some or all of these instructions might be
2238 compressed.
2239
2240 This function makes the assumption that, when the inferior reaches the
2241 'ret' instruction the stack pointer will have been restored to its value
2242 on entry to this function. This assumption will be true in most well
2243 formed programs.
2244
2245 Return true if we detect that we are in such an instruction sequence,
2246 that is PC points at one of the three instructions given above. In this
2247 case, set *OFFSET to IMM_2 if PC points to either of the first
2248 two instructions (the 'ld' or 'add'), otherwise set *OFFSET to 0.
2249
2250 Otherwise, this function returns false, and the contents of *OFFSET are
2251 undefined. */
2252
2253static bool
2254riscv_detect_end_of_function (struct gdbarch *gdbarch, CORE_ADDR pc,
2255 int *offset)
2256{
2257 *offset = 0;
2258
2259 /* We only want to scan a maximum of 3 instructions. */
2260 for (int i = 0; i < 3; ++i)
2261 {
2262 struct riscv_insn insn;
2263 insn.decode (gdbarch, pc);
2264 gdb_assert (insn.length () > 0);
2265
2266 if (is_insn_load_of_fp_from_sp (insn))
2267 {
2268 riscv_unwinder_debug_printf ("found 'ld' instruction at %s",
2269 core_addr_to_string (pc));
2270 if (i > 0)
2271 return false;
2272 pc += insn.length ();
2273 }
2274 else if (is_insn_addi_of_sp_to_sp (insn))
2275 {
2276 riscv_unwinder_debug_printf ("found 'add' instruction at %s",
2277 core_addr_to_string (pc));
2278 if (i > 1)
2279 return false;
2280 if (i == 0)
2281 {
2282 if (!previous_insn_is_load_fp_from_stack (gdbarch, pc))
2283 return false;
2284
2285 i = 1;
2286 }
2287 *offset = insn.imm_signed ();
2288 pc += insn.length ();
2289 }
2290 else if (insn.opcode () == riscv_insn::JALR
2291 && insn.rs1 () == RISCV_RA_REGNUM
2292 && insn.rs2 () == RISCV_ZERO_REGNUM)
2293 {
2294 riscv_unwinder_debug_printf ("found 'ret' instruction at %s",
2295 core_addr_to_string (pc));
2296 gdb_assert (i != 1);
2297 if (i == 0)
2298 {
2299 CORE_ADDR prev_pc;
2300 if (!previous_insn_is_add_imm_to_sp (gdbarch, pc, &prev_pc))
2301 return false;
2302 if (!previous_insn_is_load_fp_from_stack (gdbarch, prev_pc))
2303 return false;
2304 i = 2;
2305 }
2306
2307 pc += insn.length ();
2308 }
2309 else
2310 return false;
2311 }
2312
2313 return true;
2314}
2315
dbbb1059
AB
2316/* The prologue scanner. This is currently only used for skipping the
2317 prologue of a function when the DWARF information is not sufficient.
2318 However, it is written with filling of the frame cache in mind, which
2319 is why different groups of stack setup instructions are split apart
2320 during the core of the inner loop. In the future, the intention is to
2321 extend this function to fully support building up a frame cache that
2322 can unwind register values when there is no DWARF information. */
2323
2324static CORE_ADDR
2325riscv_scan_prologue (struct gdbarch *gdbarch,
78a3b0fa
AB
2326 CORE_ADDR start_pc, CORE_ADDR end_pc,
2327 struct riscv_unwind_cache *cache)
dbbb1059 2328{
78a3b0fa 2329 CORE_ADDR cur_pc, next_pc, after_prologue_pc;
29caf118 2330 CORE_ADDR original_end_pc = end_pc;
dbbb1059
AB
2331 CORE_ADDR end_prologue_addr = 0;
2332
78a3b0fa
AB
2333 /* Find an upper limit on the function prologue using the debug
2334 information. If the debug information could not be used to provide
2335 that bound, then use an arbitrary large number as the upper bound. */
2336 after_prologue_pc = skip_prologue_using_sal (gdbarch, start_pc);
2337 if (after_prologue_pc == 0)
2338 after_prologue_pc = start_pc + 100; /* Arbitrary large number. */
2339 if (after_prologue_pc < end_pc)
2340 end_pc = after_prologue_pc;
2341
2342 pv_t regs[RISCV_NUM_INTEGER_REGS]; /* Number of GPR. */
2343 for (int regno = 0; regno < RISCV_NUM_INTEGER_REGS; regno++)
2344 regs[regno] = pv_register (regno, 0);
2345 pv_area stack (RISCV_SP_REGNUM, gdbarch_addr_bit (gdbarch));
2346
4f6e0c44
AB
2347 riscv_unwinder_debug_printf ("function starting at %s (limit %s)",
2348 core_addr_to_string (start_pc),
2349 core_addr_to_string (end_pc));
78a3b0fa
AB
2350
2351 for (next_pc = cur_pc = start_pc; cur_pc < end_pc; cur_pc = next_pc)
dbbb1059
AB
2352 {
2353 struct riscv_insn insn;
2354
2355 /* Decode the current instruction, and decide where the next
2356 instruction lives based on the size of this instruction. */
2357 insn.decode (gdbarch, cur_pc);
2358 gdb_assert (insn.length () > 0);
2359 next_pc = cur_pc + insn.length ();
2360
2361 /* Look for common stack adjustment insns. */
29caf118 2362 if (is_insn_addi_of_sp_to_sp (insn))
dbbb1059
AB
2363 {
2364 /* Handle: addi sp, sp, -i
2365 or: addiw sp, sp, -i */
dda83cd7
SM
2366 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2367 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2368 regs[insn.rd ()]
2369 = pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ());
dbbb1059
AB
2370 }
2371 else if ((insn.opcode () == riscv_insn::SW
2372 || insn.opcode () == riscv_insn::SD)
2373 && (insn.rs1 () == RISCV_SP_REGNUM
2374 || insn.rs1 () == RISCV_FP_REGNUM))
2375 {
2376 /* Handle: sw reg, offset(sp)
2377 or: sd reg, offset(sp)
2378 or: sw reg, offset(s0)
2379 or: sd reg, offset(s0) */
2380 /* Instruction storing a register onto the stack. */
dda83cd7
SM
2381 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2382 gdb_assert (insn.rs2 () < RISCV_NUM_INTEGER_REGS);
2383 stack.store (pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ()),
2384 (insn.opcode () == riscv_insn::SW ? 4 : 8),
2385 regs[insn.rs2 ()]);
dbbb1059
AB
2386 }
2387 else if (insn.opcode () == riscv_insn::ADDI
2388 && insn.rd () == RISCV_FP_REGNUM
2389 && insn.rs1 () == RISCV_SP_REGNUM)
2390 {
2391 /* Handle: addi s0, sp, size */
2392 /* Instructions setting up the frame pointer. */
dda83cd7
SM
2393 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2394 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2395 regs[insn.rd ()]
2396 = pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ());
dbbb1059
AB
2397 }
2398 else if ((insn.opcode () == riscv_insn::ADD
2399 || insn.opcode () == riscv_insn::ADDW)
2400 && insn.rd () == RISCV_FP_REGNUM
2401 && insn.rs1 () == RISCV_SP_REGNUM
2402 && insn.rs2 () == RISCV_ZERO_REGNUM)
2403 {
2404 /* Handle: add s0, sp, 0
2405 or: addw s0, sp, 0 */
2406 /* Instructions setting up the frame pointer. */
dda83cd7
SM
2407 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2408 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2409 regs[insn.rd ()] = pv_add_constant (regs[insn.rs1 ()], 0);
dbbb1059 2410 }
d354055e 2411 else if ((insn.opcode () == riscv_insn::ADDI
dda83cd7
SM
2412 && insn.rd () == RISCV_ZERO_REGNUM
2413 && insn.rs1 () == RISCV_ZERO_REGNUM
2414 && insn.imm_signed () == 0))
dbbb1059 2415 {
d354055e 2416 /* Handle: add x0, x0, 0 (NOP) */
dbbb1059 2417 }
d354055e 2418 else if (insn.opcode () == riscv_insn::AUIPC)
dda83cd7
SM
2419 {
2420 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2421 regs[insn.rd ()] = pv_constant (cur_pc + insn.imm_signed ());
2422 }
6abf2eef
AB
2423 else if (insn.opcode () == riscv_insn::LUI
2424 || insn.opcode () == riscv_insn::LI)
dda83cd7 2425 {
d354055e 2426 /* Handle: lui REG, n
6abf2eef 2427 or: li REG, n */
dda83cd7
SM
2428 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2429 regs[insn.rd ()] = pv_constant (insn.imm_signed ());
2430 }
d354055e 2431 else if (insn.opcode () == riscv_insn::ADDI)
dda83cd7
SM
2432 {
2433 /* Handle: addi REG1, REG2, IMM */
2434 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2435 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2436 regs[insn.rd ()]
2437 = pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ());
2438 }
d354055e 2439 else if (insn.opcode () == riscv_insn::ADD)
dda83cd7 2440 {
0a9bddab 2441 /* Handle: add REG1, REG2, REG3 */
dda83cd7
SM
2442 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2443 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2444 gdb_assert (insn.rs2 () < RISCV_NUM_INTEGER_REGS);
2445 regs[insn.rd ()] = pv_add (regs[insn.rs1 ()], regs[insn.rs2 ()]);
2446 }
a35606d9
LS
2447 else if (insn.opcode () == riscv_insn::LD
2448 || insn.opcode () == riscv_insn::LW)
2449 {
2450 /* Handle: ld reg, offset(rs1)
2451 or: c.ld reg, offset(rs1)
2452 or: lw reg, offset(rs1)
2453 or: c.lw reg, offset(rs1) */
2454 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2455 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2456 regs[insn.rd ()]
2457 = stack.fetch (pv_add_constant (regs[insn.rs1 ()],
2458 insn.imm_signed ()),
2459 (insn.opcode () == riscv_insn::LW ? 4 : 8));
2460 }
2b014cc5
LS
2461 else if (insn.opcode () == riscv_insn::MV)
2462 {
2463 /* Handle: c.mv RD, RS2 */
2464 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2465 gdb_assert (insn.rs2 () < RISCV_NUM_INTEGER_REGS);
2466 gdb_assert (insn.rs2 () > 0);
2467 regs[insn.rd ()] = regs[insn.rs2 ()];
2468 }
dbbb1059
AB
2469 else
2470 {
78a3b0fa
AB
2471 end_prologue_addr = cur_pc;
2472 break;
dbbb1059
AB
2473 }
2474 }
2475
2476 if (end_prologue_addr == 0)
2477 end_prologue_addr = cur_pc;
2478
4f6e0c44
AB
2479 riscv_unwinder_debug_printf ("end of prologue at %s",
2480 core_addr_to_string (end_prologue_addr));
78a3b0fa
AB
2481
2482 if (cache != NULL)
2483 {
2484 /* Figure out if it is a frame pointer or just a stack pointer. Also
dda83cd7
SM
2485 the offset held in the pv_t is from the original register value to
2486 the current value, which for a grows down stack means a negative
2487 value. The FRAME_BASE_OFFSET is the negation of this, how to get
2488 from the current value to the original value. */
78a3b0fa
AB
2489 if (pv_is_register (regs[RISCV_FP_REGNUM], RISCV_SP_REGNUM))
2490 {
dda83cd7
SM
2491 cache->frame_base_reg = RISCV_FP_REGNUM;
2492 cache->frame_base_offset = -regs[RISCV_FP_REGNUM].k;
78a3b0fa
AB
2493 }
2494 else
2495 {
dda83cd7
SM
2496 cache->frame_base_reg = RISCV_SP_REGNUM;
2497 cache->frame_base_offset = -regs[RISCV_SP_REGNUM].k;
78a3b0fa
AB
2498 }
2499
29caf118
AB
2500 /* Check to see if we are located near to a return instruction in
2501 this function. If we are then the one or both of the stack
2502 pointer and frame pointer may have been restored to their previous
2503 value. If we can spot this situation then we can adjust which
2504 register and offset we use for the frame base. */
2505 if (cache->frame_base_reg != RISCV_SP_REGNUM
2506 || cache->frame_base_offset != 0)
2507 {
2508 int sp_offset;
2509
2510 if (riscv_detect_end_of_function (gdbarch, original_end_pc,
2511 &sp_offset))
2512 {
2513 riscv_unwinder_debug_printf
2514 ("in function epilogue at %s, stack offset is %d",
2515 core_addr_to_string (original_end_pc), sp_offset);
2516 cache->frame_base_reg= RISCV_SP_REGNUM;
2517 cache->frame_base_offset = sp_offset;
2518 }
2519 }
2520
78a3b0fa 2521 /* Assign offset from old SP to all saved registers. As we don't
dda83cd7
SM
2522 have the previous value for the frame base register at this
2523 point, we store the offset as the address in the trad_frame, and
2524 then convert this to an actual address later. */
78a3b0fa
AB
2525 for (int i = 0; i <= RISCV_NUM_INTEGER_REGS; i++)
2526 {
2527 CORE_ADDR offset;
2528 if (stack.find_reg (gdbarch, i, &offset))
dda83cd7 2529 {
4f6e0c44
AB
2530 /* Display OFFSET as a signed value, the offsets are from the
2531 frame base address to the registers location on the stack,
2532 with a descending stack this means the offsets are always
2533 negative. */
2534 riscv_unwinder_debug_printf ("register $%s at stack offset %s",
2535 gdbarch_register_name (gdbarch, i),
2536 plongest ((LONGEST) offset));
a9a87d35 2537 cache->regs[i].set_addr (offset);
dda83cd7 2538 }
78a3b0fa
AB
2539 }
2540 }
2541
dbbb1059
AB
2542 return end_prologue_addr;
2543}
2544
2545/* Implement the riscv_skip_prologue gdbarch method. */
2546
2547static CORE_ADDR
78a3b0fa 2548riscv_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR pc)
dbbb1059 2549{
dbbb1059
AB
2550 CORE_ADDR func_addr;
2551
2552 /* See if we can determine the end of the prologue via the symbol
2553 table. If so, then return either PC, or the PC after the
2554 prologue, whichever is greater. */
2555 if (find_pc_partial_function (pc, NULL, &func_addr, NULL))
2556 {
2557 CORE_ADDR post_prologue_pc
2558 = skip_prologue_using_sal (gdbarch, func_addr);
2559
2560 if (post_prologue_pc != 0)
2561 return std::max (pc, post_prologue_pc);
2562 }
2563
2564 /* Can't determine prologue from the symbol table, need to examine
78a3b0fa
AB
2565 instructions. Pass -1 for the end address to indicate the prologue
2566 scanner can scan as far as it needs to find the end of the prologue. */
2567 return riscv_scan_prologue (gdbarch, pc, ((CORE_ADDR) -1), NULL);
dbbb1059
AB
2568}
2569
2570/* Implement the gdbarch push dummy code callback. */
2571
2572static CORE_ADDR
2573riscv_push_dummy_code (struct gdbarch *gdbarch, CORE_ADDR sp,
2574 CORE_ADDR funaddr, struct value **args, int nargs,
2575 struct type *value_type, CORE_ADDR *real_pc,
2576 CORE_ADDR *bp_addr, struct regcache *regcache)
2577{
01e175fe
AB
2578 /* A nop instruction is 'add x0, x0, 0'. */
2579 static const gdb_byte nop_insn[] = { 0x13, 0x00, 0x00, 0x00 };
2580
dbbb1059 2581 /* Allocate space for a breakpoint, and keep the stack correctly
01e175fe
AB
2582 aligned. The space allocated here must be at least big enough to
2583 accommodate the NOP_INSN defined above. */
dbbb1059
AB
2584 sp -= 16;
2585 *bp_addr = sp;
2586 *real_pc = funaddr;
01e175fe
AB
2587
2588 /* When we insert a breakpoint we select whether to use a compressed
2589 breakpoint or not based on the existing contents of the memory.
2590
2591 If the breakpoint is being placed onto the stack as part of setting up
2592 for an inferior call from GDB, then the existing stack contents may
2593 randomly appear to be a compressed instruction, causing GDB to insert
2594 a compressed breakpoint. If this happens on a target that does not
2595 support compressed instructions then this could cause problems.
2596
2597 To prevent this issue we write an uncompressed nop onto the stack at
2598 the location where the breakpoint will be inserted. In this way we
2599 ensure that we always use an uncompressed breakpoint, which should
2600 work on all targets.
2601
2602 We call TARGET_WRITE_MEMORY here so that if the write fails we don't
2603 throw an exception. Instead we ignore the error and move on. The
2604 assumption is that either GDB will error later when actually trying to
2605 insert a software breakpoint, or GDB will use hardware breakpoints and
2606 there will be no need to write to memory later. */
2607 int status = target_write_memory (*bp_addr, nop_insn, sizeof (nop_insn));
2608
4f6e0c44
AB
2609 riscv_infcall_debug_printf ("writing %s-byte nop instruction to %s: %s",
2610 plongest (sizeof (nop_insn)),
2611 paddress (gdbarch, *bp_addr),
2612 (status == 0 ? "success" : "failed"));
01e175fe 2613
dbbb1059
AB
2614 return sp;
2615}
2616
a9158a86
AB
2617/* Implement the gdbarch type alignment method, overrides the generic
2618 alignment algorithm for anything that is RISC-V specific. */
dbbb1059 2619
a9158a86
AB
2620static ULONGEST
2621riscv_type_align (gdbarch *gdbarch, type *type)
dbbb1059 2622{
a9158a86 2623 type = check_typedef (type);
bd63c870 2624 if (type->code () == TYPE_CODE_ARRAY && type->is_vector ())
df86565b 2625 return std::min (type->length (), (ULONGEST) BIGGEST_ALIGNMENT);
dbbb1059 2626
a9158a86
AB
2627 /* Anything else will be aligned by the generic code. */
2628 return 0;
dbbb1059
AB
2629}
2630
2631/* Holds information about a single argument either being passed to an
2632 inferior function, or returned from an inferior function. This includes
2633 information about the size, type, etc of the argument, and also
2634 information about how the argument will be passed (or returned). */
2635
2636struct riscv_arg_info
2637{
2638 /* Contents of the argument. */
2639 const gdb_byte *contents;
2640
2641 /* Length of argument. */
2642 int length;
2643
2644 /* Alignment required for an argument of this type. */
2645 int align;
2646
2647 /* The type for this argument. */
2648 struct type *type;
2649
2650 /* Each argument can have either 1 or 2 locations assigned to it. Each
2651 location describes where part of the argument will be placed. The
2652 second location is valid based on the LOC_TYPE and C_LENGTH fields
2653 of the first location (which is always valid). */
2654 struct location
2655 {
2656 /* What type of location this is. */
2657 enum location_type
2658 {
2659 /* Argument passed in a register. */
2660 in_reg,
2661
2662 /* Argument passed as an on stack argument. */
2663 on_stack,
2664
2665 /* Argument passed by reference. The second location is always
2666 valid for a BY_REF argument, and describes where the address
2667 of the BY_REF argument should be placed. */
2668 by_ref
2669 } loc_type;
2670
2671 /* Information that depends on the location type. */
2672 union
2673 {
2674 /* Which register number to use. */
2675 int regno;
2676
2677 /* The offset into the stack region. */
2678 int offset;
2679 } loc_data;
2680
2681 /* The length of contents covered by this location. If this is less
2682 than the total length of the argument, then the second location
2683 will be valid, and will describe where the rest of the argument
2684 will go. */
2685 int c_length;
2686
dd895392
AB
2687 /* The offset within CONTENTS for this part of the argument. This can
2688 be non-zero even for the first part (the first field of a struct can
2689 have a non-zero offset due to padding). For the second part of the
dbbb1059
AB
2690 argument, this might be the C_LENGTH value of the first part,
2691 however, if we are passing a structure in two registers, and there's
2692 is padding between the first and second field, then this offset
2693 might be greater than the length of the first argument part. When
2694 the second argument location is not holding part of the argument
2695 value, but is instead holding the address of a reference argument,
2696 then this offset will be set to 0. */
2697 int c_offset;
2698 } argloc[2];
8b2d40cb
JW
2699
2700 /* TRUE if this is an unnamed argument. */
2701 bool is_unnamed;
dbbb1059
AB
2702};
2703
2704/* Information about a set of registers being used for passing arguments as
2705 part of a function call. The register set must be numerically
2706 sequential from NEXT_REGNUM to LAST_REGNUM. The register set can be
2707 disabled from use by setting NEXT_REGNUM greater than LAST_REGNUM. */
2708
2709struct riscv_arg_reg
2710{
2711 riscv_arg_reg (int first, int last)
2712 : next_regnum (first),
2713 last_regnum (last)
2714 {
2715 /* Nothing. */
2716 }
2717
2718 /* The GDB register number to use in this set. */
2719 int next_regnum;
2720
2721 /* The last GDB register number to use in this set. */
2722 int last_regnum;
2723};
2724
2725/* Arguments can be passed as on stack arguments, or by reference. The
2726 on stack arguments must be in a continuous region starting from $sp,
2727 while the by reference arguments can be anywhere, but we'll put them
2728 on the stack after (at higher address) the on stack arguments.
2729
2730 This might not be the right approach to take. The ABI is clear that
2731 an argument passed by reference can be modified by the callee, which
2732 us placing the argument (temporarily) onto the stack will not achieve
2733 (changes will be lost). There's also the possibility that very large
2734 arguments could overflow the stack.
2735
2736 This struct is used to track offset into these two areas for where
2737 arguments are to be placed. */
2738struct riscv_memory_offsets
2739{
2740 riscv_memory_offsets ()
2741 : arg_offset (0),
2742 ref_offset (0)
2743 {
2744 /* Nothing. */
2745 }
2746
2747 /* Offset into on stack argument area. */
2748 int arg_offset;
2749
2750 /* Offset into the pass by reference area. */
2751 int ref_offset;
2752};
2753
2754/* Holds information about where arguments to a call will be placed. This
2755 is updated as arguments are added onto the call, and can be used to
2756 figure out where the next argument should be placed. */
2757
2758struct riscv_call_info
2759{
2760 riscv_call_info (struct gdbarch *gdbarch)
2761 : int_regs (RISCV_A0_REGNUM, RISCV_A0_REGNUM + 7),
2762 float_regs (RISCV_FA0_REGNUM, RISCV_FA0_REGNUM + 7)
2763 {
113b7b81
AB
2764 xlen = riscv_abi_xlen (gdbarch);
2765 flen = riscv_abi_flen (gdbarch);
dbbb1059 2766
25428040
AB
2767 /* Reduce the number of integer argument registers when using the
2768 embedded abi (i.e. rv32e). */
2769 if (riscv_abi_embedded (gdbarch))
2770 int_regs.last_regnum = RISCV_A0_REGNUM + 5;
2771
dbbb1059
AB
2772 /* Disable use of floating point registers if needed. */
2773 if (!riscv_has_fp_abi (gdbarch))
2774 float_regs.next_regnum = float_regs.last_regnum + 1;
2775 }
2776
2777 /* Track the memory areas used for holding in-memory arguments to a
2778 call. */
2779 struct riscv_memory_offsets memory;
2780
2781 /* Holds information about the next integer register to use for passing
2782 an argument. */
2783 struct riscv_arg_reg int_regs;
2784
2785 /* Holds information about the next floating point register to use for
2786 passing an argument. */
2787 struct riscv_arg_reg float_regs;
2788
2789 /* The XLEN and FLEN are copied in to this structure for convenience, and
113b7b81 2790 are just the results of calling RISCV_ABI_XLEN and RISCV_ABI_FLEN. */
dbbb1059
AB
2791 int xlen;
2792 int flen;
2793};
2794
2795/* Return the number of registers available for use as parameters in the
2796 register set REG. Returned value can be 0 or more. */
2797
2798static int
2799riscv_arg_regs_available (struct riscv_arg_reg *reg)
2800{
2801 if (reg->next_regnum > reg->last_regnum)
2802 return 0;
2803
2804 return (reg->last_regnum - reg->next_regnum + 1);
2805}
2806
2807/* If there is at least one register available in the register set REG then
2808 the next register from REG is assigned to LOC and the length field of
2809 LOC is updated to LENGTH. The register set REG is updated to indicate
2810 that the assigned register is no longer available and the function
2811 returns true.
2812
2813 If there are no registers available in REG then the function returns
2814 false, and LOC and REG are unchanged. */
2815
2816static bool
2817riscv_assign_reg_location (struct riscv_arg_info::location *loc,
2818 struct riscv_arg_reg *reg,
2819 int length, int offset)
2820{
2821 if (reg->next_regnum <= reg->last_regnum)
2822 {
2823 loc->loc_type = riscv_arg_info::location::in_reg;
2824 loc->loc_data.regno = reg->next_regnum;
2825 reg->next_regnum++;
2826 loc->c_length = length;
2827 loc->c_offset = offset;
2828 return true;
2829 }
2830
2831 return false;
2832}
2833
2834/* Assign LOC a location as the next stack parameter, and update MEMORY to
2835 record that an area of stack has been used to hold the parameter
2836 described by LOC.
2837
2838 The length field of LOC is updated to LENGTH, the length of the
2839 parameter being stored, and ALIGN is the alignment required by the
2840 parameter, which will affect how memory is allocated out of MEMORY. */
2841
2842static void
2843riscv_assign_stack_location (struct riscv_arg_info::location *loc,
2844 struct riscv_memory_offsets *memory,
2845 int length, int align)
2846{
2847 loc->loc_type = riscv_arg_info::location::on_stack;
2848 memory->arg_offset
2849 = align_up (memory->arg_offset, align);
2850 loc->loc_data.offset = memory->arg_offset;
2851 memory->arg_offset += length;
2852 loc->c_length = length;
2853
2854 /* Offset is always 0, either we're the first location part, in which
2855 case we're reading content from the start of the argument, or we're
2856 passing the address of a reference argument, so 0. */
2857 loc->c_offset = 0;
2858}
2859
2860/* Update AINFO, which describes an argument that should be passed or
2861 returned using the integer ABI. The argloc fields within AINFO are
2862 updated to describe the location in which the argument will be passed to
2863 a function, or returned from a function.
2864
2865 The CINFO structure contains the ongoing call information, the holds
2866 information such as which argument registers are remaining to be
2867 assigned to parameter, and how much memory has been used by parameters
2868 so far.
2869
2870 By examining the state of CINFO a suitable location can be selected,
2871 and assigned to AINFO. */
2872
2873static void
2874riscv_call_arg_scalar_int (struct riscv_arg_info *ainfo,
2875 struct riscv_call_info *cinfo)
2876{
84067a55
TV
2877 auto lang_req = language_pass_by_reference (ainfo->type);
2878
911627e7 2879 if (TYPE_HAS_DYNAMIC_LENGTH (ainfo->type)
84067a55
TV
2880 || ainfo->length > (2 * cinfo->xlen)
2881 || !lang_req.trivially_copy_constructible
2882 || !lang_req.trivially_destructible)
dbbb1059
AB
2883 {
2884 /* Argument is going to be passed by reference. */
2885 ainfo->argloc[0].loc_type
2886 = riscv_arg_info::location::by_ref;
2887 cinfo->memory.ref_offset
2888 = align_up (cinfo->memory.ref_offset, ainfo->align);
2889 ainfo->argloc[0].loc_data.offset = cinfo->memory.ref_offset;
2890 cinfo->memory.ref_offset += ainfo->length;
2891 ainfo->argloc[0].c_length = ainfo->length;
2892
2893 /* The second location for this argument is given over to holding the
2894 address of the by-reference data. Pass 0 for the offset as this
2895 is not part of the actual argument value. */
2896 if (!riscv_assign_reg_location (&ainfo->argloc[1],
2897 &cinfo->int_regs,
2898 cinfo->xlen, 0))
2899 riscv_assign_stack_location (&ainfo->argloc[1],
2900 &cinfo->memory, cinfo->xlen,
2901 cinfo->xlen);
2902 }
2903 else
2904 {
174f8ac8
JW
2905 int len = std::min (ainfo->length, cinfo->xlen);
2906 int align = std::max (ainfo->align, cinfo->xlen);
dbbb1059 2907
8b2d40cb
JW
2908 /* Unnamed arguments in registers that require 2*XLEN alignment are
2909 passed in an aligned register pair. */
2910 if (ainfo->is_unnamed && (align == cinfo->xlen * 2)
2911 && cinfo->int_regs.next_regnum & 1)
2912 cinfo->int_regs.next_regnum++;
2913
dbbb1059
AB
2914 if (!riscv_assign_reg_location (&ainfo->argloc[0],
2915 &cinfo->int_regs, len, 0))
2916 riscv_assign_stack_location (&ainfo->argloc[0],
174f8ac8 2917 &cinfo->memory, len, align);
dbbb1059
AB
2918
2919 if (len < ainfo->length)
2920 {
2921 len = ainfo->length - len;
2922 if (!riscv_assign_reg_location (&ainfo->argloc[1],
2923 &cinfo->int_regs, len,
2924 cinfo->xlen))
2925 riscv_assign_stack_location (&ainfo->argloc[1],
2926 &cinfo->memory, len, cinfo->xlen);
2927 }
2928 }
2929}
2930
2931/* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
2932 is being passed with the floating point ABI. */
2933
2934static void
2935riscv_call_arg_scalar_float (struct riscv_arg_info *ainfo,
2936 struct riscv_call_info *cinfo)
2937{
4de3d8d0 2938 if (ainfo->length > cinfo->flen || ainfo->is_unnamed)
dbbb1059
AB
2939 return riscv_call_arg_scalar_int (ainfo, cinfo);
2940 else
2941 {
2942 if (!riscv_assign_reg_location (&ainfo->argloc[0],
2943 &cinfo->float_regs,
2944 ainfo->length, 0))
2945 return riscv_call_arg_scalar_int (ainfo, cinfo);
2946 }
2947}
2948
2949/* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
2950 is a complex floating point argument, and is therefore handled
2951 differently to other argument types. */
2952
2953static void
2954riscv_call_arg_complex_float (struct riscv_arg_info *ainfo,
2955 struct riscv_call_info *cinfo)
2956{
2957 if (ainfo->length <= (2 * cinfo->flen)
4de3d8d0
AB
2958 && riscv_arg_regs_available (&cinfo->float_regs) >= 2
2959 && !ainfo->is_unnamed)
dbbb1059
AB
2960 {
2961 bool result;
2962 int len = ainfo->length / 2;
2963
2964 result = riscv_assign_reg_location (&ainfo->argloc[0],
9f0272f8 2965 &cinfo->float_regs, len, 0);
dbbb1059
AB
2966 gdb_assert (result);
2967
2968 result = riscv_assign_reg_location (&ainfo->argloc[1],
2969 &cinfo->float_regs, len, len);
2970 gdb_assert (result);
2971 }
2972 else
2973 return riscv_call_arg_scalar_int (ainfo, cinfo);
2974}
2975
2976/* A structure used for holding information about a structure type within
2977 the inferior program. The RiscV ABI has special rules for handling some
2978 structures with a single field or with two fields. The counting of
2979 fields here is done after flattening out all nested structures. */
2980
2981class riscv_struct_info
2982{
2983public:
2984 riscv_struct_info ()
2985 : m_number_of_fields (0),
9f0272f8
AB
2986 m_types { nullptr, nullptr },
2987 m_offsets { 0, 0 }
dbbb1059
AB
2988 {
2989 /* Nothing. */
2990 }
2991
2992 /* Analyse TYPE descending into nested structures, count the number of
2993 scalar fields and record the types of the first two fields found. */
9f0272f8
AB
2994 void analyse (struct type *type)
2995 {
2996 analyse_inner (type, 0);
2997 }
dbbb1059
AB
2998
2999 /* The number of scalar fields found in the analysed type. This is
3000 currently only accurate if the value returned is 0, 1, or 2 as the
3001 analysis stops counting when the number of fields is 3. This is
3002 because the RiscV ABI only has special cases for 1 or 2 fields,
3003 anything else we just don't care about. */
3004 int number_of_fields () const
3005 { return m_number_of_fields; }
3006
3007 /* Return the type for scalar field INDEX within the analysed type. Will
3008 return nullptr if there is no field at that index. Only INDEX values
3009 0 and 1 can be requested as the RiscV ABI only has special cases for
3010 structures with 1 or 2 fields. */
3011 struct type *field_type (int index) const
3012 {
3013 gdb_assert (index < (sizeof (m_types) / sizeof (m_types[0])));
3014 return m_types[index];
3015 }
3016
9f0272f8
AB
3017 /* Return the offset of scalar field INDEX within the analysed type. Will
3018 return 0 if there is no field at that index. Only INDEX values 0 and
3019 1 can be requested as the RiscV ABI only has special cases for
3020 structures with 1 or 2 fields. */
3021 int field_offset (int index) const
3022 {
3023 gdb_assert (index < (sizeof (m_offsets) / sizeof (m_offsets[0])));
3024 return m_offsets[index];
3025 }
3026
dbbb1059
AB
3027private:
3028 /* The number of scalar fields found within the structure after recursing
3029 into nested structures. */
3030 int m_number_of_fields;
3031
3032 /* The types of the first two scalar fields found within the structure
3033 after recursing into nested structures. */
3034 struct type *m_types[2];
9f0272f8
AB
3035
3036 /* The offsets of the first two scalar fields found within the structure
3037 after recursing into nested structures. */
3038 int m_offsets[2];
3039
3040 /* Recursive core for ANALYSE, the OFFSET parameter tracks the byte
3041 offset from the start of the top level structure being analysed. */
3042 void analyse_inner (struct type *type, int offset);
dbbb1059
AB
3043};
3044
9f0272f8 3045/* See description in class declaration. */
dbbb1059
AB
3046
3047void
9f0272f8 3048riscv_struct_info::analyse_inner (struct type *type, int offset)
dbbb1059 3049{
1f704f76 3050 unsigned int count = type->num_fields ();
dbbb1059
AB
3051 unsigned int i;
3052
3053 for (i = 0; i < count; ++i)
3054 {
2ad53ea1 3055 if (type->field (i).loc_kind () != FIELD_LOC_KIND_BITPOS)
dbbb1059
AB
3056 continue;
3057
940da03e 3058 struct type *field_type = type->field (i).type ();
dbbb1059 3059 field_type = check_typedef (field_type);
9f0272f8 3060 int field_offset
b610c045 3061 = offset + type->field (i).loc_bitpos () / TARGET_CHAR_BIT;
dbbb1059 3062
78134374 3063 switch (field_type->code ())
dbbb1059
AB
3064 {
3065 case TYPE_CODE_STRUCT:
9f0272f8 3066 analyse_inner (field_type, field_offset);
dbbb1059
AB
3067 break;
3068
3069 default:
3070 /* RiscV only flattens out structures. Anything else does not
3071 need to be flattened, we just record the type, and when we
3072 look at the analysis results we'll realise this is not a
3073 structure we can special case, and pass the structure in
3074 memory. */
3075 if (m_number_of_fields < 2)
9f0272f8
AB
3076 {
3077 m_types[m_number_of_fields] = field_type;
3078 m_offsets[m_number_of_fields] = field_offset;
3079 }
dbbb1059
AB
3080 m_number_of_fields++;
3081 break;
3082 }
3083
3084 /* RiscV only has special handling for structures with 1 or 2 scalar
3085 fields, any more than that and the structure is just passed in
3086 memory. We can safely drop out early when we find 3 or more
3087 fields then. */
3088
3089 if (m_number_of_fields > 2)
3090 return;
3091 }
3092}
3093
3094/* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
3095 is a structure. Small structures on RiscV have some special case
3096 handling in order that the structure might be passed in register.
3097 Larger structures are passed in memory. After assigning location
3098 information to AINFO, CINFO will have been updated. */
3099
3100static void
3101riscv_call_arg_struct (struct riscv_arg_info *ainfo,
3102 struct riscv_call_info *cinfo)
3103{
3104 if (riscv_arg_regs_available (&cinfo->float_regs) >= 1)
3105 {
3106 struct riscv_struct_info sinfo;
3107
3108 sinfo.analyse (ainfo->type);
3109 if (sinfo.number_of_fields () == 1
78134374 3110 && sinfo.field_type(0)->code () == TYPE_CODE_COMPLEX)
dbbb1059 3111 {
9f0272f8
AB
3112 /* The following is similar to RISCV_CALL_ARG_COMPLEX_FLOAT,
3113 except we use the type of the complex field instead of the
3114 type from AINFO, and the first location might be at a non-zero
3115 offset. */
df86565b 3116 if (sinfo.field_type (0)->length () <= (2 * cinfo->flen)
9f0272f8
AB
3117 && riscv_arg_regs_available (&cinfo->float_regs) >= 2
3118 && !ainfo->is_unnamed)
3119 {
3120 bool result;
df86565b 3121 int len = sinfo.field_type (0)->length () / 2;
9f0272f8
AB
3122 int offset = sinfo.field_offset (0);
3123
3124 result = riscv_assign_reg_location (&ainfo->argloc[0],
3125 &cinfo->float_regs, len,
3126 offset);
3127 gdb_assert (result);
3128
3129 result = riscv_assign_reg_location (&ainfo->argloc[1],
3130 &cinfo->float_regs, len,
3131 (offset + len));
3132 gdb_assert (result);
3133 }
3134 else
3135 riscv_call_arg_scalar_int (ainfo, cinfo);
3136 return;
dbbb1059
AB
3137 }
3138
3139 if (sinfo.number_of_fields () == 1
78134374 3140 && sinfo.field_type(0)->code () == TYPE_CODE_FLT)
dbbb1059 3141 {
9f0272f8
AB
3142 /* The following is similar to RISCV_CALL_ARG_SCALAR_FLOAT,
3143 except we use the type of the first scalar field instead of
3144 the type from AINFO. Also the location might be at a non-zero
3145 offset. */
df86565b 3146 if (sinfo.field_type (0)->length () > cinfo->flen
9f0272f8
AB
3147 || ainfo->is_unnamed)
3148 riscv_call_arg_scalar_int (ainfo, cinfo);
3149 else
3150 {
3151 int offset = sinfo.field_offset (0);
df86565b 3152 int len = sinfo.field_type (0)->length ();
9f0272f8
AB
3153
3154 if (!riscv_assign_reg_location (&ainfo->argloc[0],
3155 &cinfo->float_regs,
3156 len, offset))
3157 riscv_call_arg_scalar_int (ainfo, cinfo);
3158 }
3159 return;
dbbb1059
AB
3160 }
3161
3162 if (sinfo.number_of_fields () == 2
78134374 3163 && sinfo.field_type(0)->code () == TYPE_CODE_FLT
df86565b 3164 && sinfo.field_type (0)->length () <= cinfo->flen
78134374 3165 && sinfo.field_type(1)->code () == TYPE_CODE_FLT
df86565b 3166 && sinfo.field_type (1)->length () <= cinfo->flen
dbbb1059
AB
3167 && riscv_arg_regs_available (&cinfo->float_regs) >= 2)
3168 {
df86565b 3169 int len0 = sinfo.field_type (0)->length ();
9f0272f8 3170 int offset = sinfo.field_offset (0);
dbbb1059 3171 if (!riscv_assign_reg_location (&ainfo->argloc[0],
9f0272f8 3172 &cinfo->float_regs, len0, offset))
dbbb1059
AB
3173 error (_("failed during argument setup"));
3174
df86565b 3175 int len1 = sinfo.field_type (1)->length ();
9f0272f8 3176 offset = sinfo.field_offset (1);
df86565b
SM
3177 gdb_assert (len1 <= (ainfo->type->length ()
3178 - sinfo.field_type (0)->length ()));
dbbb1059
AB
3179
3180 if (!riscv_assign_reg_location (&ainfo->argloc[1],
3181 &cinfo->float_regs,
3182 len1, offset))
3183 error (_("failed during argument setup"));
3184 return;
3185 }
3186
3187 if (sinfo.number_of_fields () == 2
3188 && riscv_arg_regs_available (&cinfo->int_regs) >= 1
78134374 3189 && (sinfo.field_type(0)->code () == TYPE_CODE_FLT
df86565b 3190 && sinfo.field_type (0)->length () <= cinfo->flen
dbbb1059 3191 && is_integral_type (sinfo.field_type (1))
df86565b 3192 && sinfo.field_type (1)->length () <= cinfo->xlen))
dbbb1059 3193 {
df86565b 3194 int len0 = sinfo.field_type (0)->length ();
9f0272f8 3195 int offset = sinfo.field_offset (0);
dbbb1059 3196 if (!riscv_assign_reg_location (&ainfo->argloc[0],
9f0272f8 3197 &cinfo->float_regs, len0, offset))
dbbb1059
AB
3198 error (_("failed during argument setup"));
3199
df86565b 3200 int len1 = sinfo.field_type (1)->length ();
9f0272f8 3201 offset = sinfo.field_offset (1);
dbbb1059
AB
3202 gdb_assert (len1 <= cinfo->xlen);
3203 if (!riscv_assign_reg_location (&ainfo->argloc[1],
3204 &cinfo->int_regs, len1, offset))
3205 error (_("failed during argument setup"));
3206 return;
3207 }
3208
3209 if (sinfo.number_of_fields () == 2
3210 && riscv_arg_regs_available (&cinfo->int_regs) >= 1
3211 && (is_integral_type (sinfo.field_type (0))
df86565b 3212 && sinfo.field_type (0)->length () <= cinfo->xlen
78134374 3213 && sinfo.field_type(1)->code () == TYPE_CODE_FLT
df86565b 3214 && sinfo.field_type (1)->length () <= cinfo->flen))
dbbb1059 3215 {
df86565b
SM
3216 int len0 = sinfo.field_type (0)->length ();
3217 int len1 = sinfo.field_type (1)->length ();
dbbb1059
AB
3218
3219 gdb_assert (len0 <= cinfo->xlen);
3220 gdb_assert (len1 <= cinfo->flen);
3221
9f0272f8 3222 int offset = sinfo.field_offset (0);
dbbb1059 3223 if (!riscv_assign_reg_location (&ainfo->argloc[0],
9f0272f8 3224 &cinfo->int_regs, len0, offset))
dbbb1059
AB
3225 error (_("failed during argument setup"));
3226
9f0272f8 3227 offset = sinfo.field_offset (1);
dbbb1059
AB
3228 if (!riscv_assign_reg_location (&ainfo->argloc[1],
3229 &cinfo->float_regs,
3230 len1, offset))
3231 error (_("failed during argument setup"));
3232
3233 return;
3234 }
3235 }
3236
3237 /* Non of the structure flattening cases apply, so we just pass using
3238 the integer ABI. */
dbbb1059
AB
3239 riscv_call_arg_scalar_int (ainfo, cinfo);
3240}
3241
3242/* Assign a location to call (or return) argument AINFO, the location is
3243 selected from CINFO which holds information about what call argument
3244 locations are available for use next. The TYPE is the type of the
3245 argument being passed, this information is recorded into AINFO (along
8b2d40cb
JW
3246 with some additional information derived from the type). IS_UNNAMED
3247 is true if this is an unnamed (stdarg) argument, this info is also
3248 recorded into AINFO.
dbbb1059
AB
3249
3250 After assigning a location to AINFO, CINFO will have been updated. */
3251
3252static void
3253riscv_arg_location (struct gdbarch *gdbarch,
3254 struct riscv_arg_info *ainfo,
3255 struct riscv_call_info *cinfo,
8b2d40cb 3256 struct type *type, bool is_unnamed)
dbbb1059
AB
3257{
3258 ainfo->type = type;
df86565b 3259 ainfo->length = ainfo->type->length ();
a9158a86 3260 ainfo->align = type_align (ainfo->type);
8b2d40cb 3261 ainfo->is_unnamed = is_unnamed;
dbbb1059 3262 ainfo->contents = nullptr;
9f0272f8
AB
3263 ainfo->argloc[0].c_length = 0;
3264 ainfo->argloc[1].c_length = 0;
dbbb1059 3265
78134374 3266 switch (ainfo->type->code ())
dbbb1059
AB
3267 {
3268 case TYPE_CODE_INT:
3269 case TYPE_CODE_BOOL:
3270 case TYPE_CODE_CHAR:
3271 case TYPE_CODE_RANGE:
3272 case TYPE_CODE_ENUM:
3273 case TYPE_CODE_PTR:
0abb4049 3274 case TYPE_CODE_FIXED_POINT:
dbbb1059
AB
3275 if (ainfo->length <= cinfo->xlen)
3276 {
3277 ainfo->type = builtin_type (gdbarch)->builtin_long;
3278 ainfo->length = cinfo->xlen;
3279 }
3280 else if (ainfo->length <= (2 * cinfo->xlen))
3281 {
3282 ainfo->type = builtin_type (gdbarch)->builtin_long_long;
3283 ainfo->length = 2 * cinfo->xlen;
3284 }
3285
3286 /* Recalculate the alignment requirement. */
a9158a86 3287 ainfo->align = type_align (ainfo->type);
dbbb1059
AB
3288 riscv_call_arg_scalar_int (ainfo, cinfo);
3289 break;
3290
3291 case TYPE_CODE_FLT:
3292 riscv_call_arg_scalar_float (ainfo, cinfo);
3293 break;
3294
3295 case TYPE_CODE_COMPLEX:
3296 riscv_call_arg_complex_float (ainfo, cinfo);
3297 break;
3298
3299 case TYPE_CODE_STRUCT:
911627e7
TT
3300 if (!TYPE_HAS_DYNAMIC_LENGTH (ainfo->type))
3301 {
3302 riscv_call_arg_struct (ainfo, cinfo);
3303 break;
3304 }
d182e398 3305 [[fallthrough]];
dbbb1059
AB
3306
3307 default:
3308 riscv_call_arg_scalar_int (ainfo, cinfo);
3309 break;
3310 }
3311}
3312
cab5bb9d
AB
3313/* Used for printing debug information about the call argument location in
3314 INFO to STREAM. The addresses in SP_REFS and SP_ARGS are the base
3315 addresses for the location of pass-by-reference and
3316 arguments-on-the-stack memory areas. */
3317
dbbb1059 3318static void
cab5bb9d 3319riscv_print_arg_location (ui_file *stream, struct gdbarch *gdbarch,
dbbb1059
AB
3320 struct riscv_arg_info *info,
3321 CORE_ADDR sp_refs, CORE_ADDR sp_args)
3322{
6cb06a8c
TT
3323 gdb_printf (stream, "type: '%s', length: 0x%x, alignment: 0x%x",
3324 TYPE_SAFE_NAME (info->type), info->length, info->align);
dbbb1059
AB
3325 switch (info->argloc[0].loc_type)
3326 {
3327 case riscv_arg_info::location::in_reg:
6cb06a8c 3328 gdb_printf
cab5bb9d
AB
3329 (stream, ", register %s",
3330 gdbarch_register_name (gdbarch, info->argloc[0].loc_data.regno));
dbbb1059
AB
3331 if (info->argloc[0].c_length < info->length)
3332 {
3333 switch (info->argloc[1].loc_type)
3334 {
3335 case riscv_arg_info::location::in_reg:
6cb06a8c 3336 gdb_printf
cab5bb9d
AB
3337 (stream, ", register %s",
3338 gdbarch_register_name (gdbarch,
3339 info->argloc[1].loc_data.regno));
dbbb1059
AB
3340 break;
3341
3342 case riscv_arg_info::location::on_stack:
6cb06a8c
TT
3343 gdb_printf (stream, ", on stack at offset 0x%x",
3344 info->argloc[1].loc_data.offset);
dbbb1059
AB
3345 break;
3346
3347 case riscv_arg_info::location::by_ref:
3348 default:
3349 /* The second location should never be a reference, any
3350 argument being passed by reference just places its address
3351 in the first location and is done. */
3352 error (_("invalid argument location"));
3353 break;
3354 }
3355
3356 if (info->argloc[1].c_offset > info->argloc[0].c_length)
6cb06a8c
TT
3357 gdb_printf (stream, " (offset 0x%x)",
3358 info->argloc[1].c_offset);
dbbb1059
AB
3359 }
3360 break;
3361
3362 case riscv_arg_info::location::on_stack:
6cb06a8c
TT
3363 gdb_printf (stream, ", on stack at offset 0x%x",
3364 info->argloc[0].loc_data.offset);
dbbb1059
AB
3365 break;
3366
3367 case riscv_arg_info::location::by_ref:
6cb06a8c 3368 gdb_printf
cab5bb9d
AB
3369 (stream, ", by reference, data at offset 0x%x (%s)",
3370 info->argloc[0].loc_data.offset,
3371 core_addr_to_string (sp_refs + info->argloc[0].loc_data.offset));
dbbb1059
AB
3372 if (info->argloc[1].loc_type
3373 == riscv_arg_info::location::in_reg)
6cb06a8c 3374 gdb_printf
cab5bb9d
AB
3375 (stream, ", address in register %s",
3376 gdbarch_register_name (gdbarch, info->argloc[1].loc_data.regno));
dbbb1059
AB
3377 else
3378 {
3379 gdb_assert (info->argloc[1].loc_type
3380 == riscv_arg_info::location::on_stack);
6cb06a8c 3381 gdb_printf
cab5bb9d
AB
3382 (stream, ", address on stack at offset 0x%x (%s)",
3383 info->argloc[1].loc_data.offset,
3384 core_addr_to_string (sp_args + info->argloc[1].loc_data.offset));
dbbb1059
AB
3385 }
3386 break;
3387
3388 default:
557b4d76 3389 gdb_assert_not_reached ("unknown argument location type");
dbbb1059
AB
3390 }
3391}
3392
dd895392
AB
3393/* Wrapper around REGCACHE->cooked_write. Places the LEN bytes of DATA
3394 into a buffer that is at least as big as the register REGNUM, padding
3395 out the DATA with either 0x00, or 0xff. For floating point registers
3396 0xff is used, for everyone else 0x00 is used. */
3397
3398static void
3399riscv_regcache_cooked_write (int regnum, const gdb_byte *data, int len,
3400 struct regcache *regcache, int flen)
3401{
3402 gdb_byte tmp [sizeof (ULONGEST)];
3403
3404 /* FP values in FP registers must be NaN-boxed. */
3405 if (riscv_is_fp_regno_p (regnum) && len < flen)
3406 memset (tmp, -1, sizeof (tmp));
3407 else
3408 memset (tmp, 0, sizeof (tmp));
3409 memcpy (tmp, data, len);
3410 regcache->cooked_write (regnum, tmp);
3411}
3412
dbbb1059
AB
3413/* Implement the push dummy call gdbarch callback. */
3414
3415static CORE_ADDR
3416riscv_push_dummy_call (struct gdbarch *gdbarch,
3417 struct value *function,
3418 struct regcache *regcache,
3419 CORE_ADDR bp_addr,
3420 int nargs,
3421 struct value **args,
3422 CORE_ADDR sp,
cf84fa6b 3423 function_call_return_method return_method,
dbbb1059
AB
3424 CORE_ADDR struct_addr)
3425{
3426 int i;
3427 CORE_ADDR sp_args, sp_refs;
3428 enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
dbbb1059
AB
3429
3430 struct riscv_arg_info *arg_info =
3431 (struct riscv_arg_info *) alloca (nargs * sizeof (struct riscv_arg_info));
dbbb1059
AB
3432
3433 struct riscv_call_info call_info (gdbarch);
3434
3435 CORE_ADDR osp = sp;
3436
d0c97917 3437 struct type *ftype = check_typedef (function->type ());
8b2d40cb 3438
78134374 3439 if (ftype->code () == TYPE_CODE_PTR)
27710edb 3440 ftype = check_typedef (ftype->target_type ());
8b2d40cb 3441
dbbb1059 3442 /* We'll use register $a0 if we're returning a struct. */
cf84fa6b 3443 if (return_method == return_method_struct)
dbbb1059
AB
3444 ++call_info.int_regs.next_regnum;
3445
b926417a 3446 for (i = 0; i < nargs; ++i)
dbbb1059
AB
3447 {
3448 struct value *arg_value;
3449 struct type *arg_type;
b926417a 3450 struct riscv_arg_info *info = &arg_info[i];
dbbb1059
AB
3451
3452 arg_value = args[i];
d0c97917 3453 arg_type = check_typedef (arg_value->type ());
dbbb1059 3454
8b2d40cb 3455 riscv_arg_location (gdbarch, info, &call_info, arg_type,
a409645d 3456 ftype->has_varargs () && i >= ftype->num_fields ());
dbbb1059
AB
3457
3458 if (info->type != arg_type)
3459 arg_value = value_cast (info->type, arg_value);
efaf1ae0 3460 info->contents = arg_value->contents ().data ();
dbbb1059
AB
3461 }
3462
3463 /* Adjust the stack pointer and align it. */
3464 sp = sp_refs = align_down (sp - call_info.memory.ref_offset, SP_ALIGNMENT);
3465 sp = sp_args = align_down (sp - call_info.memory.arg_offset, SP_ALIGNMENT);
3466
4f6e0c44 3467 if (riscv_debug_infcall)
dbbb1059 3468 {
4f6e0c44
AB
3469 RISCV_INFCALL_SCOPED_DEBUG_START_END ("dummy call args");
3470 riscv_infcall_debug_printf ("floating point ABI %s in use",
3471 (riscv_has_fp_abi (gdbarch)
3472 ? "is" : "is not"));
3473 riscv_infcall_debug_printf ("xlen: %d", call_info.xlen);
3474 riscv_infcall_debug_printf ("flen: %d", call_info.flen);
cf84fa6b 3475 if (return_method == return_method_struct)
4f6e0c44
AB
3476 riscv_infcall_debug_printf
3477 ("[**] struct return pointer in register $A0");
dbbb1059
AB
3478 for (i = 0; i < nargs; ++i)
3479 {
3480 struct riscv_arg_info *info = &arg_info [i];
4f6e0c44 3481 string_file tmp;
dbbb1059 3482
4f6e0c44
AB
3483 riscv_print_arg_location (&tmp, gdbarch, info, sp_refs, sp_args);
3484 riscv_infcall_debug_printf ("[%2d] %s", i, tmp.string ().c_str ());
dbbb1059
AB
3485 }
3486 if (call_info.memory.arg_offset > 0
3487 || call_info.memory.ref_offset > 0)
3488 {
4f6e0c44
AB
3489 riscv_infcall_debug_printf (" Original sp: %s",
3490 core_addr_to_string (osp));
3491 riscv_infcall_debug_printf ("Stack required (for args): 0x%x",
3492 call_info.memory.arg_offset);
3493 riscv_infcall_debug_printf ("Stack required (for refs): 0x%x",
3494 call_info.memory.ref_offset);
3495 riscv_infcall_debug_printf (" Stack allocated: %s",
3496 core_addr_to_string_nz (osp - sp));
dbbb1059
AB
3497 }
3498 }
3499
3500 /* Now load the argument into registers, or onto the stack. */
3501
cf84fa6b 3502 if (return_method == return_method_struct)
dbbb1059
AB
3503 {
3504 gdb_byte buf[sizeof (LONGEST)];
3505
3506 store_unsigned_integer (buf, call_info.xlen, byte_order, struct_addr);
b66f5587 3507 regcache->cooked_write (RISCV_A0_REGNUM, buf);
dbbb1059
AB
3508 }
3509
3510 for (i = 0; i < nargs; ++i)
3511 {
3512 CORE_ADDR dst;
3513 int second_arg_length = 0;
3514 const gdb_byte *second_arg_data;
3515 struct riscv_arg_info *info = &arg_info [i];
3516
3517 gdb_assert (info->length > 0);
3518
3519 switch (info->argloc[0].loc_type)
3520 {
3521 case riscv_arg_info::location::in_reg:
3522 {
dbbb1059 3523 gdb_assert (info->argloc[0].c_length <= info->length);
dd895392
AB
3524
3525 riscv_regcache_cooked_write (info->argloc[0].loc_data.regno,
3526 (info->contents
3527 + info->argloc[0].c_offset),
3528 info->argloc[0].c_length,
3529 regcache, call_info.flen);
dbbb1059 3530 second_arg_length =
9f0272f8 3531 (((info->argloc[0].c_length + info->argloc[0].c_offset) < info->length)
dbbb1059
AB
3532 ? info->argloc[1].c_length : 0);
3533 second_arg_data = info->contents + info->argloc[1].c_offset;
3534 }
3535 break;
3536
3537 case riscv_arg_info::location::on_stack:
3538 dst = sp_args + info->argloc[0].loc_data.offset;
3539 write_memory (dst, info->contents, info->length);
3540 second_arg_length = 0;
3541 break;
3542
3543 case riscv_arg_info::location::by_ref:
3544 dst = sp_refs + info->argloc[0].loc_data.offset;
3545 write_memory (dst, info->contents, info->length);
3546
3547 second_arg_length = call_info.xlen;
3548 second_arg_data = (gdb_byte *) &dst;
3549 break;
3550
3551 default:
557b4d76 3552 gdb_assert_not_reached ("unknown argument location type");
dbbb1059
AB
3553 }
3554
3555 if (second_arg_length > 0)
3556 {
3557 switch (info->argloc[1].loc_type)
3558 {
3559 case riscv_arg_info::location::in_reg:
3560 {
8c49aa89
AB
3561 gdb_assert ((riscv_is_fp_regno_p (info->argloc[1].loc_data.regno)
3562 && second_arg_length <= call_info.flen)
3563 || second_arg_length <= call_info.xlen);
dd895392
AB
3564 riscv_regcache_cooked_write (info->argloc[1].loc_data.regno,
3565 second_arg_data,
3566 second_arg_length,
3567 regcache, call_info.flen);
dbbb1059
AB
3568 }
3569 break;
3570
3571 case riscv_arg_info::location::on_stack:
3572 {
3573 CORE_ADDR arg_addr;
3574
3575 arg_addr = sp_args + info->argloc[1].loc_data.offset;
3576 write_memory (arg_addr, second_arg_data, second_arg_length);
3577 break;
3578 }
3579
3580 case riscv_arg_info::location::by_ref:
3581 default:
3582 /* The second location should never be a reference, any
3583 argument being passed by reference just places its address
3584 in the first location and is done. */
3585 error (_("invalid argument location"));
3586 break;
3587 }
3588 }
3589 }
3590
3591 /* Set the dummy return value to bp_addr.
3592 A dummy breakpoint will be setup to execute the call. */
3593
4f6e0c44
AB
3594 riscv_infcall_debug_printf ("writing $ra = %s",
3595 core_addr_to_string (bp_addr));
dbbb1059
AB
3596 regcache_cooked_write_unsigned (regcache, RISCV_RA_REGNUM, bp_addr);
3597
3598 /* Finally, update the stack pointer. */
3599
4f6e0c44 3600 riscv_infcall_debug_printf ("writing $sp = %s", core_addr_to_string (sp));
dbbb1059
AB
3601 regcache_cooked_write_unsigned (regcache, RISCV_SP_REGNUM, sp);
3602
3603 return sp;
3604}
3605
3606/* Implement the return_value gdbarch method. */
3607
3608static enum return_value_convention
3609riscv_return_value (struct gdbarch *gdbarch,
3610 struct value *function,
3611 struct type *type,
3612 struct regcache *regcache,
5cb0f2d5 3613 struct value **read_value,
dbbb1059
AB
3614 const gdb_byte *writebuf)
3615{
dbbb1059
AB
3616 struct riscv_call_info call_info (gdbarch);
3617 struct riscv_arg_info info;
3618 struct type *arg_type;
3619
3620 arg_type = check_typedef (type);
8b2d40cb 3621 riscv_arg_location (gdbarch, &info, &call_info, arg_type, false);
dbbb1059 3622
4f6e0c44 3623 if (riscv_debug_infcall)
dbbb1059 3624 {
4f6e0c44
AB
3625 string_file tmp;
3626 riscv_print_arg_location (&tmp, gdbarch, &info, 0, 0);
3627 riscv_infcall_debug_printf ("[R] %s", tmp.string ().c_str ());
dbbb1059
AB
3628 }
3629
911627e7 3630 if (read_value != nullptr || writebuf != nullptr)
dbbb1059 3631 {
0bce60ac
TT
3632 unsigned int arg_len;
3633 struct value *abi_val;
911627e7 3634 gdb_byte *readbuf = nullptr;
0bce60ac
TT
3635 int regnum;
3636
3637 /* We only do one thing at a time. */
911627e7 3638 gdb_assert (read_value == nullptr || writebuf == nullptr);
0bce60ac
TT
3639
3640 /* In some cases the argument is not returned as the declared type,
3641 and we need to cast to or from the ABI type in order to
3642 correctly access the argument. When writing to the machine we
3643 do the cast here, when reading from the machine the cast occurs
3644 later, after extracting the value. As the ABI type can be
3645 larger than the declared type, then the read or write buffers
3646 passed in might be too small. Here we ensure that we are using
3647 buffers of sufficient size. */
3648 if (writebuf != nullptr)
3649 {
3650 struct value *arg_val;
3651
3652 if (is_fixed_point_type (arg_type))
3653 {
3654 /* Convert the argument to the type used to pass
3655 the return value, but being careful to preserve
3656 the fact that the value needs to be returned
3657 unscaled. */
3658 gdb_mpz unscaled;
3659
3660 unscaled.read (gdb::make_array_view (writebuf,
3661 arg_type->length ()),
3662 type_byte_order (arg_type),
3663 arg_type->is_unsigned ());
317c3ed9 3664 abi_val = value::allocate (info.type);
bbe912ba 3665 unscaled.write (abi_val->contents_raw (),
0bce60ac
TT
3666 type_byte_order (info.type),
3667 info.type->is_unsigned ());
3668 }
3669 else
3670 {
3671 arg_val = value_from_contents (arg_type, writebuf);
3672 abi_val = value_cast (info.type, arg_val);
3673 }
bbe912ba 3674 writebuf = abi_val->contents_raw ().data ();
0bce60ac
TT
3675 }
3676 else
3677 {
317c3ed9 3678 abi_val = value::allocate (info.type);
bbe912ba 3679 readbuf = abi_val->contents_raw ().data ();
0bce60ac
TT
3680 }
3681 arg_len = info.type->length ();
3682
3683 switch (info.argloc[0].loc_type)
3684 {
3685 /* Return value in register(s). */
3686 case riscv_arg_info::location::in_reg:
74e3300d 3687 {
0bce60ac
TT
3688 regnum = info.argloc[0].loc_data.regno;
3689 gdb_assert (info.argloc[0].c_length <= arg_len);
3690 gdb_assert (info.argloc[0].c_length
3691 <= register_size (gdbarch, regnum));
0abb4049 3692
0bce60ac 3693 if (readbuf)
0abb4049 3694 {
0bce60ac
TT
3695 gdb_byte *ptr = readbuf + info.argloc[0].c_offset;
3696 regcache->cooked_read_part (regnum, 0,
3697 info.argloc[0].c_length,
3698 ptr);
0abb4049 3699 }
0bce60ac
TT
3700
3701 if (writebuf)
0abb4049 3702 {
0bce60ac
TT
3703 const gdb_byte *ptr = writebuf + info.argloc[0].c_offset;
3704 riscv_regcache_cooked_write (regnum, ptr,
3705 info.argloc[0].c_length,
3706 regcache, call_info.flen);
3707 }
3708
3709 /* A return value in register can have a second part in a
3710 second register. */
3711 if (info.argloc[1].c_length > 0)
3712 {
3713 switch (info.argloc[1].loc_type)
3714 {
3715 case riscv_arg_info::location::in_reg:
3716 regnum = info.argloc[1].loc_data.regno;
3717
3718 gdb_assert ((info.argloc[0].c_length
3719 + info.argloc[1].c_length) <= arg_len);
3720 gdb_assert (info.argloc[1].c_length
3721 <= register_size (gdbarch, regnum));
3722
3723 if (readbuf)
3724 {
3725 readbuf += info.argloc[1].c_offset;
3726 regcache->cooked_read_part (regnum, 0,
3727 info.argloc[1].c_length,
3728 readbuf);
3729 }
3730
3731 if (writebuf)
3732 {
3733 const gdb_byte *ptr
3734 = writebuf + info.argloc[1].c_offset;
3735 riscv_regcache_cooked_write
3736 (regnum, ptr, info.argloc[1].c_length,
3737 regcache, call_info.flen);
3738 }
3739 break;
3740
3741 case riscv_arg_info::location::by_ref:
3742 case riscv_arg_info::location::on_stack:
3743 default:
3744 error (_("invalid argument location"));
3745 break;
3746 }
0abb4049 3747 }
74e3300d 3748 }
0bce60ac 3749 break;
dbbb1059 3750
0bce60ac
TT
3751 /* Return value by reference will have its address in A0. */
3752 case riscv_arg_info::location::by_ref:
dbbb1059 3753 {
0bce60ac
TT
3754 ULONGEST addr;
3755
3756 regcache_cooked_read_unsigned (regcache, RISCV_A0_REGNUM,
3757 &addr);
911627e7
TT
3758 if (read_value != nullptr)
3759 {
3760 abi_val = value_at_non_lval (type, addr);
3761 /* Also reset the expected type, so that the cast
3762 later on is a no-op. If the cast is not a no-op,
3763 and if the return type is variably-sized, then the
3764 type of ABI_VAL will differ from ARG_TYPE due to
3765 dynamic type resolution, and so will most likely
3766 fail. */
d0c97917 3767 arg_type = abi_val->type ();
911627e7 3768 }
0bce60ac
TT
3769 if (writebuf != nullptr)
3770 write_memory (addr, writebuf, info.length);
3771 }
3772 break;
dbbb1059 3773
0bce60ac
TT
3774 case riscv_arg_info::location::on_stack:
3775 default:
3776 error (_("invalid argument location"));
3777 break;
3778 }
dbbb1059 3779
0bce60ac
TT
3780 /* This completes the cast from abi type back to the declared type
3781 in the case that we are reading from the machine. See the
3782 comment at the head of this block for more details. */
911627e7 3783 if (read_value != nullptr)
0bce60ac 3784 {
0bce60ac 3785 if (is_fixed_point_type (arg_type))
dbbb1059 3786 {
0bce60ac
TT
3787 /* Convert abi_val to the actual return type, but
3788 being careful to preserve the fact that abi_val
3789 is unscaled. */
3790 gdb_mpz unscaled;
3791
efaf1ae0 3792 unscaled.read (abi_val->contents (),
0bce60ac
TT
3793 type_byte_order (info.type),
3794 info.type->is_unsigned ());
317c3ed9 3795 *read_value = value::allocate (arg_type);
bbe912ba 3796 unscaled.write ((*read_value)->contents_raw (),
0bce60ac
TT
3797 type_byte_order (arg_type),
3798 arg_type->is_unsigned ());
dbbb1059 3799 }
0bce60ac 3800 else
911627e7 3801 *read_value = value_cast (arg_type, abi_val);
0bce60ac 3802 }
dbbb1059
AB
3803 }
3804
3805 switch (info.argloc[0].loc_type)
3806 {
3807 case riscv_arg_info::location::in_reg:
3808 return RETURN_VALUE_REGISTER_CONVENTION;
3809 case riscv_arg_info::location::by_ref:
d4be21dc 3810 return RETURN_VALUE_ABI_PRESERVES_ADDRESS;
dbbb1059
AB
3811 case riscv_arg_info::location::on_stack:
3812 default:
3813 error (_("invalid argument location"));
3814 }
3815}
3816
3817/* Implement the frame_align gdbarch method. */
3818
3819static CORE_ADDR
3820riscv_frame_align (struct gdbarch *gdbarch, CORE_ADDR addr)
3821{
3822 return align_down (addr, 16);
3823}
3824
dbbb1059
AB
3825/* Generate, or return the cached frame cache for the RiscV frame
3826 unwinder. */
3827
78a3b0fa 3828static struct riscv_unwind_cache *
8480a37e 3829riscv_frame_cache (const frame_info_ptr &this_frame, void **this_cache)
dbbb1059 3830{
78a3b0fa
AB
3831 CORE_ADDR pc, start_addr;
3832 struct riscv_unwind_cache *cache;
dbbb1059 3833 struct gdbarch *gdbarch = get_frame_arch (this_frame);
78a3b0fa 3834 int numregs, regno;
dbbb1059
AB
3835
3836 if ((*this_cache) != NULL)
78a3b0fa 3837 return (struct riscv_unwind_cache *) *this_cache;
dbbb1059 3838
78a3b0fa
AB
3839 cache = FRAME_OBSTACK_ZALLOC (struct riscv_unwind_cache);
3840 cache->regs = trad_frame_alloc_saved_regs (this_frame);
3841 (*this_cache) = cache;
dbbb1059 3842
78a3b0fa
AB
3843 /* Scan the prologue, filling in the cache. */
3844 start_addr = get_frame_func (this_frame);
dbbb1059 3845 pc = get_frame_pc (this_frame);
78a3b0fa
AB
3846 riscv_scan_prologue (gdbarch, start_addr, pc, cache);
3847
3848 /* We can now calculate the frame base address. */
3849 cache->frame_base
e1f57067 3850 = (get_frame_register_unsigned (this_frame, cache->frame_base_reg)
6c9d681b 3851 + cache->frame_base_offset);
4f6e0c44
AB
3852 riscv_unwinder_debug_printf ("frame base is %s ($%s + 0x%x)",
3853 core_addr_to_string (cache->frame_base),
3854 gdbarch_register_name (gdbarch,
3855 cache->frame_base_reg),
3856 cache->frame_base_offset);
78a3b0fa
AB
3857
3858 /* The prologue scanner sets the address of registers stored to the stack
3859 as the offset of that register from the frame base. The prologue
3860 scanner doesn't know the actual frame base value, and so is unable to
3861 compute the exact address. We do now know the frame base value, so
3862 update the address of registers stored to the stack. */
3863 numregs = gdbarch_num_regs (gdbarch) + gdbarch_num_pseudo_regs (gdbarch);
3864 for (regno = 0; regno < numregs; ++regno)
3865 {
a9a87d35 3866 if (cache->regs[regno].is_addr ())
098caef4
LM
3867 cache->regs[regno].set_addr (cache->regs[regno].addr ()
3868 + cache->frame_base);
78a3b0fa
AB
3869 }
3870
3871 /* The previous $pc can be found wherever the $ra value can be found.
3872 The previous $ra value is gone, this would have been stored be the
3873 previous frame if required. */
3874 cache->regs[gdbarch_pc_regnum (gdbarch)] = cache->regs[RISCV_RA_REGNUM];
a9a87d35 3875 cache->regs[RISCV_RA_REGNUM].set_unknown ();
78a3b0fa
AB
3876
3877 /* Build the frame id. */
3878 cache->this_id = frame_id_build (cache->frame_base, start_addr);
dbbb1059 3879
78a3b0fa 3880 /* The previous $sp value is the frame base value. */
a9a87d35 3881 cache->regs[gdbarch_sp_regnum (gdbarch)].set_value (cache->frame_base);
dbbb1059 3882
78a3b0fa 3883 return cache;
dbbb1059
AB
3884}
3885
3886/* Implement the this_id callback for RiscV frame unwinder. */
3887
3888static void
8480a37e 3889riscv_frame_this_id (const frame_info_ptr &this_frame,
dbbb1059
AB
3890 void **prologue_cache,
3891 struct frame_id *this_id)
3892{
78a3b0fa 3893 struct riscv_unwind_cache *cache;
dbbb1059 3894
a70b8144 3895 try
17cf2897
AB
3896 {
3897 cache = riscv_frame_cache (this_frame, prologue_cache);
3898 *this_id = cache->this_id;
3899 }
230d2906 3900 catch (const gdb_exception_error &ex)
17cf2897
AB
3901 {
3902 /* Ignore errors, this leaves the frame id as the predefined outer
dda83cd7 3903 frame id which terminates the backtrace at this point. */
17cf2897 3904 }
dbbb1059
AB
3905}
3906
3907/* Implement the prev_register callback for RiscV frame unwinder. */
3908
3909static struct value *
8480a37e 3910riscv_frame_prev_register (const frame_info_ptr &this_frame,
dbbb1059
AB
3911 void **prologue_cache,
3912 int regnum)
3913{
78a3b0fa 3914 struct riscv_unwind_cache *cache;
dbbb1059 3915
78a3b0fa
AB
3916 cache = riscv_frame_cache (this_frame, prologue_cache);
3917 return trad_frame_get_prev_register (this_frame, cache->regs, regnum);
dbbb1059
AB
3918}
3919
3920/* Structure defining the RiscV normal frame unwind functions. Since we
3921 are the fallback unwinder (DWARF unwinder is used first), we use the
3922 default frame sniffer, which always accepts the frame. */
3923
1239e7cf 3924static const struct frame_unwind_legacy riscv_frame_unwind (
a154d838 3925 /*.name =*/ "riscv prologue",
dbbb1059 3926 /*.type =*/ NORMAL_FRAME,
ce36ef63 3927 /*.unwinder_class=*/FRAME_UNWIND_ARCH,
dbbb1059
AB
3928 /*.stop_reason =*/ default_frame_unwind_stop_reason,
3929 /*.this_id =*/ riscv_frame_this_id,
3930 /*.prev_register =*/ riscv_frame_prev_register,
3931 /*.unwind_data =*/ NULL,
3932 /*.sniffer =*/ default_frame_sniffer,
3933 /*.dealloc_cache =*/ NULL,
1239e7cf
GL
3934 /*.prev_arch =*/ NULL
3935);
dbbb1059 3936
895b7b4e
AB
3937/* Extract a set of required target features out of ABFD. If ABFD is
3938 nullptr then a RISCV_GDBARCH_FEATURES is returned in its default state. */
dbbb1059 3939
90af0679 3940static struct riscv_gdbarch_features
895b7b4e 3941riscv_features_from_bfd (const bfd *abfd)
dbbb1059 3942{
b5ffee31 3943 struct riscv_gdbarch_features features;
dbbb1059 3944
b5ffee31
AB
3945 /* Now try to improve on the defaults by looking at the binary we are
3946 going to execute. We assume the user knows what they are doing and
3947 that the target will match the binary. Remember, this code path is
3948 only used at all if the target hasn't given us a description, so this
3949 is really a last ditched effort to do something sane before giving
3950 up. */
895b7b4e 3951 if (abfd != nullptr && bfd_get_flavour (abfd) == bfd_target_elf_flavour)
dbbb1059 3952 {
895b7b4e
AB
3953 unsigned char eclass = elf_elfheader (abfd)->e_ident[EI_CLASS];
3954 int e_flags = elf_elfheader (abfd)->e_flags;
dbbb1059
AB
3955
3956 if (eclass == ELFCLASS32)
b5ffee31 3957 features.xlen = 4;
dbbb1059 3958 else if (eclass == ELFCLASS64)
b5ffee31 3959 features.xlen = 8;
dbbb1059 3960 else
f34652de 3961 internal_error (_("unknown ELF header class %d"), eclass);
dbbb1059 3962
dbbb1059 3963 if (e_flags & EF_RISCV_FLOAT_ABI_DOUBLE)
113b7b81 3964 features.flen = 8;
dbbb1059 3965 else if (e_flags & EF_RISCV_FLOAT_ABI_SINGLE)
113b7b81 3966 features.flen = 4;
25428040
AB
3967
3968 if (e_flags & EF_RISCV_RVE)
3969 {
3970 if (features.xlen == 8)
3971 {
3972 warning (_("64-bit ELF with RV32E flag set! Assuming 32-bit"));
3973 features.xlen = 4;
3974 }
3975 features.embedded = true;
3976 }
dbbb1059 3977 }
dbbb1059 3978
90af0679
AB
3979 return features;
3980}
3981
3982/* Find a suitable default target description. Use the contents of INFO,
3983 specifically the bfd object being executed, to guide the selection of a
3984 suitable default target description. */
3985
3986static const struct target_desc *
3987riscv_find_default_target_description (const struct gdbarch_info info)
3988{
3989 /* Extract desired feature set from INFO. */
3990 struct riscv_gdbarch_features features
895b7b4e 3991 = riscv_features_from_bfd (info.abfd);
90af0679 3992
895b7b4e
AB
3993 /* If the XLEN field is still 0 then we got nothing useful from INFO.BFD,
3994 maybe there was no bfd object. In this case we fall back to a minimal
3995 useful target with no floating point, the x-register size is selected
3996 based on the architecture from INFO. */
90af0679 3997 if (features.xlen == 0)
895b7b4e 3998 features.xlen = info.bfd_arch_info->bits_per_word == 32 ? 4 : 8;
90af0679 3999
b5ffee31 4000 /* Now build a target description based on the feature set. */
d1c9b20f 4001 return riscv_lookup_target_description (features);
b5ffee31
AB
4002}
4003
e7d69e72 4004/* Add all the RISC-V specific register groups into GDBARCH. */
b5ffee31
AB
4005
4006static void
4007riscv_add_reggroups (struct gdbarch *gdbarch)
4008{
b5ffee31
AB
4009 reggroup_add (gdbarch, csr_reggroup);
4010}
4011
fb44d95a
AB
4012/* Implement the "dwarf2_reg_to_regnum" gdbarch method. */
4013
4014static int
4015riscv_dwarf_reg_to_regnum (struct gdbarch *gdbarch, int reg)
4016{
c8ea5e40 4017 if (reg <= RISCV_DWARF_REGNUM_X31)
fb44d95a
AB
4018 return RISCV_ZERO_REGNUM + (reg - RISCV_DWARF_REGNUM_X0);
4019
c8ea5e40 4020 else if (reg <= RISCV_DWARF_REGNUM_F31)
fb44d95a
AB
4021 return RISCV_FIRST_FP_REGNUM + (reg - RISCV_DWARF_REGNUM_F0);
4022
550820e1
AB
4023 else if (reg >= RISCV_DWARF_FIRST_CSR && reg <= RISCV_DWARF_LAST_CSR)
4024 return RISCV_FIRST_CSR_REGNUM + (reg - RISCV_DWARF_FIRST_CSR);
4025
96f842cb
AB
4026 else if (reg >= RISCV_DWARF_REGNUM_V0 && reg <= RISCV_DWARF_REGNUM_V31)
4027 return RISCV_V0_REGNUM + (reg - RISCV_DWARF_REGNUM_V0);
4028
fb44d95a
AB
4029 return -1;
4030}
4031
ff371ec9
JW
4032/* Implement the gcc_target_options method. We have to select the arch and abi
4033 from the feature info. We have enough feature info to select the abi, but
4034 not enough info for the arch given all of the possible architecture
4035 extensions. So choose reasonable defaults for now. */
4036
4037static std::string
4038riscv_gcc_target_options (struct gdbarch *gdbarch)
4039{
4040 int isa_xlen = riscv_isa_xlen (gdbarch);
4041 int isa_flen = riscv_isa_flen (gdbarch);
4042 int abi_xlen = riscv_abi_xlen (gdbarch);
4043 int abi_flen = riscv_abi_flen (gdbarch);
4044 std::string target_options;
4045
4046 target_options = "-march=rv";
4047 if (isa_xlen == 8)
4048 target_options += "64";
4049 else
4050 target_options += "32";
4051 if (isa_flen == 8)
4052 target_options += "gc";
4053 else if (isa_flen == 4)
4054 target_options += "imafc";
4055 else
4056 target_options += "imac";
4057
4058 target_options += " -mabi=";
4059 if (abi_xlen == 8)
4060 target_options += "lp64";
4061 else
4062 target_options += "ilp32";
4063 if (abi_flen == 8)
4064 target_options += "d";
4065 else if (abi_flen == 4)
4066 target_options += "f";
4067
4068 /* The gdb loader doesn't handle link-time relaxation relocations. */
4069 target_options += " -mno-relax";
4070
4071 return target_options;
4072}
4073
2e52d038
AB
4074/* Call back from tdesc_use_registers, called for each unknown register
4075 found in the target description.
4076
4077 See target-description.h (typedef tdesc_unknown_register_ftype) for a
4078 discussion of the arguments and return values. */
4079
4080static int
4081riscv_tdesc_unknown_reg (struct gdbarch *gdbarch, tdesc_feature *feature,
4082 const char *reg_name, int possible_regnum)
4083{
4084 /* At one point in time GDB had an incorrect default target description
4085 that duplicated the fflags, frm, and fcsr registers in both the FPU
4086 and CSR register sets.
4087
4088 Some targets (QEMU) copied these target descriptions into their source
0e6a6e40 4089 tree, and so we're now stuck working with some versions of QEMU that
2e52d038
AB
4090 declare the same registers twice.
4091
0e6a6e40
AB
4092 To make matters worse, if GDB tries to read or write to these
4093 registers using the register number assigned in the FPU feature set,
4094 then QEMU will fail to read the register, so we must use the register
4095 number declared in the CSR feature set.
4096
4097 Luckily, GDB scans the FPU feature first, and then the CSR feature,
4098 which means that the CSR feature will be the one we end up using, the
4099 versions of these registers in the FPU feature will appear as unknown
4100 registers and will be passed through to this code.
4101
4102 To prevent these duplicate registers showing up in any of the register
4103 lists, and to prevent GDB every trying to access the FPU feature copies,
4104 we spot the three problematic registers here, and record the register
4105 number that GDB has assigned them. Then in riscv_register_name we will
4106 return no name for the three duplicates, this hides the duplicates from
4107 the user. */
25428040 4108 if (strcmp (tdesc_feature_name (feature), riscv_freg_feature.name ()) == 0)
2e52d038 4109 {
08106042 4110 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
2e52d038
AB
4111 int *regnum_ptr = nullptr;
4112
4113 if (strcmp (reg_name, "fflags") == 0)
4114 regnum_ptr = &tdep->duplicate_fflags_regnum;
4115 else if (strcmp (reg_name, "frm") == 0)
4116 regnum_ptr = &tdep->duplicate_frm_regnum;
4117 else if (strcmp (reg_name, "fcsr") == 0)
4118 regnum_ptr = &tdep->duplicate_fcsr_regnum;
4119
4120 if (regnum_ptr != nullptr)
4121 {
4122 /* This means the register appears more than twice in the target
4123 description. Just let GDB add this as another register.
4124 We'll have duplicates in the register name list, but there's
4125 not much more we can do. */
4126 if (*regnum_ptr != -1)
4127 return -1;
4128
4129 /* Record the number assigned to this register, then return the
4130 number (so it actually gets assigned to this register). */
4131 *regnum_ptr = possible_regnum;
4132 return possible_regnum;
4133 }
4134 }
4135
4136 /* Any unknown registers in the CSR feature are recorded within a single
4137 block so we can easily identify these registers when making choices
4138 about register groups in riscv_register_reggroup_p. */
25428040 4139 if (strcmp (tdesc_feature_name (feature), riscv_csr_feature.name ()) == 0)
2e52d038 4140 {
08106042 4141 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
2e52d038
AB
4142 if (tdep->unknown_csrs_first_regnum == -1)
4143 tdep->unknown_csrs_first_regnum = possible_regnum;
4144 gdb_assert (tdep->unknown_csrs_first_regnum
4145 + tdep->unknown_csrs_count == possible_regnum);
4146 tdep->unknown_csrs_count++;
4147 return possible_regnum;
4148 }
4149
4150 /* Some other unknown register. Don't assign this a number now, it will
4151 be assigned a number automatically later by the target description
4152 handling code. */
4153 return -1;
4154}
4155
ff371ec9
JW
4156/* Implement the gnu_triplet_regexp method. A single compiler supports both
4157 32-bit and 64-bit code, and may be named riscv32 or riscv64 or (not
4158 recommended) riscv. */
4159
4160static const char *
4161riscv_gnu_triplet_regexp (struct gdbarch *gdbarch)
4162{
4163 return "riscv(32|64)?";
4164}
4165
2f79f2e7
AB
4166/* Implementation of `gdbarch_stap_is_single_operand', as defined in
4167 gdbarch.h. */
4168
4169static int
4170riscv_stap_is_single_operand (struct gdbarch *gdbarch, const char *s)
4171{
4172 return (ISDIGIT (*s) /* Literal number. */
4173 || *s == '(' /* Register indirection. */
4174 || ISALPHA (*s)); /* Register value. */
4175}
4176
4177/* String that appears before a register name in a SystemTap register
4178 indirect expression. */
4179
4180static const char *const stap_register_indirection_prefixes[] =
4181{
4182 "(", nullptr
4183};
4184
4185/* String that appears after a register name in a SystemTap register
4186 indirect expression. */
4187
4188static const char *const stap_register_indirection_suffixes[] =
4189{
4190 ")", nullptr
4191};
4192
b5ffee31 4193/* Initialize the current architecture based on INFO. If possible,
973c5759 4194 reuse an architecture from ARCHES, which is a list of
b5ffee31
AB
4195 architectures already created during this debugging session.
4196
4197 Called e.g. at program startup, when reading a core file, and when
4198 reading a binary file. */
4199
4200static struct gdbarch *
4201riscv_gdbarch_init (struct gdbarch_info info,
4202 struct gdbarch_list *arches)
4203{
b5ffee31
AB
4204 struct riscv_gdbarch_features features;
4205 const struct target_desc *tdesc = info.target_desc;
4206
4207 /* Ensure we always have a target description. */
4208 if (!tdesc_has_registers (tdesc))
4209 tdesc = riscv_find_default_target_description (info);
25428040 4210 gdb_assert (tdesc != nullptr);
b5ffee31 4211
4f6e0c44 4212 riscv_gdbarch_debug_printf ("have got a target description");
b5ffee31 4213
c1e1314d 4214 tdesc_arch_data_up tdesc_data = tdesc_data_alloc ();
767a879e 4215 std::vector<riscv_pending_register_alias> pending_aliases;
b5ffee31 4216
25428040
AB
4217 bool valid_p = (riscv_xreg_feature.check (tdesc, tdesc_data.get (),
4218 &pending_aliases, &features)
4219 && riscv_freg_feature.check (tdesc, tdesc_data.get (),
4220 &pending_aliases, &features)
4221 && riscv_virtual_feature.check (tdesc, tdesc_data.get (),
4222 &pending_aliases, &features)
4223 && riscv_csr_feature.check (tdesc, tdesc_data.get (),
96f842cb
AB
4224 &pending_aliases, &features)
4225 && riscv_vector_feature.check (tdesc, tdesc_data.get (),
4226 &pending_aliases, &features));
b5ffee31
AB
4227 if (!valid_p)
4228 {
4f6e0c44 4229 riscv_gdbarch_debug_printf ("target description is not valid");
b5ffee31
AB
4230 return NULL;
4231 }
4232
4749b84b
AB
4233 if (tdesc_found_register (tdesc_data.get (), RISCV_CSR_FFLAGS_REGNUM))
4234 features.has_fflags_reg = true;
4235 if (tdesc_found_register (tdesc_data.get (), RISCV_CSR_FRM_REGNUM))
4236 features.has_frm_reg = true;
4237 if (tdesc_found_register (tdesc_data.get (), RISCV_CSR_FCSR_REGNUM))
4238 features.has_fcsr_reg = true;
4239
90af0679
AB
4240 /* Have a look at what the supplied (if any) bfd object requires of the
4241 target, then check that this matches with what the target is
4242 providing. */
113b7b81 4243 struct riscv_gdbarch_features abi_features
895b7b4e 4244 = riscv_features_from_bfd (info.abfd);
25428040
AB
4245
4246 /* If the ABI_FEATURES xlen is 0 then this indicates we got no useful abi
4247 features from the INFO object. In this case we just treat the
4248 hardware features as defining the abi. */
4249 if (abi_features.xlen == 0)
4250 abi_features = features;
4251
113b7b81
AB
4252 /* In theory a binary compiled for RV32 could run on an RV64 target,
4253 however, this has not been tested in GDB yet, so for now we require
4254 that the requested xlen match the targets xlen. */
25428040 4255 if (abi_features.xlen != features.xlen)
90af0679 4256 error (_("bfd requires xlen %d, but target has xlen %d"),
dda83cd7 4257 abi_features.xlen, features.xlen);
113b7b81
AB
4258 /* We do support running binaries compiled for 32-bit float on targets
4259 with 64-bit float, so we only complain if the binary requires more
4260 than the target has available. */
4261 if (abi_features.flen > features.flen)
90af0679 4262 error (_("bfd requires flen %d, but target has flen %d"),
dda83cd7 4263 abi_features.flen, features.flen);
90af0679 4264
dbbb1059
AB
4265 /* Find a candidate among the list of pre-declared architectures. */
4266 for (arches = gdbarch_list_lookup_by_info (arches, &info);
4267 arches != NULL;
4268 arches = gdbarch_list_lookup_by_info (arches->next, &info))
b5ffee31
AB
4269 {
4270 /* Check that the feature set of the ARCHES matches the feature set
dda83cd7
SM
4271 we are looking for. If it doesn't then we can't reuse this
4272 gdbarch. */
345bd07c 4273 riscv_gdbarch_tdep *other_tdep
08106042 4274 = gdbarch_tdep<riscv_gdbarch_tdep> (arches->gdbarch);
b5ffee31 4275
113b7b81
AB
4276 if (other_tdep->isa_features != features
4277 || other_tdep->abi_features != abi_features)
dda83cd7 4278 continue;
b5ffee31
AB
4279
4280 break;
4281 }
4282
4283 if (arches != NULL)
c1e1314d 4284 return arches->gdbarch;
dbbb1059
AB
4285
4286 /* None found, so create a new architecture from the information provided. */
2b16913c
SM
4287 gdbarch *gdbarch
4288 = gdbarch_alloc (&info, gdbarch_tdep_up (new riscv_gdbarch_tdep));
4289 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
4290
113b7b81
AB
4291 tdep->isa_features = features;
4292 tdep->abi_features = abi_features;
dbbb1059
AB
4293
4294 /* Target data types. */
4295 set_gdbarch_short_bit (gdbarch, 16);
4296 set_gdbarch_int_bit (gdbarch, 32);
4297 set_gdbarch_long_bit (gdbarch, riscv_isa_xlen (gdbarch) * 8);
4298 set_gdbarch_long_long_bit (gdbarch, 64);
4299 set_gdbarch_float_bit (gdbarch, 32);
4300 set_gdbarch_double_bit (gdbarch, 64);
4301 set_gdbarch_long_double_bit (gdbarch, 128);
552f1157 4302 set_gdbarch_long_double_format (gdbarch, floatformats_ieee_quad);
dbbb1059
AB
4303 set_gdbarch_ptr_bit (gdbarch, riscv_isa_xlen (gdbarch) * 8);
4304 set_gdbarch_char_signed (gdbarch, 0);
a9158a86 4305 set_gdbarch_type_align (gdbarch, riscv_type_align);
dbbb1059
AB
4306
4307 /* Information about the target architecture. */
5cb0f2d5 4308 set_gdbarch_return_value_as_value (gdbarch, riscv_return_value);
dbbb1059
AB
4309 set_gdbarch_breakpoint_kind_from_pc (gdbarch, riscv_breakpoint_kind_from_pc);
4310 set_gdbarch_sw_breakpoint_from_kind (gdbarch, riscv_sw_breakpoint_from_kind);
5a77b1b4 4311 set_gdbarch_have_nonsteppable_watchpoint (gdbarch, 1);
dbbb1059 4312
dbbb1059 4313 /* Functions to analyze frames. */
dbbb1059
AB
4314 set_gdbarch_skip_prologue (gdbarch, riscv_skip_prologue);
4315 set_gdbarch_inner_than (gdbarch, core_addr_lessthan);
4316 set_gdbarch_frame_align (gdbarch, riscv_frame_align);
4317
dbbb1059
AB
4318 /* Functions handling dummy frames. */
4319 set_gdbarch_call_dummy_location (gdbarch, ON_STACK);
4320 set_gdbarch_push_dummy_code (gdbarch, riscv_push_dummy_code);
4321 set_gdbarch_push_dummy_call (gdbarch, riscv_push_dummy_call);
dbbb1059
AB
4322
4323 /* Frame unwinders. Use DWARF debug info if available, otherwise use our own
4324 unwinder. */
4325 dwarf2_append_unwinders (gdbarch);
4326 frame_unwind_append_unwinder (gdbarch, &riscv_frame_unwind);
4327
b5ffee31
AB
4328 /* Register architecture. */
4329 riscv_add_reggroups (gdbarch);
4330
fb44d95a
AB
4331 /* Internal <-> external register number maps. */
4332 set_gdbarch_dwarf2_reg_to_regnum (gdbarch, riscv_dwarf_reg_to_regnum);
4333
b5ffee31
AB
4334 /* We reserve all possible register numbers for the known registers.
4335 This means the target description mechanism will add any target
4336 specific registers after this number. This helps make debugging GDB
4337 just a little easier. */
4338 set_gdbarch_num_regs (gdbarch, RISCV_LAST_REGNUM + 1);
4339
b5ffee31
AB
4340 /* Some specific register numbers GDB likes to know about. */
4341 set_gdbarch_sp_regnum (gdbarch, RISCV_SP_REGNUM);
4342 set_gdbarch_pc_regnum (gdbarch, RISCV_PC_REGNUM);
4343
4344 set_gdbarch_print_registers_info (gdbarch, riscv_print_registers_info);
4345
4749b84b
AB
4346 set_tdesc_pseudo_register_name (gdbarch, riscv_pseudo_register_name);
4347 set_tdesc_pseudo_register_type (gdbarch, riscv_pseudo_register_type);
4348 set_tdesc_pseudo_register_reggroup_p (gdbarch,
4349 riscv_pseudo_register_reggroup_p);
4350 set_gdbarch_pseudo_register_read (gdbarch, riscv_pseudo_register_read);
7f0f3b0f
SM
4351 set_gdbarch_deprecated_pseudo_register_write (gdbarch,
4352 riscv_pseudo_register_write);
4749b84b 4353
b5ffee31 4354 /* Finalise the target description registers. */
c1e1314d
TT
4355 tdesc_use_registers (gdbarch, tdesc, std::move (tdesc_data),
4356 riscv_tdesc_unknown_reg);
b5ffee31 4357
4749b84b
AB
4358 /* Calculate the number of pseudo registers we need. The fflags and frm
4359 registers are sub-fields of the fcsr CSR register (csr3). However,
4360 these registers can also be accessed directly as separate CSR
4361 registers (fflags is csr1, and frm is csr2). And so, some targets
4362 might choose to offer direct access to all three registers in the
4363 target description, while other targets might choose to only offer
4364 access to fcsr.
4365
4366 As we scan the target description we spot which of fcsr, fflags, and
4367 frm are available. If fcsr is available but either of fflags and/or
4368 frm are not available, then we add pseudo-registers to provide the
4369 missing functionality.
4370
4371 This has to be done after the call to tdesc_use_registers as we don't
4372 know the final register number until after that call, and the pseudo
4373 register numbers need to be after the physical registers. */
4374 int num_pseudo_regs = 0;
4375 int next_pseudo_regnum = gdbarch_num_regs (gdbarch);
4376
4377 if (features.has_fflags_reg)
4378 tdep->fflags_regnum = RISCV_CSR_FFLAGS_REGNUM;
4379 else if (features.has_fcsr_reg)
4380 {
4381 tdep->fflags_regnum = next_pseudo_regnum;
4382 pending_aliases.emplace_back ("csr1", (void *) &tdep->fflags_regnum);
4383 next_pseudo_regnum++;
4384 num_pseudo_regs++;
4385 }
4386
4387 if (features.has_frm_reg)
4388 tdep->frm_regnum = RISCV_CSR_FRM_REGNUM;
4389 else if (features.has_fcsr_reg)
4390 {
4391 tdep->frm_regnum = next_pseudo_regnum;
4392 pending_aliases.emplace_back ("csr2", (void *) &tdep->frm_regnum);
4393 next_pseudo_regnum++;
4394 num_pseudo_regs++;
4395 }
4396
4397 set_gdbarch_num_pseudo_regs (gdbarch, num_pseudo_regs);
4398
b5ffee31
AB
4399 /* Override the register type callback setup by the target description
4400 mechanism. This allows us to provide special type for floating point
4401 registers. */
4402 set_gdbarch_register_type (gdbarch, riscv_register_type);
4403
4404 /* Override the register name callback setup by the target description
4405 mechanism. This allows us to force our preferred names for the
4406 registers, no matter what the target description called them. */
4407 set_gdbarch_register_name (gdbarch, riscv_register_name);
4408
f8053219 4409 /* Tell GDB which RISC-V registers are read-only. */
4410 set_gdbarch_cannot_store_register (gdbarch, riscv_cannot_store_register);
4411
b5ffee31
AB
4412 /* Override the register group callback setup by the target description
4413 mechanism. This allows us to force registers into the groups we
4414 want, ignoring what the target tells us. */
4415 set_gdbarch_register_reggroup_p (gdbarch, riscv_register_reggroup_p);
4416
767a879e
AB
4417 /* Create register aliases for alternative register names. We only
4418 create aliases for registers which were mentioned in the target
4419 description. */
4420 for (const auto &alias : pending_aliases)
4421 alias.create (gdbarch);
dbbb1059 4422
ff371ec9
JW
4423 /* Compile command hooks. */
4424 set_gdbarch_gcc_target_options (gdbarch, riscv_gcc_target_options);
4425 set_gdbarch_gnu_triplet_regexp (gdbarch, riscv_gnu_triplet_regexp);
4426
61a5375b
AB
4427 /* Disassembler options support. */
4428 set_gdbarch_valid_disassembler_options (gdbarch,
4429 disassembler_options_riscv ());
4430 set_gdbarch_disassembler_options (gdbarch, &riscv_disassembler_options);
4431
2f79f2e7
AB
4432 /* SystemTap Support. */
4433 set_gdbarch_stap_is_single_operand (gdbarch, riscv_stap_is_single_operand);
4434 set_gdbarch_stap_register_indirection_prefixes
4435 (gdbarch, stap_register_indirection_prefixes);
4436 set_gdbarch_stap_register_indirection_suffixes
4437 (gdbarch, stap_register_indirection_suffixes);
4438
b9c7eed0
T
4439 /* Process record-replay */
4440 set_gdbarch_process_record (gdbarch, riscv_process_record);
4441
117a0e99
JW
4442 /* Hook in OS ABI-specific overrides, if they have been registered. */
4443 gdbarch_init_osabi (info, gdbarch);
4444
db3ad2f0
TT
4445 register_riscv_ravenscar_ops (gdbarch);
4446
dbbb1059
AB
4447 return gdbarch;
4448}
4449
5c720ed8
JW
4450/* This decodes the current instruction and determines the address of the
4451 next instruction. */
4452
4453static CORE_ADDR
4454riscv_next_pc (struct regcache *regcache, CORE_ADDR pc)
4455{
4456 struct gdbarch *gdbarch = regcache->arch ();
345bd07c 4457 const riscv_gdbarch_tdep *tdep
08106042 4458 = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
5c720ed8
JW
4459 struct riscv_insn insn;
4460 CORE_ADDR next_pc;
4461
4462 insn.decode (gdbarch, pc);
4463 next_pc = pc + insn.length ();
4464
4465 if (insn.opcode () == riscv_insn::JAL)
4466 next_pc = pc + insn.imm_signed ();
4467 else if (insn.opcode () == riscv_insn::JALR)
4468 {
4469 LONGEST source;
4470 regcache->cooked_read (insn.rs1 (), &source);
4471 next_pc = (source + insn.imm_signed ()) & ~(CORE_ADDR) 0x1;
4472 }
4473 else if (insn.opcode () == riscv_insn::BEQ)
4474 {
4475 LONGEST src1, src2;
4476 regcache->cooked_read (insn.rs1 (), &src1);
4477 regcache->cooked_read (insn.rs2 (), &src2);
4478 if (src1 == src2)
4479 next_pc = pc + insn.imm_signed ();
4480 }
4481 else if (insn.opcode () == riscv_insn::BNE)
4482 {
4483 LONGEST src1, src2;
4484 regcache->cooked_read (insn.rs1 (), &src1);
4485 regcache->cooked_read (insn.rs2 (), &src2);
4486 if (src1 != src2)
4487 next_pc = pc + insn.imm_signed ();
4488 }
4489 else if (insn.opcode () == riscv_insn::BLT)
4490 {
4491 LONGEST src1, src2;
4492 regcache->cooked_read (insn.rs1 (), &src1);
4493 regcache->cooked_read (insn.rs2 (), &src2);
4494 if (src1 < src2)
4495 next_pc = pc + insn.imm_signed ();
4496 }
4497 else if (insn.opcode () == riscv_insn::BGE)
4498 {
4499 LONGEST src1, src2;
4500 regcache->cooked_read (insn.rs1 (), &src1);
4501 regcache->cooked_read (insn.rs2 (), &src2);
4502 if (src1 >= src2)
4503 next_pc = pc + insn.imm_signed ();
4504 }
4505 else if (insn.opcode () == riscv_insn::BLTU)
4506 {
4507 ULONGEST src1, src2;
4508 regcache->cooked_read (insn.rs1 (), &src1);
4509 regcache->cooked_read (insn.rs2 (), &src2);
4510 if (src1 < src2)
4511 next_pc = pc + insn.imm_signed ();
4512 }
4513 else if (insn.opcode () == riscv_insn::BGEU)
4514 {
4515 ULONGEST src1, src2;
4516 regcache->cooked_read (insn.rs1 (), &src1);
4517 regcache->cooked_read (insn.rs2 (), &src2);
4518 if (src1 >= src2)
4519 next_pc = pc + insn.imm_signed ();
4520 }
e843807b
LS
4521 else if (insn.opcode () == riscv_insn::ECALL)
4522 {
4523 if (tdep->syscall_next_pc != nullptr)
4524 next_pc = tdep->syscall_next_pc (get_current_frame ());
4525 }
5c720ed8
JW
4526
4527 return next_pc;
4528}
4529
b273287f
YL
4530/* Return true if INSN is not a control transfer instruction and is allowed to
4531 appear in the middle of the lr/sc sequence. */
4532
4533static bool
4534riscv_insn_is_non_cti_and_allowed_in_atomic_sequence
4535 (const struct riscv_insn &insn)
4536{
4537 switch (insn.opcode ())
4538 {
4539 case riscv_insn::LUI:
4540 case riscv_insn::AUIPC:
4541 case riscv_insn::ADDI:
4542 case riscv_insn::ADDIW:
4543 case riscv_insn::SLTI:
4544 case riscv_insn::SLTIU:
4545 case riscv_insn::XORI:
4546 case riscv_insn::ORI:
4547 case riscv_insn::ANDI:
4548 case riscv_insn::SLLI:
4549 case riscv_insn::SLLIW:
4550 case riscv_insn::SRLI:
4551 case riscv_insn::SRLIW:
4552 case riscv_insn::SRAI:
4553 case riscv_insn::ADD:
4554 case riscv_insn::ADDW:
4555 case riscv_insn::SRAIW:
4556 case riscv_insn::SUB:
4557 case riscv_insn::SUBW:
4558 case riscv_insn::SLL:
4559 case riscv_insn::SLLW:
4560 case riscv_insn::SLT:
4561 case riscv_insn::SLTU:
4562 case riscv_insn::XOR:
4563 case riscv_insn::SRL:
4564 case riscv_insn::SRLW:
4565 case riscv_insn::SRA:
4566 case riscv_insn::SRAW:
4567 case riscv_insn::OR:
4568 case riscv_insn::AND:
4569 return true;
4570 }
4571
4572 return false;
4573}
4574
4575/* Return true if INSN is a direct branch instruction. */
4576
4577static bool
4578riscv_insn_is_direct_branch (const struct riscv_insn &insn)
4579{
4580 switch (insn.opcode ())
4581 {
4582 case riscv_insn::BEQ:
4583 case riscv_insn::BNE:
4584 case riscv_insn::BLT:
4585 case riscv_insn::BGE:
4586 case riscv_insn::BLTU:
4587 case riscv_insn::BGEU:
4588 case riscv_insn::JAL:
4589 return true;
4590 }
4591
4592 return false;
4593}
4594
5c720ed8
JW
4595/* We can't put a breakpoint in the middle of a lr/sc atomic sequence, so look
4596 for the end of the sequence and put the breakpoint there. */
4597
b273287f
YL
4598static std::vector<CORE_ADDR>
4599riscv_deal_with_atomic_sequence (struct regcache *regcache, CORE_ADDR pc)
5c720ed8
JW
4600{
4601 struct gdbarch *gdbarch = regcache->arch ();
4602 struct riscv_insn insn;
b273287f
YL
4603 CORE_ADDR cur_step_pc = pc, next_pc;
4604 std::vector<CORE_ADDR> next_pcs;
4605 bool found_valid_atomic_sequence = false;
4606 enum riscv_insn::opcode lr_opcode;
5c720ed8
JW
4607
4608 /* First instruction has to be a load reserved. */
4609 insn.decode (gdbarch, cur_step_pc);
b273287f
YL
4610 lr_opcode = insn.opcode ();
4611 if (lr_opcode != riscv_insn::LR_D && lr_opcode != riscv_insn::LR_W)
4612 return {};
4613
4614 /* The loop comprises only an LR/SC sequence and code to retry the sequence in
4615 the case of failure, and must comprise at most 16 instructions placed
4616 sequentially in memory. While our code tries to follow these restrictions,
4617 it has the following limitations:
4618
4619 (a) We expect the loop to start with an LR and end with a BNE.
4620 Apparently this does not cover all cases for a valid sequence.
4621 (b) The atomic limitations only apply to the code that is actually
4622 executed, so here again it's overly restrictive.
4623 (c) The lr/sc are required to be for the same target address, but this
4624 information is only known at runtime. Same as (b), in order to check
4625 this we will end up needing to simulate the sequence, which is more
4626 complicated than what we're doing right now.
4627
4628 Also note that we only expect a maximum of (16-2) instructions in the for
4629 loop as we have assumed the presence of LR and BNE at the beginning and end
4630 respectively. */
4631 for (int insn_count = 0; insn_count < 16 - 2; ++insn_count)
4632 {
4633 cur_step_pc += insn.length ();
4634 insn.decode (gdbarch, cur_step_pc);
5c720ed8 4635
b273287f
YL
4636 /* The dynamic code executed between lr/sc can only contain instructions
4637 from the base I instruction set, excluding loads, stores, backward
4638 jumps, taken backward branches, JALR, FENCE, FENCE.I, and SYSTEM
4639 instructions. If the C extension is supported, then compressed forms
4640 of the aforementioned I instructions are also permitted. */
5c720ed8 4641
b273287f
YL
4642 if (riscv_insn_is_non_cti_and_allowed_in_atomic_sequence (insn))
4643 continue;
4644 /* Look for a conditional branch instruction, check if it's taken forward
4645 or not. */
4646 else if (riscv_insn_is_direct_branch (insn))
4647 {
4648 if (insn.imm_signed () > 0)
4649 {
4650 next_pc = cur_step_pc + insn.imm_signed ();
4651 next_pcs.push_back (next_pc);
4652 }
4653 else
4654 break;
4655 }
4656 /* Look for a paired SC instruction which closes the atomic sequence. */
4657 else if ((insn.opcode () == riscv_insn::SC_D
4658 && lr_opcode == riscv_insn::LR_D)
4659 || (insn.opcode () == riscv_insn::SC_W
4660 && lr_opcode == riscv_insn::LR_W))
4661 found_valid_atomic_sequence = true;
4662 else
4663 break;
4664 }
4665
4666 if (!found_valid_atomic_sequence)
4667 return {};
5c720ed8
JW
4668
4669 /* Next instruction should be branch to start. */
4670 insn.decode (gdbarch, cur_step_pc);
4671 if (insn.opcode () != riscv_insn::BNE)
b273287f 4672 return {};
5c720ed8 4673 if (pc != (cur_step_pc + insn.imm_signed ()))
b273287f
YL
4674 return {};
4675 cur_step_pc += insn.length ();
5c720ed8 4676
b273287f
YL
4677 /* Remove all PCs that jump within the sequence. */
4678 auto matcher = [cur_step_pc] (const CORE_ADDR addr) -> bool
4679 {
4680 return addr < cur_step_pc;
4681 };
4682 auto it = std::remove_if (next_pcs.begin (), next_pcs.end (), matcher);
4683 next_pcs.erase (it, next_pcs.end ());
5c720ed8 4684
b273287f
YL
4685 next_pc = cur_step_pc;
4686 next_pcs.push_back (next_pc);
4687 return next_pcs;
5c720ed8
JW
4688}
4689
4690/* This is called just before we want to resume the inferior, if we want to
4691 single-step it but there is no hardware or kernel single-step support. We
4692 find the target of the coming instruction and breakpoint it. */
4693
4694std::vector<CORE_ADDR>
4695riscv_software_single_step (struct regcache *regcache)
4696{
b273287f
YL
4697 CORE_ADDR cur_pc = regcache_read_pc (regcache), next_pc;
4698 std::vector<CORE_ADDR> next_pcs
4699 = riscv_deal_with_atomic_sequence (regcache, cur_pc);
5c720ed8 4700
b273287f
YL
4701 if (!next_pcs.empty ())
4702 return next_pcs;
5c720ed8 4703
b273287f 4704 next_pc = riscv_next_pc (regcache, cur_pc);
5c720ed8
JW
4705
4706 return {next_pc};
4707}
4708
b5ffee31
AB
4709/* Create RISC-V specific reggroups. */
4710
4711static void
4712riscv_init_reggroups ()
4713{
4714 csr_reggroup = reggroup_new ("csr", USER_REGGROUP);
4715}
4716
6a9ad81c
AB
4717/* See riscv-tdep.h. */
4718
4719void
4720riscv_supply_regset (const struct regset *regset,
4721 struct regcache *regcache, int regnum,
4722 const void *regs, size_t len)
4723{
4724 regcache->supply_regset (regset, regnum, regs, len);
4725
4726 if (regnum == -1 || regnum == RISCV_ZERO_REGNUM)
4727 regcache->raw_supply_zeroed (RISCV_ZERO_REGNUM);
4728
4749b84b
AB
4729 struct gdbarch *gdbarch = regcache->arch ();
4730 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
4731
4732 if (regnum == -1
4733 || regnum == tdep->fflags_regnum
4734 || regnum == tdep->frm_regnum)
6a9ad81c
AB
4735 {
4736 int fcsr_regnum = RISCV_CSR_FCSR_REGNUM;
4737
4738 /* Ensure that FCSR has been read into REGCACHE. */
4739 if (regnum != -1)
4740 regcache->supply_regset (regset, fcsr_regnum, regs, len);
4741
4742 /* Grab the FCSR value if it is now in the regcache. We must check
4743 the status first as, if the register was not supplied by REGSET,
4744 this call will trigger a recursive attempt to fetch the
4745 registers. */
4746 if (regcache->get_register_status (fcsr_regnum) == REG_VALID)
4747 {
4749b84b
AB
4748 /* If we have an fcsr register then we should have fflags and frm
4749 too, either provided by the target, or provided as a pseudo
4750 register by GDB. */
4751 gdb_assert (tdep->fflags_regnum >= 0);
4752 gdb_assert (tdep->frm_regnum >= 0);
4753
6a9ad81c
AB
4754 ULONGEST fcsr_val;
4755 regcache->raw_read (fcsr_regnum, &fcsr_val);
4756
4757 /* Extract the fflags and frm values. */
4758 ULONGEST fflags_val = fcsr_val & 0x1f;
4759 ULONGEST frm_val = (fcsr_val >> 5) & 0x7;
4760
4749b84b
AB
4761 /* And supply these if needed. We can only supply real
4762 registers, so don't try to supply fflags or frm if they are
4763 implemented as pseudo-registers. */
4764 if ((regnum == -1 || regnum == tdep->fflags_regnum)
4765 && tdep->fflags_regnum < gdbarch_num_regs (gdbarch))
4766 regcache->raw_supply_integer (tdep->fflags_regnum,
6a9ad81c
AB
4767 (gdb_byte *) &fflags_val,
4768 sizeof (fflags_val),
4769 /* is_signed */ false);
4770
4749b84b
AB
4771 if ((regnum == -1 || regnum == tdep->frm_regnum)
4772 && tdep->frm_regnum < gdbarch_num_regs (gdbarch))
4773 regcache->raw_supply_integer (tdep->frm_regnum,
6a9ad81c
AB
4774 (gdb_byte *)&frm_val,
4775 sizeof (fflags_val),
4776 /* is_signed */ false);
4777 }
4778 }
4779}
4780
5fe70629 4781INIT_GDB_FILE (riscv_tdep)
dbbb1059 4782{
b5ffee31
AB
4783 riscv_init_reggroups ();
4784
dbbb1059
AB
4785 gdbarch_register (bfd_arch_riscv, riscv_gdbarch_init, NULL);
4786
dbbb1059
AB
4787 /* Add root prefix command for all "set debug riscv" and "show debug
4788 riscv" commands. */
f54bdb6d
SM
4789 add_setshow_prefix_cmd ("riscv", no_class,
4790 _("RISC-V specific debug commands."),
4791 _("RISC-V specific debug commands."),
4792 &setdebugriscvcmdlist, &showdebugriscvcmdlist,
4793 &setdebuglist, &showdebuglist);
dbbb1059 4794
4f6e0c44
AB
4795 add_setshow_boolean_cmd ("breakpoints", class_maintenance,
4796 &riscv_debug_breakpoints, _("\
f37bc8b1
JB
4797Set riscv breakpoint debugging."), _("\
4798Show riscv breakpoint debugging."), _("\
4799When non-zero, print debugging information for the riscv specific parts\n\
4800of the breakpoint mechanism."),
4f6e0c44
AB
4801 nullptr,
4802 show_riscv_debug_variable,
4803 &setdebugriscvcmdlist, &showdebugriscvcmdlist);
f37bc8b1 4804
4f6e0c44
AB
4805 add_setshow_boolean_cmd ("infcall", class_maintenance,
4806 &riscv_debug_infcall, _("\
dbbb1059
AB
4807Set riscv inferior call debugging."), _("\
4808Show riscv inferior call debugging."), _("\
4809When non-zero, print debugging information for the riscv specific parts\n\
4810of the inferior call mechanism."),
4f6e0c44
AB
4811 nullptr,
4812 show_riscv_debug_variable,
4813 &setdebugriscvcmdlist, &showdebugriscvcmdlist);
78a3b0fa 4814
4f6e0c44
AB
4815 add_setshow_boolean_cmd ("unwinder", class_maintenance,
4816 &riscv_debug_unwinder, _("\
78a3b0fa
AB
4817Set riscv stack unwinding debugging."), _("\
4818Show riscv stack unwinding debugging."), _("\
4f6e0c44 4819When on, print debugging information for the riscv specific parts\n\
78a3b0fa 4820of the stack unwinding mechanism."),
4f6e0c44
AB
4821 nullptr,
4822 show_riscv_debug_variable,
4823 &setdebugriscvcmdlist, &showdebugriscvcmdlist);
b5ffee31 4824
4f6e0c44
AB
4825 add_setshow_boolean_cmd ("gdbarch", class_maintenance,
4826 &riscv_debug_gdbarch, _("\
b5ffee31
AB
4827Set riscv gdbarch initialisation debugging."), _("\
4828Show riscv gdbarch initialisation debugging."), _("\
4829When non-zero, print debugging information for the riscv gdbarch\n\
4830initialisation process."),
4f6e0c44
AB
4831 nullptr,
4832 show_riscv_debug_variable,
4833 &setdebugriscvcmdlist, &showdebugriscvcmdlist);
dbbb1059
AB
4834
4835 /* Add root prefix command for all "set riscv" and "show riscv" commands. */
f54bdb6d
SM
4836 add_setshow_prefix_cmd ("riscv", no_class,
4837 _("RISC-V specific commands."),
4838 _("RISC-V specific commands."),
4839 &setriscvcmdlist, &showriscvcmdlist,
4840 &setlist, &showlist);
dbbb1059
AB
4841
4842
4843 use_compressed_breakpoints = AUTO_BOOLEAN_AUTO;
4844 add_setshow_auto_boolean_cmd ("use-compressed-breakpoints", no_class,
4845 &use_compressed_breakpoints,
4846 _("\
6a2dbb74 4847Set debugger's use of compressed breakpoints."), _("\
dbbb1059 4848Show debugger's use of compressed breakpoints."), _("\
f37bc8b1
JB
4849Debugging compressed code requires compressed breakpoints to be used. If\n\
4850left to 'auto' then gdb will use them if the existing instruction is a\n\
4851compressed instruction. If that doesn't give the correct behavior, then\n\
4852this option can be used."),
dbbb1059
AB
4853 NULL,
4854 show_use_compressed_breakpoints,
4855 &setriscvcmdlist,
4856 &showriscvcmdlist);
2047479c
CW
4857
4858 add_setshow_boolean_cmd ("numeric-register-names", no_class,
4859 &numeric_register_names,
4860 _("\
4861Set displaying registers with numeric names instead of abi names."), _("\
4862Show whether registers are displayed with numeric names instead of abi names."),
4863 _("\
4864When enabled, registers will be shown with their numeric names (such as x28)\n\
4865instead of their abi names (such as t0).\n\
4866Also consider using the 'set disassembler-options numeric' command for the\n\
4867equivalent change in the disassembler output."),
4868 NULL,
4869 show_numeric_register_names,
4870 &setriscvcmdlist,
4871 &showriscvcmdlist);
dbbb1059 4872}
b9c7eed0
T
4873
4874/* A wrapper to read register under number regnum to address addr.
4875 Returns false if error happened and makes warning. */
4876
4877static bool
4878try_read (struct regcache *regcache, int regnum, ULONGEST &addr)
4879{
4880 gdb_assert (regcache != nullptr);
4881
4882 if (regcache->raw_read (regnum, &addr)
4883 != register_status::REG_VALID)
4884 {
5f02f0fa 4885 warning (_("Can not read at address %s"), hex_string (addr));
b9c7eed0
T
4886 return false;
4887 }
4888 return true;
4889}
4890
4891/* Helper class to record instruction. */
4892
4893class riscv_recorded_insn final
4894{
4895public:
4896 /* Type for saved register. */
4897 using regnum_type = int;
4898 /* Type for saved memory. First is address, second is length. */
4899 using memory_type = std::pair<CORE_ADDR, int>;
4900
4901 /* Enum class that represents which type does recording belong to. */
4902 enum class record_type
4903 {
4904 UNKNOWN,
4905 ORDINARY,
4906
4907 /* Corner cases. */
4908 ECALL,
4909 EBREAK,
4910 };
4911
4912private:
4913 /* Type for set of registers that need to be saved. */
4914 using recorded_regs = std::vector<regnum_type>;
4915 /* Type for set of memory records that need to be saved. */
4916 using recorded_mems = std::vector<memory_type>;
4917
4918 /* Type for memory address, extracted from memory_type. */
4919 using mem_addr = decltype (std::declval<memory_type> ().first);
4920 /* Type for memory length, extracted from memory_type. */
4921 using mem_len = decltype (std::declval<memory_type> ().second);
4922
4923 /* Record type of current instruction. */
4924 record_type m_record_type = record_type::UNKNOWN;
4925
4926 /* Flag that represents was there an error in current recording. */
4927 bool m_error_occured = false;
4928
4929 /* Set of registers that need to be recorded. */
4930 recorded_regs m_regs;
4931 /* Set of memory chunks that need to be recorded. */
4932 recorded_mems m_mems;
4933
4934 /* Width in bytes of the general purpose registers for GDBARCH,
4935 where recording is happening. */
4936 int m_xlen = 0;
4937
4938 /* Helper for decode 16-bit instruction RS1. */
4939 static regnum_type
4940 decode_crs1_short (ULONGEST opcode) noexcept
4941 {
4942 return ((opcode >> OP_SH_CRS1S) & OP_MASK_CRS1S) + 8;
4943 }
4944
4945 /* Helper for decode 16-bit instruction RS2. */
4946 static regnum_type
4947 decode_crs2_short (ULONGEST opcode) noexcept
4948 {
4949 return ((opcode >> OP_SH_CRS2S) & OP_MASK_CRS2S) + 8;
4950 }
4951
4952 /* Helper for decode 16-bit instruction CRS1. */
4953 static regnum_type
4954 decode_crs1 (ULONGEST opcode) noexcept
4955 {
4956 return ((opcode >> OP_SH_RD) & OP_MASK_RD);
4957 }
4958
4959 /* Helper for decode 16-bit instruction CRS2. */
4960 static regnum_type
4961 decode_crs2 (ULONGEST opcode) noexcept
4962 {
4963 return ((opcode >> OP_SH_CRS2) & OP_MASK_CRS2);
4964 }
4965
4966 /* Helper for decode 32-bit instruction RD. */
4967 static regnum_type
4968 decode_rd (ULONGEST ival) noexcept
4969 {
4970 return (ival >> OP_SH_RD) & OP_MASK_RD;
4971 }
4972
4973 /* Helper for decode 32-bit instruction RS1. */
4974 static regnum_type
4975 decode_rs1 (ULONGEST ival) noexcept
4976 {
4977 return (ival >> OP_SH_RS1) & OP_MASK_RS1;
4978 }
4979
4980 /* Helper for decode 32-bit instruction RS2. */
4981 static regnum_type
4982 decode_rs2 (ULONGEST ival) noexcept
4983 {
4984 return (ival >> OP_SH_RS2) & OP_MASK_RS2;
4985 }
4986
4987 /* Helper for decode 32-bit instruction CSR. */
4988 static regnum_type
4989 decode_csr (ULONGEST ival) noexcept
4990 {
4991 return (ival >> OP_SH_CSR) & OP_MASK_CSR;
4992 }
4993
4994 /* Set ordinary record type. Always returns true. */
4995 bool
4996 set_ordinary_record_type () noexcept
4997 {
4998 m_record_type = record_type::ORDINARY;
4999 return true;
5000 }
5001
5002 /* Set error happened. Always returns false. */
5003 bool
5004 set_error () noexcept
5005 {
5006 m_error_occured = true;
5007 return false;
5008 }
5009
5010 /* Check if current recording has an error. */
5011 bool
5012 has_error () const noexcept
5013 {
5014 return m_error_occured;
5015 }
5016
5017 /* Reads register. Sets error and returns false if error happened. */
5018 bool
5019 read_reg (struct regcache *regcache, regnum_type reg,
5020 ULONGEST &addr) noexcept
5021 {
5022 gdb_assert (regcache != nullptr);
5023
5024 if (!try_read (regcache, reg, addr))
5025 return set_error ();
5026 return true;
5027 }
5028
5029 /* Save register. Returns true or aborts if exception happened. */
5030 bool
5031 save_reg (regnum_type regnum) noexcept
5032 {
5033 m_regs.emplace_back (regnum);
5034 return true;
5035 }
5036
5037 /* Save memory chunk. Returns true or aborts if exception happened. */
5038 bool
5039 save_mem (mem_addr addr, mem_len len) noexcept
5040 {
5041 m_mems.emplace_back (addr, len);
5042 return true;
5043 }
5044
5045 /* Returns true if instruction needs only saving pc. */
5046 static bool
5047 need_save_pc (ULONGEST ival) noexcept
5048 {
5049 return (is_beq_insn (ival) || is_bne_insn (ival) || is_blt_insn (ival)
5050 || is_bge_insn (ival) || is_bltu_insn (ival) || is_bgeu_insn (ival)
5051 || is_fence_insn (ival) || is_pause_insn (ival)
5052 || is_fence_i_insn (ival));
5053 }
5054
5055 /* Returns true if instruction is classified. */
5056 bool
5057 try_save_pc (ULONGEST ival) noexcept
5058 {
5059 if (!need_save_pc (ival))
5060 return false;
5061
5062 return set_ordinary_record_type ();
5063 }
5064
5065 /* Returns true if instruction needs only saving pc and rd. */
5066 static bool
5067 need_save_pc_rd (ULONGEST ival) noexcept
5068 {
5069 return (is_lui_insn (ival) || is_auipc_insn (ival) || is_jal_insn (ival)
5070 || is_jalr_insn (ival) || is_lb_insn (ival) || is_lh_insn (ival)
5071 || is_lw_insn (ival) || is_lbu_insn (ival) || is_lhu_insn (ival)
5072 || is_addi_insn (ival) || is_slti_insn (ival)
5073 || is_sltiu_insn (ival) || is_xori_insn (ival) || is_ori_insn (ival)
5074 || is_andi_insn (ival) || is_slli_rv32_insn (ival)
5075 || is_srli_rv32_insn (ival) || is_srai_rv32_insn (ival)
5076 || is_add_insn (ival) || is_sub_insn (ival) || is_sll_insn (ival)
5077 || is_slt_insn (ival) || is_sltu_insn (ival) || is_xor_insn (ival)
5078 || is_srl_insn (ival) || is_sra_insn (ival) || is_or_insn (ival)
5079 || is_and_insn (ival) || is_lwu_insn (ival) || is_ld_insn (ival)
5080 || is_slli_insn (ival) || is_srli_insn (ival) || is_srai_insn (ival)
5081 || is_addiw_insn (ival) || is_slliw_insn (ival)
5082 || is_srliw_insn (ival) || is_sraiw_insn (ival)
5083 || is_addw_insn (ival) || is_subw_insn (ival) || is_sllw_insn (ival)
5084 || is_srlw_insn (ival) || is_sraw_insn (ival) || is_mul_insn (ival)
5085 || is_mulh_insn (ival) || is_mulhsu_insn (ival)
5086 || is_mulhu_insn (ival) || is_div_insn (ival) || is_divu_insn (ival)
5087 || is_rem_insn (ival) || is_remu_insn (ival) || is_mulw_insn (ival)
5088 || is_divw_insn (ival) || is_divuw_insn (ival)
5089 || is_remw_insn (ival) || is_remuw_insn (ival)
5090 || is_lr_w_insn (ival) || is_lr_d_insn (ival)
5091 || is_fcvt_w_s_insn (ival) || is_fcvt_wu_s_insn (ival)
5092 || is_fmv_x_s_insn (ival) || is_feq_s_insn (ival)
5093 || is_flt_s_insn (ival) || is_fle_s_insn (ival)
5094 || is_fclass_s_insn (ival) || is_fcvt_l_s_insn (ival)
5095 || is_fcvt_lu_s_insn (ival) || is_feq_d_insn (ival)
5096 || is_flt_d_insn (ival) || is_fle_d_insn (ival)
5097 || is_fclass_d_insn (ival) || is_fcvt_w_d_insn (ival)
5098 || is_fcvt_wu_d_insn (ival) || is_fcvt_l_d_insn (ival)
5099 || is_fcvt_lu_d_insn (ival) || is_fmv_x_d_insn (ival));
5100 }
5101
5102 /* Returns true if instruction is classified. This function can set
5103 m_error_occured. */
5104 bool
5105 try_save_pc_rd (ULONGEST ival) noexcept
5106 {
5107 if (!need_save_pc_rd (ival))
5108 return false;
5109
5110 return (!save_reg (decode_rd (ival)) || set_ordinary_record_type ());
5111 }
5112
5113 /* Returns true if instruction needs only saving pc and
5114 floating point rd. */
5115 static bool
5116 need_save_pc_fprd (ULONGEST ival) noexcept
5117 {
5118 return (is_flw_insn (ival) || is_fmadd_s_insn (ival)
5119 || is_fmsub_s_insn (ival) || is_fnmsub_s_insn (ival)
5120 || is_fnmadd_s_insn (ival) || is_fadd_s_insn (ival)
5121 || is_fsub_s_insn (ival) || is_fmul_s_insn (ival)
5122 || is_fdiv_s_insn (ival) || is_fsqrt_s_insn (ival)
5123 || is_fsgnj_s_insn (ival) || is_fsgnjn_s_insn (ival)
5124 || is_fsgnjx_s_insn (ival) || is_fmin_s_insn (ival)
5125 || is_fmax_s_insn (ival) || is_fcvt_s_w_insn (ival)
5126 || is_fcvt_s_wu_insn (ival) || is_fmv_s_x_insn (ival)
5127 || is_fcvt_s_l_insn (ival) || is_fcvt_s_lu_insn (ival)
5128 || is_fld_insn (ival) || is_fmadd_d_insn (ival)
5129 || is_fmsub_d_insn (ival) || is_fnmsub_d_insn (ival)
5130 || is_fnmadd_d_insn (ival) || is_fadd_d_insn (ival)
5131 || is_fsub_d_insn (ival) || is_fmul_d_insn (ival)
5132 || is_fdiv_d_insn (ival) || is_fsqrt_d_insn (ival)
5133 || is_fsgnj_d_insn (ival) || is_fsgnjn_d_insn (ival)
5134 || is_fsgnjx_d_insn (ival) || is_fmin_d_insn (ival)
5135 || is_fmax_d_insn (ival) || is_fcvt_s_d_insn (ival)
5136 || is_fcvt_d_s_insn (ival) || is_fcvt_d_w_insn (ival)
5137 || is_fcvt_d_wu_insn (ival) || is_fcvt_d_l_insn (ival)
5138 || is_fcvt_d_lu_insn (ival) || is_fmv_d_x_insn (ival));
5139 }
5140
5141 /* Returns true if instruction is classified. This function can set
5142 m_error_occured. */
5143 bool
5144 try_save_pc_fprd (ULONGEST ival) noexcept
5145 {
5146 if (!need_save_pc_fprd (ival))
5147 return false;
5148
5149 return (!save_reg (RISCV_FIRST_FP_REGNUM + decode_rd (ival))
5150 || set_ordinary_record_type ());
5151 }
5152
5153 /* Returns true if instruction needs only saving pc, rd and csr. */
5154 static bool
5155 need_save_pc_rd_csr (ULONGEST ival) noexcept
5156 {
5157 return (is_csrrw_insn (ival) || is_csrrs_insn (ival) || is_csrrc_insn (ival)
5158 || is_csrrwi_insn (ival) || is_csrrsi_insn (ival)
fc616d42 5159 || is_csrrci_insn (ival));
b9c7eed0
T
5160 }
5161
5162 /* Returns true if instruction is classified. This function can set
5163 m_error_occured. */
5164 bool
5165 try_save_pc_rd_csr (ULONGEST ival) noexcept
5166 {
5167 if (!need_save_pc_rd_csr (ival))
5168 return false;
5169
5170 return (!save_reg (decode_rd (ival))
5171 || !save_reg (RISCV_FIRST_CSR_REGNUM + decode_csr (ival))
5172 || set_ordinary_record_type ());
5173 }
5174
5175 /* Returns the size of the memory chunk that needs to be saved if the
5176 instruction belongs to the group that needs only saving pc and memory.
5177 Otherwise returns 0. */
5178 static mem_len
5179 need_save_pc_mem (ULONGEST ival) noexcept
5180 {
5181 if (is_sb_insn (ival))
5182 return 1;
5183 if (is_sh_insn (ival))
5184 return 2;
5185 if (is_sw_insn (ival) || is_fsw_insn (ival))
5186 return 4;
5187 if (is_sd_insn (ival) || is_fsd_insn (ival))
5188 return 8;
5189 return 0;
5190 }
5191
5192 /* Returns true if instruction is classified. This function can set
5193 m_error_occured. */
5194 bool
5195 try_save_pc_mem (ULONGEST ival, struct regcache *regcache) noexcept
5196 {
5197 gdb_assert (regcache != nullptr);
5198
5199 mem_addr addr = mem_addr{};
5200 mem_len len = need_save_pc_mem (ival);
5201 if (len <= 0)
5202 return false;
5203
5204 mem_len offset = EXTRACT_STYPE_IMM (ival);
5205 return (!read_reg (regcache, decode_rs1 (ival), addr)
5206 || !save_mem (addr + offset, len) || set_ordinary_record_type ());
5207 }
5208
5209 /* Returns the size of the memory chunk that needs to be saved if the
5210 instruction belongs to the group that needs only saving pc, rd and memory.
5211 Otherwise returns 0. */
5212 static mem_len
5213 need_save_pc_rd_mem (ULONGEST ival) noexcept
5214 {
5215 if (is_sc_w_insn (ival) || is_amoswap_w_insn (ival)
5216 || is_amoadd_w_insn (ival) || is_amoxor_w_insn (ival)
5217 || is_amoand_w_insn (ival) || is_amoor_w_insn (ival)
5218 || is_amomin_w_insn (ival) || is_amomax_w_insn (ival)
5219 || is_amominu_w_insn (ival) || is_amomaxu_w_insn (ival))
5220 return 4;
5221 if (is_sc_d_insn (ival) || is_amoswap_d_insn (ival)
5222 || is_amoadd_d_insn (ival) || is_amoxor_d_insn (ival)
5223 || is_amoand_d_insn (ival) || is_amoor_d_insn (ival)
5224 || is_amomin_d_insn (ival) || is_amomax_d_insn (ival)
5225 || is_amominu_d_insn (ival) || is_amomaxu_d_insn (ival))
5226 return 8;
5227 return 0;
5228 }
5229
5230 /* Returns true if instruction is classified. This function can set
5231 m_error_occured. */
5232 bool
5233 try_save_pc_rd_mem (ULONGEST ival, struct regcache *regcache) noexcept
5234 {
5235 gdb_assert (regcache != nullptr);
5236
5237 mem_len len = need_save_pc_rd_mem (ival);
5238 mem_addr addr = 0;
5239 if (len <= 0)
5240 return false;
5241
5242 return (!read_reg (regcache, decode_rs1 (ival), addr)
5243 || !save_mem (addr, len) || !save_reg (decode_rd (ival))
5244 || set_ordinary_record_type ());
5245 }
5246
5247 /* Returns true if instruction is successfully recordered. The length of
5248 the instruction must be equal 4 bytes. */
5249 bool
5250 record_insn_len4 (ULONGEST ival, struct regcache *regcache) noexcept
5251 {
5252 gdb_assert (regcache != nullptr);
5253
5254 if (is_ecall_insn (ival))
5255 {
5256 m_record_type = record_type::ECALL;
5257 return true;
5258 }
5259
5260 if (is_ebreak_insn (ival))
5261 {
5262 m_record_type = record_type::EBREAK;
5263 return true;
5264 }
5265
5266 if (try_save_pc (ival) || try_save_pc_rd (ival) || try_save_pc_fprd (ival)
5267 || try_save_pc_rd_csr (ival) || try_save_pc_mem (ival, regcache)
5268 || try_save_pc_rd_mem (ival, regcache))
5269 return !has_error ();
5270
5f02f0fa
TV
5271 warning (_("Currently this instruction with len 4(%s) is unsupported"),
5272 hex_string (ival));
b9c7eed0
T
5273 return false;
5274 }
5275
5276 /* Returns true if instruction is successfully recordered. The length of
5277 the instruction must be equal 2 bytes. */
5278 bool
5279 record_insn_len2 (ULONGEST ival, struct regcache *regcache) noexcept
5280 {
5281 gdb_assert (regcache != nullptr);
5282
5283 mem_addr addr = mem_addr{};
5284
5285 /* The order here is very important, because
5286 opcodes of some instructions may be the same. */
5287
5288 if (is_c_addi4spn_insn (ival) || is_c_lw_insn (ival)
5289 || (m_xlen == 8 && is_c_ld_insn (ival)))
5290 return (!save_reg (decode_crs2_short (ival))
5291 || set_ordinary_record_type ());
5292
5293 if (is_c_fld_insn (ival) || (m_xlen == 4 && is_c_flw_insn (ival)))
5294 return (!save_reg (RISCV_FIRST_FP_REGNUM + decode_crs2_short (ival))
5295 || set_ordinary_record_type ());
5296
5297 if (is_c_fsd_insn (ival) || (m_xlen == 8 && is_c_sd_insn (ival)))
5298 {
5299 ULONGEST offset = ULONGEST{EXTRACT_CLTYPE_LD_IMM (ival)};
5300 return (!read_reg (regcache, decode_crs1_short (ival), addr)
5301 || !save_mem (addr + offset, 8) || set_ordinary_record_type ());
5302 }
5303
5304 if ((m_xlen == 4 && is_c_fsw_insn (ival)) || is_c_sw_insn (ival))
5305 {
5306 ULONGEST offset = ULONGEST{EXTRACT_CLTYPE_LW_IMM (ival)};
5307 return (!read_reg (regcache, decode_crs1_short (ival), addr)
5308 || !save_mem (addr + offset, 4) || set_ordinary_record_type ());
5309 }
5310
5311 if (is_c_nop_insn (ival))
5312 return set_ordinary_record_type ();
5313
5314 if (is_c_addi_insn (ival))
5315 return (!save_reg (decode_crs1 (ival)) || set_ordinary_record_type ());
5316
5317 if (m_xlen == 4 && is_c_jal_insn (ival))
5318 return (!save_reg (RISCV_RA_REGNUM) || set_ordinary_record_type ());
5319
5320 if ((m_xlen == 8 && is_c_addiw_insn (ival)) || is_c_li_insn (ival))
5321 return (!save_reg (decode_crs1 (ival)) || set_ordinary_record_type ());
5322
5323 if (is_c_addi16sp_insn (ival))
5324 return (!save_reg (RISCV_SP_REGNUM) || set_ordinary_record_type ());
5325
5326 if (is_c_lui_insn (ival))
5327 return (!save_reg (decode_crs1 (ival)) || set_ordinary_record_type ());
5328
5329 if (is_c_srli_insn (ival) || is_c_srai_insn (ival) || is_c_andi_insn (ival)
5330 || is_c_sub_insn (ival) || is_c_xor_insn (ival) || is_c_or_insn (ival)
5331 || is_c_and_insn (ival) || (m_xlen == 8 && is_c_subw_insn (ival))
5332 || (m_xlen == 8 && is_c_addw_insn (ival)))
5333 return (!save_reg (decode_crs1_short (ival))
5334 || set_ordinary_record_type ());
5335
5336 if (is_c_j_insn (ival) || is_c_beqz_insn (ival) || is_c_bnez_insn (ival))
5337 return set_ordinary_record_type ();
5338
5339 if (is_c_slli_insn (ival))
5340 return (!save_reg (decode_crs1 (ival)) || set_ordinary_record_type ());
5341
5342 if (is_c_fldsp_insn (ival) || (m_xlen == 4 && is_c_flwsp_insn (ival)))
5343 return (!save_reg (RISCV_FIRST_FP_REGNUM + decode_crs1 (ival))
5344 || set_ordinary_record_type ());
5345
5346 if (is_c_lwsp_insn (ival) || (m_xlen == 8 && is_c_ldsp_insn (ival)))
5347 return (!save_reg (decode_crs1 (ival)) || set_ordinary_record_type ());
5348
5349 if (is_c_jr_insn (ival))
5350 return set_ordinary_record_type ();
5351
5352 if (is_c_mv_insn (ival))
5353 return (!save_reg (decode_crs1 (ival)) || set_ordinary_record_type ());
5354
5355 if (is_c_ebreak_insn (ival))
5356 {
5357 m_record_type = record_type::EBREAK;
5358 return true;
5359 }
5360
5361 if (is_c_jalr_insn (ival))
5362 return (!save_reg (RISCV_RA_REGNUM) || set_ordinary_record_type ());
5363
5364 if (is_c_add_insn (ival))
5365 return (!save_reg (decode_crs1 (ival)) || set_ordinary_record_type ());
5366
5367 if (is_c_fsdsp_insn (ival) || (m_xlen == 8 && is_c_sdsp_insn (ival)))
5368 {
5369 ULONGEST offset = ULONGEST{EXTRACT_CSSTYPE_SDSP_IMM (ival)};
5370 return (!read_reg (regcache, RISCV_SP_REGNUM, addr)
5371 || !save_mem (addr + offset, 8) || set_ordinary_record_type ());
5372 }
5373
5374 if (is_c_swsp_insn (ival) || (m_xlen == 4 && is_c_fswsp_insn (ival)))
5375 {
5376 ULONGEST offset = ULONGEST{EXTRACT_CSSTYPE_SWSP_IMM (ival)};
5377 return (!read_reg (regcache, RISCV_SP_REGNUM, addr)
5378 || !save_mem (addr + offset, 4) || set_ordinary_record_type ());
5379 }
5380
5f02f0fa
TV
5381 warning (_("Currently this instruction with len 2(%s) is unsupported"),
5382 hex_string (ival));
b9c7eed0
T
5383 return false;
5384 }
5385
5386public:
5387 /* Iterator for registers that need to be recorded. */
5388 using regs_iter = recorded_regs::const_iterator;
5389 /* Iterator for memory chunks that need to be recorded. */
5390 using mems_iter = recorded_mems::const_iterator;
5391
5392 /* Record instruction at address addr. Returns false if error happened. */
5393 bool
5394 record (gdbarch *gdbarch, struct regcache *regcache, CORE_ADDR addr) noexcept
5395 {
5396 gdb_assert (gdbarch != nullptr);
5397 gdb_assert (regcache != nullptr);
5398
5399 int m_length = 0;
5400 m_xlen = riscv_isa_xlen (gdbarch);
5401 ULONGEST ival = riscv_insn::fetch_instruction (gdbarch, addr, &m_length);
5402 if (!save_reg (RISCV_PC_REGNUM))
5403 return false;
5404
5405 if (m_length == 4)
5406 return record_insn_len4 (ival, regcache);
5407
5408 if (m_length == 2)
5409 return record_insn_len2 (ival, regcache);
5410
5411 /* 6 bytes or more. If the instruction is longer than 8 bytes, we don't
5412 have full instruction bits in ival. At least, such long instructions
5413 are not defined yet, so just ignore it. */
5414 gdb_assert (m_length > 0 && m_length % 2 == 0);
5415
5f02f0fa
TV
5416 warning (_("Can not record unknown instruction (opcode = %s)"),
5417 hex_string (ival));
b9c7eed0
T
5418 return false;
5419 }
5420
5421 /* Get record type of instruction. */
5422 record_type
5423 get_record_type () const noexcept
5424 {
5425 return m_record_type;
5426 }
5427
5428 /* Returns an iterator to the beginning of the registers that need
5429 to be saved. */
5430 regs_iter
5431 regs_begin () const noexcept
5432 {
5433 return m_regs.begin ();
5434 }
5435
5436 /* Returns an iterator to the end of the registers that need
5437 to be saved. */
5438 regs_iter
5439 regs_end () const noexcept
5440 {
5441 return m_regs.end ();
5442 }
5443
5444 /* Returns an iterator to the beginning of the memory chunks that need
5445 to be saved. */
5446 mems_iter
5447 mems_begin () const noexcept
5448 {
5449 return m_mems.begin ();
5450 }
5451
5452 /* Returns an iterator to the end of the memory chunks that need
5453 to be saved. */
5454 mems_iter
5455 mems_end () const noexcept
5456 {
5457 return m_mems.end ();
5458 }
5459};
5460
5461/* A helper function to record instruction using record API. */
5462
5463static int
5464riscv_record_insn_details (struct gdbarch *gdbarch, struct regcache *regcache,
5465 const riscv_recorded_insn &insn)
5466{
5467 gdb_assert (gdbarch != nullptr);
5468 gdb_assert (regcache != nullptr);
5469
5470 riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
5471 auto regs_begin = insn.regs_begin ();
5472 auto regs_end = insn.regs_end ();
5473 if (std::any_of (regs_begin,
5474 regs_end,
5475 [&regcache] (auto &&reg_it)
5476 {
5477 return record_full_arch_list_add_reg (regcache, reg_it);
5478 }))
5479 return -1;
5480
5481 auto mems_begin = insn.mems_begin ();
5482 auto mems_end = insn.mems_end ();
5483 if (std::any_of (mems_begin,
5484 mems_end,
5485 [] (auto &&mem_it)
5486 {
5487 return record_full_arch_list_add_mem (mem_it.first,
5488 mem_it.second);
5489 }))
5490 return -1;
5491
5492 switch (insn.get_record_type ())
5493 {
5494 case riscv_recorded_insn::record_type::ORDINARY:
5495 break;
5496
5497 case riscv_recorded_insn::record_type::ECALL:
5498 {
5499 if (!tdep->riscv_syscall_record)
5500 {
5501 warning (_("Syscall record is not supported"));
5502 return -1;
5503 }
5504 ULONGEST reg_val = ULONGEST{};
5505 if (!try_read (regcache, RISCV_A7_REGNUM, reg_val))
5506 return -1;
5507 return tdep->riscv_syscall_record (regcache, reg_val);
5508 }
5509
5510 case riscv_recorded_insn::record_type::EBREAK:
5511 break;
5512
5513 default:
5514 return -1;
5515 }
5516 return 0;
5517}
5518
5519/* Parse the current instruction and record the values of the registers and
5520 memory that will be changed in current instruction to record_arch_list.
5521 Return -1 if something is wrong. */
5522
5523int
5524riscv_process_record (struct gdbarch *gdbarch, struct regcache *regcache,
5525 CORE_ADDR addr)
5526{
5527 gdb_assert (gdbarch != nullptr);
5528 gdb_assert (regcache != nullptr);
5529
5530 riscv_recorded_insn insn;
5531 if (!insn.record (gdbarch, regcache, addr))
5532 {
5533 record_full_arch_list_add_end ();
5534 return -1;
5535 }
5536
5537 int ret_val = riscv_record_insn_details (gdbarch, regcache, insn);
5538
5539 if (record_full_arch_list_add_end ())
5540 return -1;
5541
5542 return ret_val;
5543}