Use XCNEW gdbarch_tdep
[external/binutils.git] / gdb / arc-tdep.c
1 /* Target dependent code for ARC arhitecture, for GDB.
2
3    Copyright 2005-2017 Free Software Foundation, Inc.
4    Contributed by Synopsys Inc.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21 /* GDB header files.  */
22 #include "defs.h"
23 #include "arch-utils.h"
24 #include "disasm.h"
25 #include "dwarf2-frame.h"
26 #include "frame-base.h"
27 #include "frame-unwind.h"
28 #include "gdbcore.h"
29 #include "gdbcmd.h"
30 #include "objfiles.h"
31 #include "prologue-value.h"
32 #include "trad-frame.h"
33
34 /* ARC header files.  */
35 #include "opcode/arc.h"
36 #include "opcodes/arc-dis.h"
37 #include "arc-tdep.h"
38
39 /* Standard headers.  */
40 #include <algorithm>
41
42 /* Default target descriptions.  */
43 #include "features/arc-v2.c"
44 #include "features/arc-arcompact.c"
45
46 /* The frame unwind cache for ARC.  */
47
48 struct arc_frame_cache
49 {
50   /* The stack pointer at the time this frame was created; i.e. the caller's
51      stack pointer when this function was called.  It is used to identify this
52      frame.  */
53   CORE_ADDR prev_sp;
54
55   /* Register that is a base for this frame - FP for normal frame, SP for
56      non-FP frames.  */
57   int frame_base_reg;
58
59   /* Offset from the previous SP to the current frame base.  If GCC uses
60      `SUB SP,SP,offset` to allocate space for local variables, then it will be
61      done after setting up a frame pointer, but it still will be considered
62      part of prologue, therefore SP will be lesser than FP at the end of the
63      prologue analysis.  In this case that would be an offset from old SP to a
64      new FP.  But in case of non-FP frames, frame base is an SP and thus that
65      would be an offset from old SP to new SP.  What is important is that this
66      is an offset from old SP to a known register, so it can be used to find
67      old SP.
68
69      Using FP is preferable, when possible, because SP can change in function
70      body after prologue due to alloca, variadic arguments or other shenanigans.
71      If that is the case in the caller frame, then PREV_SP will point to SP at
72      the moment of function call, but it will be different from SP value at the
73      end of the caller prologue.  As a result it will not be possible to
74      reconstruct caller's frame and go past it in the backtrace.  Those things
75      are unlikely to happen to FP - FP value at the moment of function call (as
76      stored on stack in callee prologue) is also an FP value at the end of the
77      caller's prologue.  */
78
79   LONGEST frame_base_offset;
80
81   /* Store addresses for registers saved in prologue.  During prologue analysis
82      GDB stores offsets relatively to "old SP", then after old SP is evaluated,
83      offsets are replaced with absolute addresses.  */
84   struct trad_frame_saved_reg *saved_regs;
85 };
86
87 /* Global debug flag.  */
88
89 int arc_debug;
90
91 /* List of "maintenance print arc" commands.  */
92
93 static struct cmd_list_element *maintenance_print_arc_list = NULL;
94
95 /* XML target description features.  */
96
97 static const char core_v2_feature_name[] = "org.gnu.gdb.arc.core.v2";
98 static const char
99   core_reduced_v2_feature_name[] = "org.gnu.gdb.arc.core-reduced.v2";
100 static const char
101   core_arcompact_feature_name[] = "org.gnu.gdb.arc.core.arcompact";
102 static const char aux_minimal_feature_name[] = "org.gnu.gdb.arc.aux-minimal";
103
104 /* XML target description known registers.  */
105
106 static const char *const core_v2_register_names[] = {
107   "r0", "r1", "r2", "r3",
108   "r4", "r5", "r6", "r7",
109   "r8", "r9", "r10", "r11",
110   "r12", "r13", "r14", "r15",
111   "r16", "r17", "r18", "r19",
112   "r20", "r21", "r22", "r23",
113   "r24", "r25", "gp", "fp",
114   "sp", "ilink", "r30", "blink",
115   "r32", "r33", "r34", "r35",
116   "r36", "r37", "r38", "r39",
117   "r40", "r41", "r42", "r43",
118   "r44", "r45", "r46", "r47",
119   "r48", "r49", "r50", "r51",
120   "r52", "r53", "r54", "r55",
121   "r56", "r57", "accl", "acch",
122   "lp_count", "reserved", "limm", "pcl",
123 };
124
125 static const char *const aux_minimal_register_names[] = {
126   "pc", "status32",
127 };
128
129 static const char *const core_arcompact_register_names[] = {
130   "r0", "r1", "r2", "r3",
131   "r4", "r5", "r6", "r7",
132   "r8", "r9", "r10", "r11",
133   "r12", "r13", "r14", "r15",
134   "r16", "r17", "r18", "r19",
135   "r20", "r21", "r22", "r23",
136   "r24", "r25", "gp", "fp",
137   "sp", "ilink1", "ilink2", "blink",
138   "r32", "r33", "r34", "r35",
139   "r36", "r37", "r38", "r39",
140   "r40", "r41", "r42", "r43",
141   "r44", "r45", "r46", "r47",
142   "r48", "r49", "r50", "r51",
143   "r52", "r53", "r54", "r55",
144   "r56", "r57", "r58", "r59",
145   "lp_count", "reserved", "limm", "pcl",
146 };
147
148 /* Functions are sorted in the order as they are used in the
149    _initialize_arc_tdep (), which uses the same order as gdbarch.h.  Static
150    functions are defined before the first invocation.  */
151
152 /* Returns an unsigned value of OPERAND_NUM in instruction INSN.
153    For relative branch instructions returned value is an offset, not an actual
154    branch target.  */
155
156 static ULONGEST
157 arc_insn_get_operand_value (const struct arc_instruction &insn,
158                             unsigned int operand_num)
159 {
160   switch (insn.operands[operand_num].kind)
161     {
162     case ARC_OPERAND_KIND_LIMM:
163       gdb_assert (insn.limm_p);
164       return insn.limm_value;
165     case ARC_OPERAND_KIND_SHIMM:
166       return insn.operands[operand_num].value;
167     default:
168       /* Value in instruction is a register number.  */
169       struct regcache *regcache = get_current_regcache ();
170       ULONGEST value;
171       regcache_cooked_read_unsigned (regcache,
172                                      insn.operands[operand_num].value,
173                                      &value);
174       return value;
175     }
176 }
177
178 /* Like arc_insn_get_operand_value, but returns a signed value.  */
179
180 static LONGEST
181 arc_insn_get_operand_value_signed (const struct arc_instruction &insn,
182                                    unsigned int operand_num)
183 {
184   switch (insn.operands[operand_num].kind)
185     {
186     case ARC_OPERAND_KIND_LIMM:
187       gdb_assert (insn.limm_p);
188       /* Convert unsigned raw value to signed one.  This assumes 2's
189          complement arithmetic, but so is the LONG_MIN value from generic
190          defs.h and that assumption is true for ARC.  */
191       gdb_static_assert (sizeof (insn.limm_value) == sizeof (int));
192       return (((LONGEST) insn.limm_value) ^ INT_MIN) - INT_MIN;
193     case ARC_OPERAND_KIND_SHIMM:
194       /* Sign conversion has been done by binutils.  */
195       return insn.operands[operand_num].value;
196     default:
197       /* Value in instruction is a register number.  */
198       struct regcache *regcache = get_current_regcache ();
199       LONGEST value;
200       regcache_cooked_read_signed (regcache,
201                                    insn.operands[operand_num].value,
202                                    &value);
203       return value;
204     }
205 }
206
207 /* Get register with base address of memory operation.  */
208
209 int
210 arc_insn_get_memory_base_reg (const struct arc_instruction &insn)
211 {
212   /* POP_S and PUSH_S have SP as an implicit argument in a disassembler.  */
213   if (insn.insn_class == PUSH || insn.insn_class == POP)
214     return ARC_SP_REGNUM;
215
216   gdb_assert (insn.insn_class == LOAD || insn.insn_class == STORE);
217
218   /* Other instructions all have at least two operands: operand 0 is data,
219      operand 1 is address.  Operand 2 is offset from address.  However, see
220      comment to arc_instruction.operands - in some cases, third operand may be
221      missing, namely if it is 0.  */
222   gdb_assert (insn.operands_count >= 2);
223   return insn.operands[1].value;
224 }
225
226 /* Get offset of a memory operation INSN.  */
227
228 CORE_ADDR
229 arc_insn_get_memory_offset (const struct arc_instruction &insn)
230 {
231   /* POP_S and PUSH_S have offset as an implicit argument in a
232      disassembler.  */
233   if (insn.insn_class == POP)
234     return 4;
235   else if (insn.insn_class == PUSH)
236     return -4;
237
238   gdb_assert (insn.insn_class == LOAD || insn.insn_class == STORE);
239
240   /* Other instructions all have at least two operands: operand 0 is data,
241      operand 1 is address.  Operand 2 is offset from address.  However, see
242      comment to arc_instruction.operands - in some cases, third operand may be
243      missing, namely if it is 0.  */
244   if (insn.operands_count < 3)
245     return 0;
246
247   CORE_ADDR value = arc_insn_get_operand_value (insn, 2);
248   /* Handle scaling.  */
249   if (insn.writeback_mode == ARC_WRITEBACK_AS)
250     {
251       /* Byte data size is not valid for AS.  Halfword means shift by 1 bit.
252          Word and double word means shift by 2 bits.  */
253       gdb_assert (insn.data_size_mode != ARC_SCALING_B);
254       if (insn.data_size_mode == ARC_SCALING_H)
255         value <<= 1;
256       else
257         value <<= 2;
258     }
259   return value;
260 }
261
262 CORE_ADDR
263 arc_insn_get_branch_target (const struct arc_instruction &insn)
264 {
265   gdb_assert (insn.is_control_flow);
266
267   /* BI [c]: PC = nextPC + (c << 2).  */
268   if (insn.insn_class == BI)
269     {
270       ULONGEST reg_value = arc_insn_get_operand_value (insn, 0);
271       return arc_insn_get_linear_next_pc (insn) + (reg_value << 2);
272     }
273   /* BIH [c]: PC = nextPC + (c << 1).  */
274   else if (insn.insn_class == BIH)
275     {
276       ULONGEST reg_value = arc_insn_get_operand_value (insn, 0);
277       return arc_insn_get_linear_next_pc (insn) + (reg_value << 1);
278     }
279   /* JLI and EI.  */
280   /* JLI and EI depend on optional AUX registers.  Not supported right now.  */
281   else if (insn.insn_class == JLI)
282     {
283       fprintf_unfiltered (gdb_stderr,
284                           "JLI_S instruction is not supported by the GDB.");
285       return 0;
286     }
287   else if (insn.insn_class == EI)
288     {
289       fprintf_unfiltered (gdb_stderr,
290                           "EI_S instruction is not supported by the GDB.");
291       return 0;
292     }
293   /* LEAVE_S: PC = BLINK.  */
294   else if (insn.insn_class == LEAVE)
295     {
296       struct regcache *regcache = get_current_regcache ();
297       ULONGEST value;
298       regcache_cooked_read_unsigned (regcache, ARC_BLINK_REGNUM, &value);
299       return value;
300     }
301   /* BBIT0/1, BRcc: PC = currentPC + operand.  */
302   else if (insn.insn_class == BBIT0 || insn.insn_class == BBIT1
303            || insn.insn_class == BRCC)
304     {
305       /* Most instructions has branch target as their sole argument.  However
306          conditional brcc/bbit has it as a third operand.  */
307       CORE_ADDR pcrel_addr = arc_insn_get_operand_value (insn, 2);
308
309       /* Offset is relative to the 4-byte aligned address of the current
310          instruction, hence last two bits should be truncated.  */
311       return pcrel_addr + align_down (insn.address, 4);
312     }
313   /* B, Bcc, BL, BLcc, LP, LPcc: PC = currentPC + operand.  */
314   else if (insn.insn_class == BRANCH || insn.insn_class == LOOP)
315     {
316       CORE_ADDR pcrel_addr = arc_insn_get_operand_value (insn, 0);
317
318       /* Offset is relative to the 4-byte aligned address of the current
319          instruction, hence last two bits should be truncated.  */
320       return pcrel_addr + align_down (insn.address, 4);
321     }
322   /* J, Jcc, JL, JLcc: PC = operand.  */
323   else if (insn.insn_class == JUMP)
324     {
325       /* All jumps are single-operand.  */
326       return arc_insn_get_operand_value (insn, 0);
327     }
328
329   /* This is some new and unknown instruction.  */
330   gdb_assert_not_reached ("Unknown branch instruction.");
331 }
332
333 /* Dump INSN into gdb_stdlog.  */
334
335 void
336 arc_insn_dump (const struct arc_instruction &insn)
337 {
338   struct gdbarch *gdbarch = target_gdbarch ();
339
340   arc_print ("Dumping arc_instruction at %s\n",
341              paddress (gdbarch, insn.address));
342   arc_print ("\tlength = %u\n", insn.length);
343
344   if (!insn.valid)
345     {
346       arc_print ("\tThis is not a valid ARC instruction.\n");
347       return;
348     }
349
350   arc_print ("\tlength_with_limm = %u\n", insn.length + (insn.limm_p ? 4 : 0));
351   arc_print ("\tcc = 0x%x\n", insn.condition_code);
352   arc_print ("\tinsn_class = %u\n", insn.insn_class);
353   arc_print ("\tis_control_flow = %i\n", insn.is_control_flow);
354   arc_print ("\thas_delay_slot = %i\n", insn.has_delay_slot);
355
356   CORE_ADDR next_pc = arc_insn_get_linear_next_pc (insn);
357   arc_print ("\tlinear_next_pc = %s\n", paddress (gdbarch, next_pc));
358
359   if (insn.is_control_flow)
360     {
361       CORE_ADDR t = arc_insn_get_branch_target (insn);
362       arc_print ("\tbranch_target = %s\n", paddress (gdbarch, t));
363     }
364
365   arc_print ("\tlimm_p = %i\n", insn.limm_p);
366   if (insn.limm_p)
367     arc_print ("\tlimm_value = 0x%08x\n", insn.limm_value);
368
369   if (insn.insn_class == STORE || insn.insn_class == LOAD
370       || insn.insn_class == PUSH || insn.insn_class == POP)
371     {
372       arc_print ("\twriteback_mode = %u\n", insn.writeback_mode);
373       arc_print ("\tdata_size_mode = %u\n", insn.data_size_mode);
374       arc_print ("\tmemory_base_register = %s\n",
375                  gdbarch_register_name (gdbarch,
376                                         arc_insn_get_memory_base_reg (insn)));
377       /* get_memory_offset returns an unsigned CORE_ADDR, but treat it as a
378          LONGEST for a nicer representation.  */
379       arc_print ("\taddr_offset = %s\n",
380                  plongest (arc_insn_get_memory_offset (insn)));
381     }
382
383   arc_print ("\toperands_count = %u\n", insn.operands_count);
384   for (unsigned int i = 0; i < insn.operands_count; ++i)
385     {
386       int is_reg = (insn.operands[i].kind == ARC_OPERAND_KIND_REG);
387
388       arc_print ("\toperand[%u] = {\n", i);
389       arc_print ("\t\tis_reg = %i\n", is_reg);
390       if (is_reg)
391         arc_print ("\t\tregister = %s\n",
392                    gdbarch_register_name (gdbarch, insn.operands[i].value));
393       /* Don't know if this value is signed or not, so print both
394          representations.  This tends to look quite ugly, especially for big
395          numbers.  */
396       arc_print ("\t\tunsigned value = %s\n",
397                  pulongest (arc_insn_get_operand_value (insn, i)));
398       arc_print ("\t\tsigned value = %s\n",
399                  plongest (arc_insn_get_operand_value_signed (insn, i)));
400       arc_print ("\t}\n");
401     }
402 }
403
404 CORE_ADDR
405 arc_insn_get_linear_next_pc (const struct arc_instruction &insn)
406 {
407   /* In ARC long immediate is always 4 bytes.  */
408   return (insn.address + insn.length + (insn.limm_p ? 4 : 0));
409 }
410
411 /* Implement the "write_pc" gdbarch method.
412
413    In ARC PC register is a normal register so in most cases setting PC value
414    is a straightforward process: debugger just writes PC value.  However it
415    gets trickier in case when current instruction is an instruction in delay
416    slot.  In this case CPU will execute instruction at current PC value, then
417    will set PC to the current value of BTA register; also current instruction
418    cannot be branch/jump and some of the other instruction types.  Thus if
419    debugger would try to just change PC value in this case, this instruction
420    will get executed, but then core will "jump" to the original branch target.
421
422    Whether current instruction is a delay-slot instruction or not is indicated
423    by DE bit in STATUS32 register indicates if current instruction is a delay
424    slot instruction.  This bit is writable by debug host, which allows debug
425    host to prevent core from jumping after the delay slot instruction.  It
426    also works in another direction: setting this bit will make core to treat
427    any current instructions as a delay slot instruction and to set PC to the
428    current value of BTA register.
429
430    To workaround issues with changing PC register while in delay slot
431    instruction, debugger should check for the STATUS32.DE bit and reset it if
432    it is set.  No other change is required in this function.  Most common
433    case, where this function might be required is calling inferior functions
434    from debugger.  Generic GDB logic handles this pretty well: current values
435    of registers are stored, value of PC is changed (that is the job of this
436    function), and after inferior function is executed, GDB restores all
437    registers, include BTA and STATUS32, which also means that core is returned
438    to its original state of being halted on delay slot instructions.
439
440    This method is useless for ARC 600, because it doesn't have externally
441    exposed BTA register.  In the case of ARC 600 it is impossible to restore
442    core to its state in all occasions thus core should never be halted (from
443    the perspective of debugger host) in the delay slot.  */
444
445 static void
446 arc_write_pc (struct regcache *regcache, CORE_ADDR new_pc)
447 {
448   struct gdbarch *gdbarch = get_regcache_arch (regcache);
449
450   if (arc_debug)
451     debug_printf ("arc: Writing PC, new value=%s\n",
452                   paddress (gdbarch, new_pc));
453
454   regcache_cooked_write_unsigned (regcache, gdbarch_pc_regnum (gdbarch),
455                                   new_pc);
456
457   ULONGEST status32;
458   regcache_cooked_read_unsigned (regcache, gdbarch_ps_regnum (gdbarch),
459                                  &status32);
460
461   /* Mask for DE bit is 0x40.  */
462   if (status32 & 0x40)
463     {
464       if (arc_debug)
465         {
466           debug_printf ("arc: Changing PC while in delay slot.  Will "
467                         "reset STATUS32.DE bit to zero.  Value of STATUS32 "
468                         "register is 0x%s\n",
469                         phex (status32, ARC_REGISTER_SIZE));
470         }
471
472       /* Reset bit and write to the cache.  */
473       status32 &= ~0x40;
474       regcache_cooked_write_unsigned (regcache, gdbarch_ps_regnum (gdbarch),
475                                       status32);
476     }
477 }
478
479 /* Implement the "virtual_frame_pointer" gdbarch method.
480
481    According to ABI the FP (r27) is used to point to the middle of the current
482    stack frame, just below the saved FP and before local variables, register
483    spill area and outgoing args.  However for optimization levels above O2 and
484    in any case in leaf functions, the frame pointer is usually not set at all.
485    The exception being when handling nested functions.
486
487    We use this function to return a "virtual" frame pointer, marking the start
488    of the current stack frame as a register-offset pair.  If the FP is not
489    being used, then it should return SP, with an offset of the frame size.
490
491    The current implementation doesn't actually know the frame size, nor
492    whether the FP is actually being used, so for now we just return SP and an
493    offset of zero.  This is no worse than other architectures, but is needed
494    to avoid assertion failures.
495
496    TODO: Can we determine the frame size to get a correct offset?
497
498    PC is a program counter where we need the virtual FP.  REG_PTR is the base
499    register used for the virtual FP.  OFFSET_PTR is the offset used for the
500    virtual FP.  */
501
502 static void
503 arc_virtual_frame_pointer (struct gdbarch *gdbarch, CORE_ADDR pc,
504                            int *reg_ptr, LONGEST *offset_ptr)
505 {
506   *reg_ptr = gdbarch_sp_regnum (gdbarch);
507   *offset_ptr = 0;
508 }
509
510 /* Implement the "dummy_id" gdbarch method.
511
512    Tear down a dummy frame created by arc_push_dummy_call ().  This data has
513    to be constructed manually from the data in our hand.  The stack pointer
514    and program counter can be obtained from the frame info.  */
515
516 static struct frame_id
517 arc_dummy_id (struct gdbarch *gdbarch, struct frame_info *this_frame)
518 {
519   return frame_id_build (get_frame_sp (this_frame),
520                          get_frame_pc (this_frame));
521 }
522
523 /* Implement the "push_dummy_call" gdbarch method.
524
525    Stack Frame Layout
526
527    This shows the layout of the stack frame for the general case of a
528    function call; a given function might not have a variable number of
529    arguments or local variables, or might not save any registers, so it would
530    not have the corresponding frame areas.  Additionally, a leaf function
531    (i.e. one which calls no other functions) does not need to save the
532    contents of the BLINK register (which holds its return address), and a
533    function might not have a frame pointer.
534
535    The stack grows downward, so SP points below FP in memory; SP always
536    points to the last used word on the stack, not the first one.
537
538                       |                       |   |
539                       |      arg word N       |   | caller's
540                       |           :           |   | frame
541                       |      arg word 10      |   |
542                       |      arg word 9       |   |
543           old SP ---> +-----------------------+ --+
544                       |                       |   |
545                       |      callee-saved     |   |
546                       |       registers       |   |
547                       |  including fp, blink  |   |
548                       |                       |   | callee's
549           new FP ---> +-----------------------+   | frame
550                       |                       |   |
551                       |         local         |   |
552                       |       variables       |   |
553                       |                       |   |
554                       |       register        |   |
555                       |      spill area       |   |
556                       |                       |   |
557                       |     outgoing args     |   |
558                       |                       |   |
559           new SP ---> +-----------------------+ --+
560                       |                       |
561                       |         unused        |
562                       |                       |
563                                   |
564                                   |
565                                   V
566                               downwards
567
568    The list of arguments to be passed to a function is considered to be a
569    sequence of _N_ words (as though all the parameters were stored in order in
570    memory with each parameter occupying an integral number of words).  Words
571    1..8 are passed in registers 0..7; if the function has more than 8 words of
572    arguments then words 9..@em N are passed on the stack in the caller's frame.
573
574    If the function has a variable number of arguments, e.g. it has a form such
575    as `function (p1, p2, ...);' and _P_ words are required to hold the values
576    of the named parameters (which are passed in registers 0..@em P -1), then
577    the remaining 8 - _P_ words passed in registers _P_..7 are spilled into the
578    top of the frame so that the anonymous parameter words occupy a continuous
579    region.
580
581    Any arguments are already in target byte order.  We just need to store
582    them!
583
584    BP_ADDR is the return address where breakpoint must be placed.  NARGS is
585    the number of arguments to the function.  ARGS is the arguments values (in
586    target byte order).  SP is the Current value of SP register.  STRUCT_RETURN
587    is TRUE if structures are returned by the function.  STRUCT_ADDR is the
588    hidden address for returning a struct.  Returns SP of a new frame.  */
589
590 static CORE_ADDR
591 arc_push_dummy_call (struct gdbarch *gdbarch, struct value *function,
592                      struct regcache *regcache, CORE_ADDR bp_addr, int nargs,
593                      struct value **args, CORE_ADDR sp, int struct_return,
594                      CORE_ADDR struct_addr)
595 {
596   if (arc_debug)
597     debug_printf ("arc: push_dummy_call (nargs = %d)\n", nargs);
598
599   int arg_reg = ARC_FIRST_ARG_REGNUM;
600
601   /* Push the return address.  */
602   regcache_cooked_write_unsigned (regcache, ARC_BLINK_REGNUM, bp_addr);
603
604   /* Are we returning a value using a structure return instead of a normal
605      value return?  If so, struct_addr is the address of the reserved space for
606      the return structure to be written on the stack, and that address is
607      passed to that function as a hidden first argument.  */
608   if (struct_return)
609     {
610       /* Pass the return address in the first argument register.  */
611       regcache_cooked_write_unsigned (regcache, arg_reg, struct_addr);
612
613       if (arc_debug)
614         debug_printf ("arc: struct return address %s passed in R%d",
615                       print_core_address (gdbarch, struct_addr), arg_reg);
616
617       arg_reg++;
618     }
619
620   if (nargs > 0)
621     {
622       unsigned int total_space = 0;
623
624       /* How much space do the arguments occupy in total?  Must round each
625          argument's size up to an integral number of words.  */
626       for (int i = 0; i < nargs; i++)
627         {
628           unsigned int len = TYPE_LENGTH (value_type (args[i]));
629           unsigned int space = align_up (len, 4);
630
631           total_space += space;
632
633           if (arc_debug)
634             debug_printf ("arc: arg %d: %u bytes -> %u\n", i, len, space);
635         }
636
637       /* Allocate a buffer to hold a memory image of the arguments.  */
638       gdb_byte *memory_image = XCNEWVEC (gdb_byte, total_space);
639
640       /* Now copy all of the arguments into the buffer, correctly aligned.  */
641       gdb_byte *data = memory_image;
642       for (int i = 0; i < nargs; i++)
643         {
644           unsigned int len = TYPE_LENGTH (value_type (args[i]));
645           unsigned int space = align_up (len, 4);
646
647           memcpy (data, value_contents (args[i]), (size_t) len);
648           if (arc_debug)
649             debug_printf ("arc: copying arg %d, val 0x%08x, len %d to mem\n",
650                           i, *((int *) value_contents (args[i])), len);
651
652           data += space;
653         }
654
655       /* Now load as much as possible of the memory image into registers.  */
656       data = memory_image;
657       while (arg_reg <= ARC_LAST_ARG_REGNUM)
658         {
659           if (arc_debug)
660             debug_printf ("arc: passing 0x%02x%02x%02x%02x in register R%d\n",
661                           data[0], data[1], data[2], data[3], arg_reg);
662
663           /* Note we don't use write_unsigned here, since that would convert
664              the byte order, but we are already in the correct byte order.  */
665           regcache_cooked_write (regcache, arg_reg, data);
666
667           data += ARC_REGISTER_SIZE;
668           total_space -= ARC_REGISTER_SIZE;
669
670           /* All the data is now in registers.  */
671           if (total_space == 0)
672             break;
673
674           arg_reg++;
675         }
676
677       /* If there is any data left, push it onto the stack (in a single write
678          operation).  */
679       if (total_space > 0)
680         {
681           if (arc_debug)
682             debug_printf ("arc: passing %d bytes on stack\n", total_space);
683
684           sp -= total_space;
685           write_memory (sp, data, (int) total_space);
686         }
687
688       xfree (memory_image);
689     }
690
691   /* Finally, update the SP register.  */
692   regcache_cooked_write_unsigned (regcache, gdbarch_sp_regnum (gdbarch), sp);
693
694   return sp;
695 }
696
697 /* Implement the "push_dummy_code" gdbarch method.
698
699    We don't actually push any code.  We just identify where a breakpoint can
700    be inserted to which we are can return and the resume address where we
701    should be called.
702
703    ARC does not necessarily have an executable stack, so we can't put the
704    return breakpoint there.  Instead we put it at the entry point of the
705    function.  This means the SP is unchanged.
706
707    SP is a current stack pointer FUNADDR is an address of the function to be
708    called.  ARGS is arguments to pass.  NARGS is a number of args to pass.
709    VALUE_TYPE is a type of value returned.  REAL_PC is a resume address when
710    the function is called.  BP_ADDR is an address where breakpoint should be
711    set.  Returns the updated stack pointer.  */
712
713 static CORE_ADDR
714 arc_push_dummy_code (struct gdbarch *gdbarch, CORE_ADDR sp, CORE_ADDR funaddr,
715                      struct value **args, int nargs, struct type *value_type,
716                      CORE_ADDR *real_pc, CORE_ADDR *bp_addr,
717                      struct regcache *regcache)
718 {
719   *real_pc = funaddr;
720   *bp_addr = entry_point_address ();
721   return sp;
722 }
723
724 /* Implement the "cannot_fetch_register" gdbarch method.  */
725
726 static int
727 arc_cannot_fetch_register (struct gdbarch *gdbarch, int regnum)
728 {
729   /* Assume that register is readable if it is unknown.  LIMM and RESERVED are
730      not real registers, but specific register numbers.  They are available as
731      regnums to align architectural register numbers with GDB internal regnums,
732      but they shouldn't appear in target descriptions generated by
733      GDB-servers.  */
734   switch (regnum)
735     {
736     case ARC_RESERVED_REGNUM:
737     case ARC_LIMM_REGNUM:
738       return true;
739     default:
740       return false;
741     }
742 }
743
744 /* Implement the "cannot_store_register" gdbarch method.  */
745
746 static int
747 arc_cannot_store_register (struct gdbarch *gdbarch, int regnum)
748 {
749   /* Assume that register is writable if it is unknown.  See comment in
750      arc_cannot_fetch_register about LIMM and RESERVED.  */
751   switch (regnum)
752     {
753     case ARC_RESERVED_REGNUM:
754     case ARC_LIMM_REGNUM:
755     case ARC_PCL_REGNUM:
756       return true;
757     default:
758       return false;
759     }
760 }
761
762 /* Get the return value of a function from the registers/memory used to
763    return it, according to the convention used by the ABI - 4-bytes values are
764    in the R0, while 8-byte values are in the R0-R1.
765
766    TODO: This implementation ignores the case of "complex double", where
767    according to ABI, value is returned in the R0-R3 registers.
768
769    TYPE is a returned value's type.  VALBUF is a buffer for the returned
770    value.  */
771
772 static void
773 arc_extract_return_value (struct gdbarch *gdbarch, struct type *type,
774                           struct regcache *regcache, gdb_byte *valbuf)
775 {
776   unsigned int len = TYPE_LENGTH (type);
777
778   if (arc_debug)
779     debug_printf ("arc: extract_return_value\n");
780
781   if (len <= ARC_REGISTER_SIZE)
782     {
783       ULONGEST val;
784
785       /* Get the return value from one register.  */
786       regcache_cooked_read_unsigned (regcache, ARC_R0_REGNUM, &val);
787       store_unsigned_integer (valbuf, (int) len,
788                               gdbarch_byte_order (gdbarch), val);
789
790       if (arc_debug)
791         debug_printf ("arc: returning 0x%s\n", phex (val, ARC_REGISTER_SIZE));
792     }
793   else if (len <= ARC_REGISTER_SIZE * 2)
794     {
795       ULONGEST low, high;
796
797       /* Get the return value from two registers.  */
798       regcache_cooked_read_unsigned (regcache, ARC_R0_REGNUM, &low);
799       regcache_cooked_read_unsigned (regcache, ARC_R1_REGNUM, &high);
800
801       store_unsigned_integer (valbuf, ARC_REGISTER_SIZE,
802                               gdbarch_byte_order (gdbarch), low);
803       store_unsigned_integer (valbuf + ARC_REGISTER_SIZE,
804                               (int) len - ARC_REGISTER_SIZE,
805                               gdbarch_byte_order (gdbarch), high);
806
807       if (arc_debug)
808         debug_printf ("arc: returning 0x%s%s\n",
809                       phex (high, ARC_REGISTER_SIZE),
810                       phex (low, ARC_REGISTER_SIZE));
811     }
812   else
813     error (_("arc: extract_return_value: type length %u too large"), len);
814 }
815
816
817 /* Store the return value of a function into the registers/memory used to
818    return it, according to the convention used by the ABI.
819
820    TODO: This implementation ignores the case of "complex double", where
821    according to ABI, value is returned in the R0-R3 registers.
822
823    TYPE is a returned value's type.  VALBUF is a buffer with the value to
824    return.  */
825
826 static void
827 arc_store_return_value (struct gdbarch *gdbarch, struct type *type,
828                         struct regcache *regcache, const gdb_byte *valbuf)
829 {
830   unsigned int len = TYPE_LENGTH (type);
831
832   if (arc_debug)
833     debug_printf ("arc: store_return_value\n");
834
835   if (len <= ARC_REGISTER_SIZE)
836     {
837       ULONGEST val;
838
839       /* Put the return value into one register.  */
840       val = extract_unsigned_integer (valbuf, (int) len,
841                                       gdbarch_byte_order (gdbarch));
842       regcache_cooked_write_unsigned (regcache, ARC_R0_REGNUM, val);
843
844       if (arc_debug)
845         debug_printf ("arc: storing 0x%s\n", phex (val, ARC_REGISTER_SIZE));
846     }
847   else if (len <= ARC_REGISTER_SIZE * 2)
848     {
849       ULONGEST low, high;
850
851       /* Put the return value into  two registers.  */
852       low = extract_unsigned_integer (valbuf, ARC_REGISTER_SIZE,
853                                       gdbarch_byte_order (gdbarch));
854       high = extract_unsigned_integer (valbuf + ARC_REGISTER_SIZE,
855                                        (int) len - ARC_REGISTER_SIZE,
856                                        gdbarch_byte_order (gdbarch));
857
858       regcache_cooked_write_unsigned (regcache, ARC_R0_REGNUM, low);
859       regcache_cooked_write_unsigned (regcache, ARC_R1_REGNUM, high);
860
861       if (arc_debug)
862         debug_printf ("arc: storing 0x%s%s\n",
863                       phex (high, ARC_REGISTER_SIZE),
864                       phex (low, ARC_REGISTER_SIZE));
865     }
866   else
867     error (_("arc_store_return_value: type length too large."));
868 }
869
870 /* Implement the "get_longjmp_target" gdbarch method.  */
871
872 static int
873 arc_get_longjmp_target (struct frame_info *frame, CORE_ADDR *pc)
874 {
875   if (arc_debug)
876     debug_printf ("arc: get_longjmp_target\n");
877
878   struct gdbarch *gdbarch = get_frame_arch (frame);
879   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
880   int pc_offset = tdep->jb_pc * ARC_REGISTER_SIZE;
881   gdb_byte buf[ARC_REGISTER_SIZE];
882   CORE_ADDR jb_addr = get_frame_register_unsigned (frame, ARC_FIRST_ARG_REGNUM);
883
884   if (target_read_memory (jb_addr + pc_offset, buf, ARC_REGISTER_SIZE))
885     return 0; /* Failed to read from memory.  */
886
887   *pc = extract_unsigned_integer (buf, ARC_REGISTER_SIZE,
888                                   gdbarch_byte_order (gdbarch));
889   return 1;
890 }
891
892 /* Implement the "return_value" gdbarch method.  */
893
894 static enum return_value_convention
895 arc_return_value (struct gdbarch *gdbarch, struct value *function,
896                   struct type *valtype, struct regcache *regcache,
897                   gdb_byte *readbuf, const gdb_byte *writebuf)
898 {
899   /* If the return type is a struct, or a union, or would occupy more than two
900      registers, the ABI uses the "struct return convention": the calling
901      function passes a hidden first parameter to the callee (in R0).  That
902      parameter is the address at which the value being returned should be
903      stored.  Otherwise, the result is returned in registers.  */
904   int is_struct_return = (TYPE_CODE (valtype) == TYPE_CODE_STRUCT
905                           || TYPE_CODE (valtype) == TYPE_CODE_UNION
906                           || TYPE_LENGTH (valtype) > 2 * ARC_REGISTER_SIZE);
907
908   if (arc_debug)
909     debug_printf ("arc: return_value (readbuf = %s, writebuf = %s)\n",
910                   host_address_to_string (readbuf),
911                   host_address_to_string (writebuf));
912
913   if (writebuf != NULL)
914     {
915       /* Case 1.  GDB should not ask us to set a struct return value: it
916          should know the struct return location and write the value there
917          itself.  */
918       gdb_assert (!is_struct_return);
919       arc_store_return_value (gdbarch, valtype, regcache, writebuf);
920     }
921   else if (readbuf != NULL)
922     {
923       /* Case 2.  GDB should not ask us to get a struct return value: it
924          should know the struct return location and read the value from there
925          itself.  */
926       gdb_assert (!is_struct_return);
927       arc_extract_return_value (gdbarch, valtype, regcache, readbuf);
928     }
929
930   return (is_struct_return
931           ? RETURN_VALUE_STRUCT_CONVENTION
932           : RETURN_VALUE_REGISTER_CONVENTION);
933 }
934
935 /* Return the base address of the frame.  For ARC, the base address is the
936    frame pointer.  */
937
938 static CORE_ADDR
939 arc_frame_base_address (struct frame_info *this_frame, void **prologue_cache)
940 {
941   return (CORE_ADDR) get_frame_register_unsigned (this_frame, ARC_FP_REGNUM);
942 }
943
944 /* Helper function that returns valid pv_t for an instruction operand:
945    either a register or a constant.  */
946
947 static pv_t
948 arc_pv_get_operand (pv_t *regs, const struct arc_instruction &insn, int operand)
949 {
950   if (insn.operands[operand].kind == ARC_OPERAND_KIND_REG)
951     return regs[insn.operands[operand].value];
952   else
953     return pv_constant (arc_insn_get_operand_value (insn, operand));
954 }
955
956 /* Determine whether the given disassembled instruction may be part of a
957    function prologue.  If it is, the information in the frame unwind cache will
958    be updated.  */
959
960 static bool
961 arc_is_in_prologue (struct gdbarch *gdbarch, const struct arc_instruction &insn,
962                     pv_t *regs, struct pv_area *stack)
963 {
964   /* It might be that currently analyzed address doesn't contain an
965      instruction, hence INSN is not valid.  It likely means that address points
966      to a data, non-initialized memory, or middle of a 32-bit instruction.  In
967      practice this may happen if GDB connects to a remote target that has
968      non-zeroed memory.  GDB would read PC value and would try to analyze
969      prologue, but there is no guarantee that memory contents at the address
970      specified in PC is address is a valid instruction.  There is not much that
971      that can be done about that.  */
972   if (!insn.valid)
973     return false;
974
975   /* Branch/jump or a predicated instruction.  */
976   if (insn.is_control_flow || insn.condition_code != ARC_CC_AL)
977     return false;
978
979   /* Store of some register.  May or may not update base address register.  */
980   if (insn.insn_class == STORE || insn.insn_class == PUSH)
981     {
982       /* There is definetely at least one operand - register/value being
983          stored.  */
984       gdb_assert (insn.operands_count > 0);
985
986       /* Store at some constant address.  */
987       if (insn.operands_count > 1
988           && insn.operands[1].kind != ARC_OPERAND_KIND_REG)
989         return false;
990
991       /* Writeback modes:
992          Mode   Address used                Writeback value
993          --------------------------------------------------
994          No     reg + offset                no
995          A/AW   reg + offset                reg + offset
996          AB     reg                         reg + offset
997          AS     reg + (offset << scaling)   no
998
999          "PUSH reg" is an alias to "ST.AW reg, [SP, -4]" encoding.  However
1000          16-bit PUSH_S is a distinct instruction encoding, where offset and
1001          base register are implied through opcode.  */
1002
1003       /* Register with base memory address.  */
1004       int base_reg = arc_insn_get_memory_base_reg (insn);
1005
1006       /* Address where to write.  arc_insn_get_memory_offset returns scaled
1007          value for ARC_WRITEBACK_AS.  */
1008       pv_t addr;
1009       if (insn.writeback_mode == ARC_WRITEBACK_AB)
1010         addr = regs[base_reg];
1011       else
1012         addr = pv_add_constant (regs[base_reg],
1013                                 arc_insn_get_memory_offset (insn));
1014
1015       if (pv_area_store_would_trash (stack, addr))
1016         return false;
1017
1018       if (insn.data_size_mode != ARC_SCALING_D)
1019         {
1020           /* Find the value being stored.  */
1021           pv_t store_value = arc_pv_get_operand (regs, insn, 0);
1022
1023           /* What is the size of a the stored value?  */
1024           CORE_ADDR size;
1025           if (insn.data_size_mode == ARC_SCALING_B)
1026             size = 1;
1027           else if (insn.data_size_mode == ARC_SCALING_H)
1028             size = 2;
1029           else
1030             size = ARC_REGISTER_SIZE;
1031
1032           pv_area_store (stack, addr, size, store_value);
1033         }
1034       else
1035         {
1036           if (insn.operands[0].kind == ARC_OPERAND_KIND_REG)
1037             {
1038               /* If this is a double store, than write N+1 register as well.  */
1039               pv_t store_value1 = regs[insn.operands[0].value];
1040               pv_t store_value2 = regs[insn.operands[0].value + 1];
1041               pv_area_store (stack, addr, ARC_REGISTER_SIZE, store_value1);
1042               pv_area_store (stack,
1043                              pv_add_constant (addr, ARC_REGISTER_SIZE),
1044                              ARC_REGISTER_SIZE, store_value2);
1045             }
1046           else
1047             {
1048               pv_t store_value
1049                 = pv_constant (arc_insn_get_operand_value (insn, 0));
1050               pv_area_store (stack, addr, ARC_REGISTER_SIZE * 2, store_value);
1051             }
1052         }
1053
1054       /* Is base register updated?  */
1055       if (insn.writeback_mode == ARC_WRITEBACK_A
1056           || insn.writeback_mode == ARC_WRITEBACK_AB)
1057         regs[base_reg] = pv_add_constant (regs[base_reg],
1058                                           arc_insn_get_memory_offset (insn));
1059
1060       return true;
1061     }
1062   else if (insn.insn_class == MOVE)
1063     {
1064       gdb_assert (insn.operands_count == 2);
1065
1066       /* Destination argument can be "0", so nothing will happen.  */
1067       if (insn.operands[0].kind == ARC_OPERAND_KIND_REG)
1068         {
1069           int dst_regnum = insn.operands[0].value;
1070           regs[dst_regnum] = arc_pv_get_operand (regs, insn, 1);
1071         }
1072       return true;
1073     }
1074   else if (insn.insn_class == SUB)
1075     {
1076       gdb_assert (insn.operands_count == 3);
1077
1078       /* SUB 0,b,c.  */
1079       if (insn.operands[0].kind != ARC_OPERAND_KIND_REG)
1080         return true;
1081
1082       int dst_regnum = insn.operands[0].value;
1083       regs[dst_regnum] = pv_subtract (arc_pv_get_operand (regs, insn, 1),
1084                                       arc_pv_get_operand (regs, insn, 2));
1085       return true;
1086     }
1087   else if (insn.insn_class == ENTER)
1088     {
1089       /* ENTER_S is a prologue-in-instruction - it saves all callee-saved
1090          registers according to given arguments thus greatly reducing code
1091          size.  Which registers will be actually saved depends on arguments.
1092
1093          ENTER_S {R13-...,FP,BLINK} stores registers in following order:
1094
1095          new SP ->
1096                    BLINK
1097                    R13
1098                    R14
1099                    R15
1100                    ...
1101                    FP
1102          old SP ->
1103
1104          There are up to three arguments for this opcode, as presented by ARC
1105          disassembler:
1106          1) amount of general-purpose registers to be saved - this argument is
1107             always present even when it is 0;
1108          2) FP register number (27) if FP has to be stored, otherwise argument
1109             is not present;
1110          3) BLINK register number (31) if BLINK has to be stored, otherwise
1111             argument is not present.  If both FP and BLINK are stored, then FP
1112             is present before BLINK in argument list.  */
1113       gdb_assert (insn.operands_count > 0);
1114
1115       int regs_saved = arc_insn_get_operand_value (insn, 0);
1116
1117       bool is_fp_saved;
1118       if (insn.operands_count > 1)
1119         is_fp_saved = (insn.operands[1].value  == ARC_FP_REGNUM);
1120       else
1121         is_fp_saved = false;
1122
1123       bool is_blink_saved;
1124       if (insn.operands_count > 1)
1125         is_blink_saved = (insn.operands[insn.operands_count - 1].value
1126                           == ARC_BLINK_REGNUM);
1127       else
1128         is_blink_saved = false;
1129
1130       /* Amount of bytes to be allocated to store specified registers.  */
1131       CORE_ADDR st_size = ((regs_saved + is_fp_saved + is_blink_saved)
1132                            * ARC_REGISTER_SIZE);
1133       pv_t new_sp = pv_add_constant (regs[ARC_SP_REGNUM], -st_size);
1134
1135       /* Assume that if the last register (closest to new SP) can be written,
1136          then it is possible to write all of them.  */
1137       if (pv_area_store_would_trash (stack, new_sp))
1138         return false;
1139
1140       /* Current store address.  */
1141       pv_t addr = regs[ARC_SP_REGNUM];
1142
1143       if (is_fp_saved)
1144         {
1145           addr = pv_add_constant (addr, -ARC_REGISTER_SIZE);
1146           pv_area_store (stack, addr, ARC_REGISTER_SIZE, regs[ARC_FP_REGNUM]);
1147         }
1148
1149       /* Registers are stored in backward order: from GP (R26) to R13.  */
1150       for (int i = ARC_R13_REGNUM + regs_saved - 1; i >= ARC_R13_REGNUM; i--)
1151         {
1152           addr = pv_add_constant (addr, -ARC_REGISTER_SIZE);
1153           pv_area_store (stack, addr, ARC_REGISTER_SIZE, regs[i]);
1154         }
1155
1156       if (is_blink_saved)
1157         {
1158           addr = pv_add_constant (addr, -ARC_REGISTER_SIZE);
1159           pv_area_store (stack, addr, ARC_REGISTER_SIZE,
1160                          regs[ARC_BLINK_REGNUM]);
1161         }
1162
1163       gdb_assert (pv_is_identical (addr, new_sp));
1164
1165       regs[ARC_SP_REGNUM] = new_sp;
1166
1167       if (is_fp_saved)
1168         regs[ARC_FP_REGNUM] = regs[ARC_SP_REGNUM];
1169
1170       return true;
1171     }
1172
1173   /* Some other architectures, like nds32 or arm, try to continue as far as
1174      possible when building a prologue cache (as opposed to when skipping
1175      prologue), so that cache will be as full as possible.  However current
1176      code for ARC doesn't recognize some instructions that may modify SP, like
1177      ADD, AND, OR, etc, hence there is no way to guarantee that SP wasn't
1178      clobbered by the skipped instruction.  Potential existence of extension
1179      instruction, which may do anything they want makes this even more complex,
1180      so it is just better to halt on a first unrecognized instruction.  */
1181
1182   return false;
1183 }
1184
1185 /* Copy of gdb_buffered_insn_length_fprintf from disasm.c.  */
1186
1187 static int ATTRIBUTE_PRINTF (2, 3)
1188 arc_fprintf_disasm (void *stream, const char *format, ...)
1189 {
1190   return 0;
1191 }
1192
1193 struct disassemble_info
1194 arc_disassemble_info (struct gdbarch *gdbarch)
1195 {
1196   struct disassemble_info di;
1197   init_disassemble_info (&di, &null_stream, arc_fprintf_disasm);
1198   di.arch = gdbarch_bfd_arch_info (gdbarch)->arch;
1199   di.mach = gdbarch_bfd_arch_info (gdbarch)->mach;
1200   di.endian = gdbarch_byte_order (gdbarch);
1201   di.read_memory_func = [](bfd_vma memaddr, gdb_byte *myaddr,
1202                            unsigned int len, struct disassemble_info *info)
1203     {
1204       return target_read_code (memaddr, myaddr, len);
1205     };
1206   return di;
1207 }
1208
1209 /* Analyze the prologue and update the corresponding frame cache for the frame
1210    unwinder for unwinding frames that doesn't have debug info.  In such
1211    situation GDB attempts to parse instructions in the prologue to understand
1212    where each register is saved.
1213
1214    If CACHE is not NULL, then it will be filled with information about saved
1215    registers.
1216
1217    There are several variations of prologue which GDB may encouter.  "Full"
1218    prologue looks like this:
1219
1220         sub     sp,sp,<imm>   ; Space for variadic arguments.
1221         push    blink         ; Store return address.
1222         push    r13           ; Store callee saved registers (up to R26/GP).
1223         push    r14
1224         push    fp            ; Store frame pointer.
1225         mov     fp,sp         ; Update frame pointer.
1226         sub     sp,sp,<imm>   ; Create space for local vars on the stack.
1227
1228    Depending on compiler options lots of things may change:
1229
1230     1) BLINK is not saved in leaf functions.
1231     2) Frame pointer is not saved and updated if -fomit-frame-pointer is used.
1232     3) 16-bit versions of those instructions may be used.
1233     4) Instead of a sequence of several push'es, compiler may instead prefer to
1234     do one subtract on stack pointer and then store registers using normal
1235     store, that doesn't update SP.  Like this:
1236
1237
1238         sub     sp,sp,8         ; Create space for calee-saved registers.
1239         st      r13,[sp,4]      ; Store callee saved registers (up to R26/GP).
1240         st      r14,[sp,0]
1241
1242     5) ENTER_S instruction can encode most of prologue sequence in one
1243     instruction (except for those subtracts for variadic arguments and local
1244     variables).
1245     6) GCC may use "millicode" functions from libgcc to store callee-saved
1246     registers with minimal code-size requirements.  This function currently
1247     doesn't support this.
1248
1249    ENTRYPOINT is a function entry point where prologue starts.
1250
1251    LIMIT_PC is a maximum possible end address of prologue (meaning address
1252    of first instruction after the prologue).  It might also point to the middle
1253    of prologue if execution has been stopped by the breakpoint at this address
1254    - in this case debugger should analyze prologue only up to this address,
1255    because further instructions haven't been executed yet.
1256
1257    Returns address of the first instruction after the prologue.  */
1258
1259 static CORE_ADDR
1260 arc_analyze_prologue (struct gdbarch *gdbarch, const CORE_ADDR entrypoint,
1261                       const CORE_ADDR limit_pc, struct arc_frame_cache *cache)
1262 {
1263   if (arc_debug)
1264     debug_printf ("arc: analyze_prologue (entrypoint=%s, limit_pc=%s)\n",
1265                   paddress (gdbarch, entrypoint),
1266                   paddress (gdbarch, limit_pc));
1267
1268   /* Prologue values.  Only core registers can be stored.  */
1269   pv_t regs[ARC_LAST_CORE_REGNUM + 1];
1270   for (int i = 0; i <= ARC_LAST_CORE_REGNUM; i++)
1271     regs[i] = pv_register (i, 0);
1272   struct pv_area *stack = make_pv_area (ARC_SP_REGNUM,
1273                                         gdbarch_addr_bit (gdbarch));
1274   struct cleanup *back_to = make_cleanup_free_pv_area (stack);
1275
1276   CORE_ADDR current_prologue_end = entrypoint;
1277
1278   /* Look at each instruction in the prologue.  */
1279   while (current_prologue_end < limit_pc)
1280     {
1281       struct arc_instruction insn;
1282       struct disassemble_info di = arc_disassemble_info (gdbarch);
1283       arc_insn_decode (current_prologue_end, &di, arc_delayed_print_insn,
1284                        &insn);
1285
1286       if (arc_debug >= 2)
1287         arc_insn_dump (insn);
1288
1289       /* If this instruction is in the prologue, fields in the cache will be
1290          updated, and the saved registers mask may be updated.  */
1291       if (!arc_is_in_prologue (gdbarch, insn, regs, stack))
1292         {
1293           /* Found an instruction that is not in the prologue.  */
1294           if (arc_debug)
1295             debug_printf ("arc: End of prologue reached at address %s\n",
1296                           paddress (gdbarch, insn.address));
1297           break;
1298         }
1299
1300       current_prologue_end = arc_insn_get_linear_next_pc (insn);
1301     }
1302
1303   if (cache != NULL)
1304     {
1305       /* Figure out if it is a frame pointer or just a stack pointer.  */
1306       if (pv_is_register (regs[ARC_FP_REGNUM], ARC_SP_REGNUM))
1307         {
1308           cache->frame_base_reg = ARC_FP_REGNUM;
1309           cache->frame_base_offset = -regs[ARC_FP_REGNUM].k;
1310         }
1311       else
1312         {
1313           cache->frame_base_reg = ARC_SP_REGNUM;
1314           cache->frame_base_offset = -regs[ARC_SP_REGNUM].k;
1315         }
1316
1317       /* Assign offset from old SP to all saved registers.  */
1318       for (int i = 0; i <= ARC_LAST_CORE_REGNUM; i++)
1319         {
1320           CORE_ADDR offset;
1321           if (pv_area_find_reg (stack, gdbarch, i, &offset))
1322             cache->saved_regs[i].addr = offset;
1323         }
1324     }
1325
1326   do_cleanups (back_to);
1327   return current_prologue_end;
1328 }
1329
1330 /* Estimated maximum prologue length in bytes.  This should include:
1331    1) Store instruction for each callee-saved register (R25 - R13 + 1)
1332    2) Two instructions for FP
1333    3) One for BLINK
1334    4) Three substract instructions for SP (for variadic args, for
1335    callee saved regs and for local vars) and assuming that those SUB use
1336    long-immediate (hence double length).
1337    5) Stores of arguments registers are considered part of prologue too
1338       (R7 - R1 + 1).
1339    This is quite an extreme case, because even with -O0 GCC will collapse first
1340    two SUBs into one and long immediate values are quite unlikely to appear in
1341    this case, but still better to overshoot a bit - prologue analysis will
1342    anyway stop at the first instruction that doesn't fit prologue, so this
1343    limit will be rarely reached.  */
1344
1345 const static int MAX_PROLOGUE_LENGTH
1346   = 4 * (ARC_R25_REGNUM - ARC_R13_REGNUM + 1 + 2 + 1 + 6
1347          + ARC_LAST_ARG_REGNUM - ARC_FIRST_ARG_REGNUM + 1);
1348
1349 /* Implement the "skip_prologue" gdbarch method.
1350
1351    Skip the prologue for the function at PC.  This is done by checking from
1352    the line information read from the DWARF, if possible; otherwise, we scan
1353    the function prologue to find its end.  */
1354
1355 static CORE_ADDR
1356 arc_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR pc)
1357 {
1358   if (arc_debug)
1359     debug_printf ("arc: skip_prologue\n");
1360
1361   CORE_ADDR func_addr;
1362   const char *func_name;
1363
1364   /* See what the symbol table says.  */
1365   if (find_pc_partial_function (pc, &func_name, &func_addr, NULL))
1366     {
1367       /* Found a function.  */
1368       CORE_ADDR postprologue_pc
1369         = skip_prologue_using_sal (gdbarch, func_addr);
1370
1371       if (postprologue_pc != 0)
1372         return std::max (pc, postprologue_pc);
1373     }
1374
1375   /* No prologue info in symbol table, have to analyze prologue.  */
1376
1377   /* Find an upper limit on the function prologue using the debug
1378      information.  If there is no debug information about prologue end, then
1379      skip_prologue_using_sal will return 0.  */
1380   CORE_ADDR limit_pc = skip_prologue_using_sal (gdbarch, pc);
1381
1382   /* If there is no debug information at all, it is required to give some
1383      semi-arbitrary hard limit on amount of bytes to scan during prologue
1384      analysis.  */
1385   if (limit_pc == 0)
1386     limit_pc = pc + MAX_PROLOGUE_LENGTH;
1387
1388   /* Find the address of the first instruction after the prologue by scanning
1389      through it - no other information is needed, so pass NULL as a cache.  */
1390   return arc_analyze_prologue (gdbarch, pc, limit_pc, NULL);
1391 }
1392
1393 /* Implement the "print_insn" gdbarch method.
1394
1395    arc_get_disassembler () may return different functions depending on bfd
1396    type, so it is not possible to pass print_insn directly to
1397    set_gdbarch_print_insn ().  Instead this wrapper function is used.  It also
1398    may be used by other functions to get disassemble_info for address.  It is
1399    important to note, that those print_insn from opcodes always print
1400    instruction to the stream specified in the INFO.  If this is not desired,
1401    then either `print_insn` function in INFO should be set to some function
1402    that will not print, or `stream` should be different from standard
1403    gdb_stdlog.  */
1404
1405 int
1406 arc_delayed_print_insn (bfd_vma addr, struct disassemble_info *info)
1407 {
1408   int (*print_insn) (bfd_vma, struct disassemble_info *);
1409   /* exec_bfd may be null, if GDB is run without a target BFD file.  Opcodes
1410      will handle NULL value gracefully.  */
1411   print_insn = arc_get_disassembler (exec_bfd);
1412   gdb_assert (print_insn != NULL);
1413   return print_insn (addr, info);
1414 }
1415
1416 /* Baremetal breakpoint instructions.
1417
1418    ARC supports both big- and little-endian.  However, instructions for
1419    little-endian processors are encoded in the middle-endian: half-words are
1420    in big-endian, while bytes inside the half-words are in little-endian; data
1421    is represented in the "normal" little-endian.  Big-endian processors treat
1422    data and code identically.
1423
1424    Assuming the number 0x01020304, it will be presented this way:
1425
1426    Address            :  N   N+1  N+2  N+3
1427    little-endian      : 0x04 0x03 0x02 0x01
1428    big-endian         : 0x01 0x02 0x03 0x04
1429    ARC middle-endian  : 0x02 0x01 0x04 0x03
1430   */
1431
1432 static const gdb_byte arc_brk_s_be[] = { 0x7f, 0xff };
1433 static const gdb_byte arc_brk_s_le[] = { 0xff, 0x7f };
1434 static const gdb_byte arc_brk_be[] = { 0x25, 0x6f, 0x00, 0x3f };
1435 static const gdb_byte arc_brk_le[] = { 0x6f, 0x25, 0x3f, 0x00 };
1436
1437 /* For ARC ELF, breakpoint uses the 16-bit BRK_S instruction, which is 0x7fff
1438    (little endian) or 0xff7f (big endian).  We used to insert BRK_S even
1439    instead of 32-bit instructions, which works mostly ok, unless breakpoint is
1440    inserted into delay slot instruction.  In this case if branch is taken
1441    BLINK value will be set to address of instruction after delay slot, however
1442    if we replaced 32-bit instruction in delay slot with 16-bit long BRK_S,
1443    then BLINK value will have an invalid value - it will point to the address
1444    after the BRK_S (which was there at the moment of branch execution) while
1445    it should point to the address after the 32-bit long instruction.  To avoid
1446    such issues this function disassembles instruction at target location and
1447    evaluates it value.
1448
1449    ARC 600 supports only 16-bit BRK_S.
1450
1451    NB: Baremetal GDB uses BRK[_S], while user-space GDB uses TRAP_S.  BRK[_S]
1452    is much better because it doesn't commit unlike TRAP_S, so it can be set in
1453    delay slots; however it cannot be used in user-mode, hence usage of TRAP_S
1454    in GDB for user-space.  */
1455
1456 /* Implement the "breakpoint_kind_from_pc" gdbarch method.  */
1457
1458 static int
1459 arc_breakpoint_kind_from_pc (struct gdbarch *gdbarch, CORE_ADDR *pcptr)
1460 {
1461   size_t length_with_limm = gdb_insn_length (gdbarch, *pcptr);
1462
1463   /* Replace 16-bit instruction with BRK_S, replace 32-bit instructions with
1464      BRK.  LIMM is part of instruction length, so it can be either 4 or 8
1465      bytes for 32-bit instructions.  */
1466   if ((length_with_limm == 4 || length_with_limm == 8)
1467       && !arc_mach_is_arc600 (gdbarch))
1468     return sizeof (arc_brk_le);
1469   else
1470     return sizeof (arc_brk_s_le);
1471 }
1472
1473 /* Implement the "sw_breakpoint_from_kind" gdbarch method.  */
1474
1475 static const gdb_byte *
1476 arc_sw_breakpoint_from_kind (struct gdbarch *gdbarch, int kind, int *size)
1477 {
1478   *size = kind;
1479
1480   if (kind == sizeof (arc_brk_le))
1481     {
1482       return ((gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
1483               ? arc_brk_be
1484               : arc_brk_le);
1485     }
1486   else
1487     {
1488       return ((gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
1489               ? arc_brk_s_be
1490               : arc_brk_s_le);
1491     }
1492 }
1493
1494 /* Implement the "unwind_pc" gdbarch method.  */
1495
1496 static CORE_ADDR
1497 arc_unwind_pc (struct gdbarch *gdbarch, struct frame_info *next_frame)
1498 {
1499   int pc_regnum = gdbarch_pc_regnum (gdbarch);
1500   CORE_ADDR pc = frame_unwind_register_unsigned (next_frame, pc_regnum);
1501
1502   if (arc_debug)
1503     debug_printf ("arc: unwind PC: %s\n", paddress (gdbarch, pc));
1504
1505   return pc;
1506 }
1507
1508 /* Implement the "unwind_sp" gdbarch method.  */
1509
1510 static CORE_ADDR
1511 arc_unwind_sp (struct gdbarch *gdbarch, struct frame_info *next_frame)
1512 {
1513   int sp_regnum = gdbarch_sp_regnum (gdbarch);
1514   CORE_ADDR sp = frame_unwind_register_unsigned (next_frame, sp_regnum);
1515
1516   if (arc_debug)
1517     debug_printf ("arc: unwind SP: %s\n", paddress (gdbarch, sp));
1518
1519   return sp;
1520 }
1521
1522 /* Implement the "frame_align" gdbarch method.  */
1523
1524 static CORE_ADDR
1525 arc_frame_align (struct gdbarch *gdbarch, CORE_ADDR sp)
1526 {
1527   return align_down (sp, 4);
1528 }
1529
1530 /* Dump the frame info.  Used for internal debugging only.  */
1531
1532 static void
1533 arc_print_frame_cache (struct gdbarch *gdbarch, const char *message,
1534                        struct arc_frame_cache *cache, int addresses_known)
1535 {
1536   debug_printf ("arc: frame_info %s\n", message);
1537   debug_printf ("arc: prev_sp = %s\n", paddress (gdbarch, cache->prev_sp));
1538   debug_printf ("arc: frame_base_reg = %i\n", cache->frame_base_reg);
1539   debug_printf ("arc: frame_base_offset = %s\n",
1540                 plongest (cache->frame_base_offset));
1541
1542   for (int i = 0; i <= ARC_BLINK_REGNUM; i++)
1543     {
1544       if (trad_frame_addr_p (cache->saved_regs, i))
1545         debug_printf ("arc: saved register %s at %s %s\n",
1546                       gdbarch_register_name (gdbarch, i),
1547                       (addresses_known) ? "address" : "offset",
1548                       paddress (gdbarch, cache->saved_regs[i].addr));
1549     }
1550 }
1551
1552 /* Frame unwinder for normal frames.  */
1553
1554 static struct arc_frame_cache *
1555 arc_make_frame_cache (struct frame_info *this_frame)
1556 {
1557   if (arc_debug)
1558     debug_printf ("arc: frame_cache\n");
1559
1560   struct gdbarch *gdbarch = get_frame_arch (this_frame);
1561
1562   CORE_ADDR block_addr = get_frame_address_in_block (this_frame);
1563   CORE_ADDR entrypoint, prologue_end;
1564   if (find_pc_partial_function (block_addr, NULL, &entrypoint, &prologue_end))
1565     {
1566       struct symtab_and_line sal = find_pc_line (entrypoint, 0);
1567       CORE_ADDR prev_pc = get_frame_pc (this_frame);
1568       if (sal.line == 0)
1569         /* No line info so use current PC.  */
1570         prologue_end = prev_pc;
1571       else if (sal.end < prologue_end)
1572         /* The next line begins after the function end.  */
1573         prologue_end = sal.end;
1574
1575       prologue_end = std::min (prologue_end, prev_pc);
1576     }
1577   else
1578     {
1579       /* If find_pc_partial_function returned nothing then there is no symbol
1580          information at all for this PC.  Currently it is assumed in this case
1581          that current PC is entrypoint to function and try to construct the
1582          frame from that.  This is, probably, suboptimal, for example ARM
1583          assumes in this case that program is inside the normal frame (with
1584          frame pointer).  ARC, perhaps, should try to do the same.  */
1585       entrypoint = get_frame_register_unsigned (this_frame,
1586                                                 gdbarch_pc_regnum (gdbarch));
1587       prologue_end = entrypoint + MAX_PROLOGUE_LENGTH;
1588     }
1589
1590   /* Allocate new frame cache instance and space for saved register info.
1591      FRAME_OBSTACK_ZALLOC will initialize fields to zeroes.  */
1592   struct arc_frame_cache *cache
1593     = FRAME_OBSTACK_ZALLOC (struct arc_frame_cache);
1594   cache->saved_regs = trad_frame_alloc_saved_regs (this_frame);
1595
1596   arc_analyze_prologue (gdbarch, entrypoint, prologue_end, cache);
1597
1598   if (arc_debug)
1599     arc_print_frame_cache (gdbarch, "after prologue", cache, false);
1600
1601   CORE_ADDR unwound_fb = get_frame_register_unsigned (this_frame,
1602                                                       cache->frame_base_reg);
1603   if (unwound_fb == 0)
1604     return cache;
1605   cache->prev_sp = unwound_fb + cache->frame_base_offset;
1606
1607   for (int i = 0; i <= ARC_LAST_CORE_REGNUM; i++)
1608     {
1609       if (trad_frame_addr_p (cache->saved_regs, i))
1610         cache->saved_regs[i].addr += cache->prev_sp;
1611     }
1612
1613   if (arc_debug)
1614     arc_print_frame_cache (gdbarch, "after previous SP found", cache, true);
1615
1616   return cache;
1617 }
1618
1619 /* Implement the "this_id" frame_unwind method.  */
1620
1621 static void
1622 arc_frame_this_id (struct frame_info *this_frame, void **this_cache,
1623                    struct frame_id *this_id)
1624 {
1625   if (arc_debug)
1626     debug_printf ("arc: frame_this_id\n");
1627
1628   struct gdbarch *gdbarch = get_frame_arch (this_frame);
1629
1630   if (*this_cache == NULL)
1631     *this_cache = arc_make_frame_cache (this_frame);
1632   struct arc_frame_cache *cache = (struct arc_frame_cache *) (*this_cache);
1633
1634   CORE_ADDR stack_addr = cache->prev_sp;
1635
1636   /* There are 4 possible situation which decide how frame_id->code_addr is
1637      evaluated:
1638
1639      1) Function is compiled with option -g.  Then frame_id will be created
1640      in dwarf_* function and not in this function.  NB: even if target
1641      binary is compiled with -g, some std functions like __start and _init
1642      are not, so they still will follow one of the following choices.
1643
1644      2) Function is compiled without -g and binary hasn't been stripped in
1645      any way.  In this case GDB still has enough information to evaluate
1646      frame code_addr properly.  This case is covered by call to
1647      get_frame_func ().
1648
1649      3) Binary has been striped with option -g (strip debug symbols).  In
1650      this case there is still enough symbols for get_frame_func () to work
1651      properly, so this case is also covered by it.
1652
1653      4) Binary has been striped with option -s (strip all symbols).  In this
1654      case GDB cannot get function start address properly, so we return current
1655      PC value instead.
1656    */
1657   CORE_ADDR code_addr = get_frame_func (this_frame);
1658   if (code_addr == 0)
1659     code_addr = get_frame_register_unsigned (this_frame,
1660                                              gdbarch_pc_regnum (gdbarch));
1661
1662   *this_id = frame_id_build (stack_addr, code_addr);
1663 }
1664
1665 /* Implement the "prev_register" frame_unwind method.  */
1666
1667 static struct value *
1668 arc_frame_prev_register (struct frame_info *this_frame,
1669                          void **this_cache, int regnum)
1670 {
1671   if (*this_cache == NULL)
1672     *this_cache = arc_make_frame_cache (this_frame);
1673   struct arc_frame_cache *cache = (struct arc_frame_cache *) (*this_cache);
1674
1675   struct gdbarch *gdbarch = get_frame_arch (this_frame);
1676
1677   /* If we are asked to unwind the PC, then we need to return BLINK instead:
1678      the saved value of PC points into this frame's function's prologue, not
1679      the next frame's function's resume location.  */
1680   if (regnum == gdbarch_pc_regnum (gdbarch))
1681     regnum = ARC_BLINK_REGNUM;
1682
1683   /* SP is a special case - we should return prev_sp, because
1684      trad_frame_get_prev_register will return _current_ SP value.
1685      Alternatively we could have stored cache->prev_sp in the cache->saved
1686      regs, but here we follow the lead of AArch64, ARM and Xtensa and will
1687      leave that logic in this function, instead of prologue analyzers.  That I
1688      think is a bit more clear as `saved_regs` should contain saved regs, not
1689      computable.
1690
1691      Because value has been computed, "got_constant" should be used, so that
1692      returned value will be a "not_lval" - immutable.  */
1693
1694   if (regnum == gdbarch_sp_regnum (gdbarch))
1695     return frame_unwind_got_constant (this_frame, regnum, cache->prev_sp);
1696
1697   return trad_frame_get_prev_register (this_frame, cache->saved_regs, regnum);
1698 }
1699
1700 /* Implement the "init_reg" dwarf2_frame method.  */
1701
1702 static void
1703 arc_dwarf2_frame_init_reg (struct gdbarch *gdbarch, int regnum,
1704                            struct dwarf2_frame_state_reg *reg,
1705                            struct frame_info *info)
1706 {
1707   if (regnum == gdbarch_pc_regnum (gdbarch))
1708     /* The return address column.  */
1709     reg->how = DWARF2_FRAME_REG_RA;
1710   else if (regnum == gdbarch_sp_regnum (gdbarch))
1711     /* The call frame address.  */
1712     reg->how = DWARF2_FRAME_REG_CFA;
1713 }
1714
1715 /* Structure defining the ARC ordinary frame unwind functions.  Since we are
1716    the fallback unwinder, we use the default frame sniffer, which always
1717    accepts the frame.  */
1718
1719 static const struct frame_unwind arc_frame_unwind = {
1720   NORMAL_FRAME,
1721   default_frame_unwind_stop_reason,
1722   arc_frame_this_id,
1723   arc_frame_prev_register,
1724   NULL,
1725   default_frame_sniffer,
1726   NULL,
1727   NULL
1728 };
1729
1730
1731 static const struct frame_base arc_normal_base = {
1732   &arc_frame_unwind,
1733   arc_frame_base_address,
1734   arc_frame_base_address,
1735   arc_frame_base_address
1736 };
1737
1738 /* Initialize target description for the ARC.
1739
1740    Returns TRUE if input tdesc was valid and in this case it will assign TDESC
1741    and TDESC_DATA output parameters.  */
1742
1743 static int
1744 arc_tdesc_init (struct gdbarch_info info, const struct target_desc **tdesc,
1745                 struct tdesc_arch_data **tdesc_data)
1746 {
1747   if (arc_debug)
1748     debug_printf ("arc: Target description initialization.\n");
1749
1750   const struct target_desc *tdesc_loc = info.target_desc;
1751
1752   /* Depending on whether this is ARCompact or ARCv2 we will assign
1753      different default registers sets (which will differ in exactly two core
1754      registers).  GDB will also refuse to accept register feature from invalid
1755      ISA - v2 features can be used only with v2 ARChitecture.  We read
1756      bfd_arch_info, which looks like to be a safe bet here, as it looks like it
1757      is always initialized even when we don't pass any elf file to GDB at all
1758      (it uses default arch in this case).  Also GDB will call this function
1759      multiple times, and if XML target description file contains architecture
1760      specifications, then GDB will set this architecture to info.bfd_arch_info,
1761      overriding value from ELF file if they are different.  That means that,
1762      where matters, this value is always our best guess on what CPU we are
1763      debugging.  It has been noted that architecture specified in tdesc file
1764      has higher precedence over ELF and even "set architecture" - that is,
1765      using "set architecture" command will have no effect when tdesc has "arch"
1766      tag.  */
1767   /* Cannot use arc_mach_is_arcv2 (), because gdbarch is not created yet.  */
1768   const int is_arcv2 = (info.bfd_arch_info->mach == bfd_mach_arc_arcv2);
1769   int is_reduced_rf;
1770   const char *const *core_regs;
1771   const char *core_feature_name;
1772
1773   /* If target doesn't provide a description - use default one.  */
1774   if (!tdesc_has_registers (tdesc_loc))
1775     {
1776       if (is_arcv2)
1777         {
1778           tdesc_loc = tdesc_arc_v2;
1779           if (arc_debug)
1780             debug_printf ("arc: Using default register set for ARC v2.\n");
1781         }
1782       else
1783         {
1784           tdesc_loc = tdesc_arc_arcompact;
1785           if (arc_debug)
1786             debug_printf ("arc: Using default register set for ARCompact.\n");
1787         }
1788     }
1789   else
1790     {
1791       if (arc_debug)
1792         debug_printf ("arc: Using provided register set.\n");
1793     }
1794   gdb_assert (tdesc_loc != NULL);
1795
1796   /* Now we can search for base registers.  Core registers can be either full
1797      or reduced.  Summary:
1798
1799      - core.v2 + aux-minimal
1800      - core-reduced.v2 + aux-minimal
1801      - core.arcompact + aux-minimal
1802
1803      NB: It is entirely feasible to have ARCompact with reduced core regs, but
1804      we ignore that because GCC doesn't support that and at the same time
1805      ARCompact is considered obsolete, so there is not much reason to support
1806      that.  */
1807   const struct tdesc_feature *feature
1808     = tdesc_find_feature (tdesc_loc, core_v2_feature_name);
1809   if (feature != NULL)
1810     {
1811       /* Confirm that register and architecture match, to prevent accidents in
1812          some situations.  This code will trigger an error if:
1813
1814          1. XML tdesc doesn't specify arch explicitly, registers are for arch
1815          X, but ELF specifies arch Y.
1816
1817          2. XML tdesc specifies arch X, but contains registers for arch Y.
1818
1819          It will not protect from case where XML or ELF specify arch X,
1820          registers are for the same arch X, but the real target is arch Y.  To
1821          detect this case we need to check IDENTITY register.  */
1822       if (!is_arcv2)
1823         {
1824           arc_print (_("Error: ARC v2 target description supplied for "
1825                        "non-ARCv2 target.\n"));
1826           return FALSE;
1827         }
1828
1829       is_reduced_rf = FALSE;
1830       core_feature_name = core_v2_feature_name;
1831       core_regs = core_v2_register_names;
1832     }
1833   else
1834     {
1835       feature = tdesc_find_feature (tdesc_loc, core_reduced_v2_feature_name);
1836       if (feature != NULL)
1837         {
1838           if (!is_arcv2)
1839             {
1840               arc_print (_("Error: ARC v2 target description supplied for "
1841                            "non-ARCv2 target.\n"));
1842               return FALSE;
1843             }
1844
1845           is_reduced_rf = TRUE;
1846           core_feature_name = core_reduced_v2_feature_name;
1847           core_regs = core_v2_register_names;
1848         }
1849       else
1850         {
1851           feature = tdesc_find_feature (tdesc_loc,
1852                                         core_arcompact_feature_name);
1853           if (feature != NULL)
1854             {
1855               if (is_arcv2)
1856                 {
1857                   arc_print (_("Error: ARCompact target description supplied "
1858                                "for non-ARCompact target.\n"));
1859                   return FALSE;
1860                 }
1861
1862               is_reduced_rf = FALSE;
1863               core_feature_name = core_arcompact_feature_name;
1864               core_regs = core_arcompact_register_names;
1865             }
1866           else
1867             {
1868               arc_print (_("Error: Couldn't find core register feature in "
1869                            "supplied target description."));
1870               return FALSE;
1871             }
1872         }
1873     }
1874
1875   struct tdesc_arch_data *tdesc_data_loc = tdesc_data_alloc ();
1876
1877   gdb_assert (feature != NULL);
1878   int valid_p = 1;
1879
1880   for (int i = 0; i <= ARC_LAST_CORE_REGNUM; i++)
1881     {
1882       /* If rf16, then skip extra registers.  */
1883       if (is_reduced_rf && ((i >= ARC_R4_REGNUM && i <= ARC_R9_REGNUM)
1884                             || (i >= ARC_R16_REGNUM && i <= ARC_R25_REGNUM)))
1885         continue;
1886
1887       valid_p = tdesc_numbered_register (feature, tdesc_data_loc, i,
1888                                          core_regs[i]);
1889
1890       /* - Ignore errors in extension registers - they are optional.
1891          - Ignore missing ILINK because it doesn't make sense for Linux.
1892          - Ignore missing ILINK2 when architecture is ARCompact, because it
1893          doesn't make sense for Linux targets.
1894
1895          In theory those optional registers should be in separate features, but
1896          that would create numerous but tiny features, which looks like an
1897          overengineering of a rather simple task.  */
1898       if (!valid_p && (i <= ARC_SP_REGNUM || i == ARC_BLINK_REGNUM
1899                        || i == ARC_LP_COUNT_REGNUM || i == ARC_PCL_REGNUM
1900                        || (i == ARC_R30_REGNUM && is_arcv2)))
1901         {
1902           arc_print (_("Error: Cannot find required register `%s' in "
1903                        "feature `%s'.\n"), core_regs[i], core_feature_name);
1904           tdesc_data_cleanup (tdesc_data_loc);
1905           return FALSE;
1906         }
1907     }
1908
1909   /* Mandatory AUX registeres are intentionally few and are common between
1910      ARCompact and ARC v2, so same code can be used for both.  */
1911   feature = tdesc_find_feature (tdesc_loc, aux_minimal_feature_name);
1912   if (feature == NULL)
1913     {
1914       arc_print (_("Error: Cannot find required feature `%s' in supplied "
1915                    "target description.\n"), aux_minimal_feature_name);
1916       tdesc_data_cleanup (tdesc_data_loc);
1917       return FALSE;
1918     }
1919
1920   for (int i = ARC_FIRST_AUX_REGNUM; i <= ARC_LAST_AUX_REGNUM; i++)
1921     {
1922       const char *name = aux_minimal_register_names[i - ARC_FIRST_AUX_REGNUM];
1923       valid_p = tdesc_numbered_register (feature, tdesc_data_loc, i, name);
1924       if (!valid_p)
1925         {
1926           arc_print (_("Error: Cannot find required register `%s' "
1927                        "in feature `%s'.\n"),
1928                      name, tdesc_feature_name (feature));
1929           tdesc_data_cleanup (tdesc_data_loc);
1930           return FALSE;
1931         }
1932     }
1933
1934   *tdesc = tdesc_loc;
1935   *tdesc_data = tdesc_data_loc;
1936
1937   return TRUE;
1938 }
1939
1940 /* Implement the "init" gdbarch method.  */
1941
1942 static struct gdbarch *
1943 arc_gdbarch_init (struct gdbarch_info info, struct gdbarch_list *arches)
1944 {
1945   const struct target_desc *tdesc;
1946   struct tdesc_arch_data *tdesc_data;
1947
1948   if (arc_debug)
1949     debug_printf ("arc: Architecture initialization.\n");
1950
1951   if (!arc_tdesc_init (info, &tdesc, &tdesc_data))
1952     return NULL;
1953
1954   /* Allocate the ARC-private target-dependent information structure, and the
1955      GDB target-independent information structure.  */
1956   struct gdbarch_tdep *tdep = XCNEW (struct gdbarch_tdep);
1957   tdep->jb_pc = -1; /* No longjmp support by default.  */
1958   struct gdbarch *gdbarch = gdbarch_alloc (&info, tdep);
1959
1960   /* Data types.  */
1961   set_gdbarch_short_bit (gdbarch, 16);
1962   set_gdbarch_int_bit (gdbarch, 32);
1963   set_gdbarch_long_bit (gdbarch, 32);
1964   set_gdbarch_long_long_bit (gdbarch, 64);
1965   set_gdbarch_long_long_align_bit (gdbarch, 32);
1966   set_gdbarch_float_bit (gdbarch, 32);
1967   set_gdbarch_float_format (gdbarch, floatformats_ieee_single);
1968   set_gdbarch_double_bit (gdbarch, 64);
1969   set_gdbarch_double_format (gdbarch, floatformats_ieee_double);
1970   set_gdbarch_ptr_bit (gdbarch, 32);
1971   set_gdbarch_addr_bit (gdbarch, 32);
1972   set_gdbarch_char_signed (gdbarch, 0);
1973
1974   set_gdbarch_write_pc (gdbarch, arc_write_pc);
1975
1976   set_gdbarch_virtual_frame_pointer (gdbarch, arc_virtual_frame_pointer);
1977
1978   /* tdesc_use_registers expects gdbarch_num_regs to return number of registers
1979      parsed by gdbarch_init, and then it will add all of the remaining
1980      registers and will increase number of registers.  */
1981   set_gdbarch_num_regs (gdbarch, ARC_LAST_REGNUM + 1);
1982   set_gdbarch_num_pseudo_regs (gdbarch, 0);
1983   set_gdbarch_sp_regnum (gdbarch, ARC_SP_REGNUM);
1984   set_gdbarch_pc_regnum (gdbarch, ARC_PC_REGNUM);
1985   set_gdbarch_ps_regnum (gdbarch, ARC_STATUS32_REGNUM);
1986   set_gdbarch_fp0_regnum (gdbarch, -1); /* No FPU registers.  */
1987
1988   set_gdbarch_dummy_id (gdbarch, arc_dummy_id);
1989   set_gdbarch_push_dummy_call (gdbarch, arc_push_dummy_call);
1990   set_gdbarch_push_dummy_code (gdbarch, arc_push_dummy_code);
1991
1992   set_gdbarch_cannot_fetch_register (gdbarch, arc_cannot_fetch_register);
1993   set_gdbarch_cannot_store_register (gdbarch, arc_cannot_store_register);
1994
1995   set_gdbarch_believe_pcc_promotion (gdbarch, 1);
1996
1997   set_gdbarch_return_value (gdbarch, arc_return_value);
1998
1999   set_gdbarch_skip_prologue (gdbarch, arc_skip_prologue);
2000   set_gdbarch_inner_than (gdbarch, core_addr_lessthan);
2001
2002   set_gdbarch_breakpoint_kind_from_pc (gdbarch, arc_breakpoint_kind_from_pc);
2003   set_gdbarch_sw_breakpoint_from_kind (gdbarch, arc_sw_breakpoint_from_kind);
2004
2005   /* On ARC 600 BRK_S instruction advances PC, unlike other ARC cores.  */
2006   if (!arc_mach_is_arc600 (gdbarch))
2007     set_gdbarch_decr_pc_after_break (gdbarch, 0);
2008   else
2009     set_gdbarch_decr_pc_after_break (gdbarch, 2);
2010
2011   set_gdbarch_unwind_pc (gdbarch, arc_unwind_pc);
2012   set_gdbarch_unwind_sp (gdbarch, arc_unwind_sp);
2013
2014   set_gdbarch_frame_align (gdbarch, arc_frame_align);
2015
2016   set_gdbarch_cannot_step_breakpoint (gdbarch, 1);
2017
2018   /* "nonsteppable" watchpoint means that watchpoint triggers before
2019      instruction is committed, therefore it is required to remove watchpoint
2020      to step though instruction that triggers it.  ARC watchpoints trigger
2021      only after instruction is committed, thus there is no need to remove
2022      them.  In fact on ARC watchpoint for memory writes may trigger with more
2023      significant delay, like one or two instructions, depending on type of
2024      memory where write is performed (CCM or external) and next instruction
2025      after the memory write.  */
2026   set_gdbarch_have_nonsteppable_watchpoint (gdbarch, 0);
2027
2028   /* This doesn't include possible long-immediate value.  */
2029   set_gdbarch_max_insn_length (gdbarch, 4);
2030
2031   /* Frame unwinders and sniffers.  */
2032   dwarf2_frame_set_init_reg (gdbarch, arc_dwarf2_frame_init_reg);
2033   dwarf2_append_unwinders (gdbarch);
2034   frame_unwind_append_unwinder (gdbarch, &arc_frame_unwind);
2035   frame_base_set_default (gdbarch, &arc_normal_base);
2036
2037   /* Setup stuff specific to a particular environment (baremetal or Linux).
2038      It can override functions set earlier.  */
2039   gdbarch_init_osabi (info, gdbarch);
2040
2041   if (tdep->jb_pc >= 0)
2042     set_gdbarch_get_longjmp_target (gdbarch, arc_get_longjmp_target);
2043
2044   tdesc_use_registers (gdbarch, tdesc, tdesc_data);
2045
2046   return gdbarch;
2047 }
2048
2049 /* Implement the "dump_tdep" gdbarch method.  */
2050
2051 static void
2052 arc_dump_tdep (struct gdbarch *gdbarch, struct ui_file *file)
2053 {
2054   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
2055
2056   fprintf_unfiltered (file, "arc_dump_tdep: jb_pc = %i\n", tdep->jb_pc);
2057 }
2058
2059 /* Wrapper for "maintenance print arc" list of commands.  */
2060
2061 static void
2062 maintenance_print_arc_command (char *args, int from_tty)
2063 {
2064   cmd_show_list (maintenance_print_arc_list, from_tty, "");
2065 }
2066
2067 /* This command accepts single argument - address of instruction to
2068    disassemble.  */
2069
2070 static void
2071 dump_arc_instruction_command (char *args, int from_tty)
2072 {
2073   struct value *val;
2074   if (args != NULL && strlen (args) > 0)
2075     val = evaluate_expression (parse_expression (args).get ());
2076   else
2077     val = access_value_history (0);
2078   record_latest_value (val);
2079
2080   CORE_ADDR address = value_as_address (val);
2081   struct arc_instruction insn;
2082   struct disassemble_info di = arc_disassemble_info (target_gdbarch ());
2083   arc_insn_decode (address, &di, arc_delayed_print_insn, &insn);
2084   arc_insn_dump (insn);
2085 }
2086
2087 /* Suppress warning from -Wmissing-prototypes.  */
2088 extern initialize_file_ftype _initialize_arc_tdep;
2089
2090 void
2091 _initialize_arc_tdep (void)
2092 {
2093   gdbarch_register (bfd_arch_arc, arc_gdbarch_init, arc_dump_tdep);
2094
2095   initialize_tdesc_arc_v2 ();
2096   initialize_tdesc_arc_arcompact ();
2097
2098   /* Register ARC-specific commands with gdb.  */
2099
2100   /* Add root prefix command for "maintenance print arc" commands.  */
2101   add_prefix_cmd ("arc", class_maintenance, maintenance_print_arc_command,
2102                   _("ARC-specific maintenance commands for printing GDB "
2103                     "internal state."),
2104                   &maintenance_print_arc_list, "maintenance print arc ", 0,
2105                   &maintenanceprintlist);
2106
2107   add_cmd ("arc-instruction", class_maintenance,
2108            dump_arc_instruction_command,
2109            _("Dump arc_instruction structure for specified address."),
2110            &maintenance_print_arc_list);
2111
2112   /* Debug internals for ARC GDB.  */
2113   add_setshow_zinteger_cmd ("arc", class_maintenance,
2114                             &arc_debug,
2115                             _("Set ARC specific debugging."),
2116                             _("Show ARC specific debugging."),
2117                             _("Non-zero enables ARC specific debugging."),
2118                             NULL, NULL, &setdebuglist, &showdebuglist);
2119 }