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