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