Automatic date update in version.in
[binutils-gdb.git] / gdb / riscv-tdep.c
blobbfd93c65d22285765c03fc7f098abf651b6654b2
1 /* Target-dependent code for the RISC-V architecture, for GDB.
3 Copyright (C) 2018-2021 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
20 #include "defs.h"
21 #include "frame.h"
22 #include "inferior.h"
23 #include "symtab.h"
24 #include "value.h"
25 #include "gdbcmd.h"
26 #include "language.h"
27 #include "gdbcore.h"
28 #include "symfile.h"
29 #include "objfiles.h"
30 #include "gdbtypes.h"
31 #include "target.h"
32 #include "arch-utils.h"
33 #include "regcache.h"
34 #include "osabi.h"
35 #include "riscv-tdep.h"
36 #include "block.h"
37 #include "reggroups.h"
38 #include "opcode/riscv.h"
39 #include "elf/riscv.h"
40 #include "elf-bfd.h"
41 #include "symcat.h"
42 #include "dis-asm.h"
43 #include "frame-unwind.h"
44 #include "frame-base.h"
45 #include "trad-frame.h"
46 #include "infcall.h"
47 #include "floatformat.h"
48 #include "remote.h"
49 #include "target-descriptions.h"
50 #include "dwarf2/frame.h"
51 #include "user-regs.h"
52 #include "valprint.h"
53 #include "gdbsupport/common-defs.h"
54 #include "opcode/riscv-opc.h"
55 #include "cli/cli-decode.h"
56 #include "observable.h"
57 #include "prologue-value.h"
58 #include "arch/riscv.h"
59 #include "riscv-ravenscar-thread.h"
61 /* The stack must be 16-byte aligned. */
62 #define SP_ALIGNMENT 16
64 /* The biggest alignment that the target supports. */
65 #define BIGGEST_ALIGNMENT 16
67 /* Define a series of is_XXX_insn functions to check if the value INSN
68 is an instance of instruction XXX. */
69 #define DECLARE_INSN(INSN_NAME, INSN_MATCH, INSN_MASK) \
70 static inline bool is_ ## INSN_NAME ## _insn (long insn) \
71 { \
72 return (insn & INSN_MASK) == INSN_MATCH; \
74 #include "opcode/riscv-opc.h"
75 #undef DECLARE_INSN
77 /* When this is set to non-zero debugging information about breakpoint
78 kinds will be printed. */
80 static unsigned int riscv_debug_breakpoints = 0;
82 /* When this is set to non-zero debugging information about inferior calls
83 will be printed. */
85 static unsigned int riscv_debug_infcall = 0;
87 /* When this is set to non-zero debugging information about stack unwinding
88 will be printed. */
90 static unsigned int riscv_debug_unwinder = 0;
92 /* When this is set to non-zero debugging information about gdbarch
93 initialisation will be printed. */
95 static unsigned int riscv_debug_gdbarch = 0;
97 /* The names of the RISC-V target description features. */
98 const char *riscv_feature_name_csr = "org.gnu.gdb.riscv.csr";
99 static const char *riscv_feature_name_cpu = "org.gnu.gdb.riscv.cpu";
100 static const char *riscv_feature_name_fpu = "org.gnu.gdb.riscv.fpu";
101 static const char *riscv_feature_name_virtual = "org.gnu.gdb.riscv.virtual";
102 static const char *riscv_feature_name_vector = "org.gnu.gdb.riscv.vector";
104 /* Cached information about a frame. */
106 struct riscv_unwind_cache
108 /* The register from which we can calculate the frame base. This is
109 usually $sp or $fp. */
110 int frame_base_reg;
112 /* The offset from the current value in register FRAME_BASE_REG to the
113 actual frame base address. */
114 int frame_base_offset;
116 /* Information about previous register values. */
117 trad_frame_saved_reg *regs;
119 /* The id for this frame. */
120 struct frame_id this_id;
122 /* The base (stack) address for this frame. This is the stack pointer
123 value on entry to this frame before any adjustments are made. */
124 CORE_ADDR frame_base;
127 /* RISC-V specific register group for CSRs. */
129 static reggroup *csr_reggroup = NULL;
131 /* Callback function for user_reg_add. */
133 static struct value *
134 value_of_riscv_user_reg (struct frame_info *frame, const void *baton)
136 const int *reg_p = (const int *) baton;
137 return value_of_register (*reg_p, frame);
140 /* Information about a register alias that needs to be set up for this
141 target. These are collected when the target's XML description is
142 analysed, and then processed later, once the gdbarch has been created. */
144 class riscv_pending_register_alias
146 public:
147 /* Constructor. */
149 riscv_pending_register_alias (const char *name, const void *baton)
150 : m_name (name),
151 m_baton (baton)
152 { /* Nothing. */ }
154 /* Convert this into a user register for GDBARCH. */
156 void create (struct gdbarch *gdbarch) const
158 user_reg_add (gdbarch, m_name, value_of_riscv_user_reg, m_baton);
161 private:
162 /* The name for this alias. */
163 const char *m_name;
165 /* The baton value for passing to user_reg_add. This must point to some
166 data that will live for at least as long as the gdbarch object to
167 which the user register is attached. */
168 const void *m_baton;
171 /* A set of registers that we expect to find in a tdesc_feature. These
172 are use in RISCV_GDBARCH_INIT when processing the target description. */
174 struct riscv_register_feature
176 explicit riscv_register_feature (const char *feature_name)
177 : m_feature_name (feature_name)
178 { /* Delete. */ }
180 riscv_register_feature () = delete;
181 DISABLE_COPY_AND_ASSIGN (riscv_register_feature);
183 /* Information for a single register. */
184 struct register_info
186 /* The GDB register number for this register. */
187 int regnum;
189 /* List of names for this register. The first name in this list is the
190 preferred name, the name GDB should use when describing this
191 register. */
192 std::vector<const char *> names;
194 /* Look in FEATURE for a register with a name from this classes names
195 list. If the register is found then register its number with
196 TDESC_DATA and add all its aliases to the ALIASES list.
197 PREFER_FIRST_NAME_P is used when deciding which aliases to create. */
198 bool check (struct tdesc_arch_data *tdesc_data,
199 const struct tdesc_feature *feature,
200 bool prefer_first_name_p,
201 std::vector<riscv_pending_register_alias> *aliases) const;
204 /* Return the name of this feature. */
205 const char *name () const
206 { return m_feature_name; }
208 protected:
210 /* Return a target description feature extracted from TDESC for this
211 register feature. Will return nullptr if there is no feature in TDESC
212 with the name M_FEATURE_NAME. */
213 const struct tdesc_feature *tdesc_feature (const struct target_desc *tdesc) const
215 return tdesc_find_feature (tdesc, name ());
218 /* List of all the registers that we expect that we might find in this
219 register set. */
220 std::vector<struct register_info> m_registers;
222 private:
224 /* The name for this feature. This is the name used to find this feature
225 within the target description. */
226 const char *m_feature_name;
229 /* See description in the class declaration above. */
231 bool
232 riscv_register_feature::register_info::check
233 (struct tdesc_arch_data *tdesc_data,
234 const struct tdesc_feature *feature,
235 bool prefer_first_name_p,
236 std::vector<riscv_pending_register_alias> *aliases) const
238 for (const char *name : this->names)
240 bool found = tdesc_numbered_register (feature, tdesc_data,
241 this->regnum, name);
242 if (found)
244 /* We know that the target description mentions this
245 register. In RISCV_REGISTER_NAME we ensure that GDB
246 always uses the first name for each register, so here we
247 add aliases for all of the remaining names. */
248 int start_index = prefer_first_name_p ? 1 : 0;
249 for (int i = start_index; i < this->names.size (); ++i)
251 const char *alias = this->names[i];
252 if (alias == name && !prefer_first_name_p)
253 continue;
254 aliases->emplace_back (alias, (void *) &this->regnum);
256 return true;
259 return false;
262 /* Class representing the x-registers feature set. */
264 struct riscv_xreg_feature : public riscv_register_feature
266 riscv_xreg_feature ()
267 : riscv_register_feature (riscv_feature_name_cpu)
269 m_registers = {
270 { RISCV_ZERO_REGNUM + 0, { "zero", "x0" } },
271 { RISCV_ZERO_REGNUM + 1, { "ra", "x1" } },
272 { RISCV_ZERO_REGNUM + 2, { "sp", "x2" } },
273 { RISCV_ZERO_REGNUM + 3, { "gp", "x3" } },
274 { RISCV_ZERO_REGNUM + 4, { "tp", "x4" } },
275 { RISCV_ZERO_REGNUM + 5, { "t0", "x5" } },
276 { RISCV_ZERO_REGNUM + 6, { "t1", "x6" } },
277 { RISCV_ZERO_REGNUM + 7, { "t2", "x7" } },
278 { RISCV_ZERO_REGNUM + 8, { "fp", "x8", "s0" } },
279 { RISCV_ZERO_REGNUM + 9, { "s1", "x9" } },
280 { RISCV_ZERO_REGNUM + 10, { "a0", "x10" } },
281 { RISCV_ZERO_REGNUM + 11, { "a1", "x11" } },
282 { RISCV_ZERO_REGNUM + 12, { "a2", "x12" } },
283 { RISCV_ZERO_REGNUM + 13, { "a3", "x13" } },
284 { RISCV_ZERO_REGNUM + 14, { "a4", "x14" } },
285 { RISCV_ZERO_REGNUM + 15, { "a5", "x15" } },
286 { RISCV_ZERO_REGNUM + 16, { "a6", "x16" } },
287 { RISCV_ZERO_REGNUM + 17, { "a7", "x17" } },
288 { RISCV_ZERO_REGNUM + 18, { "s2", "x18" } },
289 { RISCV_ZERO_REGNUM + 19, { "s3", "x19" } },
290 { RISCV_ZERO_REGNUM + 20, { "s4", "x20" } },
291 { RISCV_ZERO_REGNUM + 21, { "s5", "x21" } },
292 { RISCV_ZERO_REGNUM + 22, { "s6", "x22" } },
293 { RISCV_ZERO_REGNUM + 23, { "s7", "x23" } },
294 { RISCV_ZERO_REGNUM + 24, { "s8", "x24" } },
295 { RISCV_ZERO_REGNUM + 25, { "s9", "x25" } },
296 { RISCV_ZERO_REGNUM + 26, { "s10", "x26" } },
297 { RISCV_ZERO_REGNUM + 27, { "s11", "x27" } },
298 { RISCV_ZERO_REGNUM + 28, { "t3", "x28" } },
299 { RISCV_ZERO_REGNUM + 29, { "t4", "x29" } },
300 { RISCV_ZERO_REGNUM + 30, { "t5", "x30" } },
301 { RISCV_ZERO_REGNUM + 31, { "t6", "x31" } },
302 { RISCV_ZERO_REGNUM + 32, { "pc" } }
306 /* Return the preferred name for the register with gdb register number
307 REGNUM, which must be in the inclusive range RISCV_ZERO_REGNUM to
308 RISCV_PC_REGNUM. */
309 const char *register_name (int regnum) const
311 gdb_assert (regnum >= RISCV_ZERO_REGNUM && regnum <= m_registers.size ());
312 return m_registers[regnum].names[0];
315 /* Check this feature within TDESC, record the registers from this
316 feature into TDESC_DATA and update ALIASES and FEATURES. */
317 bool check (const struct target_desc *tdesc,
318 struct tdesc_arch_data *tdesc_data,
319 std::vector<riscv_pending_register_alias> *aliases,
320 struct riscv_gdbarch_features *features) const
322 const struct tdesc_feature *feature_cpu = tdesc_feature (tdesc);
324 if (feature_cpu == nullptr)
325 return false;
327 bool seen_an_optional_reg_p = false;
328 for (const auto &reg : m_registers)
330 bool found = reg.check (tdesc_data, feature_cpu, true, aliases);
332 bool is_optional_reg_p = (reg.regnum >= RISCV_ZERO_REGNUM + 16
333 && reg.regnum < RISCV_ZERO_REGNUM + 32);
335 if (!found && (!is_optional_reg_p || seen_an_optional_reg_p))
336 return false;
337 else if (found && is_optional_reg_p)
338 seen_an_optional_reg_p = true;
341 /* Check that all of the core cpu registers have the same bitsize. */
342 int xlen_bitsize = tdesc_register_bitsize (feature_cpu, "pc");
344 bool valid_p = true;
345 for (auto &tdesc_reg : feature_cpu->registers)
346 valid_p &= (tdesc_reg->bitsize == xlen_bitsize);
348 features->xlen = (xlen_bitsize / 8);
349 features->embedded = !seen_an_optional_reg_p;
351 return valid_p;
355 /* An instance of the x-register feature set. */
357 static const struct riscv_xreg_feature riscv_xreg_feature;
359 /* Class representing the f-registers feature set. */
361 struct riscv_freg_feature : public riscv_register_feature
363 riscv_freg_feature ()
364 : riscv_register_feature (riscv_feature_name_fpu)
366 m_registers = {
367 { RISCV_FIRST_FP_REGNUM + 0, { "ft0", "f0" } },
368 { RISCV_FIRST_FP_REGNUM + 1, { "ft1", "f1" } },
369 { RISCV_FIRST_FP_REGNUM + 2, { "ft2", "f2" } },
370 { RISCV_FIRST_FP_REGNUM + 3, { "ft3", "f3" } },
371 { RISCV_FIRST_FP_REGNUM + 4, { "ft4", "f4" } },
372 { RISCV_FIRST_FP_REGNUM + 5, { "ft5", "f5" } },
373 { RISCV_FIRST_FP_REGNUM + 6, { "ft6", "f6" } },
374 { RISCV_FIRST_FP_REGNUM + 7, { "ft7", "f7" } },
375 { RISCV_FIRST_FP_REGNUM + 8, { "fs0", "f8" } },
376 { RISCV_FIRST_FP_REGNUM + 9, { "fs1", "f9" } },
377 { RISCV_FIRST_FP_REGNUM + 10, { "fa0", "f10" } },
378 { RISCV_FIRST_FP_REGNUM + 11, { "fa1", "f11" } },
379 { RISCV_FIRST_FP_REGNUM + 12, { "fa2", "f12" } },
380 { RISCV_FIRST_FP_REGNUM + 13, { "fa3", "f13" } },
381 { RISCV_FIRST_FP_REGNUM + 14, { "fa4", "f14" } },
382 { RISCV_FIRST_FP_REGNUM + 15, { "fa5", "f15" } },
383 { RISCV_FIRST_FP_REGNUM + 16, { "fa6", "f16" } },
384 { RISCV_FIRST_FP_REGNUM + 17, { "fa7", "f17" } },
385 { RISCV_FIRST_FP_REGNUM + 18, { "fs2", "f18" } },
386 { RISCV_FIRST_FP_REGNUM + 19, { "fs3", "f19" } },
387 { RISCV_FIRST_FP_REGNUM + 20, { "fs4", "f20" } },
388 { RISCV_FIRST_FP_REGNUM + 21, { "fs5", "f21" } },
389 { RISCV_FIRST_FP_REGNUM + 22, { "fs6", "f22" } },
390 { RISCV_FIRST_FP_REGNUM + 23, { "fs7", "f23" } },
391 { RISCV_FIRST_FP_REGNUM + 24, { "fs8", "f24" } },
392 { RISCV_FIRST_FP_REGNUM + 25, { "fs9", "f25" } },
393 { RISCV_FIRST_FP_REGNUM + 26, { "fs10", "f26" } },
394 { RISCV_FIRST_FP_REGNUM + 27, { "fs11", "f27" } },
395 { RISCV_FIRST_FP_REGNUM + 28, { "ft8", "f28" } },
396 { RISCV_FIRST_FP_REGNUM + 29, { "ft9", "f29" } },
397 { RISCV_FIRST_FP_REGNUM + 30, { "ft10", "f30" } },
398 { RISCV_FIRST_FP_REGNUM + 31, { "ft11", "f31" } },
399 { RISCV_CSR_FFLAGS_REGNUM, { "fflags", "csr1" } },
400 { RISCV_CSR_FRM_REGNUM, { "frm", "csr2" } },
401 { RISCV_CSR_FCSR_REGNUM, { "fcsr", "csr3" } },
405 /* Return the preferred name for the register with gdb register number
406 REGNUM, which must be in the inclusive range RISCV_FIRST_FP_REGNUM to
407 RISCV_LAST_FP_REGNUM. */
408 const char *register_name (int regnum) const
410 gdb_static_assert (RISCV_LAST_FP_REGNUM == RISCV_FIRST_FP_REGNUM + 31);
411 gdb_assert (regnum >= RISCV_FIRST_FP_REGNUM
412 && regnum <= RISCV_LAST_FP_REGNUM);
413 regnum -= RISCV_FIRST_FP_REGNUM;
414 return m_registers[regnum].names[0];
417 /* Check this feature within TDESC, record the registers from this
418 feature into TDESC_DATA and update ALIASES and FEATURES. */
419 bool check (const struct target_desc *tdesc,
420 struct tdesc_arch_data *tdesc_data,
421 std::vector<riscv_pending_register_alias> *aliases,
422 struct riscv_gdbarch_features *features) const
424 const struct tdesc_feature *feature_fpu = tdesc_feature (tdesc);
426 /* It's fine if this feature is missing. Update the architecture
427 feature set and return. */
428 if (feature_fpu == nullptr)
430 features->flen = 0;
431 return true;
434 /* Check all of the floating pointer registers are present. We also
435 check that the floating point CSRs are present too, though if these
436 are missing this is not fatal. */
437 for (const auto &reg : m_registers)
439 bool found = reg.check (tdesc_data, feature_fpu, true, aliases);
441 bool is_ctrl_reg_p = reg.regnum > RISCV_LAST_FP_REGNUM;
443 if (!found && !is_ctrl_reg_p)
444 return false;
447 /* Look through all of the floating point registers (not the FP CSRs
448 though), and check they all have the same bitsize. Use this bitsize
449 to update the feature set for this gdbarch. */
450 int fp_bitsize = -1;
451 for (const auto &reg : m_registers)
453 /* Stop once we get to the CSRs which are at the end of the
454 M_REGISTERS list. */
455 if (reg.regnum > RISCV_LAST_FP_REGNUM)
456 break;
458 int reg_bitsize = -1;
459 for (const char *name : reg.names)
461 if (tdesc_unnumbered_register (feature_fpu, name))
463 reg_bitsize = tdesc_register_bitsize (feature_fpu, name);
464 break;
467 gdb_assert (reg_bitsize != -1);
468 if (fp_bitsize == -1)
469 fp_bitsize = reg_bitsize;
470 else if (fp_bitsize != reg_bitsize)
471 return false;
474 features->flen = (fp_bitsize / 8);
475 return true;
479 /* An instance of the f-register feature set. */
481 static const struct riscv_freg_feature riscv_freg_feature;
483 /* Class representing the virtual registers. These are not physical
484 registers on the hardware, but might be available from the target.
485 These are not pseudo registers, reading these really does result in a
486 register read from the target, it is just that there might not be a
487 physical register backing the result. */
489 struct riscv_virtual_feature : public riscv_register_feature
491 riscv_virtual_feature ()
492 : riscv_register_feature (riscv_feature_name_virtual)
494 m_registers = {
495 { RISCV_PRIV_REGNUM, { "priv" } }
499 bool check (const struct target_desc *tdesc,
500 struct tdesc_arch_data *tdesc_data,
501 std::vector<riscv_pending_register_alias> *aliases,
502 struct riscv_gdbarch_features *features) const
504 const struct tdesc_feature *feature_virtual = tdesc_feature (tdesc);
506 /* It's fine if this feature is missing. */
507 if (feature_virtual == nullptr)
508 return true;
510 /* We don't check the return value from the call to check here, all the
511 registers in this feature are optional. */
512 for (const auto &reg : m_registers)
513 reg.check (tdesc_data, feature_virtual, true, aliases);
515 return true;
519 /* An instance of the virtual register feature. */
521 static const struct riscv_virtual_feature riscv_virtual_feature;
523 /* Class representing the CSR feature. */
525 struct riscv_csr_feature : public riscv_register_feature
527 riscv_csr_feature ()
528 : riscv_register_feature (riscv_feature_name_csr)
530 m_registers = {
531 #define DECLARE_CSR(NAME,VALUE,CLASS,DEFINE_VER,ABORT_VER) \
532 { RISCV_ ## VALUE ## _REGNUM, { # NAME } },
533 #include "opcode/riscv-opc.h"
534 #undef DECLARE_CSR
536 riscv_create_csr_aliases ();
539 bool check (const struct target_desc *tdesc,
540 struct tdesc_arch_data *tdesc_data,
541 std::vector<riscv_pending_register_alias> *aliases,
542 struct riscv_gdbarch_features *features) const
544 const struct tdesc_feature *feature_csr = tdesc_feature (tdesc);
546 /* It's fine if this feature is missing. */
547 if (feature_csr == nullptr)
548 return true;
550 /* We don't check the return value from the call to check here, all the
551 registers in this feature are optional. */
552 for (const auto &reg : m_registers)
553 reg.check (tdesc_data, feature_csr, true, aliases);
555 return true;
558 private:
560 /* Complete RISCV_CSR_FEATURE, building the CSR alias names and adding them
561 to the name list for each register. */
563 void
564 riscv_create_csr_aliases ()
566 for (auto &reg : m_registers)
568 int csr_num = reg.regnum - RISCV_FIRST_CSR_REGNUM;
569 const char *alias = xstrprintf ("csr%d", csr_num);
570 reg.names.push_back (alias);
575 /* An instance of the csr register feature. */
577 static const struct riscv_csr_feature riscv_csr_feature;
579 /* Class representing the v-registers feature set. */
581 struct riscv_vector_feature : public riscv_register_feature
583 riscv_vector_feature ()
584 : riscv_register_feature (riscv_feature_name_vector)
586 m_registers = {
587 { RISCV_V0_REGNUM + 0, { "v0" } },
588 { RISCV_V0_REGNUM + 1, { "v1" } },
589 { RISCV_V0_REGNUM + 2, { "v2" } },
590 { RISCV_V0_REGNUM + 3, { "v3" } },
591 { RISCV_V0_REGNUM + 4, { "v4" } },
592 { RISCV_V0_REGNUM + 5, { "v5" } },
593 { RISCV_V0_REGNUM + 6, { "v6" } },
594 { RISCV_V0_REGNUM + 7, { "v7" } },
595 { RISCV_V0_REGNUM + 8, { "v8" } },
596 { RISCV_V0_REGNUM + 9, { "v9" } },
597 { RISCV_V0_REGNUM + 10, { "v10" } },
598 { RISCV_V0_REGNUM + 11, { "v11" } },
599 { RISCV_V0_REGNUM + 12, { "v12" } },
600 { RISCV_V0_REGNUM + 13, { "v13" } },
601 { RISCV_V0_REGNUM + 14, { "v14" } },
602 { RISCV_V0_REGNUM + 15, { "v15" } },
603 { RISCV_V0_REGNUM + 16, { "v16" } },
604 { RISCV_V0_REGNUM + 17, { "v17" } },
605 { RISCV_V0_REGNUM + 18, { "v18" } },
606 { RISCV_V0_REGNUM + 19, { "v19" } },
607 { RISCV_V0_REGNUM + 20, { "v20" } },
608 { RISCV_V0_REGNUM + 21, { "v21" } },
609 { RISCV_V0_REGNUM + 22, { "v22" } },
610 { RISCV_V0_REGNUM + 23, { "v23" } },
611 { RISCV_V0_REGNUM + 24, { "v24" } },
612 { RISCV_V0_REGNUM + 25, { "v25" } },
613 { RISCV_V0_REGNUM + 26, { "v26" } },
614 { RISCV_V0_REGNUM + 27, { "v27" } },
615 { RISCV_V0_REGNUM + 28, { "v28" } },
616 { RISCV_V0_REGNUM + 29, { "v29" } },
617 { RISCV_V0_REGNUM + 30, { "v30" } },
618 { RISCV_V0_REGNUM + 31, { "v31" } },
622 /* Return the preferred name for the register with gdb register number
623 REGNUM, which must be in the inclusive range RISCV_V0_REGNUM to
624 RISCV_V0_REGNUM + 31. */
625 const char *register_name (int regnum) const
627 gdb_assert (regnum >= RISCV_V0_REGNUM
628 && regnum <= RISCV_V0_REGNUM + 31);
629 regnum -= RISCV_V0_REGNUM;
630 return m_registers[regnum].names[0];
633 /* Check this feature within TDESC, record the registers from this
634 feature into TDESC_DATA and update ALIASES and FEATURES. */
635 bool check (const struct target_desc *tdesc,
636 struct tdesc_arch_data *tdesc_data,
637 std::vector<riscv_pending_register_alias> *aliases,
638 struct riscv_gdbarch_features *features) const
640 const struct tdesc_feature *feature_vector = tdesc_feature (tdesc);
642 /* It's fine if this feature is missing. Update the architecture
643 feature set and return. */
644 if (feature_vector == nullptr)
646 features->vlen = 0;
647 return true;
650 /* Check all of the vector registers are present. */
651 for (const auto &reg : m_registers)
653 if (!reg.check (tdesc_data, feature_vector, true, aliases))
654 return false;
657 /* Look through all of the vector registers and check they all have the
658 same bitsize. Use this bitsize to update the feature set for this
659 gdbarch. */
660 int vector_bitsize = -1;
661 for (const auto &reg : m_registers)
663 int reg_bitsize = -1;
664 for (const char *name : reg.names)
666 if (tdesc_unnumbered_register (feature_vector, name))
668 reg_bitsize = tdesc_register_bitsize (feature_vector, name);
669 break;
672 gdb_assert (reg_bitsize != -1);
673 if (vector_bitsize == -1)
674 vector_bitsize = reg_bitsize;
675 else if (vector_bitsize != reg_bitsize)
676 return false;
679 features->vlen = (vector_bitsize / 8);
680 return true;
684 /* An instance of the v-register feature set. */
686 static const struct riscv_vector_feature riscv_vector_feature;
688 /* Controls whether we place compressed breakpoints or not. When in auto
689 mode GDB tries to determine if the target supports compressed
690 breakpoints, and uses them if it does. */
692 static enum auto_boolean use_compressed_breakpoints;
694 /* The show callback for 'show riscv use-compressed-breakpoints'. */
696 static void
697 show_use_compressed_breakpoints (struct ui_file *file, int from_tty,
698 struct cmd_list_element *c,
699 const char *value)
701 fprintf_filtered (file,
702 _("Debugger's use of compressed breakpoints is set "
703 "to %s.\n"), value);
706 /* The set and show lists for 'set riscv' and 'show riscv' prefixes. */
708 static struct cmd_list_element *setriscvcmdlist = NULL;
709 static struct cmd_list_element *showriscvcmdlist = NULL;
711 /* The set and show lists for 'set riscv' and 'show riscv' prefixes. */
713 static struct cmd_list_element *setdebugriscvcmdlist = NULL;
714 static struct cmd_list_element *showdebugriscvcmdlist = NULL;
716 /* The show callback for all 'show debug riscv VARNAME' variables. */
718 static void
719 show_riscv_debug_variable (struct ui_file *file, int from_tty,
720 struct cmd_list_element *c,
721 const char *value)
723 fprintf_filtered (file,
724 _("RiscV debug variable `%s' is set to: %s\n"),
725 c->name, value);
728 /* See riscv-tdep.h. */
731 riscv_isa_xlen (struct gdbarch *gdbarch)
733 return gdbarch_tdep (gdbarch)->isa_features.xlen;
736 /* See riscv-tdep.h. */
739 riscv_abi_xlen (struct gdbarch *gdbarch)
741 return gdbarch_tdep (gdbarch)->abi_features.xlen;
744 /* See riscv-tdep.h. */
747 riscv_isa_flen (struct gdbarch *gdbarch)
749 return gdbarch_tdep (gdbarch)->isa_features.flen;
752 /* See riscv-tdep.h. */
755 riscv_abi_flen (struct gdbarch *gdbarch)
757 return gdbarch_tdep (gdbarch)->abi_features.flen;
760 /* See riscv-tdep.h. */
762 bool
763 riscv_abi_embedded (struct gdbarch *gdbarch)
765 return gdbarch_tdep (gdbarch)->abi_features.embedded;
768 /* Return true if the target for GDBARCH has floating point hardware. */
770 static bool
771 riscv_has_fp_regs (struct gdbarch *gdbarch)
773 return (riscv_isa_flen (gdbarch) > 0);
776 /* Return true if GDBARCH is using any of the floating point hardware ABIs. */
778 static bool
779 riscv_has_fp_abi (struct gdbarch *gdbarch)
781 return gdbarch_tdep (gdbarch)->abi_features.flen > 0;
784 /* Return true if REGNO is a floating pointer register. */
786 static bool
787 riscv_is_fp_regno_p (int regno)
789 return (regno >= RISCV_FIRST_FP_REGNUM
790 && regno <= RISCV_LAST_FP_REGNUM);
793 /* Implement the breakpoint_kind_from_pc gdbarch method. */
795 static int
796 riscv_breakpoint_kind_from_pc (struct gdbarch *gdbarch, CORE_ADDR *pcptr)
798 if (use_compressed_breakpoints == AUTO_BOOLEAN_AUTO)
800 bool unaligned_p = false;
801 gdb_byte buf[1];
803 /* Some targets don't support unaligned reads. The address can only
804 be unaligned if the C extension is supported. So it is safe to
805 use a compressed breakpoint in this case. */
806 if (*pcptr & 0x2)
807 unaligned_p = true;
808 else
810 /* Read the opcode byte to determine the instruction length. If
811 the read fails this may be because we tried to set the
812 breakpoint at an invalid address, in this case we provide a
813 fake result which will give a breakpoint length of 4.
814 Hopefully when we try to actually insert the breakpoint we
815 will see a failure then too which will be reported to the
816 user. */
817 if (target_read_code (*pcptr, buf, 1) == -1)
818 buf[0] = 0;
821 if (riscv_debug_breakpoints)
823 const char *bp = (unaligned_p || riscv_insn_length (buf[0]) == 2
824 ? "C.EBREAK" : "EBREAK");
826 fprintf_unfiltered (gdb_stdlog, "Using %s for breakpoint at %s ",
827 bp, paddress (gdbarch, *pcptr));
828 if (unaligned_p)
829 fprintf_unfiltered (gdb_stdlog, "(unaligned address)\n");
830 else
831 fprintf_unfiltered (gdb_stdlog, "(instruction length %d)\n",
832 riscv_insn_length (buf[0]));
834 if (unaligned_p || riscv_insn_length (buf[0]) == 2)
835 return 2;
836 else
837 return 4;
839 else if (use_compressed_breakpoints == AUTO_BOOLEAN_TRUE)
840 return 2;
841 else
842 return 4;
845 /* Implement the sw_breakpoint_from_kind gdbarch method. */
847 static const gdb_byte *
848 riscv_sw_breakpoint_from_kind (struct gdbarch *gdbarch, int kind, int *size)
850 static const gdb_byte ebreak[] = { 0x73, 0x00, 0x10, 0x00, };
851 static const gdb_byte c_ebreak[] = { 0x02, 0x90 };
853 *size = kind;
854 switch (kind)
856 case 2:
857 return c_ebreak;
858 case 4:
859 return ebreak;
860 default:
861 gdb_assert_not_reached (_("unhandled breakpoint kind"));
865 /* Implement the register_name gdbarch method. This is used instead of
866 the function supplied by calling TDESC_USE_REGISTERS so that we can
867 ensure the preferred names are offered for x-regs and f-regs. */
869 static const char *
870 riscv_register_name (struct gdbarch *gdbarch, int regnum)
872 /* Lookup the name through the target description. If we get back NULL
873 then this is an unknown register. If we do get a name back then we
874 look up the registers preferred name below. */
875 const char *name = tdesc_register_name (gdbarch, regnum);
876 if (name == NULL || name[0] == '\0')
877 return NULL;
879 /* We want GDB to use the ABI names for registers even if the target
880 gives us a target description with the architectural name. For
881 example we want to see 'ra' instead of 'x1' whatever the target
882 description called it. */
883 if (regnum >= RISCV_ZERO_REGNUM && regnum < RISCV_FIRST_FP_REGNUM)
884 return riscv_xreg_feature.register_name (regnum);
886 /* Like with the x-regs we prefer the abi names for the floating point
887 registers. */
888 if (regnum >= RISCV_FIRST_FP_REGNUM && regnum <= RISCV_LAST_FP_REGNUM)
890 if (riscv_has_fp_regs (gdbarch))
891 return riscv_freg_feature.register_name (regnum);
892 else
893 return NULL;
896 /* Some targets (QEMU) are reporting these three registers twice, once
897 in the FPU feature, and once in the CSR feature. Both of these read
898 the same underlying state inside the target, but naming the register
899 twice in the target description results in GDB having two registers
900 with the same name, only one of which can ever be accessed, but both
901 will show up in 'info register all'. Unless, we identify the
902 duplicate copies of these registers (in riscv_tdesc_unknown_reg) and
903 then hide the registers here by giving them no name. */
904 struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
905 if (tdep->duplicate_fflags_regnum == regnum)
906 return NULL;
907 if (tdep->duplicate_frm_regnum == regnum)
908 return NULL;
909 if (tdep->duplicate_fcsr_regnum == regnum)
910 return NULL;
912 /* The remaining registers are different. For all other registers on the
913 machine we prefer to see the names that the target description
914 provides. This is particularly important for CSRs which might be
915 renamed over time. If GDB keeps track of the "latest" name, but a
916 particular target provides an older name then we don't want to force
917 users to see the newer name in register output.
919 The other case that reaches here are any registers that the target
920 provided that GDB is completely unaware of. For these we have no
921 choice but to accept the target description name.
923 Just accept whatever name TDESC_REGISTER_NAME returned. */
924 return name;
927 /* Construct a type for 64-bit FP registers. */
929 static struct type *
930 riscv_fpreg_d_type (struct gdbarch *gdbarch)
932 struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
934 if (tdep->riscv_fpreg_d_type == nullptr)
936 const struct builtin_type *bt = builtin_type (gdbarch);
938 /* The type we're building is this: */
939 #if 0
940 union __gdb_builtin_type_fpreg_d
942 float f;
943 double d;
945 #endif
947 struct type *t;
949 t = arch_composite_type (gdbarch,
950 "__gdb_builtin_type_fpreg_d", TYPE_CODE_UNION);
951 append_composite_type_field (t, "float", bt->builtin_float);
952 append_composite_type_field (t, "double", bt->builtin_double);
953 t->set_is_vector (true);
954 t->set_name ("builtin_type_fpreg_d");
955 tdep->riscv_fpreg_d_type = t;
958 return tdep->riscv_fpreg_d_type;
961 /* Implement the register_type gdbarch method. This is installed as an
962 for the override setup by TDESC_USE_REGISTERS, for most registers we
963 delegate the type choice to the target description, but for a few
964 registers we try to improve the types if the target description has
965 taken a simplistic approach. */
967 static struct type *
968 riscv_register_type (struct gdbarch *gdbarch, int regnum)
970 struct type *type = tdesc_register_type (gdbarch, regnum);
971 int xlen = riscv_isa_xlen (gdbarch);
973 /* We want to perform some specific type "fixes" in cases where we feel
974 that we really can do better than the target description. For all
975 other cases we just return what the target description says. */
976 if (riscv_is_fp_regno_p (regnum))
978 /* This spots the case for RV64 where the double is defined as
979 either 'ieee_double' or 'float' (which is the generic name that
980 converts to 'double' on 64-bit). In these cases its better to
981 present the registers using a union type. */
982 int flen = riscv_isa_flen (gdbarch);
983 if (flen == 8
984 && type->code () == TYPE_CODE_FLT
985 && TYPE_LENGTH (type) == flen
986 && (strcmp (type->name (), "builtin_type_ieee_double") == 0
987 || strcmp (type->name (), "double") == 0))
988 type = riscv_fpreg_d_type (gdbarch);
991 if ((regnum == gdbarch_pc_regnum (gdbarch)
992 || regnum == RISCV_RA_REGNUM
993 || regnum == RISCV_FP_REGNUM
994 || regnum == RISCV_SP_REGNUM
995 || regnum == RISCV_GP_REGNUM
996 || regnum == RISCV_TP_REGNUM)
997 && type->code () == TYPE_CODE_INT
998 && TYPE_LENGTH (type) == xlen)
1000 /* This spots the case where some interesting registers are defined
1001 as simple integers of the expected size, we force these registers
1002 to be pointers as we believe that is more useful. */
1003 if (regnum == gdbarch_pc_regnum (gdbarch)
1004 || regnum == RISCV_RA_REGNUM)
1005 type = builtin_type (gdbarch)->builtin_func_ptr;
1006 else if (regnum == RISCV_FP_REGNUM
1007 || regnum == RISCV_SP_REGNUM
1008 || regnum == RISCV_GP_REGNUM
1009 || regnum == RISCV_TP_REGNUM)
1010 type = builtin_type (gdbarch)->builtin_data_ptr;
1013 return type;
1016 /* Helper for riscv_print_registers_info, prints info for a single register
1017 REGNUM. */
1019 static void
1020 riscv_print_one_register_info (struct gdbarch *gdbarch,
1021 struct ui_file *file,
1022 struct frame_info *frame,
1023 int regnum)
1025 const char *name = gdbarch_register_name (gdbarch, regnum);
1026 struct value *val;
1027 struct type *regtype;
1028 int print_raw_format;
1029 enum tab_stops { value_column_1 = 15 };
1031 fputs_filtered (name, file);
1032 print_spaces_filtered (value_column_1 - strlen (name), file);
1036 val = value_of_register (regnum, frame);
1037 regtype = value_type (val);
1039 catch (const gdb_exception_error &ex)
1041 /* Handle failure to read a register without interrupting the entire
1042 'info registers' flow. */
1043 fprintf_filtered (file, "%s\n", ex.what ());
1044 return;
1047 print_raw_format = (value_entirely_available (val)
1048 && !value_optimized_out (val));
1050 if (regtype->code () == TYPE_CODE_FLT
1051 || (regtype->code () == TYPE_CODE_UNION
1052 && regtype->num_fields () == 2
1053 && regtype->field (0).type ()->code () == TYPE_CODE_FLT
1054 && regtype->field (1).type ()->code () == TYPE_CODE_FLT)
1055 || (regtype->code () == TYPE_CODE_UNION
1056 && regtype->num_fields () == 3
1057 && regtype->field (0).type ()->code () == TYPE_CODE_FLT
1058 && regtype->field (1).type ()->code () == TYPE_CODE_FLT
1059 && regtype->field (2).type ()->code () == TYPE_CODE_FLT))
1061 struct value_print_options opts;
1062 const gdb_byte *valaddr = value_contents_for_printing (val).data ();
1063 enum bfd_endian byte_order = type_byte_order (regtype);
1065 get_user_print_options (&opts);
1066 opts.deref_ref = 1;
1068 common_val_print (val, file, 0, &opts, current_language);
1070 if (print_raw_format)
1072 fprintf_filtered (file, "\t(raw ");
1073 print_hex_chars (file, valaddr, TYPE_LENGTH (regtype), byte_order,
1074 true);
1075 fprintf_filtered (file, ")");
1078 else
1080 struct value_print_options opts;
1082 /* Print the register in hex. */
1083 get_formatted_print_options (&opts, 'x');
1084 opts.deref_ref = 1;
1085 common_val_print (val, file, 0, &opts, current_language);
1087 if (print_raw_format)
1089 if (regnum == RISCV_CSR_MSTATUS_REGNUM)
1091 LONGEST d;
1092 int size = register_size (gdbarch, regnum);
1093 unsigned xlen;
1095 /* The SD field is always in the upper bit of MSTATUS, regardless
1096 of the number of bits in MSTATUS. */
1097 d = value_as_long (val);
1098 xlen = size * 8;
1099 fprintf_filtered (file,
1100 "\tSD:%X VM:%02X MXR:%X PUM:%X MPRV:%X XS:%X "
1101 "FS:%X MPP:%x HPP:%X SPP:%X MPIE:%X HPIE:%X "
1102 "SPIE:%X UPIE:%X MIE:%X HIE:%X SIE:%X UIE:%X",
1103 (int) ((d >> (xlen - 1)) & 0x1),
1104 (int) ((d >> 24) & 0x1f),
1105 (int) ((d >> 19) & 0x1),
1106 (int) ((d >> 18) & 0x1),
1107 (int) ((d >> 17) & 0x1),
1108 (int) ((d >> 15) & 0x3),
1109 (int) ((d >> 13) & 0x3),
1110 (int) ((d >> 11) & 0x3),
1111 (int) ((d >> 9) & 0x3),
1112 (int) ((d >> 8) & 0x1),
1113 (int) ((d >> 7) & 0x1),
1114 (int) ((d >> 6) & 0x1),
1115 (int) ((d >> 5) & 0x1),
1116 (int) ((d >> 4) & 0x1),
1117 (int) ((d >> 3) & 0x1),
1118 (int) ((d >> 2) & 0x1),
1119 (int) ((d >> 1) & 0x1),
1120 (int) ((d >> 0) & 0x1));
1122 else if (regnum == RISCV_CSR_MISA_REGNUM)
1124 int base;
1125 unsigned xlen, i;
1126 LONGEST d;
1127 int size = register_size (gdbarch, regnum);
1129 /* The MXL field is always in the upper two bits of MISA,
1130 regardless of the number of bits in MISA. Mask out other
1131 bits to ensure we have a positive value. */
1132 d = value_as_long (val);
1133 base = (d >> ((size * 8) - 2)) & 0x3;
1134 xlen = 16;
1136 for (; base > 0; base--)
1137 xlen *= 2;
1138 fprintf_filtered (file, "\tRV%d", xlen);
1140 for (i = 0; i < 26; i++)
1142 if (d & (1 << i))
1143 fprintf_filtered (file, "%c", 'A' + i);
1146 else if (regnum == RISCV_CSR_FCSR_REGNUM
1147 || regnum == RISCV_CSR_FFLAGS_REGNUM
1148 || regnum == RISCV_CSR_FRM_REGNUM)
1150 LONGEST d;
1152 d = value_as_long (val);
1154 fprintf_filtered (file, "\t");
1155 if (regnum != RISCV_CSR_FRM_REGNUM)
1156 fprintf_filtered (file,
1157 "RD:%01X NV:%d DZ:%d OF:%d UF:%d NX:%d",
1158 (int) ((d >> 5) & 0x7),
1159 (int) ((d >> 4) & 0x1),
1160 (int) ((d >> 3) & 0x1),
1161 (int) ((d >> 2) & 0x1),
1162 (int) ((d >> 1) & 0x1),
1163 (int) ((d >> 0) & 0x1));
1165 if (regnum != RISCV_CSR_FFLAGS_REGNUM)
1167 static const char * const sfrm[] =
1169 "RNE (round to nearest; ties to even)",
1170 "RTZ (Round towards zero)",
1171 "RDN (Round down towards -INF)",
1172 "RUP (Round up towards +INF)",
1173 "RMM (Round to nearest; ties to max magnitude)",
1174 "INVALID[5]",
1175 "INVALID[6]",
1176 "dynamic rounding mode",
1178 int frm = ((regnum == RISCV_CSR_FCSR_REGNUM)
1179 ? (d >> 5) : d) & 0x3;
1181 fprintf_filtered (file, "%sFRM:%i [%s]",
1182 (regnum == RISCV_CSR_FCSR_REGNUM
1183 ? " " : ""),
1184 frm, sfrm[frm]);
1187 else if (regnum == RISCV_PRIV_REGNUM)
1189 LONGEST d;
1190 uint8_t priv;
1192 d = value_as_long (val);
1193 priv = d & 0xff;
1195 if (priv < 4)
1197 static const char * const sprv[] =
1199 "User/Application",
1200 "Supervisor",
1201 "Hypervisor",
1202 "Machine"
1204 fprintf_filtered (file, "\tprv:%d [%s]",
1205 priv, sprv[priv]);
1207 else
1208 fprintf_filtered (file, "\tprv:%d [INVALID]", priv);
1210 else
1212 /* If not a vector register, print it also according to its
1213 natural format. */
1214 if (regtype->is_vector () == 0)
1216 get_user_print_options (&opts);
1217 opts.deref_ref = 1;
1218 fprintf_filtered (file, "\t");
1219 common_val_print (val, file, 0, &opts, current_language);
1224 fprintf_filtered (file, "\n");
1227 /* Return true if REGNUM is a valid CSR register. The CSR register space
1228 is sparsely populated, so not every number is a named CSR. */
1230 static bool
1231 riscv_is_regnum_a_named_csr (int regnum)
1233 gdb_assert (regnum >= RISCV_FIRST_CSR_REGNUM
1234 && regnum <= RISCV_LAST_CSR_REGNUM);
1236 switch (regnum)
1238 #define DECLARE_CSR(name, num, class, define_ver, abort_ver) case RISCV_ ## num ## _REGNUM:
1239 #include "opcode/riscv-opc.h"
1240 #undef DECLARE_CSR
1241 return true;
1243 default:
1244 return false;
1248 /* Return true if REGNUM is an unknown CSR identified in
1249 riscv_tdesc_unknown_reg for GDBARCH. */
1251 static bool
1252 riscv_is_unknown_csr (struct gdbarch *gdbarch, int regnum)
1254 struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1255 return (regnum >= tdep->unknown_csrs_first_regnum
1256 && regnum < (tdep->unknown_csrs_first_regnum
1257 + tdep->unknown_csrs_count));
1260 /* Implement the register_reggroup_p gdbarch method. Is REGNUM a member
1261 of REGGROUP? */
1263 static int
1264 riscv_register_reggroup_p (struct gdbarch *gdbarch, int regnum,
1265 struct reggroup *reggroup)
1267 /* Used by 'info registers' and 'info registers <groupname>'. */
1269 if (gdbarch_register_name (gdbarch, regnum) == NULL
1270 || gdbarch_register_name (gdbarch, regnum)[0] == '\0')
1271 return 0;
1273 if (regnum > RISCV_LAST_REGNUM)
1275 /* Any extra registers from the CSR tdesc_feature (identified in
1276 riscv_tdesc_unknown_reg) are removed from the save/restore groups
1277 as some targets (QEMU) report CSRs which then can't be read and
1278 having unreadable registers in the save/restore group breaks
1279 things like inferior calls.
1281 The unknown CSRs are also removed from the general group, and
1282 added into both the csr and system group. This is inline with the
1283 known CSRs (see below). */
1284 if (riscv_is_unknown_csr (gdbarch, regnum))
1286 if (reggroup == restore_reggroup || reggroup == save_reggroup
1287 || reggroup == general_reggroup)
1288 return 0;
1289 else if (reggroup == system_reggroup || reggroup == csr_reggroup)
1290 return 1;
1293 /* This is some other unknown register from the target description.
1294 In this case we trust whatever the target description says about
1295 which groups this register should be in. */
1296 int ret = tdesc_register_in_reggroup_p (gdbarch, regnum, reggroup);
1297 if (ret != -1)
1298 return ret;
1300 return default_register_reggroup_p (gdbarch, regnum, reggroup);
1303 if (reggroup == all_reggroup)
1305 if (regnum < RISCV_FIRST_CSR_REGNUM || regnum >= RISCV_PRIV_REGNUM)
1306 return 1;
1307 if (riscv_is_regnum_a_named_csr (regnum))
1308 return 1;
1309 return 0;
1311 else if (reggroup == float_reggroup)
1312 return (riscv_is_fp_regno_p (regnum)
1313 || regnum == RISCV_CSR_FCSR_REGNUM
1314 || regnum == RISCV_CSR_FFLAGS_REGNUM
1315 || regnum == RISCV_CSR_FRM_REGNUM);
1316 else if (reggroup == general_reggroup)
1317 return regnum < RISCV_FIRST_FP_REGNUM;
1318 else if (reggroup == restore_reggroup || reggroup == save_reggroup)
1320 if (riscv_has_fp_regs (gdbarch))
1321 return (regnum <= RISCV_LAST_FP_REGNUM
1322 || regnum == RISCV_CSR_FCSR_REGNUM
1323 || regnum == RISCV_CSR_FFLAGS_REGNUM
1324 || regnum == RISCV_CSR_FRM_REGNUM);
1325 else
1326 return regnum < RISCV_FIRST_FP_REGNUM;
1328 else if (reggroup == system_reggroup || reggroup == csr_reggroup)
1330 if (regnum == RISCV_PRIV_REGNUM)
1331 return 1;
1332 if (regnum < RISCV_FIRST_CSR_REGNUM || regnum > RISCV_LAST_CSR_REGNUM)
1333 return 0;
1334 if (riscv_is_regnum_a_named_csr (regnum))
1335 return 1;
1336 return 0;
1338 else if (reggroup == vector_reggroup)
1339 return (regnum >= RISCV_V0_REGNUM && regnum <= RISCV_V31_REGNUM);
1340 else
1341 return 0;
1344 /* Implement the print_registers_info gdbarch method. This is used by
1345 'info registers' and 'info all-registers'. */
1347 static void
1348 riscv_print_registers_info (struct gdbarch *gdbarch,
1349 struct ui_file *file,
1350 struct frame_info *frame,
1351 int regnum, int print_all)
1353 if (regnum != -1)
1355 /* Print one specified register. */
1356 if (gdbarch_register_name (gdbarch, regnum) == NULL
1357 || *(gdbarch_register_name (gdbarch, regnum)) == '\0')
1358 error (_("Not a valid register for the current processor type"));
1359 riscv_print_one_register_info (gdbarch, file, frame, regnum);
1361 else
1363 struct reggroup *reggroup;
1365 if (print_all)
1366 reggroup = all_reggroup;
1367 else
1368 reggroup = general_reggroup;
1370 for (regnum = 0; regnum < gdbarch_num_cooked_regs (gdbarch); ++regnum)
1372 /* Zero never changes, so might as well hide by default. */
1373 if (regnum == RISCV_ZERO_REGNUM && !print_all)
1374 continue;
1376 /* Registers with no name are not valid on this ISA. */
1377 if (gdbarch_register_name (gdbarch, regnum) == NULL
1378 || *(gdbarch_register_name (gdbarch, regnum)) == '\0')
1379 continue;
1381 /* Is the register in the group we're interested in? */
1382 if (!gdbarch_register_reggroup_p (gdbarch, regnum, reggroup))
1383 continue;
1385 riscv_print_one_register_info (gdbarch, file, frame, regnum);
1390 /* Class that handles one decoded RiscV instruction. */
1392 class riscv_insn
1394 public:
1396 /* Enum of all the opcodes that GDB cares about during the prologue scan. */
1397 enum opcode
1399 /* Unknown value is used at initialisation time. */
1400 UNKNOWN = 0,
1402 /* These instructions are all the ones we are interested in during the
1403 prologue scan. */
1404 ADD,
1405 ADDI,
1406 ADDIW,
1407 ADDW,
1408 AUIPC,
1409 LUI,
1415 /* These are needed for software breakpoint support. */
1416 JAL,
1417 JALR,
1418 BEQ,
1419 BNE,
1420 BLT,
1421 BGE,
1422 BLTU,
1423 BGEU,
1424 /* These are needed for stepping over atomic sequences. */
1427 /* This instruction is used to do a syscall. */
1428 ECALL,
1430 /* Other instructions are not interesting during the prologue scan, and
1431 are ignored. */
1432 OTHER
1435 riscv_insn ()
1436 : m_length (0),
1437 m_opcode (OTHER),
1438 m_rd (0),
1439 m_rs1 (0),
1440 m_rs2 (0)
1442 /* Nothing. */
1445 void decode (struct gdbarch *gdbarch, CORE_ADDR pc);
1447 /* Get the length of the instruction in bytes. */
1448 int length () const
1449 { return m_length; }
1451 /* Get the opcode for this instruction. */
1452 enum opcode opcode () const
1453 { return m_opcode; }
1455 /* Get destination register field for this instruction. This is only
1456 valid if the OPCODE implies there is such a field for this
1457 instruction. */
1458 int rd () const
1459 { return m_rd; }
1461 /* Get the RS1 register field for this instruction. This is only valid
1462 if the OPCODE implies there is such a field for this instruction. */
1463 int rs1 () const
1464 { return m_rs1; }
1466 /* Get the RS2 register field for this instruction. This is only valid
1467 if the OPCODE implies there is such a field for this instruction. */
1468 int rs2 () const
1469 { return m_rs2; }
1471 /* Get the immediate for this instruction in signed form. This is only
1472 valid if the OPCODE implies there is such a field for this
1473 instruction. */
1474 int imm_signed () const
1475 { return m_imm.s; }
1477 private:
1479 /* Extract 5 bit register field at OFFSET from instruction OPCODE. */
1480 int decode_register_index (unsigned long opcode, int offset)
1482 return (opcode >> offset) & 0x1F;
1485 /* Extract 5 bit register field at OFFSET from instruction OPCODE. */
1486 int decode_register_index_short (unsigned long opcode, int offset)
1488 return ((opcode >> offset) & 0x7) + 8;
1491 /* Helper for DECODE, decode 32-bit R-type instruction. */
1492 void decode_r_type_insn (enum opcode opcode, ULONGEST ival)
1494 m_opcode = opcode;
1495 m_rd = decode_register_index (ival, OP_SH_RD);
1496 m_rs1 = decode_register_index (ival, OP_SH_RS1);
1497 m_rs2 = decode_register_index (ival, OP_SH_RS2);
1500 /* Helper for DECODE, decode 16-bit compressed R-type instruction. */
1501 void decode_cr_type_insn (enum opcode opcode, ULONGEST ival)
1503 m_opcode = opcode;
1504 m_rd = m_rs1 = decode_register_index (ival, OP_SH_CRS1S);
1505 m_rs2 = decode_register_index (ival, OP_SH_CRS2);
1508 /* Helper for DECODE, decode 32-bit I-type instruction. */
1509 void decode_i_type_insn (enum opcode opcode, ULONGEST ival)
1511 m_opcode = opcode;
1512 m_rd = decode_register_index (ival, OP_SH_RD);
1513 m_rs1 = decode_register_index (ival, OP_SH_RS1);
1514 m_imm.s = EXTRACT_ITYPE_IMM (ival);
1517 /* Helper for DECODE, decode 16-bit compressed I-type instruction. */
1518 void decode_ci_type_insn (enum opcode opcode, ULONGEST ival)
1520 m_opcode = opcode;
1521 m_rd = m_rs1 = decode_register_index (ival, OP_SH_CRS1S);
1522 m_imm.s = EXTRACT_CITYPE_IMM (ival);
1525 /* Helper for DECODE, decode 16-bit compressed CL-type instruction. */
1526 void decode_cl_type_insn (enum opcode opcode, ULONGEST ival)
1528 m_opcode = opcode;
1529 m_rd = decode_register_index_short (ival, OP_SH_CRS2S);
1530 m_rs1 = decode_register_index_short (ival, OP_SH_CRS1S);
1531 m_imm.s = EXTRACT_CLTYPE_IMM (ival);
1534 /* Helper for DECODE, decode 32-bit S-type instruction. */
1535 void decode_s_type_insn (enum opcode opcode, ULONGEST ival)
1537 m_opcode = opcode;
1538 m_rs1 = decode_register_index (ival, OP_SH_RS1);
1539 m_rs2 = decode_register_index (ival, OP_SH_RS2);
1540 m_imm.s = EXTRACT_STYPE_IMM (ival);
1543 /* Helper for DECODE, decode 16-bit CS-type instruction. The immediate
1544 encoding is different for each CS format instruction, so extracting
1545 the immediate is left up to the caller, who should pass the extracted
1546 immediate value through in IMM. */
1547 void decode_cs_type_insn (enum opcode opcode, ULONGEST ival, int imm)
1549 m_opcode = opcode;
1550 m_imm.s = imm;
1551 m_rs1 = decode_register_index_short (ival, OP_SH_CRS1S);
1552 m_rs2 = decode_register_index_short (ival, OP_SH_CRS2S);
1555 /* Helper for DECODE, decode 16-bit CSS-type instruction. The immediate
1556 encoding is different for each CSS format instruction, so extracting
1557 the immediate is left up to the caller, who should pass the extracted
1558 immediate value through in IMM. */
1559 void decode_css_type_insn (enum opcode opcode, ULONGEST ival, int imm)
1561 m_opcode = opcode;
1562 m_imm.s = imm;
1563 m_rs1 = RISCV_SP_REGNUM;
1564 /* Not a compressed register number in this case. */
1565 m_rs2 = decode_register_index (ival, OP_SH_CRS2);
1568 /* Helper for DECODE, decode 32-bit U-type instruction. */
1569 void decode_u_type_insn (enum opcode opcode, ULONGEST ival)
1571 m_opcode = opcode;
1572 m_rd = decode_register_index (ival, OP_SH_RD);
1573 m_imm.s = EXTRACT_UTYPE_IMM (ival);
1576 /* Helper for DECODE, decode 32-bit J-type instruction. */
1577 void decode_j_type_insn (enum opcode opcode, ULONGEST ival)
1579 m_opcode = opcode;
1580 m_rd = decode_register_index (ival, OP_SH_RD);
1581 m_imm.s = EXTRACT_JTYPE_IMM (ival);
1584 /* Helper for DECODE, decode 32-bit J-type instruction. */
1585 void decode_cj_type_insn (enum opcode opcode, ULONGEST ival)
1587 m_opcode = opcode;
1588 m_imm.s = EXTRACT_CJTYPE_IMM (ival);
1591 void decode_b_type_insn (enum opcode opcode, ULONGEST ival)
1593 m_opcode = opcode;
1594 m_rs1 = decode_register_index (ival, OP_SH_RS1);
1595 m_rs2 = decode_register_index (ival, OP_SH_RS2);
1596 m_imm.s = EXTRACT_BTYPE_IMM (ival);
1599 void decode_cb_type_insn (enum opcode opcode, ULONGEST ival)
1601 m_opcode = opcode;
1602 m_rs1 = decode_register_index_short (ival, OP_SH_CRS1S);
1603 m_imm.s = EXTRACT_CBTYPE_IMM (ival);
1606 /* Fetch instruction from target memory at ADDR, return the content of
1607 the instruction, and update LEN with the instruction length. */
1608 static ULONGEST fetch_instruction (struct gdbarch *gdbarch,
1609 CORE_ADDR addr, int *len);
1611 /* The length of the instruction in bytes. Should be 2 or 4. */
1612 int m_length;
1614 /* The instruction opcode. */
1615 enum opcode m_opcode;
1617 /* The three possible registers an instruction might reference. Not
1618 every instruction fills in all of these registers. Which fields are
1619 valid depends on the opcode. The naming of these fields matches the
1620 naming in the riscv isa manual. */
1621 int m_rd;
1622 int m_rs1;
1623 int m_rs2;
1625 /* Possible instruction immediate. This is only valid if the instruction
1626 format contains an immediate, not all instruction, whether this is
1627 valid depends on the opcode. Despite only having one format for now
1628 the immediate is packed into a union, later instructions might require
1629 an unsigned formatted immediate, having the union in place now will
1630 reduce the need for code churn later. */
1631 union riscv_insn_immediate
1633 riscv_insn_immediate ()
1634 : s (0)
1636 /* Nothing. */
1639 int s;
1640 } m_imm;
1643 /* Fetch instruction from target memory at ADDR, return the content of the
1644 instruction, and update LEN with the instruction length. */
1646 ULONGEST
1647 riscv_insn::fetch_instruction (struct gdbarch *gdbarch,
1648 CORE_ADDR addr, int *len)
1650 enum bfd_endian byte_order = gdbarch_byte_order_for_code (gdbarch);
1651 gdb_byte buf[8];
1652 int instlen, status;
1654 /* All insns are at least 16 bits. */
1655 status = target_read_memory (addr, buf, 2);
1656 if (status)
1657 memory_error (TARGET_XFER_E_IO, addr);
1659 /* If we need more, grab it now. */
1660 instlen = riscv_insn_length (buf[0]);
1661 gdb_assert (instlen <= sizeof (buf));
1662 *len = instlen;
1664 if (instlen > 2)
1666 status = target_read_memory (addr + 2, buf + 2, instlen - 2);
1667 if (status)
1668 memory_error (TARGET_XFER_E_IO, addr + 2);
1671 return extract_unsigned_integer (buf, instlen, byte_order);
1674 /* Fetch from target memory an instruction at PC and decode it. This can
1675 throw an error if the memory access fails, callers are responsible for
1676 handling this error if that is appropriate. */
1678 void
1679 riscv_insn::decode (struct gdbarch *gdbarch, CORE_ADDR pc)
1681 ULONGEST ival;
1683 /* Fetch the instruction, and the instructions length. */
1684 ival = fetch_instruction (gdbarch, pc, &m_length);
1686 if (m_length == 4)
1688 if (is_add_insn (ival))
1689 decode_r_type_insn (ADD, ival);
1690 else if (is_addw_insn (ival))
1691 decode_r_type_insn (ADDW, ival);
1692 else if (is_addi_insn (ival))
1693 decode_i_type_insn (ADDI, ival);
1694 else if (is_addiw_insn (ival))
1695 decode_i_type_insn (ADDIW, ival);
1696 else if (is_auipc_insn (ival))
1697 decode_u_type_insn (AUIPC, ival);
1698 else if (is_lui_insn (ival))
1699 decode_u_type_insn (LUI, ival);
1700 else if (is_sd_insn (ival))
1701 decode_s_type_insn (SD, ival);
1702 else if (is_sw_insn (ival))
1703 decode_s_type_insn (SW, ival);
1704 else if (is_jal_insn (ival))
1705 decode_j_type_insn (JAL, ival);
1706 else if (is_jalr_insn (ival))
1707 decode_i_type_insn (JALR, ival);
1708 else if (is_beq_insn (ival))
1709 decode_b_type_insn (BEQ, ival);
1710 else if (is_bne_insn (ival))
1711 decode_b_type_insn (BNE, ival);
1712 else if (is_blt_insn (ival))
1713 decode_b_type_insn (BLT, ival);
1714 else if (is_bge_insn (ival))
1715 decode_b_type_insn (BGE, ival);
1716 else if (is_bltu_insn (ival))
1717 decode_b_type_insn (BLTU, ival);
1718 else if (is_bgeu_insn (ival))
1719 decode_b_type_insn (BGEU, ival);
1720 else if (is_lr_w_insn (ival))
1721 decode_r_type_insn (LR, ival);
1722 else if (is_lr_d_insn (ival))
1723 decode_r_type_insn (LR, ival);
1724 else if (is_sc_w_insn (ival))
1725 decode_r_type_insn (SC, ival);
1726 else if (is_sc_d_insn (ival))
1727 decode_r_type_insn (SC, ival);
1728 else if (is_ecall_insn (ival))
1729 decode_i_type_insn (ECALL, ival);
1730 else if (is_ld_insn (ival))
1731 decode_i_type_insn (LD, ival);
1732 else if (is_lw_insn (ival))
1733 decode_i_type_insn (LW, ival);
1734 else
1735 /* None of the other fields are valid in this case. */
1736 m_opcode = OTHER;
1738 else if (m_length == 2)
1740 int xlen = riscv_isa_xlen (gdbarch);
1742 /* C_ADD and C_JALR have the same opcode. If RS2 is 0, then this is a
1743 C_JALR. So must try to match C_JALR first as it has more bits in
1744 mask. */
1745 if (is_c_jalr_insn (ival))
1746 decode_cr_type_insn (JALR, ival);
1747 else if (is_c_add_insn (ival))
1748 decode_cr_type_insn (ADD, ival);
1749 /* C_ADDW is RV64 and RV128 only. */
1750 else if (xlen != 4 && is_c_addw_insn (ival))
1751 decode_cr_type_insn (ADDW, ival);
1752 else if (is_c_addi_insn (ival))
1753 decode_ci_type_insn (ADDI, ival);
1754 /* C_ADDIW and C_JAL have the same opcode. C_ADDIW is RV64 and RV128
1755 only and C_JAL is RV32 only. */
1756 else if (xlen != 4 && is_c_addiw_insn (ival))
1757 decode_ci_type_insn (ADDIW, ival);
1758 else if (xlen == 4 && is_c_jal_insn (ival))
1759 decode_cj_type_insn (JAL, ival);
1760 /* C_ADDI16SP and C_LUI have the same opcode. If RD is 2, then this is a
1761 C_ADDI16SP. So must try to match C_ADDI16SP first as it has more bits
1762 in mask. */
1763 else if (is_c_addi16sp_insn (ival))
1765 m_opcode = ADDI;
1766 m_rd = m_rs1 = decode_register_index (ival, OP_SH_RD);
1767 m_imm.s = EXTRACT_CITYPE_ADDI16SP_IMM (ival);
1769 else if (is_c_addi4spn_insn (ival))
1771 m_opcode = ADDI;
1772 m_rd = decode_register_index_short (ival, OP_SH_CRS2S);
1773 m_rs1 = RISCV_SP_REGNUM;
1774 m_imm.s = EXTRACT_CIWTYPE_ADDI4SPN_IMM (ival);
1776 else if (is_c_lui_insn (ival))
1778 m_opcode = LUI;
1779 m_rd = decode_register_index (ival, OP_SH_CRS1S);
1780 m_imm.s = EXTRACT_CITYPE_LUI_IMM (ival);
1782 /* C_SD and C_FSW have the same opcode. C_SD is RV64 and RV128 only,
1783 and C_FSW is RV32 only. */
1784 else if (xlen != 4 && is_c_sd_insn (ival))
1785 decode_cs_type_insn (SD, ival, EXTRACT_CLTYPE_LD_IMM (ival));
1786 else if (is_c_sw_insn (ival))
1787 decode_cs_type_insn (SW, ival, EXTRACT_CLTYPE_LW_IMM (ival));
1788 else if (is_c_swsp_insn (ival))
1789 decode_css_type_insn (SW, ival, EXTRACT_CSSTYPE_SWSP_IMM (ival));
1790 else if (xlen != 4 && is_c_sdsp_insn (ival))
1791 decode_css_type_insn (SD, ival, EXTRACT_CSSTYPE_SDSP_IMM (ival));
1792 /* C_JR and C_MV have the same opcode. If RS2 is 0, then this is a C_JR.
1793 So must try to match C_JR first as it has more bits in mask. */
1794 else if (is_c_jr_insn (ival))
1795 decode_cr_type_insn (JALR, ival);
1796 else if (is_c_mv_insn (ival))
1797 decode_cr_type_insn (MV, ival);
1798 else if (is_c_j_insn (ival))
1799 decode_cj_type_insn (JAL, ival);
1800 else if (is_c_beqz_insn (ival))
1801 decode_cb_type_insn (BEQ, ival);
1802 else if (is_c_bnez_insn (ival))
1803 decode_cb_type_insn (BNE, ival);
1804 else if (is_c_ld_insn (ival))
1805 decode_cl_type_insn (LD, ival);
1806 else if (is_c_lw_insn (ival))
1807 decode_cl_type_insn (LW, ival);
1808 else
1809 /* None of the other fields of INSN are valid in this case. */
1810 m_opcode = OTHER;
1812 else
1814 /* This must be a 6 or 8 byte instruction, we don't currently decode
1815 any of these, so just ignore it. */
1816 gdb_assert (m_length == 6 || m_length == 8);
1817 m_opcode = OTHER;
1821 /* The prologue scanner. This is currently only used for skipping the
1822 prologue of a function when the DWARF information is not sufficient.
1823 However, it is written with filling of the frame cache in mind, which
1824 is why different groups of stack setup instructions are split apart
1825 during the core of the inner loop. In the future, the intention is to
1826 extend this function to fully support building up a frame cache that
1827 can unwind register values when there is no DWARF information. */
1829 static CORE_ADDR
1830 riscv_scan_prologue (struct gdbarch *gdbarch,
1831 CORE_ADDR start_pc, CORE_ADDR end_pc,
1832 struct riscv_unwind_cache *cache)
1834 CORE_ADDR cur_pc, next_pc, after_prologue_pc;
1835 CORE_ADDR end_prologue_addr = 0;
1837 /* Find an upper limit on the function prologue using the debug
1838 information. If the debug information could not be used to provide
1839 that bound, then use an arbitrary large number as the upper bound. */
1840 after_prologue_pc = skip_prologue_using_sal (gdbarch, start_pc);
1841 if (after_prologue_pc == 0)
1842 after_prologue_pc = start_pc + 100; /* Arbitrary large number. */
1843 if (after_prologue_pc < end_pc)
1844 end_pc = after_prologue_pc;
1846 pv_t regs[RISCV_NUM_INTEGER_REGS]; /* Number of GPR. */
1847 for (int regno = 0; regno < RISCV_NUM_INTEGER_REGS; regno++)
1848 regs[regno] = pv_register (regno, 0);
1849 pv_area stack (RISCV_SP_REGNUM, gdbarch_addr_bit (gdbarch));
1851 if (riscv_debug_unwinder)
1852 fprintf_unfiltered
1853 (gdb_stdlog,
1854 "Prologue scan for function starting at %s (limit %s)\n",
1855 core_addr_to_string (start_pc),
1856 core_addr_to_string (end_pc));
1858 for (next_pc = cur_pc = start_pc; cur_pc < end_pc; cur_pc = next_pc)
1860 struct riscv_insn insn;
1862 /* Decode the current instruction, and decide where the next
1863 instruction lives based on the size of this instruction. */
1864 insn.decode (gdbarch, cur_pc);
1865 gdb_assert (insn.length () > 0);
1866 next_pc = cur_pc + insn.length ();
1868 /* Look for common stack adjustment insns. */
1869 if ((insn.opcode () == riscv_insn::ADDI
1870 || insn.opcode () == riscv_insn::ADDIW)
1871 && insn.rd () == RISCV_SP_REGNUM
1872 && insn.rs1 () == RISCV_SP_REGNUM)
1874 /* Handle: addi sp, sp, -i
1875 or: addiw sp, sp, -i */
1876 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1877 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
1878 regs[insn.rd ()]
1879 = pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ());
1881 else if ((insn.opcode () == riscv_insn::SW
1882 || insn.opcode () == riscv_insn::SD)
1883 && (insn.rs1 () == RISCV_SP_REGNUM
1884 || insn.rs1 () == RISCV_FP_REGNUM))
1886 /* Handle: sw reg, offset(sp)
1887 or: sd reg, offset(sp)
1888 or: sw reg, offset(s0)
1889 or: sd reg, offset(s0) */
1890 /* Instruction storing a register onto the stack. */
1891 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
1892 gdb_assert (insn.rs2 () < RISCV_NUM_INTEGER_REGS);
1893 stack.store (pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ()),
1894 (insn.opcode () == riscv_insn::SW ? 4 : 8),
1895 regs[insn.rs2 ()]);
1897 else if (insn.opcode () == riscv_insn::ADDI
1898 && insn.rd () == RISCV_FP_REGNUM
1899 && insn.rs1 () == RISCV_SP_REGNUM)
1901 /* Handle: addi s0, sp, size */
1902 /* Instructions setting up the frame pointer. */
1903 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1904 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
1905 regs[insn.rd ()]
1906 = pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ());
1908 else if ((insn.opcode () == riscv_insn::ADD
1909 || insn.opcode () == riscv_insn::ADDW)
1910 && insn.rd () == RISCV_FP_REGNUM
1911 && insn.rs1 () == RISCV_SP_REGNUM
1912 && insn.rs2 () == RISCV_ZERO_REGNUM)
1914 /* Handle: add s0, sp, 0
1915 or: addw s0, sp, 0 */
1916 /* Instructions setting up the frame pointer. */
1917 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1918 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
1919 regs[insn.rd ()] = pv_add_constant (regs[insn.rs1 ()], 0);
1921 else if ((insn.opcode () == riscv_insn::ADDI
1922 && insn.rd () == RISCV_ZERO_REGNUM
1923 && insn.rs1 () == RISCV_ZERO_REGNUM
1924 && insn.imm_signed () == 0))
1926 /* Handle: add x0, x0, 0 (NOP) */
1928 else if (insn.opcode () == riscv_insn::AUIPC)
1930 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1931 regs[insn.rd ()] = pv_constant (cur_pc + insn.imm_signed ());
1933 else if (insn.opcode () == riscv_insn::LUI)
1935 /* Handle: lui REG, n
1936 Where REG is not gp register. */
1937 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1938 regs[insn.rd ()] = pv_constant (insn.imm_signed ());
1940 else if (insn.opcode () == riscv_insn::ADDI)
1942 /* Handle: addi REG1, REG2, IMM */
1943 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1944 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
1945 regs[insn.rd ()]
1946 = pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ());
1948 else if (insn.opcode () == riscv_insn::ADD)
1950 /* Handle: add REG1, REG2, REG3 */
1951 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1952 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
1953 gdb_assert (insn.rs2 () < RISCV_NUM_INTEGER_REGS);
1954 regs[insn.rd ()] = pv_add (regs[insn.rs1 ()], regs[insn.rs2 ()]);
1956 else if (insn.opcode () == riscv_insn::LD
1957 || insn.opcode () == riscv_insn::LW)
1959 /* Handle: ld reg, offset(rs1)
1960 or: c.ld reg, offset(rs1)
1961 or: lw reg, offset(rs1)
1962 or: c.lw reg, offset(rs1) */
1963 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1964 gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
1965 regs[insn.rd ()]
1966 = stack.fetch (pv_add_constant (regs[insn.rs1 ()],
1967 insn.imm_signed ()),
1968 (insn.opcode () == riscv_insn::LW ? 4 : 8));
1970 else if (insn.opcode () == riscv_insn::MV)
1972 /* Handle: c.mv RD, RS2 */
1973 gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
1974 gdb_assert (insn.rs2 () < RISCV_NUM_INTEGER_REGS);
1975 gdb_assert (insn.rs2 () > 0);
1976 regs[insn.rd ()] = regs[insn.rs2 ()];
1978 else
1980 end_prologue_addr = cur_pc;
1981 break;
1985 if (end_prologue_addr == 0)
1986 end_prologue_addr = cur_pc;
1988 if (riscv_debug_unwinder)
1989 fprintf_unfiltered (gdb_stdlog, "End of prologue at %s\n",
1990 core_addr_to_string (end_prologue_addr));
1992 if (cache != NULL)
1994 /* Figure out if it is a frame pointer or just a stack pointer. Also
1995 the offset held in the pv_t is from the original register value to
1996 the current value, which for a grows down stack means a negative
1997 value. The FRAME_BASE_OFFSET is the negation of this, how to get
1998 from the current value to the original value. */
1999 if (pv_is_register (regs[RISCV_FP_REGNUM], RISCV_SP_REGNUM))
2001 cache->frame_base_reg = RISCV_FP_REGNUM;
2002 cache->frame_base_offset = -regs[RISCV_FP_REGNUM].k;
2004 else
2006 cache->frame_base_reg = RISCV_SP_REGNUM;
2007 cache->frame_base_offset = -regs[RISCV_SP_REGNUM].k;
2010 /* Assign offset from old SP to all saved registers. As we don't
2011 have the previous value for the frame base register at this
2012 point, we store the offset as the address in the trad_frame, and
2013 then convert this to an actual address later. */
2014 for (int i = 0; i <= RISCV_NUM_INTEGER_REGS; i++)
2016 CORE_ADDR offset;
2017 if (stack.find_reg (gdbarch, i, &offset))
2019 if (riscv_debug_unwinder)
2021 /* Display OFFSET as a signed value, the offsets are from
2022 the frame base address to the registers location on
2023 the stack, with a descending stack this means the
2024 offsets are always negative. */
2025 fprintf_unfiltered (gdb_stdlog,
2026 "Register $%s at stack offset %s\n",
2027 gdbarch_register_name (gdbarch, i),
2028 plongest ((LONGEST) offset));
2030 cache->regs[i].set_addr (offset);
2035 return end_prologue_addr;
2038 /* Implement the riscv_skip_prologue gdbarch method. */
2040 static CORE_ADDR
2041 riscv_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR pc)
2043 CORE_ADDR func_addr;
2045 /* See if we can determine the end of the prologue via the symbol
2046 table. If so, then return either PC, or the PC after the
2047 prologue, whichever is greater. */
2048 if (find_pc_partial_function (pc, NULL, &func_addr, NULL))
2050 CORE_ADDR post_prologue_pc
2051 = skip_prologue_using_sal (gdbarch, func_addr);
2053 if (post_prologue_pc != 0)
2054 return std::max (pc, post_prologue_pc);
2057 /* Can't determine prologue from the symbol table, need to examine
2058 instructions. Pass -1 for the end address to indicate the prologue
2059 scanner can scan as far as it needs to find the end of the prologue. */
2060 return riscv_scan_prologue (gdbarch, pc, ((CORE_ADDR) -1), NULL);
2063 /* Implement the gdbarch push dummy code callback. */
2065 static CORE_ADDR
2066 riscv_push_dummy_code (struct gdbarch *gdbarch, CORE_ADDR sp,
2067 CORE_ADDR funaddr, struct value **args, int nargs,
2068 struct type *value_type, CORE_ADDR *real_pc,
2069 CORE_ADDR *bp_addr, struct regcache *regcache)
2071 /* A nop instruction is 'add x0, x0, 0'. */
2072 static const gdb_byte nop_insn[] = { 0x13, 0x00, 0x00, 0x00 };
2074 /* Allocate space for a breakpoint, and keep the stack correctly
2075 aligned. The space allocated here must be at least big enough to
2076 accommodate the NOP_INSN defined above. */
2077 sp -= 16;
2078 *bp_addr = sp;
2079 *real_pc = funaddr;
2081 /* When we insert a breakpoint we select whether to use a compressed
2082 breakpoint or not based on the existing contents of the memory.
2084 If the breakpoint is being placed onto the stack as part of setting up
2085 for an inferior call from GDB, then the existing stack contents may
2086 randomly appear to be a compressed instruction, causing GDB to insert
2087 a compressed breakpoint. If this happens on a target that does not
2088 support compressed instructions then this could cause problems.
2090 To prevent this issue we write an uncompressed nop onto the stack at
2091 the location where the breakpoint will be inserted. In this way we
2092 ensure that we always use an uncompressed breakpoint, which should
2093 work on all targets.
2095 We call TARGET_WRITE_MEMORY here so that if the write fails we don't
2096 throw an exception. Instead we ignore the error and move on. The
2097 assumption is that either GDB will error later when actually trying to
2098 insert a software breakpoint, or GDB will use hardware breakpoints and
2099 there will be no need to write to memory later. */
2100 int status = target_write_memory (*bp_addr, nop_insn, sizeof (nop_insn));
2102 if (riscv_debug_breakpoints || riscv_debug_infcall)
2103 fprintf_unfiltered (gdb_stdlog,
2104 "Writing %s-byte nop instruction to %s: %s\n",
2105 plongest (sizeof (nop_insn)),
2106 paddress (gdbarch, *bp_addr),
2107 (status == 0 ? "success" : "failed"));
2109 return sp;
2112 /* Implement the gdbarch type alignment method, overrides the generic
2113 alignment algorithm for anything that is RISC-V specific. */
2115 static ULONGEST
2116 riscv_type_align (gdbarch *gdbarch, type *type)
2118 type = check_typedef (type);
2119 if (type->code () == TYPE_CODE_ARRAY && type->is_vector ())
2120 return std::min (TYPE_LENGTH (type), (ULONGEST) BIGGEST_ALIGNMENT);
2122 /* Anything else will be aligned by the generic code. */
2123 return 0;
2126 /* Holds information about a single argument either being passed to an
2127 inferior function, or returned from an inferior function. This includes
2128 information about the size, type, etc of the argument, and also
2129 information about how the argument will be passed (or returned). */
2131 struct riscv_arg_info
2133 /* Contents of the argument. */
2134 const gdb_byte *contents;
2136 /* Length of argument. */
2137 int length;
2139 /* Alignment required for an argument of this type. */
2140 int align;
2142 /* The type for this argument. */
2143 struct type *type;
2145 /* Each argument can have either 1 or 2 locations assigned to it. Each
2146 location describes where part of the argument will be placed. The
2147 second location is valid based on the LOC_TYPE and C_LENGTH fields
2148 of the first location (which is always valid). */
2149 struct location
2151 /* What type of location this is. */
2152 enum location_type
2154 /* Argument passed in a register. */
2155 in_reg,
2157 /* Argument passed as an on stack argument. */
2158 on_stack,
2160 /* Argument passed by reference. The second location is always
2161 valid for a BY_REF argument, and describes where the address
2162 of the BY_REF argument should be placed. */
2163 by_ref
2164 } loc_type;
2166 /* Information that depends on the location type. */
2167 union
2169 /* Which register number to use. */
2170 int regno;
2172 /* The offset into the stack region. */
2173 int offset;
2174 } loc_data;
2176 /* The length of contents covered by this location. If this is less
2177 than the total length of the argument, then the second location
2178 will be valid, and will describe where the rest of the argument
2179 will go. */
2180 int c_length;
2182 /* The offset within CONTENTS for this part of the argument. This can
2183 be non-zero even for the first part (the first field of a struct can
2184 have a non-zero offset due to padding). For the second part of the
2185 argument, this might be the C_LENGTH value of the first part,
2186 however, if we are passing a structure in two registers, and there's
2187 is padding between the first and second field, then this offset
2188 might be greater than the length of the first argument part. When
2189 the second argument location is not holding part of the argument
2190 value, but is instead holding the address of a reference argument,
2191 then this offset will be set to 0. */
2192 int c_offset;
2193 } argloc[2];
2195 /* TRUE if this is an unnamed argument. */
2196 bool is_unnamed;
2199 /* Information about a set of registers being used for passing arguments as
2200 part of a function call. The register set must be numerically
2201 sequential from NEXT_REGNUM to LAST_REGNUM. The register set can be
2202 disabled from use by setting NEXT_REGNUM greater than LAST_REGNUM. */
2204 struct riscv_arg_reg
2206 riscv_arg_reg (int first, int last)
2207 : next_regnum (first),
2208 last_regnum (last)
2210 /* Nothing. */
2213 /* The GDB register number to use in this set. */
2214 int next_regnum;
2216 /* The last GDB register number to use in this set. */
2217 int last_regnum;
2220 /* Arguments can be passed as on stack arguments, or by reference. The
2221 on stack arguments must be in a continuous region starting from $sp,
2222 while the by reference arguments can be anywhere, but we'll put them
2223 on the stack after (at higher address) the on stack arguments.
2225 This might not be the right approach to take. The ABI is clear that
2226 an argument passed by reference can be modified by the callee, which
2227 us placing the argument (temporarily) onto the stack will not achieve
2228 (changes will be lost). There's also the possibility that very large
2229 arguments could overflow the stack.
2231 This struct is used to track offset into these two areas for where
2232 arguments are to be placed. */
2233 struct riscv_memory_offsets
2235 riscv_memory_offsets ()
2236 : arg_offset (0),
2237 ref_offset (0)
2239 /* Nothing. */
2242 /* Offset into on stack argument area. */
2243 int arg_offset;
2245 /* Offset into the pass by reference area. */
2246 int ref_offset;
2249 /* Holds information about where arguments to a call will be placed. This
2250 is updated as arguments are added onto the call, and can be used to
2251 figure out where the next argument should be placed. */
2253 struct riscv_call_info
2255 riscv_call_info (struct gdbarch *gdbarch)
2256 : int_regs (RISCV_A0_REGNUM, RISCV_A0_REGNUM + 7),
2257 float_regs (RISCV_FA0_REGNUM, RISCV_FA0_REGNUM + 7)
2259 xlen = riscv_abi_xlen (gdbarch);
2260 flen = riscv_abi_flen (gdbarch);
2262 /* Reduce the number of integer argument registers when using the
2263 embedded abi (i.e. rv32e). */
2264 if (riscv_abi_embedded (gdbarch))
2265 int_regs.last_regnum = RISCV_A0_REGNUM + 5;
2267 /* Disable use of floating point registers if needed. */
2268 if (!riscv_has_fp_abi (gdbarch))
2269 float_regs.next_regnum = float_regs.last_regnum + 1;
2272 /* Track the memory areas used for holding in-memory arguments to a
2273 call. */
2274 struct riscv_memory_offsets memory;
2276 /* Holds information about the next integer register to use for passing
2277 an argument. */
2278 struct riscv_arg_reg int_regs;
2280 /* Holds information about the next floating point register to use for
2281 passing an argument. */
2282 struct riscv_arg_reg float_regs;
2284 /* The XLEN and FLEN are copied in to this structure for convenience, and
2285 are just the results of calling RISCV_ABI_XLEN and RISCV_ABI_FLEN. */
2286 int xlen;
2287 int flen;
2290 /* Return the number of registers available for use as parameters in the
2291 register set REG. Returned value can be 0 or more. */
2293 static int
2294 riscv_arg_regs_available (struct riscv_arg_reg *reg)
2296 if (reg->next_regnum > reg->last_regnum)
2297 return 0;
2299 return (reg->last_regnum - reg->next_regnum + 1);
2302 /* If there is at least one register available in the register set REG then
2303 the next register from REG is assigned to LOC and the length field of
2304 LOC is updated to LENGTH. The register set REG is updated to indicate
2305 that the assigned register is no longer available and the function
2306 returns true.
2308 If there are no registers available in REG then the function returns
2309 false, and LOC and REG are unchanged. */
2311 static bool
2312 riscv_assign_reg_location (struct riscv_arg_info::location *loc,
2313 struct riscv_arg_reg *reg,
2314 int length, int offset)
2316 if (reg->next_regnum <= reg->last_regnum)
2318 loc->loc_type = riscv_arg_info::location::in_reg;
2319 loc->loc_data.regno = reg->next_regnum;
2320 reg->next_regnum++;
2321 loc->c_length = length;
2322 loc->c_offset = offset;
2323 return true;
2326 return false;
2329 /* Assign LOC a location as the next stack parameter, and update MEMORY to
2330 record that an area of stack has been used to hold the parameter
2331 described by LOC.
2333 The length field of LOC is updated to LENGTH, the length of the
2334 parameter being stored, and ALIGN is the alignment required by the
2335 parameter, which will affect how memory is allocated out of MEMORY. */
2337 static void
2338 riscv_assign_stack_location (struct riscv_arg_info::location *loc,
2339 struct riscv_memory_offsets *memory,
2340 int length, int align)
2342 loc->loc_type = riscv_arg_info::location::on_stack;
2343 memory->arg_offset
2344 = align_up (memory->arg_offset, align);
2345 loc->loc_data.offset = memory->arg_offset;
2346 memory->arg_offset += length;
2347 loc->c_length = length;
2349 /* Offset is always 0, either we're the first location part, in which
2350 case we're reading content from the start of the argument, or we're
2351 passing the address of a reference argument, so 0. */
2352 loc->c_offset = 0;
2355 /* Update AINFO, which describes an argument that should be passed or
2356 returned using the integer ABI. The argloc fields within AINFO are
2357 updated to describe the location in which the argument will be passed to
2358 a function, or returned from a function.
2360 The CINFO structure contains the ongoing call information, the holds
2361 information such as which argument registers are remaining to be
2362 assigned to parameter, and how much memory has been used by parameters
2363 so far.
2365 By examining the state of CINFO a suitable location can be selected,
2366 and assigned to AINFO. */
2368 static void
2369 riscv_call_arg_scalar_int (struct riscv_arg_info *ainfo,
2370 struct riscv_call_info *cinfo)
2372 if (ainfo->length > (2 * cinfo->xlen))
2374 /* Argument is going to be passed by reference. */
2375 ainfo->argloc[0].loc_type
2376 = riscv_arg_info::location::by_ref;
2377 cinfo->memory.ref_offset
2378 = align_up (cinfo->memory.ref_offset, ainfo->align);
2379 ainfo->argloc[0].loc_data.offset = cinfo->memory.ref_offset;
2380 cinfo->memory.ref_offset += ainfo->length;
2381 ainfo->argloc[0].c_length = ainfo->length;
2383 /* The second location for this argument is given over to holding the
2384 address of the by-reference data. Pass 0 for the offset as this
2385 is not part of the actual argument value. */
2386 if (!riscv_assign_reg_location (&ainfo->argloc[1],
2387 &cinfo->int_regs,
2388 cinfo->xlen, 0))
2389 riscv_assign_stack_location (&ainfo->argloc[1],
2390 &cinfo->memory, cinfo->xlen,
2391 cinfo->xlen);
2393 else
2395 int len = std::min (ainfo->length, cinfo->xlen);
2396 int align = std::max (ainfo->align, cinfo->xlen);
2398 /* Unnamed arguments in registers that require 2*XLEN alignment are
2399 passed in an aligned register pair. */
2400 if (ainfo->is_unnamed && (align == cinfo->xlen * 2)
2401 && cinfo->int_regs.next_regnum & 1)
2402 cinfo->int_regs.next_regnum++;
2404 if (!riscv_assign_reg_location (&ainfo->argloc[0],
2405 &cinfo->int_regs, len, 0))
2406 riscv_assign_stack_location (&ainfo->argloc[0],
2407 &cinfo->memory, len, align);
2409 if (len < ainfo->length)
2411 len = ainfo->length - len;
2412 if (!riscv_assign_reg_location (&ainfo->argloc[1],
2413 &cinfo->int_regs, len,
2414 cinfo->xlen))
2415 riscv_assign_stack_location (&ainfo->argloc[1],
2416 &cinfo->memory, len, cinfo->xlen);
2421 /* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
2422 is being passed with the floating point ABI. */
2424 static void
2425 riscv_call_arg_scalar_float (struct riscv_arg_info *ainfo,
2426 struct riscv_call_info *cinfo)
2428 if (ainfo->length > cinfo->flen || ainfo->is_unnamed)
2429 return riscv_call_arg_scalar_int (ainfo, cinfo);
2430 else
2432 if (!riscv_assign_reg_location (&ainfo->argloc[0],
2433 &cinfo->float_regs,
2434 ainfo->length, 0))
2435 return riscv_call_arg_scalar_int (ainfo, cinfo);
2439 /* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
2440 is a complex floating point argument, and is therefore handled
2441 differently to other argument types. */
2443 static void
2444 riscv_call_arg_complex_float (struct riscv_arg_info *ainfo,
2445 struct riscv_call_info *cinfo)
2447 if (ainfo->length <= (2 * cinfo->flen)
2448 && riscv_arg_regs_available (&cinfo->float_regs) >= 2
2449 && !ainfo->is_unnamed)
2451 bool result;
2452 int len = ainfo->length / 2;
2454 result = riscv_assign_reg_location (&ainfo->argloc[0],
2455 &cinfo->float_regs, len, 0);
2456 gdb_assert (result);
2458 result = riscv_assign_reg_location (&ainfo->argloc[1],
2459 &cinfo->float_regs, len, len);
2460 gdb_assert (result);
2462 else
2463 return riscv_call_arg_scalar_int (ainfo, cinfo);
2466 /* A structure used for holding information about a structure type within
2467 the inferior program. The RiscV ABI has special rules for handling some
2468 structures with a single field or with two fields. The counting of
2469 fields here is done after flattening out all nested structures. */
2471 class riscv_struct_info
2473 public:
2474 riscv_struct_info ()
2475 : m_number_of_fields (0),
2476 m_types { nullptr, nullptr },
2477 m_offsets { 0, 0 }
2479 /* Nothing. */
2482 /* Analyse TYPE descending into nested structures, count the number of
2483 scalar fields and record the types of the first two fields found. */
2484 void analyse (struct type *type)
2486 analyse_inner (type, 0);
2489 /* The number of scalar fields found in the analysed type. This is
2490 currently only accurate if the value returned is 0, 1, or 2 as the
2491 analysis stops counting when the number of fields is 3. This is
2492 because the RiscV ABI only has special cases for 1 or 2 fields,
2493 anything else we just don't care about. */
2494 int number_of_fields () const
2495 { return m_number_of_fields; }
2497 /* Return the type for scalar field INDEX within the analysed type. Will
2498 return nullptr if there is no field at that index. Only INDEX values
2499 0 and 1 can be requested as the RiscV ABI only has special cases for
2500 structures with 1 or 2 fields. */
2501 struct type *field_type (int index) const
2503 gdb_assert (index < (sizeof (m_types) / sizeof (m_types[0])));
2504 return m_types[index];
2507 /* Return the offset of scalar field INDEX within the analysed type. Will
2508 return 0 if there is no field at that index. Only INDEX values 0 and
2509 1 can be requested as the RiscV ABI only has special cases for
2510 structures with 1 or 2 fields. */
2511 int field_offset (int index) const
2513 gdb_assert (index < (sizeof (m_offsets) / sizeof (m_offsets[0])));
2514 return m_offsets[index];
2517 private:
2518 /* The number of scalar fields found within the structure after recursing
2519 into nested structures. */
2520 int m_number_of_fields;
2522 /* The types of the first two scalar fields found within the structure
2523 after recursing into nested structures. */
2524 struct type *m_types[2];
2526 /* The offsets of the first two scalar fields found within the structure
2527 after recursing into nested structures. */
2528 int m_offsets[2];
2530 /* Recursive core for ANALYSE, the OFFSET parameter tracks the byte
2531 offset from the start of the top level structure being analysed. */
2532 void analyse_inner (struct type *type, int offset);
2535 /* See description in class declaration. */
2537 void
2538 riscv_struct_info::analyse_inner (struct type *type, int offset)
2540 unsigned int count = type->num_fields ();
2541 unsigned int i;
2543 for (i = 0; i < count; ++i)
2545 if (type->field (i).loc_kind () != FIELD_LOC_KIND_BITPOS)
2546 continue;
2548 struct type *field_type = type->field (i).type ();
2549 field_type = check_typedef (field_type);
2550 int field_offset
2551 = offset + type->field (i).loc_bitpos () / TARGET_CHAR_BIT;
2553 switch (field_type->code ())
2555 case TYPE_CODE_STRUCT:
2556 analyse_inner (field_type, field_offset);
2557 break;
2559 default:
2560 /* RiscV only flattens out structures. Anything else does not
2561 need to be flattened, we just record the type, and when we
2562 look at the analysis results we'll realise this is not a
2563 structure we can special case, and pass the structure in
2564 memory. */
2565 if (m_number_of_fields < 2)
2567 m_types[m_number_of_fields] = field_type;
2568 m_offsets[m_number_of_fields] = field_offset;
2570 m_number_of_fields++;
2571 break;
2574 /* RiscV only has special handling for structures with 1 or 2 scalar
2575 fields, any more than that and the structure is just passed in
2576 memory. We can safely drop out early when we find 3 or more
2577 fields then. */
2579 if (m_number_of_fields > 2)
2580 return;
2584 /* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
2585 is a structure. Small structures on RiscV have some special case
2586 handling in order that the structure might be passed in register.
2587 Larger structures are passed in memory. After assigning location
2588 information to AINFO, CINFO will have been updated. */
2590 static void
2591 riscv_call_arg_struct (struct riscv_arg_info *ainfo,
2592 struct riscv_call_info *cinfo)
2594 if (riscv_arg_regs_available (&cinfo->float_regs) >= 1)
2596 struct riscv_struct_info sinfo;
2598 sinfo.analyse (ainfo->type);
2599 if (sinfo.number_of_fields () == 1
2600 && sinfo.field_type(0)->code () == TYPE_CODE_COMPLEX)
2602 /* The following is similar to RISCV_CALL_ARG_COMPLEX_FLOAT,
2603 except we use the type of the complex field instead of the
2604 type from AINFO, and the first location might be at a non-zero
2605 offset. */
2606 if (TYPE_LENGTH (sinfo.field_type (0)) <= (2 * cinfo->flen)
2607 && riscv_arg_regs_available (&cinfo->float_regs) >= 2
2608 && !ainfo->is_unnamed)
2610 bool result;
2611 int len = TYPE_LENGTH (sinfo.field_type (0)) / 2;
2612 int offset = sinfo.field_offset (0);
2614 result = riscv_assign_reg_location (&ainfo->argloc[0],
2615 &cinfo->float_regs, len,
2616 offset);
2617 gdb_assert (result);
2619 result = riscv_assign_reg_location (&ainfo->argloc[1],
2620 &cinfo->float_regs, len,
2621 (offset + len));
2622 gdb_assert (result);
2624 else
2625 riscv_call_arg_scalar_int (ainfo, cinfo);
2626 return;
2629 if (sinfo.number_of_fields () == 1
2630 && sinfo.field_type(0)->code () == TYPE_CODE_FLT)
2632 /* The following is similar to RISCV_CALL_ARG_SCALAR_FLOAT,
2633 except we use the type of the first scalar field instead of
2634 the type from AINFO. Also the location might be at a non-zero
2635 offset. */
2636 if (TYPE_LENGTH (sinfo.field_type (0)) > cinfo->flen
2637 || ainfo->is_unnamed)
2638 riscv_call_arg_scalar_int (ainfo, cinfo);
2639 else
2641 int offset = sinfo.field_offset (0);
2642 int len = TYPE_LENGTH (sinfo.field_type (0));
2644 if (!riscv_assign_reg_location (&ainfo->argloc[0],
2645 &cinfo->float_regs,
2646 len, offset))
2647 riscv_call_arg_scalar_int (ainfo, cinfo);
2649 return;
2652 if (sinfo.number_of_fields () == 2
2653 && sinfo.field_type(0)->code () == TYPE_CODE_FLT
2654 && TYPE_LENGTH (sinfo.field_type (0)) <= cinfo->flen
2655 && sinfo.field_type(1)->code () == TYPE_CODE_FLT
2656 && TYPE_LENGTH (sinfo.field_type (1)) <= cinfo->flen
2657 && riscv_arg_regs_available (&cinfo->float_regs) >= 2)
2659 int len0 = TYPE_LENGTH (sinfo.field_type (0));
2660 int offset = sinfo.field_offset (0);
2661 if (!riscv_assign_reg_location (&ainfo->argloc[0],
2662 &cinfo->float_regs, len0, offset))
2663 error (_("failed during argument setup"));
2665 int len1 = TYPE_LENGTH (sinfo.field_type (1));
2666 offset = sinfo.field_offset (1);
2667 gdb_assert (len1 <= (TYPE_LENGTH (ainfo->type)
2668 - TYPE_LENGTH (sinfo.field_type (0))));
2670 if (!riscv_assign_reg_location (&ainfo->argloc[1],
2671 &cinfo->float_regs,
2672 len1, offset))
2673 error (_("failed during argument setup"));
2674 return;
2677 if (sinfo.number_of_fields () == 2
2678 && riscv_arg_regs_available (&cinfo->int_regs) >= 1
2679 && (sinfo.field_type(0)->code () == TYPE_CODE_FLT
2680 && TYPE_LENGTH (sinfo.field_type (0)) <= cinfo->flen
2681 && is_integral_type (sinfo.field_type (1))
2682 && TYPE_LENGTH (sinfo.field_type (1)) <= cinfo->xlen))
2684 int len0 = TYPE_LENGTH (sinfo.field_type (0));
2685 int offset = sinfo.field_offset (0);
2686 if (!riscv_assign_reg_location (&ainfo->argloc[0],
2687 &cinfo->float_regs, len0, offset))
2688 error (_("failed during argument setup"));
2690 int len1 = TYPE_LENGTH (sinfo.field_type (1));
2691 offset = sinfo.field_offset (1);
2692 gdb_assert (len1 <= cinfo->xlen);
2693 if (!riscv_assign_reg_location (&ainfo->argloc[1],
2694 &cinfo->int_regs, len1, offset))
2695 error (_("failed during argument setup"));
2696 return;
2699 if (sinfo.number_of_fields () == 2
2700 && riscv_arg_regs_available (&cinfo->int_regs) >= 1
2701 && (is_integral_type (sinfo.field_type (0))
2702 && TYPE_LENGTH (sinfo.field_type (0)) <= cinfo->xlen
2703 && sinfo.field_type(1)->code () == TYPE_CODE_FLT
2704 && TYPE_LENGTH (sinfo.field_type (1)) <= cinfo->flen))
2706 int len0 = TYPE_LENGTH (sinfo.field_type (0));
2707 int len1 = TYPE_LENGTH (sinfo.field_type (1));
2709 gdb_assert (len0 <= cinfo->xlen);
2710 gdb_assert (len1 <= cinfo->flen);
2712 int offset = sinfo.field_offset (0);
2713 if (!riscv_assign_reg_location (&ainfo->argloc[0],
2714 &cinfo->int_regs, len0, offset))
2715 error (_("failed during argument setup"));
2717 offset = sinfo.field_offset (1);
2718 if (!riscv_assign_reg_location (&ainfo->argloc[1],
2719 &cinfo->float_regs,
2720 len1, offset))
2721 error (_("failed during argument setup"));
2723 return;
2727 /* Non of the structure flattening cases apply, so we just pass using
2728 the integer ABI. */
2729 riscv_call_arg_scalar_int (ainfo, cinfo);
2732 /* Assign a location to call (or return) argument AINFO, the location is
2733 selected from CINFO which holds information about what call argument
2734 locations are available for use next. The TYPE is the type of the
2735 argument being passed, this information is recorded into AINFO (along
2736 with some additional information derived from the type). IS_UNNAMED
2737 is true if this is an unnamed (stdarg) argument, this info is also
2738 recorded into AINFO.
2740 After assigning a location to AINFO, CINFO will have been updated. */
2742 static void
2743 riscv_arg_location (struct gdbarch *gdbarch,
2744 struct riscv_arg_info *ainfo,
2745 struct riscv_call_info *cinfo,
2746 struct type *type, bool is_unnamed)
2748 ainfo->type = type;
2749 ainfo->length = TYPE_LENGTH (ainfo->type);
2750 ainfo->align = type_align (ainfo->type);
2751 ainfo->is_unnamed = is_unnamed;
2752 ainfo->contents = nullptr;
2753 ainfo->argloc[0].c_length = 0;
2754 ainfo->argloc[1].c_length = 0;
2756 switch (ainfo->type->code ())
2758 case TYPE_CODE_INT:
2759 case TYPE_CODE_BOOL:
2760 case TYPE_CODE_CHAR:
2761 case TYPE_CODE_RANGE:
2762 case TYPE_CODE_ENUM:
2763 case TYPE_CODE_PTR:
2764 if (ainfo->length <= cinfo->xlen)
2766 ainfo->type = builtin_type (gdbarch)->builtin_long;
2767 ainfo->length = cinfo->xlen;
2769 else if (ainfo->length <= (2 * cinfo->xlen))
2771 ainfo->type = builtin_type (gdbarch)->builtin_long_long;
2772 ainfo->length = 2 * cinfo->xlen;
2775 /* Recalculate the alignment requirement. */
2776 ainfo->align = type_align (ainfo->type);
2777 riscv_call_arg_scalar_int (ainfo, cinfo);
2778 break;
2780 case TYPE_CODE_FLT:
2781 riscv_call_arg_scalar_float (ainfo, cinfo);
2782 break;
2784 case TYPE_CODE_COMPLEX:
2785 riscv_call_arg_complex_float (ainfo, cinfo);
2786 break;
2788 case TYPE_CODE_STRUCT:
2789 riscv_call_arg_struct (ainfo, cinfo);
2790 break;
2792 default:
2793 riscv_call_arg_scalar_int (ainfo, cinfo);
2794 break;
2798 /* Used for printing debug information about the call argument location in
2799 INFO to STREAM. The addresses in SP_REFS and SP_ARGS are the base
2800 addresses for the location of pass-by-reference and
2801 arguments-on-the-stack memory areas. */
2803 static void
2804 riscv_print_arg_location (ui_file *stream, struct gdbarch *gdbarch,
2805 struct riscv_arg_info *info,
2806 CORE_ADDR sp_refs, CORE_ADDR sp_args)
2808 fprintf_unfiltered (stream, "type: '%s', length: 0x%x, alignment: 0x%x",
2809 TYPE_SAFE_NAME (info->type), info->length, info->align);
2810 switch (info->argloc[0].loc_type)
2812 case riscv_arg_info::location::in_reg:
2813 fprintf_unfiltered
2814 (stream, ", register %s",
2815 gdbarch_register_name (gdbarch, info->argloc[0].loc_data.regno));
2816 if (info->argloc[0].c_length < info->length)
2818 switch (info->argloc[1].loc_type)
2820 case riscv_arg_info::location::in_reg:
2821 fprintf_unfiltered
2822 (stream, ", register %s",
2823 gdbarch_register_name (gdbarch,
2824 info->argloc[1].loc_data.regno));
2825 break;
2827 case riscv_arg_info::location::on_stack:
2828 fprintf_unfiltered (stream, ", on stack at offset 0x%x",
2829 info->argloc[1].loc_data.offset);
2830 break;
2832 case riscv_arg_info::location::by_ref:
2833 default:
2834 /* The second location should never be a reference, any
2835 argument being passed by reference just places its address
2836 in the first location and is done. */
2837 error (_("invalid argument location"));
2838 break;
2841 if (info->argloc[1].c_offset > info->argloc[0].c_length)
2842 fprintf_unfiltered (stream, " (offset 0x%x)",
2843 info->argloc[1].c_offset);
2845 break;
2847 case riscv_arg_info::location::on_stack:
2848 fprintf_unfiltered (stream, ", on stack at offset 0x%x",
2849 info->argloc[0].loc_data.offset);
2850 break;
2852 case riscv_arg_info::location::by_ref:
2853 fprintf_unfiltered
2854 (stream, ", by reference, data at offset 0x%x (%s)",
2855 info->argloc[0].loc_data.offset,
2856 core_addr_to_string (sp_refs + info->argloc[0].loc_data.offset));
2857 if (info->argloc[1].loc_type
2858 == riscv_arg_info::location::in_reg)
2859 fprintf_unfiltered
2860 (stream, ", address in register %s",
2861 gdbarch_register_name (gdbarch, info->argloc[1].loc_data.regno));
2862 else
2864 gdb_assert (info->argloc[1].loc_type
2865 == riscv_arg_info::location::on_stack);
2866 fprintf_unfiltered
2867 (stream, ", address on stack at offset 0x%x (%s)",
2868 info->argloc[1].loc_data.offset,
2869 core_addr_to_string (sp_args + info->argloc[1].loc_data.offset));
2871 break;
2873 default:
2874 gdb_assert_not_reached (_("unknown argument location type"));
2878 /* Wrapper around REGCACHE->cooked_write. Places the LEN bytes of DATA
2879 into a buffer that is at least as big as the register REGNUM, padding
2880 out the DATA with either 0x00, or 0xff. For floating point registers
2881 0xff is used, for everyone else 0x00 is used. */
2883 static void
2884 riscv_regcache_cooked_write (int regnum, const gdb_byte *data, int len,
2885 struct regcache *regcache, int flen)
2887 gdb_byte tmp [sizeof (ULONGEST)];
2889 /* FP values in FP registers must be NaN-boxed. */
2890 if (riscv_is_fp_regno_p (regnum) && len < flen)
2891 memset (tmp, -1, sizeof (tmp));
2892 else
2893 memset (tmp, 0, sizeof (tmp));
2894 memcpy (tmp, data, len);
2895 regcache->cooked_write (regnum, tmp);
2898 /* Implement the push dummy call gdbarch callback. */
2900 static CORE_ADDR
2901 riscv_push_dummy_call (struct gdbarch *gdbarch,
2902 struct value *function,
2903 struct regcache *regcache,
2904 CORE_ADDR bp_addr,
2905 int nargs,
2906 struct value **args,
2907 CORE_ADDR sp,
2908 function_call_return_method return_method,
2909 CORE_ADDR struct_addr)
2911 int i;
2912 CORE_ADDR sp_args, sp_refs;
2913 enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2915 struct riscv_arg_info *arg_info =
2916 (struct riscv_arg_info *) alloca (nargs * sizeof (struct riscv_arg_info));
2918 struct riscv_call_info call_info (gdbarch);
2920 CORE_ADDR osp = sp;
2922 struct type *ftype = check_typedef (value_type (function));
2924 if (ftype->code () == TYPE_CODE_PTR)
2925 ftype = check_typedef (TYPE_TARGET_TYPE (ftype));
2927 /* We'll use register $a0 if we're returning a struct. */
2928 if (return_method == return_method_struct)
2929 ++call_info.int_regs.next_regnum;
2931 for (i = 0; i < nargs; ++i)
2933 struct value *arg_value;
2934 struct type *arg_type;
2935 struct riscv_arg_info *info = &arg_info[i];
2937 arg_value = args[i];
2938 arg_type = check_typedef (value_type (arg_value));
2940 riscv_arg_location (gdbarch, info, &call_info, arg_type,
2941 ftype->has_varargs () && i >= ftype->num_fields ());
2943 if (info->type != arg_type)
2944 arg_value = value_cast (info->type, arg_value);
2945 info->contents = value_contents (arg_value).data ();
2948 /* Adjust the stack pointer and align it. */
2949 sp = sp_refs = align_down (sp - call_info.memory.ref_offset, SP_ALIGNMENT);
2950 sp = sp_args = align_down (sp - call_info.memory.arg_offset, SP_ALIGNMENT);
2952 if (riscv_debug_infcall > 0)
2954 fprintf_unfiltered (gdb_stdlog, "dummy call args:\n");
2955 fprintf_unfiltered (gdb_stdlog, ": floating point ABI %s in use\n",
2956 (riscv_has_fp_abi (gdbarch) ? "is" : "is not"));
2957 fprintf_unfiltered (gdb_stdlog, ": xlen: %d\n: flen: %d\n",
2958 call_info.xlen, call_info.flen);
2959 if (return_method == return_method_struct)
2960 fprintf_unfiltered (gdb_stdlog,
2961 "[*] struct return pointer in register $A0\n");
2962 for (i = 0; i < nargs; ++i)
2964 struct riscv_arg_info *info = &arg_info [i];
2966 fprintf_unfiltered (gdb_stdlog, "[%2d] ", i);
2967 riscv_print_arg_location (gdb_stdlog, gdbarch, info, sp_refs, sp_args);
2968 fprintf_unfiltered (gdb_stdlog, "\n");
2970 if (call_info.memory.arg_offset > 0
2971 || call_info.memory.ref_offset > 0)
2973 fprintf_unfiltered (gdb_stdlog, " Original sp: %s\n",
2974 core_addr_to_string (osp));
2975 fprintf_unfiltered (gdb_stdlog, "Stack required (for args): 0x%x\n",
2976 call_info.memory.arg_offset);
2977 fprintf_unfiltered (gdb_stdlog, "Stack required (for refs): 0x%x\n",
2978 call_info.memory.ref_offset);
2979 fprintf_unfiltered (gdb_stdlog, " Stack allocated: %s\n",
2980 core_addr_to_string_nz (osp - sp));
2984 /* Now load the argument into registers, or onto the stack. */
2986 if (return_method == return_method_struct)
2988 gdb_byte buf[sizeof (LONGEST)];
2990 store_unsigned_integer (buf, call_info.xlen, byte_order, struct_addr);
2991 regcache->cooked_write (RISCV_A0_REGNUM, buf);
2994 for (i = 0; i < nargs; ++i)
2996 CORE_ADDR dst;
2997 int second_arg_length = 0;
2998 const gdb_byte *second_arg_data;
2999 struct riscv_arg_info *info = &arg_info [i];
3001 gdb_assert (info->length > 0);
3003 switch (info->argloc[0].loc_type)
3005 case riscv_arg_info::location::in_reg:
3007 gdb_assert (info->argloc[0].c_length <= info->length);
3009 riscv_regcache_cooked_write (info->argloc[0].loc_data.regno,
3010 (info->contents
3011 + info->argloc[0].c_offset),
3012 info->argloc[0].c_length,
3013 regcache, call_info.flen);
3014 second_arg_length =
3015 (((info->argloc[0].c_length + info->argloc[0].c_offset) < info->length)
3016 ? info->argloc[1].c_length : 0);
3017 second_arg_data = info->contents + info->argloc[1].c_offset;
3019 break;
3021 case riscv_arg_info::location::on_stack:
3022 dst = sp_args + info->argloc[0].loc_data.offset;
3023 write_memory (dst, info->contents, info->length);
3024 second_arg_length = 0;
3025 break;
3027 case riscv_arg_info::location::by_ref:
3028 dst = sp_refs + info->argloc[0].loc_data.offset;
3029 write_memory (dst, info->contents, info->length);
3031 second_arg_length = call_info.xlen;
3032 second_arg_data = (gdb_byte *) &dst;
3033 break;
3035 default:
3036 gdb_assert_not_reached (_("unknown argument location type"));
3039 if (second_arg_length > 0)
3041 switch (info->argloc[1].loc_type)
3043 case riscv_arg_info::location::in_reg:
3045 gdb_assert ((riscv_is_fp_regno_p (info->argloc[1].loc_data.regno)
3046 && second_arg_length <= call_info.flen)
3047 || second_arg_length <= call_info.xlen);
3048 riscv_regcache_cooked_write (info->argloc[1].loc_data.regno,
3049 second_arg_data,
3050 second_arg_length,
3051 regcache, call_info.flen);
3053 break;
3055 case riscv_arg_info::location::on_stack:
3057 CORE_ADDR arg_addr;
3059 arg_addr = sp_args + info->argloc[1].loc_data.offset;
3060 write_memory (arg_addr, second_arg_data, second_arg_length);
3061 break;
3064 case riscv_arg_info::location::by_ref:
3065 default:
3066 /* The second location should never be a reference, any
3067 argument being passed by reference just places its address
3068 in the first location and is done. */
3069 error (_("invalid argument location"));
3070 break;
3075 /* Set the dummy return value to bp_addr.
3076 A dummy breakpoint will be setup to execute the call. */
3078 if (riscv_debug_infcall > 0)
3079 fprintf_unfiltered (gdb_stdlog, ": writing $ra = %s\n",
3080 core_addr_to_string (bp_addr));
3081 regcache_cooked_write_unsigned (regcache, RISCV_RA_REGNUM, bp_addr);
3083 /* Finally, update the stack pointer. */
3085 if (riscv_debug_infcall > 0)
3086 fprintf_unfiltered (gdb_stdlog, ": writing $sp = %s\n",
3087 core_addr_to_string (sp));
3088 regcache_cooked_write_unsigned (regcache, RISCV_SP_REGNUM, sp);
3090 return sp;
3093 /* Implement the return_value gdbarch method. */
3095 static enum return_value_convention
3096 riscv_return_value (struct gdbarch *gdbarch,
3097 struct value *function,
3098 struct type *type,
3099 struct regcache *regcache,
3100 gdb_byte *readbuf,
3101 const gdb_byte *writebuf)
3103 struct riscv_call_info call_info (gdbarch);
3104 struct riscv_arg_info info;
3105 struct type *arg_type;
3107 arg_type = check_typedef (type);
3108 riscv_arg_location (gdbarch, &info, &call_info, arg_type, false);
3110 if (riscv_debug_infcall > 0)
3112 fprintf_unfiltered (gdb_stdlog, "riscv return value:\n");
3113 fprintf_unfiltered (gdb_stdlog, "[R] ");
3114 riscv_print_arg_location (gdb_stdlog, gdbarch, &info, 0, 0);
3115 fprintf_unfiltered (gdb_stdlog, "\n");
3118 if (readbuf != nullptr || writebuf != nullptr)
3120 unsigned int arg_len;
3121 struct value *abi_val;
3122 gdb_byte *old_readbuf = nullptr;
3123 int regnum;
3125 /* We only do one thing at a time. */
3126 gdb_assert (readbuf == nullptr || writebuf == nullptr);
3128 /* In some cases the argument is not returned as the declared type,
3129 and we need to cast to or from the ABI type in order to
3130 correctly access the argument. When writing to the machine we
3131 do the cast here, when reading from the machine the cast occurs
3132 later, after extracting the value. As the ABI type can be
3133 larger than the declared type, then the read or write buffers
3134 passed in might be too small. Here we ensure that we are using
3135 buffers of sufficient size. */
3136 if (writebuf != nullptr)
3138 struct value *arg_val = value_from_contents (arg_type, writebuf);
3139 abi_val = value_cast (info.type, arg_val);
3140 writebuf = value_contents_raw (abi_val).data ();
3142 else
3144 abi_val = allocate_value (info.type);
3145 old_readbuf = readbuf;
3146 readbuf = value_contents_raw (abi_val).data ();
3148 arg_len = TYPE_LENGTH (info.type);
3150 switch (info.argloc[0].loc_type)
3152 /* Return value in register(s). */
3153 case riscv_arg_info::location::in_reg:
3155 regnum = info.argloc[0].loc_data.regno;
3156 gdb_assert (info.argloc[0].c_length <= arg_len);
3157 gdb_assert (info.argloc[0].c_length
3158 <= register_size (gdbarch, regnum));
3160 if (readbuf)
3162 gdb_byte *ptr = readbuf + info.argloc[0].c_offset;
3163 regcache->cooked_read_part (regnum, 0,
3164 info.argloc[0].c_length,
3165 ptr);
3168 if (writebuf)
3170 const gdb_byte *ptr = writebuf + info.argloc[0].c_offset;
3171 riscv_regcache_cooked_write (regnum, ptr,
3172 info.argloc[0].c_length,
3173 regcache, call_info.flen);
3176 /* A return value in register can have a second part in a
3177 second register. */
3178 if (info.argloc[1].c_length > 0)
3180 switch (info.argloc[1].loc_type)
3182 case riscv_arg_info::location::in_reg:
3183 regnum = info.argloc[1].loc_data.regno;
3185 gdb_assert ((info.argloc[0].c_length
3186 + info.argloc[1].c_length) <= arg_len);
3187 gdb_assert (info.argloc[1].c_length
3188 <= register_size (gdbarch, regnum));
3190 if (readbuf)
3192 readbuf += info.argloc[1].c_offset;
3193 regcache->cooked_read_part (regnum, 0,
3194 info.argloc[1].c_length,
3195 readbuf);
3198 if (writebuf)
3200 const gdb_byte *ptr
3201 = writebuf + info.argloc[1].c_offset;
3202 riscv_regcache_cooked_write
3203 (regnum, ptr, info.argloc[1].c_length,
3204 regcache, call_info.flen);
3206 break;
3208 case riscv_arg_info::location::by_ref:
3209 case riscv_arg_info::location::on_stack:
3210 default:
3211 error (_("invalid argument location"));
3212 break;
3216 break;
3218 /* Return value by reference will have its address in A0. */
3219 case riscv_arg_info::location::by_ref:
3221 ULONGEST addr;
3223 regcache_cooked_read_unsigned (regcache, RISCV_A0_REGNUM,
3224 &addr);
3225 if (readbuf != nullptr)
3226 read_memory (addr, readbuf, info.length);
3227 if (writebuf != nullptr)
3228 write_memory (addr, writebuf, info.length);
3230 break;
3232 case riscv_arg_info::location::on_stack:
3233 default:
3234 error (_("invalid argument location"));
3235 break;
3238 /* This completes the cast from abi type back to the declared type
3239 in the case that we are reading from the machine. See the
3240 comment at the head of this block for more details. */
3241 if (readbuf != nullptr)
3243 struct value *arg_val = value_cast (arg_type, abi_val);
3244 memcpy (old_readbuf, value_contents_raw (arg_val).data (),
3245 TYPE_LENGTH (arg_type));
3249 switch (info.argloc[0].loc_type)
3251 case riscv_arg_info::location::in_reg:
3252 return RETURN_VALUE_REGISTER_CONVENTION;
3253 case riscv_arg_info::location::by_ref:
3254 return RETURN_VALUE_ABI_RETURNS_ADDRESS;
3255 case riscv_arg_info::location::on_stack:
3256 default:
3257 error (_("invalid argument location"));
3261 /* Implement the frame_align gdbarch method. */
3263 static CORE_ADDR
3264 riscv_frame_align (struct gdbarch *gdbarch, CORE_ADDR addr)
3266 return align_down (addr, 16);
3269 /* Generate, or return the cached frame cache for the RiscV frame
3270 unwinder. */
3272 static struct riscv_unwind_cache *
3273 riscv_frame_cache (struct frame_info *this_frame, void **this_cache)
3275 CORE_ADDR pc, start_addr;
3276 struct riscv_unwind_cache *cache;
3277 struct gdbarch *gdbarch = get_frame_arch (this_frame);
3278 int numregs, regno;
3280 if ((*this_cache) != NULL)
3281 return (struct riscv_unwind_cache *) *this_cache;
3283 cache = FRAME_OBSTACK_ZALLOC (struct riscv_unwind_cache);
3284 cache->regs = trad_frame_alloc_saved_regs (this_frame);
3285 (*this_cache) = cache;
3287 /* Scan the prologue, filling in the cache. */
3288 start_addr = get_frame_func (this_frame);
3289 pc = get_frame_pc (this_frame);
3290 riscv_scan_prologue (gdbarch, start_addr, pc, cache);
3292 /* We can now calculate the frame base address. */
3293 cache->frame_base
3294 = (get_frame_register_unsigned (this_frame, cache->frame_base_reg)
3295 + cache->frame_base_offset);
3296 if (riscv_debug_unwinder)
3297 fprintf_unfiltered (gdb_stdlog, "Frame base is %s ($%s + 0x%x)\n",
3298 core_addr_to_string (cache->frame_base),
3299 gdbarch_register_name (gdbarch,
3300 cache->frame_base_reg),
3301 cache->frame_base_offset);
3303 /* The prologue scanner sets the address of registers stored to the stack
3304 as the offset of that register from the frame base. The prologue
3305 scanner doesn't know the actual frame base value, and so is unable to
3306 compute the exact address. We do now know the frame base value, so
3307 update the address of registers stored to the stack. */
3308 numregs = gdbarch_num_regs (gdbarch) + gdbarch_num_pseudo_regs (gdbarch);
3309 for (regno = 0; regno < numregs; ++regno)
3311 if (cache->regs[regno].is_addr ())
3312 cache->regs[regno].set_addr (cache->regs[regno].addr ()
3313 + cache->frame_base);
3316 /* The previous $pc can be found wherever the $ra value can be found.
3317 The previous $ra value is gone, this would have been stored be the
3318 previous frame if required. */
3319 cache->regs[gdbarch_pc_regnum (gdbarch)] = cache->regs[RISCV_RA_REGNUM];
3320 cache->regs[RISCV_RA_REGNUM].set_unknown ();
3322 /* Build the frame id. */
3323 cache->this_id = frame_id_build (cache->frame_base, start_addr);
3325 /* The previous $sp value is the frame base value. */
3326 cache->regs[gdbarch_sp_regnum (gdbarch)].set_value (cache->frame_base);
3328 return cache;
3331 /* Implement the this_id callback for RiscV frame unwinder. */
3333 static void
3334 riscv_frame_this_id (struct frame_info *this_frame,
3335 void **prologue_cache,
3336 struct frame_id *this_id)
3338 struct riscv_unwind_cache *cache;
3342 cache = riscv_frame_cache (this_frame, prologue_cache);
3343 *this_id = cache->this_id;
3345 catch (const gdb_exception_error &ex)
3347 /* Ignore errors, this leaves the frame id as the predefined outer
3348 frame id which terminates the backtrace at this point. */
3352 /* Implement the prev_register callback for RiscV frame unwinder. */
3354 static struct value *
3355 riscv_frame_prev_register (struct frame_info *this_frame,
3356 void **prologue_cache,
3357 int regnum)
3359 struct riscv_unwind_cache *cache;
3361 cache = riscv_frame_cache (this_frame, prologue_cache);
3362 return trad_frame_get_prev_register (this_frame, cache->regs, regnum);
3365 /* Structure defining the RiscV normal frame unwind functions. Since we
3366 are the fallback unwinder (DWARF unwinder is used first), we use the
3367 default frame sniffer, which always accepts the frame. */
3369 static const struct frame_unwind riscv_frame_unwind =
3371 /*.name =*/ "riscv prologue",
3372 /*.type =*/ NORMAL_FRAME,
3373 /*.stop_reason =*/ default_frame_unwind_stop_reason,
3374 /*.this_id =*/ riscv_frame_this_id,
3375 /*.prev_register =*/ riscv_frame_prev_register,
3376 /*.unwind_data =*/ NULL,
3377 /*.sniffer =*/ default_frame_sniffer,
3378 /*.dealloc_cache =*/ NULL,
3379 /*.prev_arch =*/ NULL,
3382 /* Extract a set of required target features out of ABFD. If ABFD is
3383 nullptr then a RISCV_GDBARCH_FEATURES is returned in its default state. */
3385 static struct riscv_gdbarch_features
3386 riscv_features_from_bfd (const bfd *abfd)
3388 struct riscv_gdbarch_features features;
3390 /* Now try to improve on the defaults by looking at the binary we are
3391 going to execute. We assume the user knows what they are doing and
3392 that the target will match the binary. Remember, this code path is
3393 only used at all if the target hasn't given us a description, so this
3394 is really a last ditched effort to do something sane before giving
3395 up. */
3396 if (abfd != nullptr && bfd_get_flavour (abfd) == bfd_target_elf_flavour)
3398 unsigned char eclass = elf_elfheader (abfd)->e_ident[EI_CLASS];
3399 int e_flags = elf_elfheader (abfd)->e_flags;
3401 if (eclass == ELFCLASS32)
3402 features.xlen = 4;
3403 else if (eclass == ELFCLASS64)
3404 features.xlen = 8;
3405 else
3406 internal_error (__FILE__, __LINE__,
3407 _("unknown ELF header class %d"), eclass);
3409 if (e_flags & EF_RISCV_FLOAT_ABI_DOUBLE)
3410 features.flen = 8;
3411 else if (e_flags & EF_RISCV_FLOAT_ABI_SINGLE)
3412 features.flen = 4;
3414 if (e_flags & EF_RISCV_RVE)
3416 if (features.xlen == 8)
3418 warning (_("64-bit ELF with RV32E flag set! Assuming 32-bit"));
3419 features.xlen = 4;
3421 features.embedded = true;
3425 return features;
3428 /* Find a suitable default target description. Use the contents of INFO,
3429 specifically the bfd object being executed, to guide the selection of a
3430 suitable default target description. */
3432 static const struct target_desc *
3433 riscv_find_default_target_description (const struct gdbarch_info info)
3435 /* Extract desired feature set from INFO. */
3436 struct riscv_gdbarch_features features
3437 = riscv_features_from_bfd (info.abfd);
3439 /* If the XLEN field is still 0 then we got nothing useful from INFO.BFD,
3440 maybe there was no bfd object. In this case we fall back to a minimal
3441 useful target with no floating point, the x-register size is selected
3442 based on the architecture from INFO. */
3443 if (features.xlen == 0)
3444 features.xlen = info.bfd_arch_info->bits_per_word == 32 ? 4 : 8;
3446 /* Now build a target description based on the feature set. */
3447 return riscv_lookup_target_description (features);
3450 /* Add all the expected register sets into GDBARCH. */
3452 static void
3453 riscv_add_reggroups (struct gdbarch *gdbarch)
3455 /* Add predefined register groups. */
3456 reggroup_add (gdbarch, all_reggroup);
3457 reggroup_add (gdbarch, save_reggroup);
3458 reggroup_add (gdbarch, restore_reggroup);
3459 reggroup_add (gdbarch, system_reggroup);
3460 reggroup_add (gdbarch, vector_reggroup);
3461 reggroup_add (gdbarch, general_reggroup);
3462 reggroup_add (gdbarch, float_reggroup);
3464 /* Add RISC-V specific register groups. */
3465 reggroup_add (gdbarch, csr_reggroup);
3468 /* Implement the "dwarf2_reg_to_regnum" gdbarch method. */
3470 static int
3471 riscv_dwarf_reg_to_regnum (struct gdbarch *gdbarch, int reg)
3473 if (reg < RISCV_DWARF_REGNUM_X31)
3474 return RISCV_ZERO_REGNUM + (reg - RISCV_DWARF_REGNUM_X0);
3476 else if (reg < RISCV_DWARF_REGNUM_F31)
3477 return RISCV_FIRST_FP_REGNUM + (reg - RISCV_DWARF_REGNUM_F0);
3479 else if (reg >= RISCV_DWARF_FIRST_CSR && reg <= RISCV_DWARF_LAST_CSR)
3480 return RISCV_FIRST_CSR_REGNUM + (reg - RISCV_DWARF_FIRST_CSR);
3482 else if (reg >= RISCV_DWARF_REGNUM_V0 && reg <= RISCV_DWARF_REGNUM_V31)
3483 return RISCV_V0_REGNUM + (reg - RISCV_DWARF_REGNUM_V0);
3485 return -1;
3488 /* Implement the gcc_target_options method. We have to select the arch and abi
3489 from the feature info. We have enough feature info to select the abi, but
3490 not enough info for the arch given all of the possible architecture
3491 extensions. So choose reasonable defaults for now. */
3493 static std::string
3494 riscv_gcc_target_options (struct gdbarch *gdbarch)
3496 int isa_xlen = riscv_isa_xlen (gdbarch);
3497 int isa_flen = riscv_isa_flen (gdbarch);
3498 int abi_xlen = riscv_abi_xlen (gdbarch);
3499 int abi_flen = riscv_abi_flen (gdbarch);
3500 std::string target_options;
3502 target_options = "-march=rv";
3503 if (isa_xlen == 8)
3504 target_options += "64";
3505 else
3506 target_options += "32";
3507 if (isa_flen == 8)
3508 target_options += "gc";
3509 else if (isa_flen == 4)
3510 target_options += "imafc";
3511 else
3512 target_options += "imac";
3514 target_options += " -mabi=";
3515 if (abi_xlen == 8)
3516 target_options += "lp64";
3517 else
3518 target_options += "ilp32";
3519 if (abi_flen == 8)
3520 target_options += "d";
3521 else if (abi_flen == 4)
3522 target_options += "f";
3524 /* The gdb loader doesn't handle link-time relaxation relocations. */
3525 target_options += " -mno-relax";
3527 return target_options;
3530 /* Call back from tdesc_use_registers, called for each unknown register
3531 found in the target description.
3533 See target-description.h (typedef tdesc_unknown_register_ftype) for a
3534 discussion of the arguments and return values. */
3536 static int
3537 riscv_tdesc_unknown_reg (struct gdbarch *gdbarch, tdesc_feature *feature,
3538 const char *reg_name, int possible_regnum)
3540 /* At one point in time GDB had an incorrect default target description
3541 that duplicated the fflags, frm, and fcsr registers in both the FPU
3542 and CSR register sets.
3544 Some targets (QEMU) copied these target descriptions into their source
3545 tree, and so we're currently stuck working with some targets that
3546 declare the same registers twice.
3548 There's not much we can do about this any more. Assuming the target
3549 will direct a request for either register number to the correct
3550 underlying hardware register then it doesn't matter which one GDB
3551 uses, so long as we (GDB) are consistent (so that we don't end up with
3552 invalid cache misses).
3554 As we always scan the FPU registers first, then the CSRs, if the
3555 target has included the offending registers in both sets then we will
3556 always see the FPU copies here, as the CSR versions will replace them
3557 in the register list.
3559 To prevent these duplicates showing up in any of the register list,
3560 record their register numbers here. */
3561 if (strcmp (tdesc_feature_name (feature), riscv_freg_feature.name ()) == 0)
3563 struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
3564 int *regnum_ptr = nullptr;
3566 if (strcmp (reg_name, "fflags") == 0)
3567 regnum_ptr = &tdep->duplicate_fflags_regnum;
3568 else if (strcmp (reg_name, "frm") == 0)
3569 regnum_ptr = &tdep->duplicate_frm_regnum;
3570 else if (strcmp (reg_name, "fcsr") == 0)
3571 regnum_ptr = &tdep->duplicate_fcsr_regnum;
3573 if (regnum_ptr != nullptr)
3575 /* This means the register appears more than twice in the target
3576 description. Just let GDB add this as another register.
3577 We'll have duplicates in the register name list, but there's
3578 not much more we can do. */
3579 if (*regnum_ptr != -1)
3580 return -1;
3582 /* Record the number assigned to this register, then return the
3583 number (so it actually gets assigned to this register). */
3584 *regnum_ptr = possible_regnum;
3585 return possible_regnum;
3589 /* Any unknown registers in the CSR feature are recorded within a single
3590 block so we can easily identify these registers when making choices
3591 about register groups in riscv_register_reggroup_p. */
3592 if (strcmp (tdesc_feature_name (feature), riscv_csr_feature.name ()) == 0)
3594 struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
3595 if (tdep->unknown_csrs_first_regnum == -1)
3596 tdep->unknown_csrs_first_regnum = possible_regnum;
3597 gdb_assert (tdep->unknown_csrs_first_regnum
3598 + tdep->unknown_csrs_count == possible_regnum);
3599 tdep->unknown_csrs_count++;
3600 return possible_regnum;
3603 /* Some other unknown register. Don't assign this a number now, it will
3604 be assigned a number automatically later by the target description
3605 handling code. */
3606 return -1;
3609 /* Implement the gnu_triplet_regexp method. A single compiler supports both
3610 32-bit and 64-bit code, and may be named riscv32 or riscv64 or (not
3611 recommended) riscv. */
3613 static const char *
3614 riscv_gnu_triplet_regexp (struct gdbarch *gdbarch)
3616 return "riscv(32|64)?";
3619 /* Initialize the current architecture based on INFO. If possible,
3620 re-use an architecture from ARCHES, which is a list of
3621 architectures already created during this debugging session.
3623 Called e.g. at program startup, when reading a core file, and when
3624 reading a binary file. */
3626 static struct gdbarch *
3627 riscv_gdbarch_init (struct gdbarch_info info,
3628 struct gdbarch_list *arches)
3630 struct gdbarch *gdbarch;
3631 struct gdbarch_tdep *tdep;
3632 struct riscv_gdbarch_features features;
3633 const struct target_desc *tdesc = info.target_desc;
3635 /* Ensure we always have a target description. */
3636 if (!tdesc_has_registers (tdesc))
3637 tdesc = riscv_find_default_target_description (info);
3638 gdb_assert (tdesc != nullptr);
3640 if (riscv_debug_gdbarch)
3641 fprintf_unfiltered (gdb_stdlog, "Have got a target description\n");
3643 tdesc_arch_data_up tdesc_data = tdesc_data_alloc ();
3644 std::vector<riscv_pending_register_alias> pending_aliases;
3646 bool valid_p = (riscv_xreg_feature.check (tdesc, tdesc_data.get (),
3647 &pending_aliases, &features)
3648 && riscv_freg_feature.check (tdesc, tdesc_data.get (),
3649 &pending_aliases, &features)
3650 && riscv_virtual_feature.check (tdesc, tdesc_data.get (),
3651 &pending_aliases, &features)
3652 && riscv_csr_feature.check (tdesc, tdesc_data.get (),
3653 &pending_aliases, &features)
3654 && riscv_vector_feature.check (tdesc, tdesc_data.get (),
3655 &pending_aliases, &features));
3656 if (!valid_p)
3658 if (riscv_debug_gdbarch)
3659 fprintf_unfiltered (gdb_stdlog, "Target description is not valid\n");
3660 return NULL;
3663 /* Have a look at what the supplied (if any) bfd object requires of the
3664 target, then check that this matches with what the target is
3665 providing. */
3666 struct riscv_gdbarch_features abi_features
3667 = riscv_features_from_bfd (info.abfd);
3669 /* If the ABI_FEATURES xlen is 0 then this indicates we got no useful abi
3670 features from the INFO object. In this case we just treat the
3671 hardware features as defining the abi. */
3672 if (abi_features.xlen == 0)
3673 abi_features = features;
3675 /* In theory a binary compiled for RV32 could run on an RV64 target,
3676 however, this has not been tested in GDB yet, so for now we require
3677 that the requested xlen match the targets xlen. */
3678 if (abi_features.xlen != features.xlen)
3679 error (_("bfd requires xlen %d, but target has xlen %d"),
3680 abi_features.xlen, features.xlen);
3681 /* We do support running binaries compiled for 32-bit float on targets
3682 with 64-bit float, so we only complain if the binary requires more
3683 than the target has available. */
3684 if (abi_features.flen > features.flen)
3685 error (_("bfd requires flen %d, but target has flen %d"),
3686 abi_features.flen, features.flen);
3688 /* Find a candidate among the list of pre-declared architectures. */
3689 for (arches = gdbarch_list_lookup_by_info (arches, &info);
3690 arches != NULL;
3691 arches = gdbarch_list_lookup_by_info (arches->next, &info))
3693 /* Check that the feature set of the ARCHES matches the feature set
3694 we are looking for. If it doesn't then we can't reuse this
3695 gdbarch. */
3696 struct gdbarch_tdep *other_tdep = gdbarch_tdep (arches->gdbarch);
3698 if (other_tdep->isa_features != features
3699 || other_tdep->abi_features != abi_features)
3700 continue;
3702 break;
3705 if (arches != NULL)
3706 return arches->gdbarch;
3708 /* None found, so create a new architecture from the information provided. */
3709 tdep = new (struct gdbarch_tdep);
3710 gdbarch = gdbarch_alloc (&info, tdep);
3711 tdep->isa_features = features;
3712 tdep->abi_features = abi_features;
3714 /* Target data types. */
3715 set_gdbarch_short_bit (gdbarch, 16);
3716 set_gdbarch_int_bit (gdbarch, 32);
3717 set_gdbarch_long_bit (gdbarch, riscv_isa_xlen (gdbarch) * 8);
3718 set_gdbarch_long_long_bit (gdbarch, 64);
3719 set_gdbarch_float_bit (gdbarch, 32);
3720 set_gdbarch_double_bit (gdbarch, 64);
3721 set_gdbarch_long_double_bit (gdbarch, 128);
3722 set_gdbarch_long_double_format (gdbarch, floatformats_ia64_quad);
3723 set_gdbarch_ptr_bit (gdbarch, riscv_isa_xlen (gdbarch) * 8);
3724 set_gdbarch_char_signed (gdbarch, 0);
3725 set_gdbarch_type_align (gdbarch, riscv_type_align);
3727 /* Information about the target architecture. */
3728 set_gdbarch_return_value (gdbarch, riscv_return_value);
3729 set_gdbarch_breakpoint_kind_from_pc (gdbarch, riscv_breakpoint_kind_from_pc);
3730 set_gdbarch_sw_breakpoint_from_kind (gdbarch, riscv_sw_breakpoint_from_kind);
3731 set_gdbarch_have_nonsteppable_watchpoint (gdbarch, 1);
3733 /* Functions to analyze frames. */
3734 set_gdbarch_skip_prologue (gdbarch, riscv_skip_prologue);
3735 set_gdbarch_inner_than (gdbarch, core_addr_lessthan);
3736 set_gdbarch_frame_align (gdbarch, riscv_frame_align);
3738 /* Functions handling dummy frames. */
3739 set_gdbarch_call_dummy_location (gdbarch, ON_STACK);
3740 set_gdbarch_push_dummy_code (gdbarch, riscv_push_dummy_code);
3741 set_gdbarch_push_dummy_call (gdbarch, riscv_push_dummy_call);
3743 /* Frame unwinders. Use DWARF debug info if available, otherwise use our own
3744 unwinder. */
3745 dwarf2_append_unwinders (gdbarch);
3746 frame_unwind_append_unwinder (gdbarch, &riscv_frame_unwind);
3748 /* Register architecture. */
3749 riscv_add_reggroups (gdbarch);
3751 /* Internal <-> external register number maps. */
3752 set_gdbarch_dwarf2_reg_to_regnum (gdbarch, riscv_dwarf_reg_to_regnum);
3754 /* We reserve all possible register numbers for the known registers.
3755 This means the target description mechanism will add any target
3756 specific registers after this number. This helps make debugging GDB
3757 just a little easier. */
3758 set_gdbarch_num_regs (gdbarch, RISCV_LAST_REGNUM + 1);
3760 /* We don't have to provide the count of 0 here (its the default) but
3761 include this line to make it explicit that, right now, we don't have
3762 any pseudo registers on RISC-V. */
3763 set_gdbarch_num_pseudo_regs (gdbarch, 0);
3765 /* Some specific register numbers GDB likes to know about. */
3766 set_gdbarch_sp_regnum (gdbarch, RISCV_SP_REGNUM);
3767 set_gdbarch_pc_regnum (gdbarch, RISCV_PC_REGNUM);
3769 set_gdbarch_print_registers_info (gdbarch, riscv_print_registers_info);
3771 /* Finalise the target description registers. */
3772 tdesc_use_registers (gdbarch, tdesc, std::move (tdesc_data),
3773 riscv_tdesc_unknown_reg);
3775 /* Override the register type callback setup by the target description
3776 mechanism. This allows us to provide special type for floating point
3777 registers. */
3778 set_gdbarch_register_type (gdbarch, riscv_register_type);
3780 /* Override the register name callback setup by the target description
3781 mechanism. This allows us to force our preferred names for the
3782 registers, no matter what the target description called them. */
3783 set_gdbarch_register_name (gdbarch, riscv_register_name);
3785 /* Override the register group callback setup by the target description
3786 mechanism. This allows us to force registers into the groups we
3787 want, ignoring what the target tells us. */
3788 set_gdbarch_register_reggroup_p (gdbarch, riscv_register_reggroup_p);
3790 /* Create register aliases for alternative register names. We only
3791 create aliases for registers which were mentioned in the target
3792 description. */
3793 for (const auto &alias : pending_aliases)
3794 alias.create (gdbarch);
3796 /* Compile command hooks. */
3797 set_gdbarch_gcc_target_options (gdbarch, riscv_gcc_target_options);
3798 set_gdbarch_gnu_triplet_regexp (gdbarch, riscv_gnu_triplet_regexp);
3800 /* Hook in OS ABI-specific overrides, if they have been registered. */
3801 gdbarch_init_osabi (info, gdbarch);
3803 register_riscv_ravenscar_ops (gdbarch);
3805 return gdbarch;
3808 /* This decodes the current instruction and determines the address of the
3809 next instruction. */
3811 static CORE_ADDR
3812 riscv_next_pc (struct regcache *regcache, CORE_ADDR pc)
3814 struct gdbarch *gdbarch = regcache->arch ();
3815 const struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
3816 struct riscv_insn insn;
3817 CORE_ADDR next_pc;
3819 insn.decode (gdbarch, pc);
3820 next_pc = pc + insn.length ();
3822 if (insn.opcode () == riscv_insn::JAL)
3823 next_pc = pc + insn.imm_signed ();
3824 else if (insn.opcode () == riscv_insn::JALR)
3826 LONGEST source;
3827 regcache->cooked_read (insn.rs1 (), &source);
3828 next_pc = (source + insn.imm_signed ()) & ~(CORE_ADDR) 0x1;
3830 else if (insn.opcode () == riscv_insn::BEQ)
3832 LONGEST src1, src2;
3833 regcache->cooked_read (insn.rs1 (), &src1);
3834 regcache->cooked_read (insn.rs2 (), &src2);
3835 if (src1 == src2)
3836 next_pc = pc + insn.imm_signed ();
3838 else if (insn.opcode () == riscv_insn::BNE)
3840 LONGEST src1, src2;
3841 regcache->cooked_read (insn.rs1 (), &src1);
3842 regcache->cooked_read (insn.rs2 (), &src2);
3843 if (src1 != src2)
3844 next_pc = pc + insn.imm_signed ();
3846 else if (insn.opcode () == riscv_insn::BLT)
3848 LONGEST src1, src2;
3849 regcache->cooked_read (insn.rs1 (), &src1);
3850 regcache->cooked_read (insn.rs2 (), &src2);
3851 if (src1 < src2)
3852 next_pc = pc + insn.imm_signed ();
3854 else if (insn.opcode () == riscv_insn::BGE)
3856 LONGEST src1, src2;
3857 regcache->cooked_read (insn.rs1 (), &src1);
3858 regcache->cooked_read (insn.rs2 (), &src2);
3859 if (src1 >= src2)
3860 next_pc = pc + insn.imm_signed ();
3862 else if (insn.opcode () == riscv_insn::BLTU)
3864 ULONGEST src1, src2;
3865 regcache->cooked_read (insn.rs1 (), &src1);
3866 regcache->cooked_read (insn.rs2 (), &src2);
3867 if (src1 < src2)
3868 next_pc = pc + insn.imm_signed ();
3870 else if (insn.opcode () == riscv_insn::BGEU)
3872 ULONGEST src1, src2;
3873 regcache->cooked_read (insn.rs1 (), &src1);
3874 regcache->cooked_read (insn.rs2 (), &src2);
3875 if (src1 >= src2)
3876 next_pc = pc + insn.imm_signed ();
3878 else if (insn.opcode () == riscv_insn::ECALL)
3880 if (tdep->syscall_next_pc != nullptr)
3881 next_pc = tdep->syscall_next_pc (get_current_frame ());
3884 return next_pc;
3887 /* We can't put a breakpoint in the middle of a lr/sc atomic sequence, so look
3888 for the end of the sequence and put the breakpoint there. */
3890 static bool
3891 riscv_next_pc_atomic_sequence (struct regcache *regcache, CORE_ADDR pc,
3892 CORE_ADDR *next_pc)
3894 struct gdbarch *gdbarch = regcache->arch ();
3895 struct riscv_insn insn;
3896 CORE_ADDR cur_step_pc = pc;
3897 CORE_ADDR last_addr = 0;
3899 /* First instruction has to be a load reserved. */
3900 insn.decode (gdbarch, cur_step_pc);
3901 if (insn.opcode () != riscv_insn::LR)
3902 return false;
3903 cur_step_pc = cur_step_pc + insn.length ();
3905 /* Next instruction should be branch to exit. */
3906 insn.decode (gdbarch, cur_step_pc);
3907 if (insn.opcode () != riscv_insn::BNE)
3908 return false;
3909 last_addr = cur_step_pc + insn.imm_signed ();
3910 cur_step_pc = cur_step_pc + insn.length ();
3912 /* Next instruction should be store conditional. */
3913 insn.decode (gdbarch, cur_step_pc);
3914 if (insn.opcode () != riscv_insn::SC)
3915 return false;
3916 cur_step_pc = cur_step_pc + insn.length ();
3918 /* Next instruction should be branch to start. */
3919 insn.decode (gdbarch, cur_step_pc);
3920 if (insn.opcode () != riscv_insn::BNE)
3921 return false;
3922 if (pc != (cur_step_pc + insn.imm_signed ()))
3923 return false;
3924 cur_step_pc = cur_step_pc + insn.length ();
3926 /* We should now be at the end of the sequence. */
3927 if (cur_step_pc != last_addr)
3928 return false;
3930 *next_pc = cur_step_pc;
3931 return true;
3934 /* This is called just before we want to resume the inferior, if we want to
3935 single-step it but there is no hardware or kernel single-step support. We
3936 find the target of the coming instruction and breakpoint it. */
3938 std::vector<CORE_ADDR>
3939 riscv_software_single_step (struct regcache *regcache)
3941 CORE_ADDR pc, next_pc;
3943 pc = regcache_read_pc (regcache);
3945 if (riscv_next_pc_atomic_sequence (regcache, pc, &next_pc))
3946 return {next_pc};
3948 next_pc = riscv_next_pc (regcache, pc);
3950 return {next_pc};
3953 /* Create RISC-V specific reggroups. */
3955 static void
3956 riscv_init_reggroups ()
3958 csr_reggroup = reggroup_new ("csr", USER_REGGROUP);
3961 /* See riscv-tdep.h. */
3963 void
3964 riscv_supply_regset (const struct regset *regset,
3965 struct regcache *regcache, int regnum,
3966 const void *regs, size_t len)
3968 regcache->supply_regset (regset, regnum, regs, len);
3970 if (regnum == -1 || regnum == RISCV_ZERO_REGNUM)
3971 regcache->raw_supply_zeroed (RISCV_ZERO_REGNUM);
3973 if (regnum == -1 || regnum == RISCV_CSR_FFLAGS_REGNUM
3974 || regnum == RISCV_CSR_FRM_REGNUM)
3976 int fcsr_regnum = RISCV_CSR_FCSR_REGNUM;
3978 /* Ensure that FCSR has been read into REGCACHE. */
3979 if (regnum != -1)
3980 regcache->supply_regset (regset, fcsr_regnum, regs, len);
3982 /* Grab the FCSR value if it is now in the regcache. We must check
3983 the status first as, if the register was not supplied by REGSET,
3984 this call will trigger a recursive attempt to fetch the
3985 registers. */
3986 if (regcache->get_register_status (fcsr_regnum) == REG_VALID)
3988 ULONGEST fcsr_val;
3989 regcache->raw_read (fcsr_regnum, &fcsr_val);
3991 /* Extract the fflags and frm values. */
3992 ULONGEST fflags_val = fcsr_val & 0x1f;
3993 ULONGEST frm_val = (fcsr_val >> 5) & 0x7;
3995 /* And supply these if needed. */
3996 if (regnum == -1 || regnum == RISCV_CSR_FFLAGS_REGNUM)
3997 regcache->raw_supply_integer (RISCV_CSR_FFLAGS_REGNUM,
3998 (gdb_byte *) &fflags_val,
3999 sizeof (fflags_val),
4000 /* is_signed */ false);
4002 if (regnum == -1 || regnum == RISCV_CSR_FRM_REGNUM)
4003 regcache->raw_supply_integer (RISCV_CSR_FRM_REGNUM,
4004 (gdb_byte *)&frm_val,
4005 sizeof (fflags_val),
4006 /* is_signed */ false);
4011 void _initialize_riscv_tdep ();
4012 void
4013 _initialize_riscv_tdep ()
4015 riscv_init_reggroups ();
4017 gdbarch_register (bfd_arch_riscv, riscv_gdbarch_init, NULL);
4019 /* Add root prefix command for all "set debug riscv" and "show debug
4020 riscv" commands. */
4021 add_setshow_prefix_cmd ("riscv", no_class,
4022 _("RISC-V specific debug commands."),
4023 _("RISC-V specific debug commands."),
4024 &setdebugriscvcmdlist, &showdebugriscvcmdlist,
4025 &setdebuglist, &showdebuglist);
4027 add_setshow_zuinteger_cmd ("breakpoints", class_maintenance,
4028 &riscv_debug_breakpoints, _("\
4029 Set riscv breakpoint debugging."), _("\
4030 Show riscv breakpoint debugging."), _("\
4031 When non-zero, print debugging information for the riscv specific parts\n\
4032 of the breakpoint mechanism."),
4033 NULL,
4034 show_riscv_debug_variable,
4035 &setdebugriscvcmdlist, &showdebugriscvcmdlist);
4037 add_setshow_zuinteger_cmd ("infcall", class_maintenance,
4038 &riscv_debug_infcall, _("\
4039 Set riscv inferior call debugging."), _("\
4040 Show riscv inferior call debugging."), _("\
4041 When non-zero, print debugging information for the riscv specific parts\n\
4042 of the inferior call mechanism."),
4043 NULL,
4044 show_riscv_debug_variable,
4045 &setdebugriscvcmdlist, &showdebugriscvcmdlist);
4047 add_setshow_zuinteger_cmd ("unwinder", class_maintenance,
4048 &riscv_debug_unwinder, _("\
4049 Set riscv stack unwinding debugging."), _("\
4050 Show riscv stack unwinding debugging."), _("\
4051 When non-zero, print debugging information for the riscv specific parts\n\
4052 of the stack unwinding mechanism."),
4053 NULL,
4054 show_riscv_debug_variable,
4055 &setdebugriscvcmdlist, &showdebugriscvcmdlist);
4057 add_setshow_zuinteger_cmd ("gdbarch", class_maintenance,
4058 &riscv_debug_gdbarch, _("\
4059 Set riscv gdbarch initialisation debugging."), _("\
4060 Show riscv gdbarch initialisation debugging."), _("\
4061 When non-zero, print debugging information for the riscv gdbarch\n\
4062 initialisation process."),
4063 NULL,
4064 show_riscv_debug_variable,
4065 &setdebugriscvcmdlist, &showdebugriscvcmdlist);
4067 /* Add root prefix command for all "set riscv" and "show riscv" commands. */
4068 add_setshow_prefix_cmd ("riscv", no_class,
4069 _("RISC-V specific commands."),
4070 _("RISC-V specific commands."),
4071 &setriscvcmdlist, &showriscvcmdlist,
4072 &setlist, &showlist);
4075 use_compressed_breakpoints = AUTO_BOOLEAN_AUTO;
4076 add_setshow_auto_boolean_cmd ("use-compressed-breakpoints", no_class,
4077 &use_compressed_breakpoints,
4078 _("\
4079 Set debugger's use of compressed breakpoints."), _(" \
4080 Show debugger's use of compressed breakpoints."), _("\
4081 Debugging compressed code requires compressed breakpoints to be used. If\n\
4082 left to 'auto' then gdb will use them if the existing instruction is a\n\
4083 compressed instruction. If that doesn't give the correct behavior, then\n\
4084 this option can be used."),
4085 NULL,
4086 show_use_compressed_breakpoints,
4087 &setriscvcmdlist,
4088 &showriscvcmdlist);