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