]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gas/config/tc-riscv.c
RISC-V: Scalar crypto instructions and operand set.
[thirdparty/binutils-gdb.git] / gas / config / tc-riscv.c
1 /* tc-riscv.c -- RISC-V assembler
2 Copyright (C) 2011-2021 Free Software Foundation, Inc.
3
4 Contributed by Andrew Waterman (andrew@sifive.com).
5 Based on MIPS target.
6
7 This file is part of GAS.
8
9 GAS is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
13
14 GAS is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program; see the file COPYING3. If not,
21 see <http://www.gnu.org/licenses/>. */
22
23 #include "as.h"
24 #include "config.h"
25 #include "subsegs.h"
26 #include "safe-ctype.h"
27
28 #include "itbl-ops.h"
29 #include "dwarf2dbg.h"
30 #include "dw2gencfi.h"
31
32 #include "bfd/elfxx-riscv.h"
33 #include "elf/riscv.h"
34 #include "opcode/riscv.h"
35
36 #include <stdint.h>
37
38 /* Information about an instruction, including its format, operands
39 and fixups. */
40 struct riscv_cl_insn
41 {
42 /* The opcode's entry in riscv_opcodes. */
43 const struct riscv_opcode *insn_mo;
44
45 /* The encoded instruction bits. */
46 insn_t insn_opcode;
47
48 /* The frag that contains the instruction. */
49 struct frag *frag;
50
51 /* The offset into FRAG of the first instruction byte. */
52 long where;
53
54 /* The relocs associated with the instruction, if any. */
55 fixS *fixp;
56 };
57
58 /* All RISC-V CSR belong to one of these classes. */
59 enum riscv_csr_class
60 {
61 CSR_CLASS_NONE,
62
63 CSR_CLASS_I,
64 CSR_CLASS_I_32, /* rv32 only */
65 CSR_CLASS_F, /* f-ext only */
66 CSR_CLASS_ZKR, /* zkr only */
67 CSR_CLASS_DEBUG /* debug CSR */
68 };
69
70 /* This structure holds all restricted conditions for a CSR. */
71 struct riscv_csr_extra
72 {
73 /* Class to which this CSR belongs. Used to decide whether or
74 not this CSR is legal in the current -march context. */
75 enum riscv_csr_class csr_class;
76
77 /* CSR may have differnet numbers in the previous priv spec. */
78 unsigned address;
79
80 /* Record the CSR is defined/valid in which versions. */
81 enum riscv_spec_class define_version;
82
83 /* Record the CSR is aborted/invalid from which versions. If it isn't
84 aborted in the current version, then it should be CSR_CLASS_VDRAFT. */
85 enum riscv_spec_class abort_version;
86
87 /* The CSR may have more than one setting. */
88 struct riscv_csr_extra *next;
89 };
90
91 #ifndef DEFAULT_ARCH
92 #define DEFAULT_ARCH "riscv64"
93 #endif
94
95 #ifndef DEFAULT_RISCV_ATTR
96 #define DEFAULT_RISCV_ATTR 0
97 #endif
98
99 /* Let riscv_after_parse_args set the default value according to xlen. */
100 #ifndef DEFAULT_RISCV_ARCH_WITH_EXT
101 #define DEFAULT_RISCV_ARCH_WITH_EXT NULL
102 #endif
103
104 /* Need to sync the version with RISC-V compiler. */
105 #ifndef DEFAULT_RISCV_ISA_SPEC
106 #define DEFAULT_RISCV_ISA_SPEC "2.2"
107 #endif
108
109 #ifndef DEFAULT_RISCV_PRIV_SPEC
110 #define DEFAULT_RISCV_PRIV_SPEC "1.11"
111 #endif
112
113 static const char default_arch[] = DEFAULT_ARCH;
114 static const char *default_arch_with_ext = DEFAULT_RISCV_ARCH_WITH_EXT;
115 static enum riscv_spec_class default_isa_spec = ISA_SPEC_CLASS_NONE;
116 static enum riscv_spec_class default_priv_spec = PRIV_SPEC_CLASS_NONE;
117
118 static unsigned xlen = 0; /* The width of an x-register. */
119 static unsigned abi_xlen = 0; /* The width of a pointer in the ABI. */
120 static bool rve_abi = false;
121 enum float_abi
122 {
123 FLOAT_ABI_DEFAULT = -1,
124 FLOAT_ABI_SOFT,
125 FLOAT_ABI_SINGLE,
126 FLOAT_ABI_DOUBLE,
127 FLOAT_ABI_QUAD
128 };
129 static enum float_abi float_abi = FLOAT_ABI_DEFAULT;
130
131 #define LOAD_ADDRESS_INSN (abi_xlen == 64 ? "ld" : "lw")
132 #define ADD32_INSN (xlen == 64 ? "addiw" : "addi")
133
134 static unsigned elf_flags = 0;
135
136 /* Set the default_isa_spec. Return 0 if the spec isn't supported.
137 Otherwise, return 1. */
138
139 static int
140 riscv_set_default_isa_spec (const char *s)
141 {
142 enum riscv_spec_class class = ISA_SPEC_CLASS_NONE;
143 RISCV_GET_ISA_SPEC_CLASS (s, class);
144 if (class == ISA_SPEC_CLASS_NONE)
145 {
146 as_bad ("unknown default ISA spec `%s' set by "
147 "-misa-spec or --with-isa-spec", s);
148 return 0;
149 }
150 else
151 default_isa_spec = class;
152 return 1;
153 }
154
155 /* Set the default_priv_spec. Find the privileged elf attributes when
156 the input string is NULL. Return 0 if the spec isn't supported.
157 Otherwise, return 1. */
158
159 static int
160 riscv_set_default_priv_spec (const char *s)
161 {
162 enum riscv_spec_class class = PRIV_SPEC_CLASS_NONE;
163 unsigned major, minor, revision;
164 obj_attribute *attr;
165
166 RISCV_GET_PRIV_SPEC_CLASS (s, class);
167 if (class != PRIV_SPEC_CLASS_NONE)
168 {
169 default_priv_spec = class;
170 return 1;
171 }
172
173 if (s != NULL)
174 {
175 as_bad (_("unknown default privileged spec `%s' set by "
176 "-mpriv-spec or --with-priv-spec"), s);
177 return 0;
178 }
179
180 /* Set the default_priv_spec by the privileged elf attributes. */
181 attr = elf_known_obj_attributes_proc (stdoutput);
182 major = (unsigned) attr[Tag_RISCV_priv_spec].i;
183 minor = (unsigned) attr[Tag_RISCV_priv_spec_minor].i;
184 revision = (unsigned) attr[Tag_RISCV_priv_spec_revision].i;
185 /* Version 0.0.0 is the default value and meningless. */
186 if (major == 0 && minor == 0 && revision == 0)
187 return 1;
188
189 riscv_get_priv_spec_class_from_numbers (major, minor, revision, &class);
190 if (class != PRIV_SPEC_CLASS_NONE)
191 {
192 default_priv_spec = class;
193 return 1;
194 }
195
196 /* Still can not find the privileged spec class. */
197 as_bad (_("unknown default privileged spec `%d.%d.%d' set by "
198 "privileged elf attributes"), major, minor, revision);
199 return 0;
200 }
201
202 /* This is the set of options which the .option pseudo-op may modify. */
203 struct riscv_set_options
204 {
205 int pic; /* Generate position-independent code. */
206 int rvc; /* Generate RVC code. */
207 int relax; /* Emit relocs the linker is allowed to relax. */
208 int arch_attr; /* Emit architecture and privileged elf attributes. */
209 int csr_check; /* Enable the CSR checking. */
210 };
211
212 static struct riscv_set_options riscv_opts =
213 {
214 0, /* pic */
215 0, /* rvc */
216 1, /* relax */
217 DEFAULT_RISCV_ATTR, /* arch_attr */
218 0, /* csr_check */
219 };
220
221 /* Enable or disable the rvc flags for riscv_opts. Turn on the rvc flag
222 for elf_flags once we have enabled c extension. */
223
224 static void
225 riscv_set_rvc (bool rvc_value)
226 {
227 if (rvc_value)
228 elf_flags |= EF_RISCV_RVC;
229
230 riscv_opts.rvc = rvc_value;
231 }
232
233 /* This linked list records all enabled extensions, which are parsed from
234 the architecture string. The architecture string can be set by the
235 -march option, the elf architecture attributes, and the --with-arch
236 configure option. */
237 static riscv_subset_list_t riscv_subsets;
238 static riscv_parse_subset_t riscv_rps_as =
239 {
240 &riscv_subsets, /* subset_list. */
241 as_bad, /* error_handler. */
242 &xlen, /* xlen. */
243 &default_isa_spec, /* isa_spec. */
244 true, /* check_unknown_prefixed_ext. */
245 };
246
247 /* Set which ISA and extensions are available. */
248
249 static void
250 riscv_set_arch (const char *s)
251 {
252 if (s != NULL && strcmp (s, "") == 0)
253 {
254 as_bad (_("the architecture string of -march and elf architecture "
255 "attributes cannot be empty"));
256 return;
257 }
258
259 riscv_release_subset_list (&riscv_subsets);
260 riscv_parse_subset (&riscv_rps_as, s);
261
262 riscv_set_rvc (false);
263 if (riscv_subset_supports (&riscv_rps_as, "c"))
264 riscv_set_rvc (true);
265 }
266
267 /* Indicate -mabi option is explictly set. */
268 static bool explicit_mabi = false;
269
270 /* Set the abi information. */
271
272 static void
273 riscv_set_abi (unsigned new_xlen, enum float_abi new_float_abi, bool rve)
274 {
275 abi_xlen = new_xlen;
276 float_abi = new_float_abi;
277 rve_abi = rve;
278 }
279
280 /* If the -mabi option isn't set, then set the abi according to the
281 ISA string. Otherwise, check if there is any conflict. */
282
283 static void
284 riscv_set_abi_by_arch (void)
285 {
286 if (!explicit_mabi)
287 {
288 if (riscv_subset_supports (&riscv_rps_as, "q"))
289 riscv_set_abi (xlen, FLOAT_ABI_QUAD, false);
290 else if (riscv_subset_supports (&riscv_rps_as, "d"))
291 riscv_set_abi (xlen, FLOAT_ABI_DOUBLE, false);
292 else if (riscv_subset_supports (&riscv_rps_as, "e"))
293 riscv_set_abi (xlen, FLOAT_ABI_SOFT, true);
294 else
295 riscv_set_abi (xlen, FLOAT_ABI_SOFT, false);
296 }
297 else
298 {
299 gas_assert (abi_xlen != 0 && xlen != 0 && float_abi != FLOAT_ABI_DEFAULT);
300 if (abi_xlen > xlen)
301 as_bad ("can't have %d-bit ABI on %d-bit ISA", abi_xlen, xlen);
302 else if (abi_xlen < xlen)
303 as_bad ("%d-bit ABI not yet supported on %d-bit ISA", abi_xlen, xlen);
304
305 if (riscv_subset_supports (&riscv_rps_as, "e") && !rve_abi)
306 as_bad ("only the ilp32e ABI is supported for e extension");
307
308 if (float_abi == FLOAT_ABI_SINGLE
309 && !riscv_subset_supports (&riscv_rps_as, "f"))
310 as_bad ("ilp32f/lp64f ABI can't be used when f extension "
311 "isn't supported");
312 else if (float_abi == FLOAT_ABI_DOUBLE
313 && !riscv_subset_supports (&riscv_rps_as, "d"))
314 as_bad ("ilp32d/lp64d ABI can't be used when d extension "
315 "isn't supported");
316 else if (float_abi == FLOAT_ABI_QUAD
317 && !riscv_subset_supports (&riscv_rps_as, "q"))
318 as_bad ("ilp32q/lp64q ABI can't be used when q extension "
319 "isn't supported");
320 }
321
322 /* Update the EF_RISCV_FLOAT_ABI field of elf_flags. */
323 elf_flags &= ~EF_RISCV_FLOAT_ABI;
324 elf_flags |= float_abi << 1;
325
326 if (rve_abi)
327 elf_flags |= EF_RISCV_RVE;
328 }
329
330 /* Handle of the OPCODE hash table. */
331 static htab_t op_hash = NULL;
332
333 /* Handle of the type of .insn hash table. */
334 static htab_t insn_type_hash = NULL;
335
336 /* This array holds the chars that always start a comment. If the
337 pre-processor is disabled, these aren't very useful. */
338 const char comment_chars[] = "#";
339
340 /* This array holds the chars that only start a comment at the beginning of
341 a line. If the line seems to have the form '# 123 filename'
342 .line and .file directives will appear in the pre-processed output
343
344 Note that input_file.c hand checks for '#' at the beginning of the
345 first line of the input file. This is because the compiler outputs
346 #NO_APP at the beginning of its output.
347
348 Also note that C style comments are always supported. */
349 const char line_comment_chars[] = "#";
350
351 /* This array holds machine specific line separator characters. */
352 const char line_separator_chars[] = ";";
353
354 /* Chars that can be used to separate mant from exp in floating point nums. */
355 const char EXP_CHARS[] = "eE";
356
357 /* Chars that mean this number is a floating point constant.
358 As in 0f12.456 or 0d1.2345e12. */
359 const char FLT_CHARS[] = "rRsSfFdDxXpP";
360
361 /* Indicate we are already assemble any instructions or not. */
362 static bool start_assemble = false;
363
364 /* Indicate ELF attributes are explicitly set. */
365 static bool explicit_attr = false;
366
367 /* Indicate CSR or priv instructions are explicitly used. */
368 static bool explicit_priv_attr = false;
369
370 static char *expr_end;
371
372 /* Macros for encoding relaxation state for RVC branches and far jumps. */
373 #define RELAX_BRANCH_ENCODE(uncond, rvc, length) \
374 ((relax_substateT) \
375 (0xc0000000 \
376 | ((uncond) ? 1 : 0) \
377 | ((rvc) ? 2 : 0) \
378 | ((length) << 2)))
379 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
380 #define RELAX_BRANCH_LENGTH(i) (((i) >> 2) & 0xF)
381 #define RELAX_BRANCH_RVC(i) (((i) & 2) != 0)
382 #define RELAX_BRANCH_UNCOND(i) (((i) & 1) != 0)
383
384 /* Is the given value a sign-extended 32-bit value? */
385 #define IS_SEXT_32BIT_NUM(x) \
386 (((x) &~ (offsetT) 0x7fffffff) == 0 \
387 || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
388
389 /* Is the given value a zero-extended 32-bit value? Or a negated one? */
390 #define IS_ZEXT_32BIT_NUM(x) \
391 (((x) &~ (offsetT) 0xffffffff) == 0 \
392 || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
393
394 /* Change INSN's opcode so that the operand given by FIELD has value VALUE.
395 INSN is a riscv_cl_insn structure and VALUE is evaluated exactly once. */
396 #define INSERT_OPERAND(FIELD, INSN, VALUE) \
397 INSERT_BITS ((INSN).insn_opcode, VALUE, OP_MASK_##FIELD, OP_SH_##FIELD)
398
399 /* Determine if an instruction matches an opcode. */
400 #define OPCODE_MATCHES(OPCODE, OP) \
401 (((OPCODE) & MASK_##OP) == MATCH_##OP)
402
403 /* Create a new mapping symbol for the transition to STATE. */
404
405 static void
406 make_mapping_symbol (enum riscv_seg_mstate state,
407 valueT value,
408 fragS *frag)
409 {
410 const char *name;
411 switch (state)
412 {
413 case MAP_DATA:
414 name = "$d";
415 break;
416 case MAP_INSN:
417 name = "$x";
418 break;
419 default:
420 abort ();
421 }
422
423 symbolS *symbol = symbol_new (name, now_seg, frag, value);
424 symbol_get_bfdsym (symbol)->flags |= (BSF_NO_FLAGS | BSF_LOCAL);
425
426 /* If .fill or other data filling directive generates zero sized data,
427 or we are adding odd alignemnts, then the mapping symbol for the
428 following code will have the same value. */
429 if (value == 0)
430 {
431 if (frag->tc_frag_data.first_map_symbol != NULL)
432 {
433 know (S_GET_VALUE (frag->tc_frag_data.first_map_symbol)
434 == S_GET_VALUE (symbol));
435 /* Remove the old one. */
436 symbol_remove (frag->tc_frag_data.first_map_symbol,
437 &symbol_rootP, &symbol_lastP);
438 }
439 frag->tc_frag_data.first_map_symbol = symbol;
440 }
441 if (frag->tc_frag_data.last_map_symbol != NULL)
442 {
443 /* The mapping symbols should be added in offset order. */
444 know (S_GET_VALUE (frag->tc_frag_data.last_map_symbol)
445 <= S_GET_VALUE (symbol));
446 /* Remove the old one. */
447 if (S_GET_VALUE (frag->tc_frag_data.last_map_symbol)
448 == S_GET_VALUE (symbol))
449 symbol_remove (frag->tc_frag_data.last_map_symbol,
450 &symbol_rootP, &symbol_lastP);
451 }
452 frag->tc_frag_data.last_map_symbol = symbol;
453 }
454
455 /* Set the mapping state for frag_now. */
456
457 void
458 riscv_mapping_state (enum riscv_seg_mstate to_state,
459 int max_chars)
460 {
461 enum riscv_seg_mstate from_state =
462 seg_info (now_seg)->tc_segment_info_data.map_state;
463
464 if (!SEG_NORMAL (now_seg)
465 /* For now I only add the mapping symbols to text sections.
466 Therefore, the dis-assembler only show the actual contents
467 distribution for text. Other sections will be shown as
468 data without the details. */
469 || !subseg_text_p (now_seg))
470 return;
471
472 /* The mapping symbol should be emitted if not in the right
473 mapping state */
474 if (from_state == to_state)
475 return;
476
477 valueT value = (valueT) (frag_now_fix () - max_chars);
478 seg_info (now_seg)->tc_segment_info_data.map_state = to_state;
479 make_mapping_symbol (to_state, value, frag_now);
480 }
481
482 /* Add the odd bytes of paddings for riscv_handle_align. */
483
484 static void
485 riscv_add_odd_padding_symbol (fragS *frag)
486 {
487 /* If there was already a mapping symbol, it should be
488 removed in the make_mapping_symbol. */
489 make_mapping_symbol (MAP_DATA, frag->fr_fix, frag);
490 make_mapping_symbol (MAP_INSN, frag->fr_fix + 1, frag);
491 }
492
493 /* Remove any excess mapping symbols generated for alignment frags in
494 SEC. We may have created a mapping symbol before a zero byte
495 alignment; remove it if there's a mapping symbol after the
496 alignment. */
497
498 static void
499 riscv_check_mapping_symbols (bfd *abfd ATTRIBUTE_UNUSED,
500 asection *sec,
501 void *dummy ATTRIBUTE_UNUSED)
502 {
503 segment_info_type *seginfo = seg_info (sec);
504 fragS *fragp;
505
506 if (seginfo == NULL || seginfo->frchainP == NULL)
507 return;
508
509 for (fragp = seginfo->frchainP->frch_root;
510 fragp != NULL;
511 fragp = fragp->fr_next)
512 {
513 symbolS *last = fragp->tc_frag_data.last_map_symbol;
514 fragS *next = fragp->fr_next;
515
516 if (last == NULL || next == NULL)
517 continue;
518
519 /* Check the last mapping symbol if it is at the boundary of
520 fragment. */
521 if (S_GET_VALUE (last) < next->fr_address)
522 continue;
523 know (S_GET_VALUE (last) == next->fr_address);
524
525 do
526 {
527 if (next->tc_frag_data.first_map_symbol != NULL)
528 {
529 /* The last mapping symbol overlaps with another one
530 which at the start of the next frag. */
531 symbol_remove (last, &symbol_rootP, &symbol_lastP);
532 break;
533 }
534
535 if (next->fr_next == NULL)
536 {
537 /* The last mapping symbol is at the end of the section. */
538 know (next->fr_fix == 0 && next->fr_var == 0);
539 symbol_remove (last, &symbol_rootP, &symbol_lastP);
540 break;
541 }
542
543 /* Since we may have empty frags without any mapping symbols,
544 keep looking until the non-empty frag. */
545 if (next->fr_address != next->fr_next->fr_address)
546 break;
547
548 next = next->fr_next;
549 }
550 while (next != NULL);
551 }
552 }
553
554 /* The default target format to use. */
555
556 const char *
557 riscv_target_format (void)
558 {
559 if (target_big_endian)
560 return xlen == 64 ? "elf64-bigriscv" : "elf32-bigriscv";
561 else
562 return xlen == 64 ? "elf64-littleriscv" : "elf32-littleriscv";
563 }
564
565 /* Return the length of instruction INSN. */
566
567 static inline unsigned int
568 insn_length (const struct riscv_cl_insn *insn)
569 {
570 return riscv_insn_length (insn->insn_opcode);
571 }
572
573 /* Initialise INSN from opcode entry MO. Leave its position unspecified. */
574
575 static void
576 create_insn (struct riscv_cl_insn *insn, const struct riscv_opcode *mo)
577 {
578 insn->insn_mo = mo;
579 insn->insn_opcode = mo->match;
580 insn->frag = NULL;
581 insn->where = 0;
582 insn->fixp = NULL;
583 }
584
585 /* Install INSN at the location specified by its "frag" and "where" fields. */
586
587 static void
588 install_insn (const struct riscv_cl_insn *insn)
589 {
590 char *f = insn->frag->fr_literal + insn->where;
591 number_to_chars_littleendian (f, insn->insn_opcode, insn_length (insn));
592 }
593
594 /* Move INSN to offset WHERE in FRAG. Adjust the fixups accordingly
595 and install the opcode in the new location. */
596
597 static void
598 move_insn (struct riscv_cl_insn *insn, fragS *frag, long where)
599 {
600 insn->frag = frag;
601 insn->where = where;
602 if (insn->fixp != NULL)
603 {
604 insn->fixp->fx_frag = frag;
605 insn->fixp->fx_where = where;
606 }
607 install_insn (insn);
608 }
609
610 /* Add INSN to the end of the output. */
611
612 static void
613 add_fixed_insn (struct riscv_cl_insn *insn)
614 {
615 char *f = frag_more (insn_length (insn));
616 move_insn (insn, frag_now, f - frag_now->fr_literal);
617 }
618
619 static void
620 add_relaxed_insn (struct riscv_cl_insn *insn, int max_chars, int var,
621 relax_substateT subtype, symbolS *symbol, offsetT offset)
622 {
623 frag_grow (max_chars);
624 move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
625 frag_var (rs_machine_dependent, max_chars, var,
626 subtype, symbol, offset, NULL);
627 }
628
629 /* Compute the length of a branch sequence, and adjust the stored length
630 accordingly. If FRAGP is NULL, the worst-case length is returned. */
631
632 static unsigned
633 relaxed_branch_length (fragS *fragp, asection *sec, int update)
634 {
635 int jump, rvc, length = 8;
636
637 if (!fragp)
638 return length;
639
640 jump = RELAX_BRANCH_UNCOND (fragp->fr_subtype);
641 rvc = RELAX_BRANCH_RVC (fragp->fr_subtype);
642 length = RELAX_BRANCH_LENGTH (fragp->fr_subtype);
643
644 /* Assume jumps are in range; the linker will catch any that aren't. */
645 length = jump ? 4 : 8;
646
647 if (fragp->fr_symbol != NULL
648 && S_IS_DEFINED (fragp->fr_symbol)
649 && !S_IS_WEAK (fragp->fr_symbol)
650 && sec == S_GET_SEGMENT (fragp->fr_symbol))
651 {
652 offsetT val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
653 bfd_vma rvc_range = jump ? RVC_JUMP_REACH : RVC_BRANCH_REACH;
654 val -= fragp->fr_address + fragp->fr_fix;
655
656 if (rvc && (bfd_vma)(val + rvc_range/2) < rvc_range)
657 length = 2;
658 else if ((bfd_vma)(val + RISCV_BRANCH_REACH/2) < RISCV_BRANCH_REACH)
659 length = 4;
660 else if (!jump && rvc)
661 length = 6;
662 }
663
664 if (update)
665 fragp->fr_subtype = RELAX_BRANCH_ENCODE (jump, rvc, length);
666
667 return length;
668 }
669
670 /* Information about an opcode name, mnemonics and its value. */
671 struct opcode_name_t
672 {
673 const char *name;
674 unsigned int val;
675 };
676
677 /* List for all supported opcode name. */
678 static const struct opcode_name_t opcode_name_list[] =
679 {
680 {"C0", 0x0},
681 {"C1", 0x1},
682 {"C2", 0x2},
683
684 {"LOAD", 0x03},
685 {"LOAD_FP", 0x07},
686 {"CUSTOM_0", 0x0b},
687 {"MISC_MEM", 0x0f},
688 {"OP_IMM", 0x13},
689 {"AUIPC", 0x17},
690 {"OP_IMM_32", 0x1b},
691 /* 48b 0x1f. */
692
693 {"STORE", 0x23},
694 {"STORE_FP", 0x27},
695 {"CUSTOM_1", 0x2b},
696 {"AMO", 0x2f},
697 {"OP", 0x33},
698 {"LUI", 0x37},
699 {"OP_32", 0x3b},
700 /* 64b 0x3f. */
701
702 {"MADD", 0x43},
703 {"MSUB", 0x47},
704 {"NMADD", 0x4f},
705 {"NMSUB", 0x4b},
706 {"OP_FP", 0x53},
707 /*reserved 0x57. */
708 {"CUSTOM_2", 0x5b},
709 /* 48b 0x5f. */
710
711 {"BRANCH", 0x63},
712 {"JALR", 0x67},
713 /*reserved 0x5b. */
714 {"JAL", 0x6f},
715 {"SYSTEM", 0x73},
716 /*reserved 0x77. */
717 {"CUSTOM_3", 0x7b},
718 /* >80b 0x7f. */
719
720 {NULL, 0}
721 };
722
723 /* Hash table for lookup opcode name. */
724 static htab_t opcode_names_hash = NULL;
725
726 /* Initialization for hash table of opcode name. */
727
728 static void
729 init_opcode_names_hash (void)
730 {
731 const struct opcode_name_t *opcode;
732
733 for (opcode = &opcode_name_list[0]; opcode->name != NULL; ++opcode)
734 if (str_hash_insert (opcode_names_hash, opcode->name, opcode, 0) != NULL)
735 as_fatal (_("internal: duplicate %s"), opcode->name);
736 }
737
738 /* Find `s` is a valid opcode name or not, return the opcode name info
739 if found. */
740
741 static const struct opcode_name_t *
742 opcode_name_lookup (char **s)
743 {
744 char *e;
745 char save_c;
746 struct opcode_name_t *o;
747
748 /* Find end of name. */
749 e = *s;
750 if (is_name_beginner (*e))
751 ++e;
752 while (is_part_of_name (*e))
753 ++e;
754
755 /* Terminate name. */
756 save_c = *e;
757 *e = '\0';
758
759 o = (struct opcode_name_t *) str_hash_find (opcode_names_hash, *s);
760
761 /* Advance to next token if one was recognized. */
762 if (o)
763 *s = e;
764
765 *e = save_c;
766 expr_end = e;
767
768 return o;
769 }
770
771 /* All RISC-V registers belong to one of these classes. */
772 enum reg_class
773 {
774 RCLASS_GPR,
775 RCLASS_FPR,
776 RCLASS_MAX,
777
778 RCLASS_CSR
779 };
780
781 static htab_t reg_names_hash = NULL;
782 static htab_t csr_extra_hash = NULL;
783
784 #define ENCODE_REG_HASH(cls, n) \
785 ((void *)(uintptr_t)((n) * RCLASS_MAX + (cls) + 1))
786 #define DECODE_REG_CLASS(hash) (((uintptr_t)(hash) - 1) % RCLASS_MAX)
787 #define DECODE_REG_NUM(hash) (((uintptr_t)(hash) - 1) / RCLASS_MAX)
788
789 static void
790 hash_reg_name (enum reg_class class, const char *name, unsigned n)
791 {
792 void *hash = ENCODE_REG_HASH (class, n);
793 if (str_hash_insert (reg_names_hash, name, hash, 0) != NULL)
794 as_fatal (_("internal: duplicate %s"), name);
795 }
796
797 static void
798 hash_reg_names (enum reg_class class, const char * const names[], unsigned n)
799 {
800 unsigned i;
801
802 for (i = 0; i < n; i++)
803 hash_reg_name (class, names[i], i);
804 }
805
806 /* Init hash table csr_extra_hash to handle CSR. */
807
808 static void
809 riscv_init_csr_hash (const char *name,
810 unsigned address,
811 enum riscv_csr_class class,
812 enum riscv_spec_class define_version,
813 enum riscv_spec_class abort_version)
814 {
815 struct riscv_csr_extra *entry, *pre_entry;
816 bool need_enrty = true;
817
818 pre_entry = NULL;
819 entry = (struct riscv_csr_extra *) str_hash_find (csr_extra_hash, name);
820 while (need_enrty && entry != NULL)
821 {
822 if (entry->csr_class == class
823 && entry->address == address
824 && entry->define_version == define_version
825 && entry->abort_version == abort_version)
826 need_enrty = false;
827 pre_entry = entry;
828 entry = entry->next;
829 }
830
831 /* Duplicate CSR. */
832 if (!need_enrty)
833 return;
834
835 entry = XNEW (struct riscv_csr_extra);
836 entry->csr_class = class;
837 entry->address = address;
838 entry->define_version = define_version;
839 entry->abort_version = abort_version;
840 entry->next = NULL;
841
842 if (pre_entry == NULL)
843 str_hash_insert (csr_extra_hash, name, entry, 0);
844 else
845 pre_entry->next = entry;
846 }
847
848 /* Return the CSR address after checking the ISA dependency and
849 the privileged spec version.
850
851 There are one warning and two errors for CSR,
852
853 Invalid CSR: the CSR was defined, but isn't allowed for the current ISA
854 or the privileged spec, report warning only if -mcsr-check is set.
855 Unknown CSR: the CSR has never been defined, report error.
856 Improper CSR: the CSR number over the range (> 0xfff), report error. */
857
858 static unsigned int
859 riscv_csr_address (const char *csr_name,
860 struct riscv_csr_extra *entry)
861 {
862 struct riscv_csr_extra *saved_entry = entry;
863 enum riscv_csr_class csr_class = entry->csr_class;
864 bool need_check_version = true;
865 bool result = true;
866
867 switch (csr_class)
868 {
869 case CSR_CLASS_I:
870 result = riscv_subset_supports (&riscv_rps_as, "i");
871 break;
872 case CSR_CLASS_I_32:
873 result = (xlen == 32 && riscv_subset_supports (&riscv_rps_as, "i"));
874 break;
875 case CSR_CLASS_F:
876 result = riscv_subset_supports (&riscv_rps_as, "f");
877 need_check_version = false;
878 break;
879 case CSR_CLASS_ZKR:
880 result = riscv_subset_supports (&riscv_rps_as, "zkr");
881 need_check_version = false;
882 break;
883 case CSR_CLASS_DEBUG:
884 need_check_version = false;
885 break;
886 default:
887 as_bad (_("internal: bad RISC-V CSR class (0x%x)"), csr_class);
888 }
889
890 if (riscv_opts.csr_check && !result)
891 as_warn (_("invalid CSR `%s' for the current ISA"), csr_name);
892
893 while (entry != NULL)
894 {
895 if (!need_check_version
896 || (default_priv_spec >= entry->define_version
897 && default_priv_spec < entry->abort_version))
898 {
899 /* Find the CSR according to the specific version. */
900 return entry->address;
901 }
902 entry = entry->next;
903 }
904
905 /* Can not find the CSR address from the chosen privileged version,
906 so use the newly defined value. */
907 if (riscv_opts.csr_check)
908 {
909 const char *priv_name = NULL;
910 RISCV_GET_PRIV_SPEC_NAME (priv_name, default_priv_spec);
911 if (priv_name != NULL)
912 as_warn (_("invalid CSR `%s' for the privileged spec `%s'"),
913 csr_name, priv_name);
914 }
915
916 return saved_entry->address;
917 }
918
919 /* Return -1 if the CSR has never been defined. Otherwise, return
920 the address. */
921
922 static unsigned int
923 reg_csr_lookup_internal (const char *s)
924 {
925 struct riscv_csr_extra *r =
926 (struct riscv_csr_extra *) str_hash_find (csr_extra_hash, s);
927
928 if (r == NULL)
929 return -1U;
930
931 return riscv_csr_address (s, r);
932 }
933
934 static unsigned int
935 reg_lookup_internal (const char *s, enum reg_class class)
936 {
937 void *r;
938
939 if (class == RCLASS_CSR)
940 return reg_csr_lookup_internal (s);
941
942 r = str_hash_find (reg_names_hash, s);
943 if (r == NULL || DECODE_REG_CLASS (r) != class)
944 return -1;
945
946 if (riscv_subset_supports (&riscv_rps_as, "e")
947 && class == RCLASS_GPR
948 && DECODE_REG_NUM (r) > 15)
949 return -1;
950
951 return DECODE_REG_NUM (r);
952 }
953
954 static bool
955 reg_lookup (char **s, enum reg_class class, unsigned int *regnop)
956 {
957 char *e;
958 char save_c;
959 int reg = -1;
960
961 /* Find end of name. */
962 e = *s;
963 if (is_name_beginner (*e))
964 ++e;
965 while (is_part_of_name (*e))
966 ++e;
967
968 /* Terminate name. */
969 save_c = *e;
970 *e = '\0';
971
972 /* Look for the register. Advance to next token if one was recognized. */
973 if ((reg = reg_lookup_internal (*s, class)) >= 0)
974 *s = e;
975
976 *e = save_c;
977 if (regnop)
978 *regnop = reg;
979 return reg >= 0;
980 }
981
982 static bool
983 arg_lookup (char **s, const char *const *array, size_t size, unsigned *regnop)
984 {
985 const char *p = strchr (*s, ',');
986 size_t i, len = p ? (size_t)(p - *s) : strlen (*s);
987
988 if (len == 0)
989 return false;
990
991 for (i = 0; i < size; i++)
992 if (array[i] != NULL && strncmp (array[i], *s, len) == 0)
993 {
994 *regnop = i;
995 *s += len;
996 return true;
997 }
998
999 return false;
1000 }
1001
1002 #define USE_BITS(mask,shift) (used_bits |= ((insn_t)(mask) << (shift)))
1003
1004 /* For consistency checking, verify that all bits are specified either
1005 by the match/mask part of the instruction definition, or by the
1006 operand list. The `length` could be 0, 4 or 8, 0 for auto detection. */
1007
1008 static bool
1009 validate_riscv_insn (const struct riscv_opcode *opc, int length)
1010 {
1011 const char *oparg, *opargStart;
1012 insn_t used_bits = opc->mask;
1013 int insn_width;
1014 insn_t required_bits;
1015
1016 if (length == 0)
1017 insn_width = 8 * riscv_insn_length (opc->match);
1018 else
1019 insn_width = 8 * length;
1020
1021 required_bits = ~0ULL >> (64 - insn_width);
1022
1023 if ((used_bits & opc->match) != (opc->match & required_bits))
1024 {
1025 as_bad (_("internal: bad RISC-V opcode (mask error): %s %s"),
1026 opc->name, opc->args);
1027 return false;
1028 }
1029
1030 for (oparg = opc->args; *oparg; ++oparg)
1031 {
1032 opargStart = oparg;
1033 switch (*oparg)
1034 {
1035 case 'C': /* RVC */
1036 switch (*++oparg)
1037 {
1038 case 'U': break; /* CRS1, constrained to equal RD. */
1039 case 'c': break; /* CRS1, constrained to equal sp. */
1040 case 'T': /* CRS2, floating point. */
1041 case 'V': USE_BITS (OP_MASK_CRS2, OP_SH_CRS2); break;
1042 case 'S': /* CRS1S, floating point. */
1043 case 's': USE_BITS (OP_MASK_CRS1S, OP_SH_CRS1S); break;
1044 case 'w': break; /* CRS1S, constrained to equal RD. */
1045 case 'D': /* CRS2S, floating point. */
1046 case 't': USE_BITS (OP_MASK_CRS2S, OP_SH_CRS2S); break;
1047 case 'x': break; /* CRS2S, constrained to equal RD. */
1048 case 'z': break; /* CRS2S, constrained to be x0. */
1049 case '>': /* CITYPE immediate, compressed shift. */
1050 case 'u': /* CITYPE immediate, compressed lui. */
1051 case 'v': /* CITYPE immediate, li to compressed lui. */
1052 case 'o': /* CITYPE immediate, allow zero. */
1053 case 'j': used_bits |= ENCODE_CITYPE_IMM (-1U); break;
1054 case 'L': used_bits |= ENCODE_CITYPE_ADDI16SP_IMM (-1U); break;
1055 case 'm': used_bits |= ENCODE_CITYPE_LWSP_IMM (-1U); break;
1056 case 'n': used_bits |= ENCODE_CITYPE_LDSP_IMM (-1U); break;
1057 case '6': used_bits |= ENCODE_CSSTYPE_IMM (-1U); break;
1058 case 'M': used_bits |= ENCODE_CSSTYPE_SWSP_IMM (-1U); break;
1059 case 'N': used_bits |= ENCODE_CSSTYPE_SDSP_IMM (-1U); break;
1060 case '8': used_bits |= ENCODE_CIWTYPE_IMM (-1U); break;
1061 case 'K': used_bits |= ENCODE_CIWTYPE_ADDI4SPN_IMM (-1U); break;
1062 /* CLTYPE and CSTYPE have the same immediate encoding. */
1063 case '5': used_bits |= ENCODE_CLTYPE_IMM (-1U); break;
1064 case 'k': used_bits |= ENCODE_CLTYPE_LW_IMM (-1U); break;
1065 case 'l': used_bits |= ENCODE_CLTYPE_LD_IMM (-1U); break;
1066 case 'p': used_bits |= ENCODE_CBTYPE_IMM (-1U); break;
1067 case 'a': used_bits |= ENCODE_CJTYPE_IMM (-1U); break;
1068 case 'F': /* Compressed funct for .insn directive. */
1069 switch (*++oparg)
1070 {
1071 case '6': USE_BITS (OP_MASK_CFUNCT6, OP_SH_CFUNCT6); break;
1072 case '4': USE_BITS (OP_MASK_CFUNCT4, OP_SH_CFUNCT4); break;
1073 case '3': USE_BITS (OP_MASK_CFUNCT3, OP_SH_CFUNCT3); break;
1074 case '2': USE_BITS (OP_MASK_CFUNCT2, OP_SH_CFUNCT2); break;
1075 default:
1076 goto unknown_validate_operand;
1077 }
1078 break;
1079 default:
1080 goto unknown_validate_operand;
1081 }
1082 break;
1083 case ',': break;
1084 case '(': break;
1085 case ')': break;
1086 case '<': USE_BITS (OP_MASK_SHAMTW, OP_SH_SHAMTW); break;
1087 case '>': USE_BITS (OP_MASK_SHAMT, OP_SH_SHAMT); break;
1088 case 'A': break; /* Macro operand, must be symbol. */
1089 case 'B': break; /* Macro operand, must be symbol or constant. */
1090 case 'I': break; /* Macro operand, must be constant. */
1091 case 'D': /* RD, floating point. */
1092 case 'd': USE_BITS (OP_MASK_RD, OP_SH_RD); break;
1093 case 'y': USE_BITS (OP_MASK_BS, OP_SH_BS); break;
1094 case 'Y': USE_BITS (OP_MASK_RNUM, OP_SH_RNUM); break;
1095 case 'Z': /* RS1, CSR number. */
1096 case 'S': /* RS1, floating point. */
1097 case 's': USE_BITS (OP_MASK_RS1, OP_SH_RS1); break;
1098 case 'U': /* RS1 and RS2 are the same, floating point. */
1099 USE_BITS (OP_MASK_RS1, OP_SH_RS1);
1100 /* Fall through. */
1101 case 'T': /* RS2, floating point. */
1102 case 't': USE_BITS (OP_MASK_RS2, OP_SH_RS2); break;
1103 case 'R': /* RS3, floating point. */
1104 case 'r': USE_BITS (OP_MASK_RS3, OP_SH_RS3); break;
1105 case 'm': USE_BITS (OP_MASK_RM, OP_SH_RM); break;
1106 case 'E': USE_BITS (OP_MASK_CSR, OP_SH_CSR); break;
1107 case 'P': USE_BITS (OP_MASK_PRED, OP_SH_PRED); break;
1108 case 'Q': USE_BITS (OP_MASK_SUCC, OP_SH_SUCC); break;
1109 case 'o': /* ITYPE immediate, load displacement. */
1110 case 'j': used_bits |= ENCODE_ITYPE_IMM (-1U); break;
1111 case 'a': used_bits |= ENCODE_JTYPE_IMM (-1U); break;
1112 case 'p': used_bits |= ENCODE_BTYPE_IMM (-1U); break;
1113 case 'q': used_bits |= ENCODE_STYPE_IMM (-1U); break;
1114 case 'u': used_bits |= ENCODE_UTYPE_IMM (-1U); break;
1115 case 'z': break; /* Zero immediate. */
1116 case '[': break; /* Unused operand. */
1117 case ']': break; /* Unused operand. */
1118 case '0': break; /* AMO displacement, must to zero. */
1119 case '1': break; /* Relaxation operand. */
1120 case 'F': /* Funct for .insn directive. */
1121 switch (*++oparg)
1122 {
1123 case '7': USE_BITS (OP_MASK_FUNCT7, OP_SH_FUNCT7); break;
1124 case '3': USE_BITS (OP_MASK_FUNCT3, OP_SH_FUNCT3); break;
1125 case '2': USE_BITS (OP_MASK_FUNCT2, OP_SH_FUNCT2); break;
1126 default:
1127 goto unknown_validate_operand;
1128 }
1129 break;
1130 case 'O': /* Opcode for .insn directive. */
1131 switch (*++oparg)
1132 {
1133 case '4': USE_BITS (OP_MASK_OP, OP_SH_OP); break;
1134 case '2': USE_BITS (OP_MASK_OP2, OP_SH_OP2); break;
1135 default:
1136 goto unknown_validate_operand;
1137 }
1138 break;
1139 default:
1140 unknown_validate_operand:
1141 as_bad (_("internal: bad RISC-V opcode "
1142 "(unknown operand type `%s'): %s %s"),
1143 opargStart, opc->name, opc->args);
1144 return false;
1145 }
1146 }
1147
1148 if (used_bits != required_bits)
1149 {
1150 as_bad (_("internal: bad RISC-V opcode "
1151 "(bits 0x%lx undefined): %s %s"),
1152 ~(unsigned long)(used_bits & required_bits),
1153 opc->name, opc->args);
1154 return false;
1155 }
1156 return true;
1157 }
1158
1159 #undef USE_BITS
1160
1161 struct percent_op_match
1162 {
1163 const char *str;
1164 bfd_reloc_code_real_type reloc;
1165 };
1166
1167 /* Common hash table initialization function for instruction and .insn
1168 directive. */
1169
1170 static htab_t
1171 init_opcode_hash (const struct riscv_opcode *opcodes,
1172 bool insn_directive_p)
1173 {
1174 int i = 0;
1175 int length;
1176 htab_t hash = str_htab_create ();
1177 while (opcodes[i].name)
1178 {
1179 const char *name = opcodes[i].name;
1180 if (str_hash_insert (hash, name, &opcodes[i], 0) != NULL)
1181 as_fatal (_("internal: duplicate %s"), name);
1182
1183 do
1184 {
1185 if (opcodes[i].pinfo != INSN_MACRO)
1186 {
1187 if (insn_directive_p)
1188 length = ((name[0] == 'c') ? 2 : 4);
1189 else
1190 length = 0; /* Let assembler determine the length. */
1191 if (!validate_riscv_insn (&opcodes[i], length))
1192 as_fatal (_("internal: broken assembler. "
1193 "No assembly attempted"));
1194 }
1195 else
1196 gas_assert (!insn_directive_p);
1197 ++i;
1198 }
1199 while (opcodes[i].name && !strcmp (opcodes[i].name, name));
1200 }
1201
1202 return hash;
1203 }
1204
1205 /* This function is called once, at assembler startup time. It should set up
1206 all the tables, etc. that the MD part of the assembler will need. */
1207
1208 void
1209 md_begin (void)
1210 {
1211 unsigned long mach = xlen == 64 ? bfd_mach_riscv64 : bfd_mach_riscv32;
1212
1213 if (! bfd_set_arch_mach (stdoutput, bfd_arch_riscv, mach))
1214 as_warn (_("could not set architecture and machine"));
1215
1216 op_hash = init_opcode_hash (riscv_opcodes, false);
1217 insn_type_hash = init_opcode_hash (riscv_insn_types, true);
1218
1219 reg_names_hash = str_htab_create ();
1220 hash_reg_names (RCLASS_GPR, riscv_gpr_names_numeric, NGPR);
1221 hash_reg_names (RCLASS_GPR, riscv_gpr_names_abi, NGPR);
1222 hash_reg_names (RCLASS_FPR, riscv_fpr_names_numeric, NFPR);
1223 hash_reg_names (RCLASS_FPR, riscv_fpr_names_abi, NFPR);
1224 /* Add "fp" as an alias for "s0". */
1225 hash_reg_name (RCLASS_GPR, "fp", 8);
1226
1227 /* Create and insert CSR hash tables. */
1228 csr_extra_hash = str_htab_create ();
1229 #define DECLARE_CSR(name, num, class, define_version, abort_version) \
1230 riscv_init_csr_hash (#name, num, class, define_version, abort_version);
1231 #define DECLARE_CSR_ALIAS(name, num, class, define_version, abort_version) \
1232 DECLARE_CSR(name, num, class, define_version, abort_version);
1233 #include "opcode/riscv-opc.h"
1234 #undef DECLARE_CSR
1235
1236 opcode_names_hash = str_htab_create ();
1237 init_opcode_names_hash ();
1238
1239 /* Set the default alignment for the text section. */
1240 record_alignment (text_section, riscv_opts.rvc ? 1 : 2);
1241 }
1242
1243 static insn_t
1244 riscv_apply_const_reloc (bfd_reloc_code_real_type reloc_type, bfd_vma value)
1245 {
1246 switch (reloc_type)
1247 {
1248 case BFD_RELOC_32:
1249 return value;
1250
1251 case BFD_RELOC_RISCV_HI20:
1252 return ENCODE_UTYPE_IMM (RISCV_CONST_HIGH_PART (value));
1253
1254 case BFD_RELOC_RISCV_LO12_S:
1255 return ENCODE_STYPE_IMM (value);
1256
1257 case BFD_RELOC_RISCV_LO12_I:
1258 return ENCODE_ITYPE_IMM (value);
1259
1260 default:
1261 abort ();
1262 }
1263 }
1264
1265 /* Output an instruction. IP is the instruction information.
1266 ADDRESS_EXPR is an operand of the instruction to be used with
1267 RELOC_TYPE. */
1268
1269 static void
1270 append_insn (struct riscv_cl_insn *ip, expressionS *address_expr,
1271 bfd_reloc_code_real_type reloc_type)
1272 {
1273 dwarf2_emit_insn (0);
1274
1275 if (reloc_type != BFD_RELOC_UNUSED)
1276 {
1277 reloc_howto_type *howto;
1278
1279 gas_assert (address_expr);
1280 if (reloc_type == BFD_RELOC_12_PCREL
1281 || reloc_type == BFD_RELOC_RISCV_JMP)
1282 {
1283 int j = reloc_type == BFD_RELOC_RISCV_JMP;
1284 int best_case = riscv_insn_length (ip->insn_opcode);
1285 unsigned worst_case = relaxed_branch_length (NULL, NULL, 0);
1286
1287 if (now_seg == absolute_section)
1288 {
1289 as_bad (_("relaxable branches not supported in absolute section"));
1290 return;
1291 }
1292
1293 add_relaxed_insn (ip, worst_case, best_case,
1294 RELAX_BRANCH_ENCODE (j, best_case == 2, worst_case),
1295 address_expr->X_add_symbol,
1296 address_expr->X_add_number);
1297 return;
1298 }
1299 else
1300 {
1301 howto = bfd_reloc_type_lookup (stdoutput, reloc_type);
1302 if (howto == NULL)
1303 as_bad (_("internal: unsupported RISC-V relocation number %d"),
1304 reloc_type);
1305
1306 ip->fixp = fix_new_exp (ip->frag, ip->where,
1307 bfd_get_reloc_size (howto),
1308 address_expr, false, reloc_type);
1309
1310 ip->fixp->fx_tcbit = riscv_opts.relax;
1311 }
1312 }
1313
1314 add_fixed_insn (ip);
1315 install_insn (ip);
1316
1317 /* We need to start a new frag after any instruction that can be
1318 optimized away or compressed by the linker during relaxation, to prevent
1319 the assembler from computing static offsets across such an instruction.
1320 This is necessary to get correct EH info. */
1321 if (reloc_type == BFD_RELOC_RISCV_HI20
1322 || reloc_type == BFD_RELOC_RISCV_PCREL_HI20
1323 || reloc_type == BFD_RELOC_RISCV_TPREL_HI20
1324 || reloc_type == BFD_RELOC_RISCV_TPREL_ADD)
1325 {
1326 frag_wane (frag_now);
1327 frag_new (0);
1328 }
1329 }
1330
1331 /* Build an instruction created by a macro expansion. This is passed
1332 a pointer to the count of instructions created so far, an expression,
1333 the name of the instruction to build, an operand format string, and
1334 corresponding arguments. */
1335
1336 static void
1337 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
1338 {
1339 const struct riscv_opcode *mo;
1340 struct riscv_cl_insn insn;
1341 bfd_reloc_code_real_type r;
1342 va_list args;
1343 const char *fmtStart;
1344
1345 va_start (args, fmt);
1346
1347 r = BFD_RELOC_UNUSED;
1348 mo = (struct riscv_opcode *) str_hash_find (op_hash, name);
1349 gas_assert (mo);
1350
1351 /* Find a non-RVC variant of the instruction. append_insn will compress
1352 it if possible. */
1353 while (riscv_insn_length (mo->match) < 4)
1354 mo++;
1355 gas_assert (strcmp (name, mo->name) == 0);
1356
1357 create_insn (&insn, mo);
1358 for (;; ++fmt)
1359 {
1360 fmtStart = fmt;
1361 switch (*fmt)
1362 {
1363 case 'd':
1364 INSERT_OPERAND (RD, insn, va_arg (args, int));
1365 continue;
1366 case 's':
1367 INSERT_OPERAND (RS1, insn, va_arg (args, int));
1368 continue;
1369 case 't':
1370 INSERT_OPERAND (RS2, insn, va_arg (args, int));
1371 continue;
1372
1373 case 'j':
1374 case 'u':
1375 case 'q':
1376 gas_assert (ep != NULL);
1377 r = va_arg (args, int);
1378 continue;
1379
1380 case '\0':
1381 break;
1382 case ',':
1383 continue;
1384 default:
1385 as_fatal (_("internal: invalid macro argument `%s'"), fmtStart);
1386 }
1387 break;
1388 }
1389 va_end (args);
1390 gas_assert (r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
1391
1392 append_insn (&insn, ep, r);
1393 }
1394
1395 /* Build an instruction created by a macro expansion. Like md_assemble but
1396 accept a printf-style format string and arguments. */
1397
1398 static void
1399 md_assemblef (const char *format, ...)
1400 {
1401 char *buf = NULL;
1402 va_list ap;
1403 int r;
1404
1405 va_start (ap, format);
1406
1407 r = vasprintf (&buf, format, ap);
1408
1409 if (r < 0)
1410 as_fatal (_("internal: vasprintf failed"));
1411
1412 md_assemble (buf);
1413 free(buf);
1414
1415 va_end (ap);
1416 }
1417
1418 /* Sign-extend 32-bit mode constants that have bit 31 set and all higher bits
1419 unset. */
1420
1421 static void
1422 normalize_constant_expr (expressionS *ex)
1423 {
1424 if (xlen > 32)
1425 return;
1426 if ((ex->X_op == O_constant || ex->X_op == O_symbol)
1427 && IS_ZEXT_32BIT_NUM (ex->X_add_number))
1428 ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
1429 - 0x80000000);
1430 }
1431
1432 /* Fail if an expression EX is not a constant. IP is the instruction using EX.
1433 MAYBE_CSR is true if the symbol may be an unrecognized CSR name. */
1434
1435 static void
1436 check_absolute_expr (struct riscv_cl_insn *ip, expressionS *ex,
1437 bool maybe_csr)
1438 {
1439 if (ex->X_op == O_big)
1440 as_bad (_("unsupported large constant"));
1441 else if (maybe_csr && ex->X_op == O_symbol)
1442 as_bad (_("unknown CSR `%s'"),
1443 S_GET_NAME (ex->X_add_symbol));
1444 else if (ex->X_op != O_constant)
1445 as_bad (_("instruction %s requires absolute expression"),
1446 ip->insn_mo->name);
1447 normalize_constant_expr (ex);
1448 }
1449
1450 static symbolS *
1451 make_internal_label (void)
1452 {
1453 return (symbolS *) local_symbol_make (FAKE_LABEL_NAME, now_seg, frag_now,
1454 frag_now_fix ());
1455 }
1456
1457 /* Load an entry from the GOT. */
1458
1459 static void
1460 pcrel_access (int destreg, int tempreg, expressionS *ep,
1461 const char *lo_insn, const char *lo_pattern,
1462 bfd_reloc_code_real_type hi_reloc,
1463 bfd_reloc_code_real_type lo_reloc)
1464 {
1465 expressionS ep2;
1466 ep2.X_op = O_symbol;
1467 ep2.X_add_symbol = make_internal_label ();
1468 ep2.X_add_number = 0;
1469
1470 macro_build (ep, "auipc", "d,u", tempreg, hi_reloc);
1471 macro_build (&ep2, lo_insn, lo_pattern, destreg, tempreg, lo_reloc);
1472 }
1473
1474 static void
1475 pcrel_load (int destreg, int tempreg, expressionS *ep, const char *lo_insn,
1476 bfd_reloc_code_real_type hi_reloc,
1477 bfd_reloc_code_real_type lo_reloc)
1478 {
1479 pcrel_access (destreg, tempreg, ep, lo_insn, "d,s,j", hi_reloc, lo_reloc);
1480 }
1481
1482 static void
1483 pcrel_store (int srcreg, int tempreg, expressionS *ep, const char *lo_insn,
1484 bfd_reloc_code_real_type hi_reloc,
1485 bfd_reloc_code_real_type lo_reloc)
1486 {
1487 pcrel_access (srcreg, tempreg, ep, lo_insn, "t,s,q", hi_reloc, lo_reloc);
1488 }
1489
1490 /* PC-relative function call using AUIPC/JALR, relaxed to JAL. */
1491
1492 static void
1493 riscv_call (int destreg, int tempreg, expressionS *ep,
1494 bfd_reloc_code_real_type reloc)
1495 {
1496 /* Ensure the jalr is emitted to the same frag as the auipc. */
1497 frag_grow (8);
1498 macro_build (ep, "auipc", "d,u", tempreg, reloc);
1499 macro_build (NULL, "jalr", "d,s", destreg, tempreg);
1500 /* See comment at end of append_insn. */
1501 frag_wane (frag_now);
1502 frag_new (0);
1503 }
1504
1505 /* Load an integer constant into a register. */
1506
1507 static void
1508 load_const (int reg, expressionS *ep)
1509 {
1510 int shift = RISCV_IMM_BITS;
1511 bfd_vma upper_imm, sign = (bfd_vma) 1 << (RISCV_IMM_BITS - 1);
1512 expressionS upper = *ep, lower = *ep;
1513 lower.X_add_number = ((ep->X_add_number & (sign + sign - 1)) ^ sign) - sign;
1514 upper.X_add_number -= lower.X_add_number;
1515
1516 if (ep->X_op != O_constant)
1517 {
1518 as_bad (_("unsupported large constant"));
1519 return;
1520 }
1521
1522 if (xlen > 32 && !IS_SEXT_32BIT_NUM (ep->X_add_number))
1523 {
1524 /* Reduce to a signed 32-bit constant using SLLI and ADDI. */
1525 while (((upper.X_add_number >> shift) & 1) == 0)
1526 shift++;
1527
1528 upper.X_add_number = (int64_t) upper.X_add_number >> shift;
1529 load_const (reg, &upper);
1530
1531 md_assemblef ("slli x%d, x%d, 0x%x", reg, reg, shift);
1532 if (lower.X_add_number != 0)
1533 md_assemblef ("addi x%d, x%d, %" BFD_VMA_FMT "d", reg, reg,
1534 lower.X_add_number);
1535 }
1536 else
1537 {
1538 /* Simply emit LUI and/or ADDI to build a 32-bit signed constant. */
1539 int hi_reg = 0;
1540
1541 if (upper.X_add_number != 0)
1542 {
1543 /* Discard low part and zero-extend upper immediate. */
1544 upper_imm = ((uint32_t)upper.X_add_number >> shift);
1545
1546 md_assemblef ("lui x%d, 0x%" BFD_VMA_FMT "x", reg, upper_imm);
1547 hi_reg = reg;
1548 }
1549
1550 if (lower.X_add_number != 0 || hi_reg == 0)
1551 md_assemblef ("%s x%d, x%d, %" BFD_VMA_FMT "d", ADD32_INSN, reg, hi_reg,
1552 lower.X_add_number);
1553 }
1554 }
1555
1556 /* Zero extend and sign extend byte/half-word/word. */
1557
1558 static void
1559 riscv_ext (int destreg, int srcreg, unsigned shift, bool sign)
1560 {
1561 if (sign)
1562 {
1563 md_assemblef ("slli x%d, x%d, 0x%x", destreg, srcreg, shift);
1564 md_assemblef ("srai x%d, x%d, 0x%x", destreg, destreg, shift);
1565 }
1566 else
1567 {
1568 md_assemblef ("slli x%d, x%d, 0x%x", destreg, srcreg, shift);
1569 md_assemblef ("srli x%d, x%d, 0x%x", destreg, destreg, shift);
1570 }
1571 }
1572
1573 /* Expand RISC-V assembly macros into one or more instructions. */
1574
1575 static void
1576 macro (struct riscv_cl_insn *ip, expressionS *imm_expr,
1577 bfd_reloc_code_real_type *imm_reloc)
1578 {
1579 int rd = (ip->insn_opcode >> OP_SH_RD) & OP_MASK_RD;
1580 int rs1 = (ip->insn_opcode >> OP_SH_RS1) & OP_MASK_RS1;
1581 int rs2 = (ip->insn_opcode >> OP_SH_RS2) & OP_MASK_RS2;
1582 int mask = ip->insn_mo->mask;
1583
1584 switch (mask)
1585 {
1586 case M_LI:
1587 load_const (rd, imm_expr);
1588 break;
1589
1590 case M_LA:
1591 case M_LLA:
1592 /* Load the address of a symbol into a register. */
1593 if (!IS_SEXT_32BIT_NUM (imm_expr->X_add_number))
1594 as_bad (_("offset too large"));
1595
1596 if (imm_expr->X_op == O_constant)
1597 load_const (rd, imm_expr);
1598 else if (riscv_opts.pic && mask == M_LA) /* Global PIC symbol. */
1599 pcrel_load (rd, rd, imm_expr, LOAD_ADDRESS_INSN,
1600 BFD_RELOC_RISCV_GOT_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1601 else /* Local PIC symbol, or any non-PIC symbol. */
1602 pcrel_load (rd, rd, imm_expr, "addi",
1603 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1604 break;
1605
1606 case M_LA_TLS_GD:
1607 pcrel_load (rd, rd, imm_expr, "addi",
1608 BFD_RELOC_RISCV_TLS_GD_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1609 break;
1610
1611 case M_LA_TLS_IE:
1612 pcrel_load (rd, rd, imm_expr, LOAD_ADDRESS_INSN,
1613 BFD_RELOC_RISCV_TLS_GOT_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1614 break;
1615
1616 case M_LB:
1617 pcrel_load (rd, rd, imm_expr, "lb",
1618 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1619 break;
1620
1621 case M_LBU:
1622 pcrel_load (rd, rd, imm_expr, "lbu",
1623 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1624 break;
1625
1626 case M_LH:
1627 pcrel_load (rd, rd, imm_expr, "lh",
1628 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1629 break;
1630
1631 case M_LHU:
1632 pcrel_load (rd, rd, imm_expr, "lhu",
1633 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1634 break;
1635
1636 case M_LW:
1637 pcrel_load (rd, rd, imm_expr, "lw",
1638 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1639 break;
1640
1641 case M_LWU:
1642 pcrel_load (rd, rd, imm_expr, "lwu",
1643 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1644 break;
1645
1646 case M_LD:
1647 pcrel_load (rd, rd, imm_expr, "ld",
1648 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1649 break;
1650
1651 case M_FLW:
1652 pcrel_load (rd, rs1, imm_expr, "flw",
1653 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1654 break;
1655
1656 case M_FLD:
1657 pcrel_load (rd, rs1, imm_expr, "fld",
1658 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1659 break;
1660
1661 case M_SB:
1662 pcrel_store (rs2, rs1, imm_expr, "sb",
1663 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1664 break;
1665
1666 case M_SH:
1667 pcrel_store (rs2, rs1, imm_expr, "sh",
1668 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1669 break;
1670
1671 case M_SW:
1672 pcrel_store (rs2, rs1, imm_expr, "sw",
1673 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1674 break;
1675
1676 case M_SD:
1677 pcrel_store (rs2, rs1, imm_expr, "sd",
1678 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1679 break;
1680
1681 case M_FSW:
1682 pcrel_store (rs2, rs1, imm_expr, "fsw",
1683 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1684 break;
1685
1686 case M_FSD:
1687 pcrel_store (rs2, rs1, imm_expr, "fsd",
1688 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1689 break;
1690
1691 case M_CALL:
1692 riscv_call (rd, rs1, imm_expr, *imm_reloc);
1693 break;
1694
1695 case M_ZEXTH:
1696 riscv_ext (rd, rs1, xlen - 16, false);
1697 break;
1698
1699 case M_ZEXTW:
1700 riscv_ext (rd, rs1, xlen - 32, false);
1701 break;
1702
1703 case M_SEXTB:
1704 riscv_ext (rd, rs1, xlen - 8, true);
1705 break;
1706
1707 case M_SEXTH:
1708 riscv_ext (rd, rs1, xlen - 16, true);
1709 break;
1710
1711 default:
1712 as_bad (_("internal: macro %s not implemented"), ip->insn_mo->name);
1713 break;
1714 }
1715 }
1716
1717 static const struct percent_op_match percent_op_utype[] =
1718 {
1719 {"%tprel_hi", BFD_RELOC_RISCV_TPREL_HI20},
1720 {"%pcrel_hi", BFD_RELOC_RISCV_PCREL_HI20},
1721 {"%got_pcrel_hi", BFD_RELOC_RISCV_GOT_HI20},
1722 {"%tls_ie_pcrel_hi", BFD_RELOC_RISCV_TLS_GOT_HI20},
1723 {"%tls_gd_pcrel_hi", BFD_RELOC_RISCV_TLS_GD_HI20},
1724 {"%hi", BFD_RELOC_RISCV_HI20},
1725 {0, 0}
1726 };
1727
1728 static const struct percent_op_match percent_op_itype[] =
1729 {
1730 {"%lo", BFD_RELOC_RISCV_LO12_I},
1731 {"%tprel_lo", BFD_RELOC_RISCV_TPREL_LO12_I},
1732 {"%pcrel_lo", BFD_RELOC_RISCV_PCREL_LO12_I},
1733 {0, 0}
1734 };
1735
1736 static const struct percent_op_match percent_op_stype[] =
1737 {
1738 {"%lo", BFD_RELOC_RISCV_LO12_S},
1739 {"%tprel_lo", BFD_RELOC_RISCV_TPREL_LO12_S},
1740 {"%pcrel_lo", BFD_RELOC_RISCV_PCREL_LO12_S},
1741 {0, 0}
1742 };
1743
1744 static const struct percent_op_match percent_op_rtype[] =
1745 {
1746 {"%tprel_add", BFD_RELOC_RISCV_TPREL_ADD},
1747 {0, 0}
1748 };
1749
1750 static const struct percent_op_match percent_op_null[] =
1751 {
1752 {0, 0}
1753 };
1754
1755 /* Return true if *STR points to a relocation operator. When returning true,
1756 move *STR over the operator and store its relocation code in *RELOC.
1757 Leave both *STR and *RELOC alone when returning false. */
1758
1759 static bool
1760 parse_relocation (char **str, bfd_reloc_code_real_type *reloc,
1761 const struct percent_op_match *percent_op)
1762 {
1763 for ( ; percent_op->str; percent_op++)
1764 if (strncasecmp (*str, percent_op->str, strlen (percent_op->str)) == 0)
1765 {
1766 int len = strlen (percent_op->str);
1767
1768 if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
1769 continue;
1770
1771 *str += strlen (percent_op->str);
1772 *reloc = percent_op->reloc;
1773
1774 /* Check whether the output BFD supports this relocation.
1775 If not, issue an error and fall back on something safe. */
1776 if (*reloc != BFD_RELOC_UNUSED
1777 && !bfd_reloc_type_lookup (stdoutput, *reloc))
1778 {
1779 as_bad ("internal: relocation %s isn't supported by the "
1780 "current ABI", percent_op->str);
1781 *reloc = BFD_RELOC_UNUSED;
1782 }
1783 return true;
1784 }
1785 return false;
1786 }
1787
1788 static void
1789 my_getExpression (expressionS *ep, char *str)
1790 {
1791 char *save_in;
1792
1793 save_in = input_line_pointer;
1794 input_line_pointer = str;
1795 expression (ep);
1796 expr_end = input_line_pointer;
1797 input_line_pointer = save_in;
1798 }
1799
1800 /* Parse string STR as a 16-bit relocatable operand. Store the
1801 expression in *EP and the relocation, if any, in RELOC.
1802 Return the number of relocation operators used (0 or 1).
1803
1804 On exit, EXPR_END points to the first character after the expression. */
1805
1806 static size_t
1807 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
1808 char *str, const struct percent_op_match *percent_op)
1809 {
1810 size_t reloc_index;
1811 unsigned crux_depth, str_depth, regno;
1812 char *crux;
1813
1814 /* First, check for integer registers. No callers can accept a reg, but
1815 we need to avoid accidentally creating a useless undefined symbol below,
1816 if this is an instruction pattern that can't match. A glibc build fails
1817 if this is removed. */
1818 if (reg_lookup (&str, RCLASS_GPR, &regno))
1819 {
1820 ep->X_op = O_register;
1821 ep->X_add_number = regno;
1822 expr_end = str;
1823 return 0;
1824 }
1825
1826 /* Search for the start of the main expression.
1827
1828 End the loop with CRUX pointing to the start of the main expression and
1829 with CRUX_DEPTH containing the number of open brackets at that point. */
1830 reloc_index = -1;
1831 str_depth = 0;
1832 do
1833 {
1834 reloc_index++;
1835 crux = str;
1836 crux_depth = str_depth;
1837
1838 /* Skip over whitespace and brackets, keeping count of the number
1839 of brackets. */
1840 while (*str == ' ' || *str == '\t' || *str == '(')
1841 if (*str++ == '(')
1842 str_depth++;
1843 }
1844 while (*str == '%'
1845 && reloc_index < 1
1846 && parse_relocation (&str, reloc, percent_op));
1847
1848 my_getExpression (ep, crux);
1849 str = expr_end;
1850
1851 /* Match every open bracket. */
1852 while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
1853 if (*str++ == ')')
1854 crux_depth--;
1855
1856 if (crux_depth > 0)
1857 as_bad ("unclosed '('");
1858
1859 expr_end = str;
1860
1861 return reloc_index;
1862 }
1863
1864 /* Parse opcode name, could be an mnemonics or number. */
1865
1866 static size_t
1867 my_getOpcodeExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
1868 char *str, const struct percent_op_match *percent_op)
1869 {
1870 const struct opcode_name_t *o = opcode_name_lookup (&str);
1871
1872 if (o != NULL)
1873 {
1874 ep->X_op = O_constant;
1875 ep->X_add_number = o->val;
1876 return 0;
1877 }
1878
1879 return my_getSmallExpression (ep, reloc, str, percent_op);
1880 }
1881
1882 /* Detect and handle implicitly zero load-store offsets. For example,
1883 "lw t0, (t1)" is shorthand for "lw t0, 0(t1)". Return true if such
1884 an implicit offset was detected. */
1885
1886 static bool
1887 riscv_handle_implicit_zero_offset (expressionS *ep, const char *s)
1888 {
1889 /* Check whether there is only a single bracketed expression left.
1890 If so, it must be the base register and the constant must be zero. */
1891 if (*s == '(' && strchr (s + 1, '(') == 0)
1892 {
1893 ep->X_op = O_constant;
1894 ep->X_add_number = 0;
1895 return true;
1896 }
1897
1898 return false;
1899 }
1900
1901 /* All RISC-V CSR instructions belong to one of these classes. */
1902 enum csr_insn_type
1903 {
1904 INSN_NOT_CSR,
1905 INSN_CSRRW,
1906 INSN_CSRRS,
1907 INSN_CSRRC
1908 };
1909
1910 /* Return which CSR instruction is checking. */
1911
1912 static enum csr_insn_type
1913 riscv_csr_insn_type (insn_t insn)
1914 {
1915 if (((insn ^ MATCH_CSRRW) & MASK_CSRRW) == 0
1916 || ((insn ^ MATCH_CSRRWI) & MASK_CSRRWI) == 0)
1917 return INSN_CSRRW;
1918 else if (((insn ^ MATCH_CSRRS) & MASK_CSRRS) == 0
1919 || ((insn ^ MATCH_CSRRSI) & MASK_CSRRSI) == 0)
1920 return INSN_CSRRS;
1921 else if (((insn ^ MATCH_CSRRC) & MASK_CSRRC) == 0
1922 || ((insn ^ MATCH_CSRRCI) & MASK_CSRRCI) == 0)
1923 return INSN_CSRRC;
1924 else
1925 return INSN_NOT_CSR;
1926 }
1927
1928 /* CSRRW and CSRRWI always write CSR. CSRRS, CSRRC, CSRRSI and CSRRCI write
1929 CSR when RS1 isn't zero. The CSR is read only if the [11:10] bits of
1930 CSR address is 0x3. */
1931
1932 static bool
1933 riscv_csr_read_only_check (insn_t insn)
1934 {
1935 int csr = (insn & (OP_MASK_CSR << OP_SH_CSR)) >> OP_SH_CSR;
1936 int rs1 = (insn & (OP_MASK_RS1 << OP_SH_RS1)) >> OP_SH_RS1;
1937 int readonly = (((csr & (0x3 << 10)) >> 10) == 0x3);
1938 enum csr_insn_type csr_insn = riscv_csr_insn_type (insn);
1939
1940 if (readonly
1941 && (((csr_insn == INSN_CSRRS
1942 || csr_insn == INSN_CSRRC)
1943 && rs1 != 0)
1944 || csr_insn == INSN_CSRRW))
1945 return false;
1946
1947 return true;
1948 }
1949
1950 /* Return true if it is a privileged instruction. Otherwise, return false.
1951
1952 uret is actually a N-ext instruction. So it is better to regard it as
1953 an user instruction rather than the priv instruction.
1954
1955 hret is used to return from traps in H-mode. H-mode is removed since
1956 the v1.10 priv spec, but probably be added in the new hypervisor spec.
1957 Therefore, hret should be controlled by the hypervisor spec rather than
1958 priv spec in the future.
1959
1960 dret is defined in the debug spec, so it should be checked in the future,
1961 too. */
1962
1963 static bool
1964 riscv_is_priv_insn (insn_t insn)
1965 {
1966 return (((insn ^ MATCH_SRET) & MASK_SRET) == 0
1967 || ((insn ^ MATCH_MRET) & MASK_MRET) == 0
1968 || ((insn ^ MATCH_SFENCE_VMA) & MASK_SFENCE_VMA) == 0
1969 || ((insn ^ MATCH_WFI) & MASK_WFI) == 0
1970 /* The sfence.vm is dropped in the v1.10 priv specs, but we still need to
1971 check it here to keep the compatible. */
1972 || ((insn ^ MATCH_SFENCE_VM) & MASK_SFENCE_VM) == 0);
1973 }
1974
1975 /* This routine assembles an instruction into its binary format. As a
1976 side effect, it sets the global variable imm_reloc to the type of
1977 relocation to do if one of the operands is an address expression. */
1978
1979 static const char *
1980 riscv_ip (char *str, struct riscv_cl_insn *ip, expressionS *imm_expr,
1981 bfd_reloc_code_real_type *imm_reloc, htab_t hash)
1982 {
1983 /* The operand string defined in the riscv_opcodes. */
1984 const char *oparg, *opargStart;
1985 /* The parsed operands from assembly. */
1986 char *asarg, *asargStart;
1987 char save_c = 0;
1988 struct riscv_opcode *insn;
1989 unsigned int regno;
1990 int argnum;
1991 const struct percent_op_match *p;
1992 const char *error = "unrecognized opcode";
1993 /* Indicate we are assembling instruction with CSR. */
1994 bool insn_with_csr = false;
1995
1996 /* Parse the name of the instruction. Terminate the string if whitespace
1997 is found so that str_hash_find only sees the name part of the string. */
1998 for (asarg = str; *asarg!= '\0'; ++asarg)
1999 if (ISSPACE (*asarg))
2000 {
2001 save_c = *asarg;
2002 *asarg++ = '\0';
2003 break;
2004 }
2005
2006 insn = (struct riscv_opcode *) str_hash_find (hash, str);
2007
2008 asargStart = asarg;
2009 for ( ; insn && insn->name && strcmp (insn->name, str) == 0; insn++)
2010 {
2011 if ((insn->xlen_requirement != 0) && (xlen != insn->xlen_requirement))
2012 continue;
2013
2014 if (!riscv_multi_subset_supports (&riscv_rps_as, insn->insn_class))
2015 continue;
2016
2017 create_insn (ip, insn);
2018 argnum = 1;
2019
2020 imm_expr->X_op = O_absent;
2021 *imm_reloc = BFD_RELOC_UNUSED;
2022 p = percent_op_itype;
2023
2024 for (oparg = insn->args;; ++oparg)
2025 {
2026 opargStart = oparg;
2027 asarg += strspn (asarg, " \t");
2028 switch (*oparg)
2029 {
2030 case '\0': /* End of args. */
2031 if (insn->pinfo != INSN_MACRO)
2032 {
2033 if (!insn->match_func (insn, ip->insn_opcode))
2034 break;
2035
2036 /* For .insn, insn->match and insn->mask are 0. */
2037 if (riscv_insn_length ((insn->match == 0 && insn->mask == 0)
2038 ? ip->insn_opcode
2039 : insn->match) == 2
2040 && !riscv_opts.rvc)
2041 break;
2042
2043 if (riscv_is_priv_insn (ip->insn_opcode))
2044 explicit_priv_attr = true;
2045
2046 /* Check if we write a read-only CSR by the CSR
2047 instruction. */
2048 if (insn_with_csr
2049 && riscv_opts.csr_check
2050 && !riscv_csr_read_only_check (ip->insn_opcode))
2051 {
2052 /* Restore the character in advance, since we want to
2053 report the detailed warning message here. */
2054 if (save_c)
2055 *(asargStart - 1) = save_c;
2056 as_warn (_("read-only CSR is written `%s'"), str);
2057 insn_with_csr = false;
2058 }
2059 }
2060 if (*asarg != '\0')
2061 break;
2062 /* Successful assembly. */
2063 error = NULL;
2064 insn_with_csr = false;
2065 goto out;
2066
2067 case 'C': /* RVC */
2068 switch (*++oparg)
2069 {
2070 case 's': /* RS1 x8-x15. */
2071 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2072 || !(regno >= 8 && regno <= 15))
2073 break;
2074 INSERT_OPERAND (CRS1S, *ip, regno % 8);
2075 continue;
2076 case 'w': /* RS1 x8-x15, constrained to equal RD x8-x15. */
2077 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2078 || EXTRACT_OPERAND (CRS1S, ip->insn_opcode) + 8 != regno)
2079 break;
2080 continue;
2081 case 't': /* RS2 x8-x15. */
2082 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2083 || !(regno >= 8 && regno <= 15))
2084 break;
2085 INSERT_OPERAND (CRS2S, *ip, regno % 8);
2086 continue;
2087 case 'x': /* RS2 x8-x15, constrained to equal RD x8-x15. */
2088 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2089 || EXTRACT_OPERAND (CRS2S, ip->insn_opcode) + 8 != regno)
2090 break;
2091 continue;
2092 case 'U': /* RS1, constrained to equal RD. */
2093 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2094 || EXTRACT_OPERAND (RD, ip->insn_opcode) != regno)
2095 break;
2096 continue;
2097 case 'V': /* RS2 */
2098 if (!reg_lookup (&asarg, RCLASS_GPR, &regno))
2099 break;
2100 INSERT_OPERAND (CRS2, *ip, regno);
2101 continue;
2102 case 'c': /* RS1, constrained to equal sp. */
2103 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2104 || regno != X_SP)
2105 break;
2106 continue;
2107 case 'z': /* RS2, constrained to equal x0. */
2108 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2109 || regno != 0)
2110 break;
2111 continue;
2112 case '>': /* Shift amount, 0 - (XLEN-1). */
2113 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2114 || imm_expr->X_op != O_constant
2115 || (unsigned long) imm_expr->X_add_number >= xlen)
2116 break;
2117 ip->insn_opcode |= ENCODE_CITYPE_IMM (imm_expr->X_add_number);
2118 rvc_imm_done:
2119 asarg = expr_end;
2120 imm_expr->X_op = O_absent;
2121 continue;
2122 case '5':
2123 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2124 || imm_expr->X_op != O_constant
2125 || imm_expr->X_add_number < 0
2126 || imm_expr->X_add_number >= 32
2127 || !VALID_CLTYPE_IMM ((valueT) imm_expr->X_add_number))
2128 break;
2129 ip->insn_opcode |= ENCODE_CLTYPE_IMM (imm_expr->X_add_number);
2130 goto rvc_imm_done;
2131 case '6':
2132 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2133 || imm_expr->X_op != O_constant
2134 || imm_expr->X_add_number < 0
2135 || imm_expr->X_add_number >= 64
2136 || !VALID_CSSTYPE_IMM ((valueT) imm_expr->X_add_number))
2137 break;
2138 ip->insn_opcode |= ENCODE_CSSTYPE_IMM (imm_expr->X_add_number);
2139 goto rvc_imm_done;
2140 case '8':
2141 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2142 || imm_expr->X_op != O_constant
2143 || imm_expr->X_add_number < 0
2144 || imm_expr->X_add_number >= 256
2145 || !VALID_CIWTYPE_IMM ((valueT) imm_expr->X_add_number))
2146 break;
2147 ip->insn_opcode |= ENCODE_CIWTYPE_IMM (imm_expr->X_add_number);
2148 goto rvc_imm_done;
2149 case 'j':
2150 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2151 || imm_expr->X_op != O_constant
2152 || imm_expr->X_add_number == 0
2153 || !VALID_CITYPE_IMM ((valueT) imm_expr->X_add_number))
2154 break;
2155 ip->insn_opcode |= ENCODE_CITYPE_IMM (imm_expr->X_add_number);
2156 goto rvc_imm_done;
2157 case 'k':
2158 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
2159 continue;
2160 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2161 || imm_expr->X_op != O_constant
2162 || !VALID_CLTYPE_LW_IMM ((valueT) imm_expr->X_add_number))
2163 break;
2164 ip->insn_opcode |= ENCODE_CLTYPE_LW_IMM (imm_expr->X_add_number);
2165 goto rvc_imm_done;
2166 case 'l':
2167 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
2168 continue;
2169 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2170 || imm_expr->X_op != O_constant
2171 || !VALID_CLTYPE_LD_IMM ((valueT) imm_expr->X_add_number))
2172 break;
2173 ip->insn_opcode |= ENCODE_CLTYPE_LD_IMM (imm_expr->X_add_number);
2174 goto rvc_imm_done;
2175 case 'm':
2176 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
2177 continue;
2178 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2179 || imm_expr->X_op != O_constant
2180 || !VALID_CITYPE_LWSP_IMM ((valueT) imm_expr->X_add_number))
2181 break;
2182 ip->insn_opcode |=
2183 ENCODE_CITYPE_LWSP_IMM (imm_expr->X_add_number);
2184 goto rvc_imm_done;
2185 case 'n':
2186 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
2187 continue;
2188 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2189 || imm_expr->X_op != O_constant
2190 || !VALID_CITYPE_LDSP_IMM ((valueT) imm_expr->X_add_number))
2191 break;
2192 ip->insn_opcode |=
2193 ENCODE_CITYPE_LDSP_IMM (imm_expr->X_add_number);
2194 goto rvc_imm_done;
2195 case 'o':
2196 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2197 || imm_expr->X_op != O_constant
2198 /* C.addiw, c.li, and c.andi allow zero immediate.
2199 C.addi allows zero immediate as hint. Otherwise this
2200 is same as 'j'. */
2201 || !VALID_CITYPE_IMM ((valueT) imm_expr->X_add_number))
2202 break;
2203 ip->insn_opcode |= ENCODE_CITYPE_IMM (imm_expr->X_add_number);
2204 goto rvc_imm_done;
2205 case 'K':
2206 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2207 || imm_expr->X_op != O_constant
2208 || imm_expr->X_add_number == 0
2209 || !VALID_CIWTYPE_ADDI4SPN_IMM ((valueT) imm_expr->X_add_number))
2210 break;
2211 ip->insn_opcode |=
2212 ENCODE_CIWTYPE_ADDI4SPN_IMM (imm_expr->X_add_number);
2213 goto rvc_imm_done;
2214 case 'L':
2215 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2216 || imm_expr->X_op != O_constant
2217 || !VALID_CITYPE_ADDI16SP_IMM ((valueT) imm_expr->X_add_number))
2218 break;
2219 ip->insn_opcode |=
2220 ENCODE_CITYPE_ADDI16SP_IMM (imm_expr->X_add_number);
2221 goto rvc_imm_done;
2222 case 'M':
2223 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
2224 continue;
2225 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2226 || imm_expr->X_op != O_constant
2227 || !VALID_CSSTYPE_SWSP_IMM ((valueT) imm_expr->X_add_number))
2228 break;
2229 ip->insn_opcode |=
2230 ENCODE_CSSTYPE_SWSP_IMM (imm_expr->X_add_number);
2231 goto rvc_imm_done;
2232 case 'N':
2233 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
2234 continue;
2235 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2236 || imm_expr->X_op != O_constant
2237 || !VALID_CSSTYPE_SDSP_IMM ((valueT) imm_expr->X_add_number))
2238 break;
2239 ip->insn_opcode |=
2240 ENCODE_CSSTYPE_SDSP_IMM (imm_expr->X_add_number);
2241 goto rvc_imm_done;
2242 case 'u':
2243 p = percent_op_utype;
2244 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p))
2245 break;
2246 rvc_lui:
2247 if (imm_expr->X_op != O_constant
2248 || imm_expr->X_add_number <= 0
2249 || imm_expr->X_add_number >= RISCV_BIGIMM_REACH
2250 || (imm_expr->X_add_number >= RISCV_RVC_IMM_REACH / 2
2251 && (imm_expr->X_add_number <
2252 RISCV_BIGIMM_REACH - RISCV_RVC_IMM_REACH / 2)))
2253 break;
2254 ip->insn_opcode |= ENCODE_CITYPE_IMM (imm_expr->X_add_number);
2255 goto rvc_imm_done;
2256 case 'v':
2257 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2258 || (imm_expr->X_add_number & (RISCV_IMM_REACH - 1))
2259 || ((int32_t)imm_expr->X_add_number
2260 != imm_expr->X_add_number))
2261 break;
2262 imm_expr->X_add_number =
2263 ((uint32_t) imm_expr->X_add_number) >> RISCV_IMM_BITS;
2264 goto rvc_lui;
2265 case 'p':
2266 goto branch;
2267 case 'a':
2268 goto jump;
2269 case 'S': /* Floating-point RS1 x8-x15. */
2270 if (!reg_lookup (&asarg, RCLASS_FPR, &regno)
2271 || !(regno >= 8 && regno <= 15))
2272 break;
2273 INSERT_OPERAND (CRS1S, *ip, regno % 8);
2274 continue;
2275 case 'D': /* Floating-point RS2 x8-x15. */
2276 if (!reg_lookup (&asarg, RCLASS_FPR, &regno)
2277 || !(regno >= 8 && regno <= 15))
2278 break;
2279 INSERT_OPERAND (CRS2S, *ip, regno % 8);
2280 continue;
2281 case 'T': /* Floating-point RS2. */
2282 if (!reg_lookup (&asarg, RCLASS_FPR, &regno))
2283 break;
2284 INSERT_OPERAND (CRS2, *ip, regno);
2285 continue;
2286 case 'F':
2287 switch (*++oparg)
2288 {
2289 case '6':
2290 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2291 || imm_expr->X_op != O_constant
2292 || imm_expr->X_add_number < 0
2293 || imm_expr->X_add_number >= 64)
2294 {
2295 as_bad (_("bad value for compressed funct6 "
2296 "field, value must be 0...64"));
2297 break;
2298 }
2299 INSERT_OPERAND (CFUNCT6, *ip, imm_expr->X_add_number);
2300 imm_expr->X_op = O_absent;
2301 asarg = expr_end;
2302 continue;
2303
2304 case '4':
2305 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2306 || imm_expr->X_op != O_constant
2307 || imm_expr->X_add_number < 0
2308 || imm_expr->X_add_number >= 16)
2309 {
2310 as_bad (_("bad value for compressed funct4 "
2311 "field, value must be 0...15"));
2312 break;
2313 }
2314 INSERT_OPERAND (CFUNCT4, *ip, imm_expr->X_add_number);
2315 imm_expr->X_op = O_absent;
2316 asarg = expr_end;
2317 continue;
2318
2319 case '3':
2320 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2321 || imm_expr->X_op != O_constant
2322 || imm_expr->X_add_number < 0
2323 || imm_expr->X_add_number >= 8)
2324 {
2325 as_bad (_("bad value for compressed funct3 "
2326 "field, value must be 0...7"));
2327 break;
2328 }
2329 INSERT_OPERAND (CFUNCT3, *ip, imm_expr->X_add_number);
2330 imm_expr->X_op = O_absent;
2331 asarg = expr_end;
2332 continue;
2333
2334 case '2':
2335 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2336 || imm_expr->X_op != O_constant
2337 || imm_expr->X_add_number < 0
2338 || imm_expr->X_add_number >= 4)
2339 {
2340 as_bad (_("bad value for compressed funct2 "
2341 "field, value must be 0...3"));
2342 break;
2343 }
2344 INSERT_OPERAND (CFUNCT2, *ip, imm_expr->X_add_number);
2345 imm_expr->X_op = O_absent;
2346 asarg = expr_end;
2347 continue;
2348
2349 default:
2350 goto unknown_riscv_ip_operand;
2351 }
2352 break;
2353
2354 default:
2355 goto unknown_riscv_ip_operand;
2356 }
2357 break;
2358
2359 case ',':
2360 ++argnum;
2361 if (*asarg++ == *oparg)
2362 continue;
2363 asarg--;
2364 break;
2365
2366 case '(':
2367 case ')':
2368 case '[':
2369 case ']':
2370 if (*asarg++ == *oparg)
2371 continue;
2372 break;
2373
2374 case '<': /* Shift amount, 0 - 31. */
2375 my_getExpression (imm_expr, asarg);
2376 check_absolute_expr (ip, imm_expr, false);
2377 if ((unsigned long) imm_expr->X_add_number > 31)
2378 as_bad (_("improper shift amount (%lu)"),
2379 (unsigned long) imm_expr->X_add_number);
2380 INSERT_OPERAND (SHAMTW, *ip, imm_expr->X_add_number);
2381 imm_expr->X_op = O_absent;
2382 asarg = expr_end;
2383 continue;
2384
2385 case '>': /* Shift amount, 0 - (XLEN-1). */
2386 my_getExpression (imm_expr, asarg);
2387 check_absolute_expr (ip, imm_expr, false);
2388 if ((unsigned long) imm_expr->X_add_number >= xlen)
2389 as_bad (_("improper shift amount (%lu)"),
2390 (unsigned long) imm_expr->X_add_number);
2391 INSERT_OPERAND (SHAMT, *ip, imm_expr->X_add_number);
2392 imm_expr->X_op = O_absent;
2393 asarg = expr_end;
2394 continue;
2395
2396 case 'Z': /* CSRRxI immediate. */
2397 my_getExpression (imm_expr, asarg);
2398 check_absolute_expr (ip, imm_expr, false);
2399 if ((unsigned long) imm_expr->X_add_number > 31)
2400 as_bad (_("improper CSRxI immediate (%lu)"),
2401 (unsigned long) imm_expr->X_add_number);
2402 INSERT_OPERAND (RS1, *ip, imm_expr->X_add_number);
2403 imm_expr->X_op = O_absent;
2404 asarg = expr_end;
2405 continue;
2406
2407 case 'E': /* Control register. */
2408 insn_with_csr = true;
2409 explicit_priv_attr = true;
2410 if (reg_lookup (&asarg, RCLASS_CSR, &regno))
2411 INSERT_OPERAND (CSR, *ip, regno);
2412 else
2413 {
2414 my_getExpression (imm_expr, asarg);
2415 check_absolute_expr (ip, imm_expr, true);
2416 if ((unsigned long) imm_expr->X_add_number > 0xfff)
2417 as_bad (_("improper CSR address (%lu)"),
2418 (unsigned long) imm_expr->X_add_number);
2419 INSERT_OPERAND (CSR, *ip, imm_expr->X_add_number);
2420 imm_expr->X_op = O_absent;
2421 asarg = expr_end;
2422 }
2423 continue;
2424
2425 case 'm': /* Rounding mode. */
2426 if (arg_lookup (&asarg, riscv_rm,
2427 ARRAY_SIZE (riscv_rm), &regno))
2428 {
2429 INSERT_OPERAND (RM, *ip, regno);
2430 continue;
2431 }
2432 break;
2433
2434 case 'P':
2435 case 'Q': /* Fence predecessor/successor. */
2436 if (arg_lookup (&asarg, riscv_pred_succ,
2437 ARRAY_SIZE (riscv_pred_succ), &regno))
2438 {
2439 if (*oparg == 'P')
2440 INSERT_OPERAND (PRED, *ip, regno);
2441 else
2442 INSERT_OPERAND (SUCC, *ip, regno);
2443 continue;
2444 }
2445 break;
2446
2447 case 'd': /* Destination register. */
2448 case 's': /* Source register. */
2449 case 't': /* Target register. */
2450 case 'r': /* RS3 */
2451 if (reg_lookup (&asarg, RCLASS_GPR, &regno))
2452 {
2453 char c = *oparg;
2454 if (*asarg == ' ')
2455 ++asarg;
2456
2457 /* Now that we have assembled one operand, we use the args
2458 string to figure out where it goes in the instruction. */
2459 switch (c)
2460 {
2461 case 's':
2462 INSERT_OPERAND (RS1, *ip, regno);
2463 break;
2464 case 'd':
2465 INSERT_OPERAND (RD, *ip, regno);
2466 break;
2467 case 't':
2468 INSERT_OPERAND (RS2, *ip, regno);
2469 break;
2470 case 'r':
2471 INSERT_OPERAND (RS3, *ip, regno);
2472 break;
2473 }
2474 continue;
2475 }
2476 break;
2477
2478 case 'D': /* Floating point RD. */
2479 case 'S': /* Floating point RS1. */
2480 case 'T': /* Floating point RS2. */
2481 case 'U': /* Floating point RS1 and RS2. */
2482 case 'R': /* Floating point RS3. */
2483 if (reg_lookup (&asarg, RCLASS_FPR, &regno))
2484 {
2485 char c = *oparg;
2486 if (*asarg == ' ')
2487 ++asarg;
2488 switch (c)
2489 {
2490 case 'D':
2491 INSERT_OPERAND (RD, *ip, regno);
2492 break;
2493 case 'S':
2494 INSERT_OPERAND (RS1, *ip, regno);
2495 break;
2496 case 'U':
2497 INSERT_OPERAND (RS1, *ip, regno);
2498 /* Fall through. */
2499 case 'T':
2500 INSERT_OPERAND (RS2, *ip, regno);
2501 break;
2502 case 'R':
2503 INSERT_OPERAND (RS3, *ip, regno);
2504 break;
2505 }
2506 continue;
2507 }
2508 break;
2509
2510 case 'I':
2511 my_getExpression (imm_expr, asarg);
2512 if (imm_expr->X_op != O_big
2513 && imm_expr->X_op != O_constant)
2514 break;
2515 normalize_constant_expr (imm_expr);
2516 asarg = expr_end;
2517 continue;
2518
2519 case 'A':
2520 my_getExpression (imm_expr, asarg);
2521 normalize_constant_expr (imm_expr);
2522 /* The 'A' format specifier must be a symbol. */
2523 if (imm_expr->X_op != O_symbol)
2524 break;
2525 *imm_reloc = BFD_RELOC_32;
2526 asarg = expr_end;
2527 continue;
2528
2529 case 'B':
2530 my_getExpression (imm_expr, asarg);
2531 normalize_constant_expr (imm_expr);
2532 /* The 'B' format specifier must be a symbol or a constant. */
2533 if (imm_expr->X_op != O_symbol && imm_expr->X_op != O_constant)
2534 break;
2535 if (imm_expr->X_op == O_symbol)
2536 *imm_reloc = BFD_RELOC_32;
2537 asarg = expr_end;
2538 continue;
2539
2540 case 'j': /* Sign-extended immediate. */
2541 p = percent_op_itype;
2542 *imm_reloc = BFD_RELOC_RISCV_LO12_I;
2543 goto alu_op;
2544 case 'q': /* Store displacement. */
2545 p = percent_op_stype;
2546 *imm_reloc = BFD_RELOC_RISCV_LO12_S;
2547 goto load_store;
2548 case 'o': /* Load displacement. */
2549 p = percent_op_itype;
2550 *imm_reloc = BFD_RELOC_RISCV_LO12_I;
2551 goto load_store;
2552 case '1':
2553 /* This is used for TLS, where the fourth operand is
2554 %tprel_add, to get a relocation applied to an add
2555 instruction, for relaxation to use. */
2556 p = percent_op_rtype;
2557 goto alu_op;
2558 case '0': /* AMO displacement, which must be zero. */
2559 p = percent_op_null;
2560 load_store:
2561 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
2562 continue;
2563 alu_op:
2564 /* If this value won't fit into a 16 bit offset, then go
2565 find a macro that will generate the 32 bit offset
2566 code pattern. */
2567 if (!my_getSmallExpression (imm_expr, imm_reloc, asarg, p))
2568 {
2569 normalize_constant_expr (imm_expr);
2570 if (imm_expr->X_op != O_constant
2571 || (*oparg == '0' && imm_expr->X_add_number != 0)
2572 || (*oparg == '1')
2573 || imm_expr->X_add_number >= (signed)RISCV_IMM_REACH/2
2574 || imm_expr->X_add_number < -(signed)RISCV_IMM_REACH/2)
2575 break;
2576 }
2577 asarg = expr_end;
2578 continue;
2579
2580 case 'p': /* PC-relative offset. */
2581 branch:
2582 *imm_reloc = BFD_RELOC_12_PCREL;
2583 my_getExpression (imm_expr, asarg);
2584 asarg = expr_end;
2585 continue;
2586
2587 case 'u': /* Upper 20 bits. */
2588 p = percent_op_utype;
2589 if (!my_getSmallExpression (imm_expr, imm_reloc, asarg, p))
2590 {
2591 if (imm_expr->X_op != O_constant)
2592 break;
2593
2594 if (imm_expr->X_add_number < 0
2595 || imm_expr->X_add_number >= (signed)RISCV_BIGIMM_REACH)
2596 as_bad (_("lui expression not in range 0..1048575"));
2597
2598 *imm_reloc = BFD_RELOC_RISCV_HI20;
2599 imm_expr->X_add_number <<= RISCV_IMM_BITS;
2600 }
2601 asarg = expr_end;
2602 continue;
2603
2604 case 'a': /* 20-bit PC-relative offset. */
2605 jump:
2606 my_getExpression (imm_expr, asarg);
2607 asarg = expr_end;
2608 *imm_reloc = BFD_RELOC_RISCV_JMP;
2609 continue;
2610
2611 case 'c':
2612 my_getExpression (imm_expr, asarg);
2613 asarg = expr_end;
2614 if (strcmp (asarg, "@plt") == 0)
2615 {
2616 *imm_reloc = BFD_RELOC_RISCV_CALL_PLT;
2617 asarg += 4;
2618 }
2619 else
2620 *imm_reloc = BFD_RELOC_RISCV_CALL;
2621 continue;
2622
2623 case 'O':
2624 switch (*++oparg)
2625 {
2626 case '4':
2627 if (my_getOpcodeExpression (imm_expr, imm_reloc, asarg, p)
2628 || imm_expr->X_op != O_constant
2629 || imm_expr->X_add_number < 0
2630 || imm_expr->X_add_number >= 128
2631 || (imm_expr->X_add_number & 0x3) != 3)
2632 {
2633 as_bad (_("bad value for opcode field, "
2634 "value must be 0...127 and "
2635 "lower 2 bits must be 0x3"));
2636 break;
2637 }
2638 INSERT_OPERAND (OP, *ip, imm_expr->X_add_number);
2639 imm_expr->X_op = O_absent;
2640 asarg = expr_end;
2641 continue;
2642
2643 case '2':
2644 if (my_getOpcodeExpression (imm_expr, imm_reloc, asarg, p)
2645 || imm_expr->X_op != O_constant
2646 || imm_expr->X_add_number < 0
2647 || imm_expr->X_add_number >= 3)
2648 {
2649 as_bad (_("bad value for opcode field, "
2650 "value must be 0...2"));
2651 break;
2652 }
2653 INSERT_OPERAND (OP2, *ip, imm_expr->X_add_number);
2654 imm_expr->X_op = O_absent;
2655 asarg = expr_end;
2656 continue;
2657
2658 default:
2659 goto unknown_riscv_ip_operand;
2660 }
2661 break;
2662
2663 case 'F':
2664 switch (*++oparg)
2665 {
2666 case '7':
2667 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2668 || imm_expr->X_op != O_constant
2669 || imm_expr->X_add_number < 0
2670 || imm_expr->X_add_number >= 128)
2671 {
2672 as_bad (_("bad value for funct7 field, "
2673 "value must be 0...127"));
2674 break;
2675 }
2676 INSERT_OPERAND (FUNCT7, *ip, imm_expr->X_add_number);
2677 imm_expr->X_op = O_absent;
2678 asarg = expr_end;
2679 continue;
2680
2681 case '3':
2682 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2683 || imm_expr->X_op != O_constant
2684 || imm_expr->X_add_number < 0
2685 || imm_expr->X_add_number >= 8)
2686 {
2687 as_bad (_("bad value for funct3 field, "
2688 "value must be 0...7"));
2689 break;
2690 }
2691 INSERT_OPERAND (FUNCT3, *ip, imm_expr->X_add_number);
2692 imm_expr->X_op = O_absent;
2693 asarg = expr_end;
2694 continue;
2695
2696 case '2':
2697 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2698 || imm_expr->X_op != O_constant
2699 || imm_expr->X_add_number < 0
2700 || imm_expr->X_add_number >= 4)
2701 {
2702 as_bad (_("bad value for funct2 field, "
2703 "value must be 0...3"));
2704 break;
2705 }
2706 INSERT_OPERAND (FUNCT2, *ip, imm_expr->X_add_number);
2707 imm_expr->X_op = O_absent;
2708 asarg = expr_end;
2709 continue;
2710
2711 default:
2712 goto unknown_riscv_ip_operand;
2713 }
2714 break;
2715
2716 case 'y': /* bs immediate */
2717 my_getExpression (imm_expr, asarg);
2718 check_absolute_expr (ip, imm_expr, FALSE);
2719 if ((unsigned long)imm_expr->X_add_number > 3)
2720 as_bad(_("Improper bs immediate (%lu)"),
2721 (unsigned long)imm_expr->X_add_number);
2722 INSERT_OPERAND(BS, *ip, imm_expr->X_add_number);
2723 imm_expr->X_op = O_absent;
2724 asarg = expr_end;
2725 continue;
2726
2727 case 'Y': /* rnum immediate */
2728 my_getExpression (imm_expr, asarg);
2729 check_absolute_expr (ip, imm_expr, FALSE);
2730 if ((unsigned long)imm_expr->X_add_number > 10)
2731 as_bad(_("Improper rnum immediate (%lu)"),
2732 (unsigned long)imm_expr->X_add_number);
2733 INSERT_OPERAND(RNUM, *ip, imm_expr->X_add_number);
2734 imm_expr->X_op = O_absent;
2735 asarg = expr_end;
2736 continue;
2737
2738 case 'z':
2739 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2740 || imm_expr->X_op != O_constant
2741 || imm_expr->X_add_number != 0)
2742 break;
2743 asarg = expr_end;
2744 imm_expr->X_op = O_absent;
2745 continue;
2746
2747 default:
2748 unknown_riscv_ip_operand:
2749 as_fatal (_("internal: unknown argument type `%s'"),
2750 opargStart);
2751 }
2752 break;
2753 }
2754 asarg = asargStart;
2755 error = _("illegal operands");
2756 insn_with_csr = false;
2757 }
2758
2759 out:
2760 /* Restore the character we might have clobbered above. */
2761 if (save_c)
2762 *(asargStart - 1) = save_c;
2763
2764 return error;
2765 }
2766
2767 /* Similar to riscv_ip, but assembles an instruction according to the
2768 hardcode values of .insn directive. */
2769
2770 static const char *
2771 riscv_ip_hardcode (char *str,
2772 struct riscv_cl_insn *ip,
2773 expressionS *imm_expr,
2774 const char *error)
2775 {
2776 struct riscv_opcode *insn;
2777 insn_t values[2] = {0, 0};
2778 unsigned int num = 0;
2779
2780 input_line_pointer = str;
2781 do
2782 {
2783 expression (imm_expr);
2784 if (imm_expr->X_op != O_constant)
2785 {
2786 /* The first value isn't constant, so it should be
2787 .insn <type> <operands>. We have been parsed it
2788 in the riscv_ip. */
2789 if (num == 0)
2790 return error;
2791 return _("values must be constant");
2792 }
2793 values[num++] = (insn_t) imm_expr->X_add_number;
2794 }
2795 while (*input_line_pointer++ == ',' && num < 2);
2796
2797 input_line_pointer--;
2798 if (*input_line_pointer != '\0')
2799 return _("unrecognized values");
2800
2801 insn = XNEW (struct riscv_opcode);
2802 insn->match = values[num - 1];
2803 create_insn (ip, insn);
2804 unsigned int bytes = riscv_insn_length (insn->match);
2805 if (values[num - 1] >> (8 * bytes) != 0
2806 || (num == 2 && values[0] != bytes))
2807 return _("value conflicts with instruction length");
2808
2809 return NULL;
2810 }
2811
2812 void
2813 md_assemble (char *str)
2814 {
2815 struct riscv_cl_insn insn;
2816 expressionS imm_expr;
2817 bfd_reloc_code_real_type imm_reloc = BFD_RELOC_UNUSED;
2818
2819 /* The architecture and privileged elf attributes should be set
2820 before assembling. */
2821 if (!start_assemble)
2822 {
2823 start_assemble = true;
2824
2825 riscv_set_abi_by_arch ();
2826 if (!riscv_set_default_priv_spec (NULL))
2827 return;
2828 }
2829
2830 riscv_mapping_state (MAP_INSN, 0);
2831
2832 const char *error = riscv_ip (str, &insn, &imm_expr, &imm_reloc, op_hash);
2833
2834 if (error)
2835 {
2836 as_bad ("%s `%s'", error, str);
2837 return;
2838 }
2839
2840 if (insn.insn_mo->pinfo == INSN_MACRO)
2841 macro (&insn, &imm_expr, &imm_reloc);
2842 else
2843 append_insn (&insn, &imm_expr, imm_reloc);
2844 }
2845
2846 const char *
2847 md_atof (int type, char *litP, int *sizeP)
2848 {
2849 return ieee_md_atof (type, litP, sizeP, TARGET_BYTES_BIG_ENDIAN);
2850 }
2851
2852 void
2853 md_number_to_chars (char *buf, valueT val, int n)
2854 {
2855 if (target_big_endian)
2856 number_to_chars_bigendian (buf, val, n);
2857 else
2858 number_to_chars_littleendian (buf, val, n);
2859 }
2860
2861 const char *md_shortopts = "O::g::G:";
2862
2863 enum options
2864 {
2865 OPTION_MARCH = OPTION_MD_BASE,
2866 OPTION_PIC,
2867 OPTION_NO_PIC,
2868 OPTION_MABI,
2869 OPTION_RELAX,
2870 OPTION_NO_RELAX,
2871 OPTION_ARCH_ATTR,
2872 OPTION_NO_ARCH_ATTR,
2873 OPTION_CSR_CHECK,
2874 OPTION_NO_CSR_CHECK,
2875 OPTION_MISA_SPEC,
2876 OPTION_MPRIV_SPEC,
2877 OPTION_BIG_ENDIAN,
2878 OPTION_LITTLE_ENDIAN,
2879 OPTION_END_OF_ENUM
2880 };
2881
2882 struct option md_longopts[] =
2883 {
2884 {"march", required_argument, NULL, OPTION_MARCH},
2885 {"fPIC", no_argument, NULL, OPTION_PIC},
2886 {"fpic", no_argument, NULL, OPTION_PIC},
2887 {"fno-pic", no_argument, NULL, OPTION_NO_PIC},
2888 {"mabi", required_argument, NULL, OPTION_MABI},
2889 {"mrelax", no_argument, NULL, OPTION_RELAX},
2890 {"mno-relax", no_argument, NULL, OPTION_NO_RELAX},
2891 {"march-attr", no_argument, NULL, OPTION_ARCH_ATTR},
2892 {"mno-arch-attr", no_argument, NULL, OPTION_NO_ARCH_ATTR},
2893 {"mcsr-check", no_argument, NULL, OPTION_CSR_CHECK},
2894 {"mno-csr-check", no_argument, NULL, OPTION_NO_CSR_CHECK},
2895 {"misa-spec", required_argument, NULL, OPTION_MISA_SPEC},
2896 {"mpriv-spec", required_argument, NULL, OPTION_MPRIV_SPEC},
2897 {"mbig-endian", no_argument, NULL, OPTION_BIG_ENDIAN},
2898 {"mlittle-endian", no_argument, NULL, OPTION_LITTLE_ENDIAN},
2899
2900 {NULL, no_argument, NULL, 0}
2901 };
2902 size_t md_longopts_size = sizeof (md_longopts);
2903
2904 int
2905 md_parse_option (int c, const char *arg)
2906 {
2907 switch (c)
2908 {
2909 case OPTION_MARCH:
2910 default_arch_with_ext = arg;
2911 break;
2912
2913 case OPTION_NO_PIC:
2914 riscv_opts.pic = false;
2915 break;
2916
2917 case OPTION_PIC:
2918 riscv_opts.pic = true;
2919 break;
2920
2921 case OPTION_MABI:
2922 if (strcmp (arg, "ilp32") == 0)
2923 riscv_set_abi (32, FLOAT_ABI_SOFT, false);
2924 else if (strcmp (arg, "ilp32e") == 0)
2925 riscv_set_abi (32, FLOAT_ABI_SOFT, true);
2926 else if (strcmp (arg, "ilp32f") == 0)
2927 riscv_set_abi (32, FLOAT_ABI_SINGLE, false);
2928 else if (strcmp (arg, "ilp32d") == 0)
2929 riscv_set_abi (32, FLOAT_ABI_DOUBLE, false);
2930 else if (strcmp (arg, "ilp32q") == 0)
2931 riscv_set_abi (32, FLOAT_ABI_QUAD, false);
2932 else if (strcmp (arg, "lp64") == 0)
2933 riscv_set_abi (64, FLOAT_ABI_SOFT, false);
2934 else if (strcmp (arg, "lp64f") == 0)
2935 riscv_set_abi (64, FLOAT_ABI_SINGLE, false);
2936 else if (strcmp (arg, "lp64d") == 0)
2937 riscv_set_abi (64, FLOAT_ABI_DOUBLE, false);
2938 else if (strcmp (arg, "lp64q") == 0)
2939 riscv_set_abi (64, FLOAT_ABI_QUAD, false);
2940 else
2941 return 0;
2942 explicit_mabi = true;
2943 break;
2944
2945 case OPTION_RELAX:
2946 riscv_opts.relax = true;
2947 break;
2948
2949 case OPTION_NO_RELAX:
2950 riscv_opts.relax = false;
2951 break;
2952
2953 case OPTION_ARCH_ATTR:
2954 riscv_opts.arch_attr = true;
2955 break;
2956
2957 case OPTION_NO_ARCH_ATTR:
2958 riscv_opts.arch_attr = false;
2959 break;
2960
2961 case OPTION_CSR_CHECK:
2962 riscv_opts.csr_check = true;
2963 break;
2964
2965 case OPTION_NO_CSR_CHECK:
2966 riscv_opts.csr_check = false;
2967 break;
2968
2969 case OPTION_MISA_SPEC:
2970 return riscv_set_default_isa_spec (arg);
2971
2972 case OPTION_MPRIV_SPEC:
2973 return riscv_set_default_priv_spec (arg);
2974
2975 case OPTION_BIG_ENDIAN:
2976 target_big_endian = 1;
2977 break;
2978
2979 case OPTION_LITTLE_ENDIAN:
2980 target_big_endian = 0;
2981 break;
2982
2983 default:
2984 return 0;
2985 }
2986
2987 return 1;
2988 }
2989
2990 void
2991 riscv_after_parse_args (void)
2992 {
2993 /* The --with-arch is optional for now, so we still need to set the xlen
2994 according to the default_arch, which is set by the --target. */
2995 if (xlen == 0)
2996 {
2997 if (strcmp (default_arch, "riscv32") == 0)
2998 xlen = 32;
2999 else if (strcmp (default_arch, "riscv64") == 0)
3000 xlen = 64;
3001 else
3002 as_bad ("unknown default architecture `%s'", default_arch);
3003 }
3004
3005 /* Set default specs. */
3006 if (default_isa_spec == ISA_SPEC_CLASS_NONE)
3007 riscv_set_default_isa_spec (DEFAULT_RISCV_ISA_SPEC);
3008 if (default_priv_spec == PRIV_SPEC_CLASS_NONE)
3009 riscv_set_default_priv_spec (DEFAULT_RISCV_PRIV_SPEC);
3010
3011 riscv_set_arch (default_arch_with_ext);
3012
3013 /* If the CIE to be produced has not been overridden on the command line,
3014 then produce version 3 by default. This allows us to use the full
3015 range of registers in a .cfi_return_column directive. */
3016 if (flag_dwarf_cie_version == -1)
3017 flag_dwarf_cie_version = 3;
3018 }
3019
3020 long
3021 md_pcrel_from (fixS *fixP)
3022 {
3023 return fixP->fx_where + fixP->fx_frag->fr_address;
3024 }
3025
3026 /* Apply a fixup to the object file. */
3027
3028 void
3029 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
3030 {
3031 unsigned int subtype;
3032 bfd_byte *buf = (bfd_byte *) (fixP->fx_frag->fr_literal + fixP->fx_where);
3033 bool relaxable = false;
3034 offsetT loc;
3035 segT sub_segment;
3036
3037 /* Remember value for tc_gen_reloc. */
3038 fixP->fx_addnumber = *valP;
3039
3040 switch (fixP->fx_r_type)
3041 {
3042 case BFD_RELOC_RISCV_HI20:
3043 case BFD_RELOC_RISCV_LO12_I:
3044 case BFD_RELOC_RISCV_LO12_S:
3045 bfd_putl32 (riscv_apply_const_reloc (fixP->fx_r_type, *valP)
3046 | bfd_getl32 (buf), buf);
3047 if (fixP->fx_addsy == NULL)
3048 fixP->fx_done = true;
3049 relaxable = true;
3050 break;
3051
3052 case BFD_RELOC_RISCV_GOT_HI20:
3053 case BFD_RELOC_RISCV_ADD8:
3054 case BFD_RELOC_RISCV_ADD16:
3055 case BFD_RELOC_RISCV_ADD32:
3056 case BFD_RELOC_RISCV_ADD64:
3057 case BFD_RELOC_RISCV_SUB6:
3058 case BFD_RELOC_RISCV_SUB8:
3059 case BFD_RELOC_RISCV_SUB16:
3060 case BFD_RELOC_RISCV_SUB32:
3061 case BFD_RELOC_RISCV_SUB64:
3062 case BFD_RELOC_RISCV_RELAX:
3063 break;
3064
3065 case BFD_RELOC_RISCV_TPREL_HI20:
3066 case BFD_RELOC_RISCV_TPREL_LO12_I:
3067 case BFD_RELOC_RISCV_TPREL_LO12_S:
3068 case BFD_RELOC_RISCV_TPREL_ADD:
3069 relaxable = true;
3070 /* Fall through. */
3071
3072 case BFD_RELOC_RISCV_TLS_GOT_HI20:
3073 case BFD_RELOC_RISCV_TLS_GD_HI20:
3074 case BFD_RELOC_RISCV_TLS_DTPREL32:
3075 case BFD_RELOC_RISCV_TLS_DTPREL64:
3076 if (fixP->fx_addsy != NULL)
3077 S_SET_THREAD_LOCAL (fixP->fx_addsy);
3078 else
3079 as_bad_where (fixP->fx_file, fixP->fx_line,
3080 _("TLS relocation against a constant"));
3081 break;
3082
3083 case BFD_RELOC_32:
3084 /* Use pc-relative relocation for FDE initial location.
3085 The symbol address in .eh_frame may be adjusted in
3086 _bfd_elf_discard_section_eh_frame, and the content of
3087 .eh_frame will be adjusted in _bfd_elf_write_section_eh_frame.
3088 Therefore, we cannot insert a relocation whose addend symbol is
3089 in .eh_frame. Othrewise, the value may be adjusted twice. */
3090 if (fixP->fx_addsy && fixP->fx_subsy
3091 && (sub_segment = S_GET_SEGMENT (fixP->fx_subsy))
3092 && strcmp (sub_segment->name, ".eh_frame") == 0
3093 && S_GET_VALUE (fixP->fx_subsy)
3094 == fixP->fx_frag->fr_address + fixP->fx_where)
3095 {
3096 fixP->fx_r_type = BFD_RELOC_RISCV_32_PCREL;
3097 fixP->fx_subsy = NULL;
3098 break;
3099 }
3100 /* Fall through. */
3101 case BFD_RELOC_64:
3102 case BFD_RELOC_16:
3103 case BFD_RELOC_8:
3104 case BFD_RELOC_RISCV_CFA:
3105 if (fixP->fx_addsy && fixP->fx_subsy)
3106 {
3107 fixP->fx_next = xmemdup (fixP, sizeof (*fixP), sizeof (*fixP));
3108 fixP->fx_next->fx_addsy = fixP->fx_subsy;
3109 fixP->fx_next->fx_subsy = NULL;
3110 fixP->fx_next->fx_offset = 0;
3111 fixP->fx_subsy = NULL;
3112
3113 switch (fixP->fx_r_type)
3114 {
3115 case BFD_RELOC_64:
3116 fixP->fx_r_type = BFD_RELOC_RISCV_ADD64;
3117 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB64;
3118 break;
3119
3120 case BFD_RELOC_32:
3121 fixP->fx_r_type = BFD_RELOC_RISCV_ADD32;
3122 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB32;
3123 break;
3124
3125 case BFD_RELOC_16:
3126 fixP->fx_r_type = BFD_RELOC_RISCV_ADD16;
3127 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB16;
3128 break;
3129
3130 case BFD_RELOC_8:
3131 fixP->fx_r_type = BFD_RELOC_RISCV_ADD8;
3132 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB8;
3133 break;
3134
3135 case BFD_RELOC_RISCV_CFA:
3136 /* Load the byte to get the subtype. */
3137 subtype = bfd_get_8 (NULL, &((fragS *) (fixP->fx_frag->fr_opcode))->fr_literal[fixP->fx_where]);
3138 loc = fixP->fx_frag->fr_fix - (subtype & 7);
3139 switch (subtype)
3140 {
3141 case DW_CFA_advance_loc1:
3142 fixP->fx_where = loc + 1;
3143 fixP->fx_next->fx_where = loc + 1;
3144 fixP->fx_r_type = BFD_RELOC_RISCV_SET8;
3145 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB8;
3146 break;
3147
3148 case DW_CFA_advance_loc2:
3149 fixP->fx_size = 2;
3150 fixP->fx_next->fx_size = 2;
3151 fixP->fx_where = loc + 1;
3152 fixP->fx_next->fx_where = loc + 1;
3153 fixP->fx_r_type = BFD_RELOC_RISCV_SET16;
3154 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB16;
3155 break;
3156
3157 case DW_CFA_advance_loc4:
3158 fixP->fx_size = 4;
3159 fixP->fx_next->fx_size = 4;
3160 fixP->fx_where = loc;
3161 fixP->fx_next->fx_where = loc;
3162 fixP->fx_r_type = BFD_RELOC_RISCV_SET32;
3163 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB32;
3164 break;
3165
3166 default:
3167 if (subtype < 0x80 && (subtype & 0x40))
3168 {
3169 /* DW_CFA_advance_loc */
3170 fixP->fx_frag = (fragS *) fixP->fx_frag->fr_opcode;
3171 fixP->fx_next->fx_frag = fixP->fx_frag;
3172 fixP->fx_r_type = BFD_RELOC_RISCV_SET6;
3173 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB6;
3174 }
3175 else
3176 as_fatal (_("internal: bad CFA value #%d"), subtype);
3177 break;
3178 }
3179 break;
3180
3181 default:
3182 /* This case is unreachable. */
3183 abort ();
3184 }
3185 }
3186 /* Fall through. */
3187
3188 case BFD_RELOC_RVA:
3189 /* If we are deleting this reloc entry, we must fill in the
3190 value now. This can happen if we have a .word which is not
3191 resolved when it appears but is later defined. */
3192 if (fixP->fx_addsy == NULL)
3193 {
3194 gas_assert (fixP->fx_size <= sizeof (valueT));
3195 md_number_to_chars ((char *) buf, *valP, fixP->fx_size);
3196 fixP->fx_done = 1;
3197 }
3198 break;
3199
3200 case BFD_RELOC_RISCV_JMP:
3201 if (fixP->fx_addsy)
3202 {
3203 /* Fill in a tentative value to improve objdump readability. */
3204 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
3205 bfd_vma delta = target - md_pcrel_from (fixP);
3206 bfd_putl32 (bfd_getl32 (buf) | ENCODE_JTYPE_IMM (delta), buf);
3207 }
3208 break;
3209
3210 case BFD_RELOC_12_PCREL:
3211 if (fixP->fx_addsy)
3212 {
3213 /* Fill in a tentative value to improve objdump readability. */
3214 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
3215 bfd_vma delta = target - md_pcrel_from (fixP);
3216 bfd_putl32 (bfd_getl32 (buf) | ENCODE_BTYPE_IMM (delta), buf);
3217 }
3218 break;
3219
3220 case BFD_RELOC_RISCV_RVC_BRANCH:
3221 if (fixP->fx_addsy)
3222 {
3223 /* Fill in a tentative value to improve objdump readability. */
3224 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
3225 bfd_vma delta = target - md_pcrel_from (fixP);
3226 bfd_putl16 (bfd_getl16 (buf) | ENCODE_CBTYPE_IMM (delta), buf);
3227 }
3228 break;
3229
3230 case BFD_RELOC_RISCV_RVC_JUMP:
3231 if (fixP->fx_addsy)
3232 {
3233 /* Fill in a tentative value to improve objdump readability. */
3234 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
3235 bfd_vma delta = target - md_pcrel_from (fixP);
3236 bfd_putl16 (bfd_getl16 (buf) | ENCODE_CJTYPE_IMM (delta), buf);
3237 }
3238 break;
3239
3240 case BFD_RELOC_RISCV_CALL:
3241 case BFD_RELOC_RISCV_CALL_PLT:
3242 relaxable = true;
3243 break;
3244
3245 case BFD_RELOC_RISCV_PCREL_HI20:
3246 case BFD_RELOC_RISCV_PCREL_LO12_S:
3247 case BFD_RELOC_RISCV_PCREL_LO12_I:
3248 relaxable = riscv_opts.relax;
3249 break;
3250
3251 case BFD_RELOC_RISCV_ALIGN:
3252 break;
3253
3254 default:
3255 /* We ignore generic BFD relocations we don't know about. */
3256 if (bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type) != NULL)
3257 as_fatal (_("internal: bad relocation #%d"), fixP->fx_r_type);
3258 }
3259
3260 if (fixP->fx_subsy != NULL)
3261 as_bad_subtract (fixP);
3262
3263 /* Add an R_RISCV_RELAX reloc if the reloc is relaxable. */
3264 if (relaxable && fixP->fx_tcbit && fixP->fx_addsy != NULL)
3265 {
3266 fixP->fx_next = xmemdup (fixP, sizeof (*fixP), sizeof (*fixP));
3267 fixP->fx_next->fx_addsy = fixP->fx_next->fx_subsy = NULL;
3268 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_RELAX;
3269 fixP->fx_next->fx_size = 0;
3270 }
3271 }
3272
3273 /* Because the value of .cfi_remember_state may changed after relaxation,
3274 we insert a fix to relocate it again in link-time. */
3275
3276 void
3277 riscv_pre_output_hook (void)
3278 {
3279 const frchainS *frch;
3280 segT s;
3281
3282 /* Save the current segment info. */
3283 segT seg = now_seg;
3284 subsegT subseg = now_subseg;
3285
3286 for (s = stdoutput->sections; s; s = s->next)
3287 for (frch = seg_info (s)->frchainP; frch; frch = frch->frch_next)
3288 {
3289 fragS *frag;
3290
3291 for (frag = frch->frch_root; frag; frag = frag->fr_next)
3292 {
3293 if (frag->fr_type == rs_cfa)
3294 {
3295 expressionS exp;
3296 expressionS *symval;
3297
3298 symval = symbol_get_value_expression (frag->fr_symbol);
3299 exp.X_op = O_subtract;
3300 exp.X_add_symbol = symval->X_add_symbol;
3301 exp.X_add_number = 0;
3302 exp.X_op_symbol = symval->X_op_symbol;
3303
3304 /* We must set the segment before creating a frag after all
3305 frag chains have been chained together. */
3306 subseg_set (s, frch->frch_subseg);
3307
3308 fix_new_exp (frag, (int) frag->fr_offset, 1, &exp, 0,
3309 BFD_RELOC_RISCV_CFA);
3310 }
3311 }
3312 }
3313
3314 /* Restore the original segment info. */
3315 subseg_set (seg, subseg);
3316 }
3317
3318 /* This structure is used to hold a stack of .option values. */
3319 struct riscv_option_stack
3320 {
3321 struct riscv_option_stack *next;
3322 struct riscv_set_options options;
3323 };
3324
3325 static struct riscv_option_stack *riscv_opts_stack;
3326
3327 /* Handle the .option pseudo-op. */
3328
3329 static void
3330 s_riscv_option (int x ATTRIBUTE_UNUSED)
3331 {
3332 char *name = input_line_pointer, ch;
3333
3334 while (!is_end_of_line[(unsigned char) *input_line_pointer])
3335 ++input_line_pointer;
3336 ch = *input_line_pointer;
3337 *input_line_pointer = '\0';
3338
3339 if (strcmp (name, "rvc") == 0)
3340 {
3341 riscv_update_subset (&riscv_rps_as, "c", false);
3342 riscv_set_rvc (true);
3343 }
3344 else if (strcmp (name, "norvc") == 0)
3345 {
3346 riscv_update_subset (&riscv_rps_as, "c", true);
3347 riscv_set_rvc (false);
3348 }
3349 else if (strcmp (name, "pic") == 0)
3350 riscv_opts.pic = true;
3351 else if (strcmp (name, "nopic") == 0)
3352 riscv_opts.pic = false;
3353 else if (strcmp (name, "relax") == 0)
3354 riscv_opts.relax = true;
3355 else if (strcmp (name, "norelax") == 0)
3356 riscv_opts.relax = false;
3357 else if (strcmp (name, "csr-check") == 0)
3358 riscv_opts.csr_check = true;
3359 else if (strcmp (name, "no-csr-check") == 0)
3360 riscv_opts.csr_check = false;
3361 else if (strcmp (name, "push") == 0)
3362 {
3363 struct riscv_option_stack *s;
3364
3365 s = (struct riscv_option_stack *) xmalloc (sizeof *s);
3366 s->next = riscv_opts_stack;
3367 s->options = riscv_opts;
3368 riscv_opts_stack = s;
3369 }
3370 else if (strcmp (name, "pop") == 0)
3371 {
3372 struct riscv_option_stack *s;
3373
3374 s = riscv_opts_stack;
3375 if (s == NULL)
3376 as_bad (_(".option pop with no .option push"));
3377 else
3378 {
3379 riscv_opts = s->options;
3380 riscv_opts_stack = s->next;
3381 free (s);
3382 }
3383 }
3384 else
3385 {
3386 as_warn (_("unrecognized .option directive: %s\n"), name);
3387 }
3388 *input_line_pointer = ch;
3389 demand_empty_rest_of_line ();
3390 }
3391
3392 /* Handle the .dtprelword and .dtpreldword pseudo-ops. They generate
3393 a 32-bit or 64-bit DTP-relative relocation (BYTES says which) for
3394 use in DWARF debug information. */
3395
3396 static void
3397 s_dtprel (int bytes)
3398 {
3399 expressionS ex;
3400 char *p;
3401
3402 expression (&ex);
3403
3404 if (ex.X_op != O_symbol)
3405 {
3406 as_bad (_("unsupported use of %s"), (bytes == 8
3407 ? ".dtpreldword"
3408 : ".dtprelword"));
3409 ignore_rest_of_line ();
3410 }
3411
3412 p = frag_more (bytes);
3413 md_number_to_chars (p, 0, bytes);
3414 fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, false,
3415 (bytes == 8
3416 ? BFD_RELOC_RISCV_TLS_DTPREL64
3417 : BFD_RELOC_RISCV_TLS_DTPREL32));
3418
3419 demand_empty_rest_of_line ();
3420 }
3421
3422 /* Handle the .bss pseudo-op. */
3423
3424 static void
3425 s_bss (int ignore ATTRIBUTE_UNUSED)
3426 {
3427 subseg_set (bss_section, 0);
3428 demand_empty_rest_of_line ();
3429 }
3430
3431 static void
3432 riscv_make_nops (char *buf, bfd_vma bytes)
3433 {
3434 bfd_vma i = 0;
3435
3436 /* RISC-V instructions cannot begin or end on odd addresses, so this case
3437 means we are not within a valid instruction sequence. It is thus safe
3438 to use a zero byte, even though that is not a valid instruction. */
3439 if (bytes % 2 == 1)
3440 buf[i++] = 0;
3441
3442 /* Use at most one 2-byte NOP. */
3443 if ((bytes - i) % 4 == 2)
3444 {
3445 number_to_chars_littleendian (buf + i, RVC_NOP, 2);
3446 i += 2;
3447 }
3448
3449 /* Fill the remainder with 4-byte NOPs. */
3450 for ( ; i < bytes; i += 4)
3451 number_to_chars_littleendian (buf + i, RISCV_NOP, 4);
3452 }
3453
3454 /* Called from md_do_align. Used to create an alignment frag in a
3455 code section by emitting a worst-case NOP sequence that the linker
3456 will later relax to the correct number of NOPs. We can't compute
3457 the correct alignment now because of other linker relaxations. */
3458
3459 bool
3460 riscv_frag_align_code (int n)
3461 {
3462 bfd_vma bytes = (bfd_vma) 1 << n;
3463 bfd_vma insn_alignment = riscv_opts.rvc ? 2 : 4;
3464 bfd_vma worst_case_bytes = bytes - insn_alignment;
3465 char *nops;
3466 expressionS ex;
3467
3468 /* If we are moving to a smaller alignment than the instruction size, then no
3469 alignment is required. */
3470 if (bytes <= insn_alignment)
3471 return true;
3472
3473 /* When not relaxing, riscv_handle_align handles code alignment. */
3474 if (!riscv_opts.relax)
3475 return false;
3476
3477 nops = frag_more (worst_case_bytes);
3478
3479 ex.X_op = O_constant;
3480 ex.X_add_number = worst_case_bytes;
3481
3482 riscv_make_nops (nops, worst_case_bytes);
3483
3484 fix_new_exp (frag_now, nops - frag_now->fr_literal, 0,
3485 &ex, false, BFD_RELOC_RISCV_ALIGN);
3486
3487 riscv_mapping_state (MAP_INSN, worst_case_bytes);
3488
3489 return true;
3490 }
3491
3492 /* Implement HANDLE_ALIGN. */
3493
3494 void
3495 riscv_handle_align (fragS *fragP)
3496 {
3497 switch (fragP->fr_type)
3498 {
3499 case rs_align_code:
3500 /* When relaxing, riscv_frag_align_code handles code alignment. */
3501 if (!riscv_opts.relax)
3502 {
3503 bfd_signed_vma bytes = (fragP->fr_next->fr_address
3504 - fragP->fr_address - fragP->fr_fix);
3505 /* We have 4 byte uncompressed nops. */
3506 bfd_signed_vma size = 4;
3507 bfd_signed_vma excess = bytes % size;
3508 bfd_boolean odd_padding = (excess % 2 == 1);
3509 char *p = fragP->fr_literal + fragP->fr_fix;
3510
3511 if (bytes <= 0)
3512 break;
3513
3514 /* Insert zeros or compressed nops to get 4 byte alignment. */
3515 if (excess)
3516 {
3517 if (odd_padding)
3518 riscv_add_odd_padding_symbol (fragP);
3519 riscv_make_nops (p, excess);
3520 fragP->fr_fix += excess;
3521 p += excess;
3522 }
3523
3524 /* The frag will be changed to `rs_fill` later. The function
3525 `write_contents` will try to fill the remaining spaces
3526 according to the patterns we give. In this case, we give
3527 a 4 byte uncompressed nop as the pattern, and set the size
3528 of the pattern into `fr_var`. The nop will be output to the
3529 file `fr_offset` times. However, `fr_offset` could be zero
3530 if we don't need to pad the boundary finally. */
3531 riscv_make_nops (p, size);
3532 fragP->fr_var = size;
3533 }
3534 break;
3535
3536 default:
3537 break;
3538 }
3539 }
3540
3541 /* This usually called from frag_var. */
3542
3543 void
3544 riscv_init_frag (fragS * fragP, int max_chars)
3545 {
3546 /* Do not add mapping symbol to debug sections. */
3547 if (bfd_section_flags (now_seg) & SEC_DEBUGGING)
3548 return;
3549
3550 switch (fragP->fr_type)
3551 {
3552 case rs_fill:
3553 case rs_align:
3554 case rs_align_test:
3555 riscv_mapping_state (MAP_DATA, max_chars);
3556 break;
3557 case rs_align_code:
3558 riscv_mapping_state (MAP_INSN, max_chars);
3559 break;
3560 default:
3561 break;
3562 }
3563 }
3564
3565 int
3566 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
3567 {
3568 return (fragp->fr_var = relaxed_branch_length (fragp, segtype, false));
3569 }
3570
3571 /* Translate internal representation of relocation info to BFD target
3572 format. */
3573
3574 arelent *
3575 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
3576 {
3577 arelent *reloc = (arelent *) xmalloc (sizeof (arelent));
3578
3579 reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
3580 *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
3581 reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
3582 reloc->addend = fixp->fx_addnumber;
3583
3584 reloc->howto = bfd_reloc_type_lookup (stdoutput, fixp->fx_r_type);
3585 if (reloc->howto == NULL)
3586 {
3587 if ((fixp->fx_r_type == BFD_RELOC_16 || fixp->fx_r_type == BFD_RELOC_8)
3588 && fixp->fx_addsy != NULL && fixp->fx_subsy != NULL)
3589 {
3590 /* We don't have R_RISCV_8/16, but for this special case,
3591 we can use R_RISCV_ADD8/16 with R_RISCV_SUB8/16. */
3592 return reloc;
3593 }
3594
3595 as_bad_where (fixp->fx_file, fixp->fx_line,
3596 _("cannot represent %s relocation in object file"),
3597 bfd_get_reloc_code_name (fixp->fx_r_type));
3598 return NULL;
3599 }
3600
3601 return reloc;
3602 }
3603
3604 int
3605 riscv_relax_frag (asection *sec, fragS *fragp, long stretch ATTRIBUTE_UNUSED)
3606 {
3607 if (RELAX_BRANCH_P (fragp->fr_subtype))
3608 {
3609 offsetT old_var = fragp->fr_var;
3610 fragp->fr_var = relaxed_branch_length (fragp, sec, true);
3611 return fragp->fr_var - old_var;
3612 }
3613
3614 return 0;
3615 }
3616
3617 /* Expand far branches to multi-instruction sequences. */
3618
3619 static void
3620 md_convert_frag_branch (fragS *fragp)
3621 {
3622 bfd_byte *buf;
3623 expressionS exp;
3624 fixS *fixp;
3625 insn_t insn;
3626 int rs1, reloc;
3627
3628 buf = (bfd_byte *)fragp->fr_literal + fragp->fr_fix;
3629
3630 exp.X_op = O_symbol;
3631 exp.X_add_symbol = fragp->fr_symbol;
3632 exp.X_add_number = fragp->fr_offset;
3633
3634 gas_assert (fragp->fr_var == RELAX_BRANCH_LENGTH (fragp->fr_subtype));
3635
3636 if (RELAX_BRANCH_RVC (fragp->fr_subtype))
3637 {
3638 switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
3639 {
3640 case 8:
3641 case 4:
3642 /* Expand the RVC branch into a RISC-V one. */
3643 insn = bfd_getl16 (buf);
3644 rs1 = 8 + ((insn >> OP_SH_CRS1S) & OP_MASK_CRS1S);
3645 if ((insn & MASK_C_J) == MATCH_C_J)
3646 insn = MATCH_JAL;
3647 else if ((insn & MASK_C_JAL) == MATCH_C_JAL)
3648 insn = MATCH_JAL | (X_RA << OP_SH_RD);
3649 else if ((insn & MASK_C_BEQZ) == MATCH_C_BEQZ)
3650 insn = MATCH_BEQ | (rs1 << OP_SH_RS1);
3651 else if ((insn & MASK_C_BNEZ) == MATCH_C_BNEZ)
3652 insn = MATCH_BNE | (rs1 << OP_SH_RS1);
3653 else
3654 abort ();
3655 bfd_putl32 (insn, buf);
3656 break;
3657
3658 case 6:
3659 /* Invert the branch condition. Branch over the jump. */
3660 insn = bfd_getl16 (buf);
3661 insn ^= MATCH_C_BEQZ ^ MATCH_C_BNEZ;
3662 insn |= ENCODE_CBTYPE_IMM (6);
3663 bfd_putl16 (insn, buf);
3664 buf += 2;
3665 goto jump;
3666
3667 case 2:
3668 /* Just keep the RVC branch. */
3669 reloc = RELAX_BRANCH_UNCOND (fragp->fr_subtype)
3670 ? BFD_RELOC_RISCV_RVC_JUMP : BFD_RELOC_RISCV_RVC_BRANCH;
3671 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
3672 2, &exp, false, reloc);
3673 buf += 2;
3674 goto done;
3675
3676 default:
3677 abort ();
3678 }
3679 }
3680
3681 switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
3682 {
3683 case 8:
3684 gas_assert (!RELAX_BRANCH_UNCOND (fragp->fr_subtype));
3685
3686 /* Invert the branch condition. Branch over the jump. */
3687 insn = bfd_getl32 (buf);
3688 insn ^= MATCH_BEQ ^ MATCH_BNE;
3689 insn |= ENCODE_BTYPE_IMM (8);
3690 bfd_putl32 (insn, buf);
3691 buf += 4;
3692
3693 jump:
3694 /* Jump to the target. */
3695 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
3696 4, &exp, false, BFD_RELOC_RISCV_JMP);
3697 bfd_putl32 (MATCH_JAL, buf);
3698 buf += 4;
3699 break;
3700
3701 case 4:
3702 reloc = RELAX_BRANCH_UNCOND (fragp->fr_subtype)
3703 ? BFD_RELOC_RISCV_JMP : BFD_RELOC_12_PCREL;
3704 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
3705 4, &exp, false, reloc);
3706 buf += 4;
3707 break;
3708
3709 default:
3710 abort ();
3711 }
3712
3713 done:
3714 fixp->fx_file = fragp->fr_file;
3715 fixp->fx_line = fragp->fr_line;
3716
3717 gas_assert (buf == (bfd_byte *)fragp->fr_literal
3718 + fragp->fr_fix + fragp->fr_var);
3719
3720 fragp->fr_fix += fragp->fr_var;
3721 }
3722
3723 /* Relax a machine dependent frag. This returns the amount by which
3724 the current size of the frag should change. */
3725
3726 void
3727 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec ATTRIBUTE_UNUSED,
3728 fragS *fragp)
3729 {
3730 gas_assert (RELAX_BRANCH_P (fragp->fr_subtype));
3731 md_convert_frag_branch (fragp);
3732 }
3733
3734 void
3735 md_show_usage (FILE *stream)
3736 {
3737 fprintf (stream, _("\
3738 RISC-V options:\n\
3739 -fpic or -fPIC generate position-independent code\n\
3740 -fno-pic don't generate position-independent code (default)\n\
3741 -march=ISA set the RISC-V architecture\n\
3742 -misa-spec=ISAspec set the RISC-V ISA spec (2.2, 20190608, 20191213)\n\
3743 -mpriv-spec=PRIVspec set the RISC-V privilege spec (1.9.1, 1.10, 1.11)\n\
3744 -mabi=ABI set the RISC-V ABI\n\
3745 -mrelax enable relax (default)\n\
3746 -mno-relax disable relax\n\
3747 -march-attr generate RISC-V arch attribute\n\
3748 -mno-arch-attr don't generate RISC-V arch attribute\n\
3749 -mcsr-check enable the csr ISA and privilege spec version checks\n\
3750 -mno-csr-check disable the csr ISA and privilege spec version checks (default)\n\
3751 -mbig-endian assemble for big-endian\n\
3752 -mlittle-endian assemble for little-endian\n\
3753 "));
3754 }
3755
3756 /* Standard calling conventions leave the CFA at SP on entry. */
3757
3758 void
3759 riscv_cfi_frame_initial_instructions (void)
3760 {
3761 cfi_add_CFA_def_cfa_register (X_SP);
3762 }
3763
3764 int
3765 tc_riscv_regname_to_dw2regnum (char *regname)
3766 {
3767 int reg;
3768
3769 if ((reg = reg_lookup_internal (regname, RCLASS_GPR)) >= 0)
3770 return reg;
3771
3772 if ((reg = reg_lookup_internal (regname, RCLASS_FPR)) >= 0)
3773 return reg + 32;
3774
3775 /* CSRs are numbered 4096 -> 8191. */
3776 if ((reg = reg_lookup_internal (regname, RCLASS_CSR)) >= 0)
3777 return reg + 4096;
3778
3779 as_bad (_("unknown register `%s'"), regname);
3780 return -1;
3781 }
3782
3783 void
3784 riscv_elf_final_processing (void)
3785 {
3786 riscv_set_abi_by_arch ();
3787 elf_elfheader (stdoutput)->e_flags |= elf_flags;
3788 }
3789
3790 /* Parse the .sleb128 and .uleb128 pseudos. Only allow constant expressions,
3791 since these directives break relaxation when used with symbol deltas. */
3792
3793 static void
3794 s_riscv_leb128 (int sign)
3795 {
3796 expressionS exp;
3797 char *save_in = input_line_pointer;
3798
3799 expression (&exp);
3800 if (exp.X_op != O_constant)
3801 as_bad (_("non-constant .%cleb128 is not supported"), sign ? 's' : 'u');
3802 demand_empty_rest_of_line ();
3803
3804 input_line_pointer = save_in;
3805 return s_leb128 (sign);
3806 }
3807
3808 /* Parse the .insn directive. There are three formats,
3809 Format 1: .insn <type> <operand1>, <operand2>, ...
3810 Format 2: .insn <length>, <value>
3811 Format 3: .insn <value>. */
3812
3813 static void
3814 s_riscv_insn (int x ATTRIBUTE_UNUSED)
3815 {
3816 char *str = input_line_pointer;
3817 struct riscv_cl_insn insn;
3818 expressionS imm_expr;
3819 bfd_reloc_code_real_type imm_reloc = BFD_RELOC_UNUSED;
3820 char save_c;
3821
3822 while (!is_end_of_line[(unsigned char) *input_line_pointer])
3823 ++input_line_pointer;
3824
3825 save_c = *input_line_pointer;
3826 *input_line_pointer = '\0';
3827
3828 riscv_mapping_state (MAP_INSN, 0);
3829
3830 const char *error = riscv_ip (str, &insn, &imm_expr,
3831 &imm_reloc, insn_type_hash);
3832 if (error)
3833 {
3834 char *save_in = input_line_pointer;
3835 error = riscv_ip_hardcode (str, &insn, &imm_expr, error);
3836 input_line_pointer = save_in;
3837 }
3838
3839 if (error)
3840 as_bad ("%s `%s'", error, str);
3841 else
3842 {
3843 gas_assert (insn.insn_mo->pinfo != INSN_MACRO);
3844 append_insn (&insn, &imm_expr, imm_reloc);
3845 }
3846
3847 *input_line_pointer = save_c;
3848 demand_empty_rest_of_line ();
3849 }
3850
3851 /* Update architecture and privileged elf attributes. If we don't set
3852 them, then try to output the default ones. */
3853
3854 static void
3855 riscv_write_out_attrs (void)
3856 {
3857 const char *arch_str, *priv_str, *p;
3858 /* versions[0]: major version.
3859 versions[1]: minor version.
3860 versions[2]: revision version. */
3861 unsigned versions[3] = {0}, number = 0;
3862 unsigned int i;
3863
3864 /* Re-write architecture elf attribute. */
3865 arch_str = riscv_arch_str (xlen, &riscv_subsets);
3866 bfd_elf_add_proc_attr_string (stdoutput, Tag_RISCV_arch, arch_str);
3867 xfree ((void *) arch_str);
3868
3869 /* For the file without any instruction, we don't set the default_priv_spec
3870 according to the privileged elf attributes since the md_assemble isn't
3871 called. */
3872 if (!start_assemble
3873 && !riscv_set_default_priv_spec (NULL))
3874 return;
3875
3876 /* If we already have set privileged elf attributes, then no need to do
3877 anything. Otherwise, don't generate or update them when no CSR and
3878 privileged instructions are used. */
3879 if (!explicit_priv_attr)
3880 return;
3881
3882 RISCV_GET_PRIV_SPEC_NAME (priv_str, default_priv_spec);
3883 p = priv_str;
3884 for (i = 0; *p; ++p)
3885 {
3886 if (*p == '.' && i < 3)
3887 {
3888 versions[i++] = number;
3889 number = 0;
3890 }
3891 else if (ISDIGIT (*p))
3892 number = (number * 10) + (*p - '0');
3893 else
3894 {
3895 as_bad (_("internal: bad RISC-V privileged spec (%s)"), priv_str);
3896 return;
3897 }
3898 }
3899 versions[i] = number;
3900
3901 /* Re-write privileged elf attributes. */
3902 bfd_elf_add_proc_attr_int (stdoutput, Tag_RISCV_priv_spec, versions[0]);
3903 bfd_elf_add_proc_attr_int (stdoutput, Tag_RISCV_priv_spec_minor, versions[1]);
3904 bfd_elf_add_proc_attr_int (stdoutput, Tag_RISCV_priv_spec_revision, versions[2]);
3905 }
3906
3907 /* Add the default contents for the .riscv.attributes section. */
3908
3909 static void
3910 riscv_set_public_attributes (void)
3911 {
3912 if (riscv_opts.arch_attr || explicit_attr)
3913 riscv_write_out_attrs ();
3914 }
3915
3916 /* Called after all assembly has been done. */
3917
3918 void
3919 riscv_md_end (void)
3920 {
3921 riscv_set_public_attributes ();
3922 }
3923
3924 /* Adjust the symbol table. */
3925
3926 void
3927 riscv_adjust_symtab (void)
3928 {
3929 bfd_map_over_sections (stdoutput, riscv_check_mapping_symbols, (char *) 0);
3930 elf_adjust_symtab ();
3931 }
3932
3933 /* Given a symbolic attribute NAME, return the proper integer value.
3934 Returns -1 if the attribute is not known. */
3935
3936 int
3937 riscv_convert_symbolic_attribute (const char *name)
3938 {
3939 static const struct
3940 {
3941 const char *name;
3942 const int tag;
3943 }
3944 attribute_table[] =
3945 {
3946 /* When you modify this table you should
3947 also modify the list in doc/c-riscv.texi. */
3948 #define T(tag) {#tag, Tag_RISCV_##tag}, {"Tag_RISCV_" #tag, Tag_RISCV_##tag}
3949 T(arch),
3950 T(priv_spec),
3951 T(priv_spec_minor),
3952 T(priv_spec_revision),
3953 T(unaligned_access),
3954 T(stack_align),
3955 #undef T
3956 };
3957
3958 if (name == NULL)
3959 return -1;
3960
3961 unsigned int i;
3962 for (i = 0; i < ARRAY_SIZE (attribute_table); i++)
3963 if (strcmp (name, attribute_table[i].name) == 0)
3964 return attribute_table[i].tag;
3965
3966 return -1;
3967 }
3968
3969 /* Parse a .attribute directive. */
3970
3971 static void
3972 s_riscv_attribute (int ignored ATTRIBUTE_UNUSED)
3973 {
3974 int tag = obj_elf_vendor_attribute (OBJ_ATTR_PROC);
3975 unsigned old_xlen;
3976 obj_attribute *attr;
3977
3978 explicit_attr = true;
3979 switch (tag)
3980 {
3981 case Tag_RISCV_arch:
3982 old_xlen = xlen;
3983 attr = elf_known_obj_attributes_proc (stdoutput);
3984 if (!start_assemble)
3985 riscv_set_arch (attr[Tag_RISCV_arch].s);
3986 else
3987 as_fatal (_("architecture elf attributes must set before "
3988 "any instructions"));
3989
3990 if (old_xlen != xlen)
3991 {
3992 /* We must re-init bfd again if xlen is changed. */
3993 unsigned long mach = xlen == 64 ? bfd_mach_riscv64 : bfd_mach_riscv32;
3994 bfd_find_target (riscv_target_format (), stdoutput);
3995
3996 if (! bfd_set_arch_mach (stdoutput, bfd_arch_riscv, mach))
3997 as_warn (_("could not set architecture and machine"));
3998 }
3999 break;
4000
4001 case Tag_RISCV_priv_spec:
4002 case Tag_RISCV_priv_spec_minor:
4003 case Tag_RISCV_priv_spec_revision:
4004 if (start_assemble)
4005 as_fatal (_("privileged elf attributes must set before "
4006 "any instructions"));
4007 break;
4008
4009 default:
4010 break;
4011 }
4012 }
4013
4014 /* RISC-V pseudo-ops table. */
4015 static const pseudo_typeS riscv_pseudo_table[] =
4016 {
4017 {"option", s_riscv_option, 0},
4018 {"half", cons, 2},
4019 {"word", cons, 4},
4020 {"dword", cons, 8},
4021 {"dtprelword", s_dtprel, 4},
4022 {"dtpreldword", s_dtprel, 8},
4023 {"bss", s_bss, 0},
4024 {"uleb128", s_riscv_leb128, 0},
4025 {"sleb128", s_riscv_leb128, 1},
4026 {"insn", s_riscv_insn, 0},
4027 {"attribute", s_riscv_attribute, 0},
4028
4029 { NULL, NULL, 0 },
4030 };
4031
4032 void
4033 riscv_pop_insert (void)
4034 {
4035 extern void pop_insert (const pseudo_typeS *);
4036
4037 pop_insert (riscv_pseudo_table);
4038 }