]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gas/config/tc-riscv.c
a46a6a4ec48442c6d798bcd526e62330664ea2ee
[thirdparty/binutils-gdb.git] / gas / config / tc-riscv.c
1 /* tc-riscv.c -- RISC-V assembler
2 Copyright (C) 2011-2023 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 (first bits enough to extract instruction length on a long opcode). */
47 insn_t insn_opcode;
48
49 /* The long encoded instruction bits ([0] is non-zero on a long opcode). */
50 char insn_long_opcode[RISCV_MAX_INSN_LEN];
51
52 /* The frag that contains the instruction. */
53 struct frag *frag;
54
55 /* The offset into FRAG of the first instruction byte. */
56 long where;
57
58 /* The relocs associated with the instruction, if any. */
59 fixS *fixp;
60 };
61
62 /* The identifier of the assembler macro we are expanding, if any. */
63 static int source_macro = -1;
64
65 /* All RISC-V CSR belong to one of these classes. */
66 enum riscv_csr_class
67 {
68 CSR_CLASS_NONE,
69
70 CSR_CLASS_I,
71 CSR_CLASS_I_32, /* rv32 only */
72 CSR_CLASS_F, /* f-ext only */
73 CSR_CLASS_ZKR, /* zkr only */
74 CSR_CLASS_V, /* rvv only */
75 CSR_CLASS_DEBUG, /* debug CSR */
76 CSR_CLASS_H, /* hypervisor */
77 CSR_CLASS_H_32, /* hypervisor, rv32 only */
78 CSR_CLASS_SMAIA, /* Smaia */
79 CSR_CLASS_SMAIA_32, /* Smaia, rv32 only */
80 CSR_CLASS_SMCNTRPMF, /* Smcntrpmf */
81 CSR_CLASS_SMCNTRPMF_32, /* Smcntrpmf, rv32 only */
82 CSR_CLASS_SMSTATEEN, /* Smstateen only */
83 CSR_CLASS_SMSTATEEN_32, /* Smstateen RV32 only */
84 CSR_CLASS_SSAIA, /* Ssaia */
85 CSR_CLASS_SSAIA_AND_H, /* Ssaia with H */
86 CSR_CLASS_SSAIA_32, /* Ssaia, rv32 only */
87 CSR_CLASS_SSAIA_AND_H_32, /* Ssaia with H, rv32 only */
88 CSR_CLASS_SSSTATEEN, /* S[ms]stateen only */
89 CSR_CLASS_SSSTATEEN_AND_H, /* S[ms]stateen only (with H) */
90 CSR_CLASS_SSSTATEEN_AND_H_32, /* S[ms]stateen RV32 only (with H) */
91 CSR_CLASS_SSCOFPMF, /* Sscofpmf only */
92 CSR_CLASS_SSCOFPMF_32, /* Sscofpmf RV32 only */
93 CSR_CLASS_SSTC, /* Sstc only */
94 CSR_CLASS_SSTC_AND_H, /* Sstc only (with H) */
95 CSR_CLASS_SSTC_32, /* Sstc RV32 only */
96 CSR_CLASS_SSTC_AND_H_32, /* Sstc RV32 only (with H) */
97 CSR_CLASS_XTHEADVECTOR, /* xtheadvector only */
98 };
99
100 /* This structure holds all restricted conditions for a CSR. */
101 struct riscv_csr_extra
102 {
103 /* Class to which this CSR belongs. Used to decide whether or
104 not this CSR is legal in the current -march context. */
105 enum riscv_csr_class csr_class;
106
107 /* CSR may have differnet numbers in the previous priv spec. */
108 unsigned address;
109
110 /* Record the CSR is defined/valid in which versions. */
111 enum riscv_spec_class define_version;
112
113 /* Record the CSR is aborted/invalid from which versions. If it isn't
114 aborted in the current version, then it should be PRIV_SPEC_CLASS_DRAFT. */
115 enum riscv_spec_class abort_version;
116
117 /* The CSR may have more than one setting. */
118 struct riscv_csr_extra *next;
119 };
120
121 /* This structure contains information about errors that occur within the
122 riscv_ip function */
123 struct riscv_ip_error
124 {
125 /* General error message */
126 const char* msg;
127
128 /* Statement that caused the error */
129 char* statement;
130
131 /* Missing extension that needs to be enabled */
132 const char* missing_ext;
133 };
134
135 #ifndef DEFAULT_ARCH
136 #define DEFAULT_ARCH "riscv64"
137 #endif
138
139 #ifndef DEFAULT_RISCV_ATTR
140 #define DEFAULT_RISCV_ATTR 0
141 #endif
142
143 /* Let riscv_after_parse_args set the default value according to xlen. */
144 #ifndef DEFAULT_RISCV_ARCH_WITH_EXT
145 #define DEFAULT_RISCV_ARCH_WITH_EXT NULL
146 #endif
147
148 /* Need to sync the version with RISC-V compiler. */
149 #ifndef DEFAULT_RISCV_ISA_SPEC
150 #define DEFAULT_RISCV_ISA_SPEC "20191213"
151 #endif
152
153 #ifndef DEFAULT_RISCV_PRIV_SPEC
154 #define DEFAULT_RISCV_PRIV_SPEC "1.11"
155 #endif
156
157 static const char default_arch[] = DEFAULT_ARCH;
158 static const char *default_arch_with_ext = DEFAULT_RISCV_ARCH_WITH_EXT;
159 static enum riscv_spec_class default_isa_spec = ISA_SPEC_CLASS_NONE;
160 static enum riscv_spec_class default_priv_spec = PRIV_SPEC_CLASS_NONE;
161
162 static unsigned xlen = 0; /* The width of an x-register. */
163 static unsigned abi_xlen = 0; /* The width of a pointer in the ABI. */
164 static bool rve_abi = false;
165 enum float_abi
166 {
167 FLOAT_ABI_DEFAULT = -1,
168 FLOAT_ABI_SOFT,
169 FLOAT_ABI_SINGLE,
170 FLOAT_ABI_DOUBLE,
171 FLOAT_ABI_QUAD
172 };
173 static enum float_abi float_abi = FLOAT_ABI_DEFAULT;
174
175 #define LOAD_ADDRESS_INSN (abi_xlen == 64 ? "ld" : "lw")
176 #define ADD32_INSN (xlen == 64 ? "addiw" : "addi")
177
178 static unsigned elf_flags = 0;
179
180 static bool probing_insn_operands;
181
182 /* Set the default_isa_spec. Return 0 if the spec isn't supported.
183 Otherwise, return 1. */
184
185 static int
186 riscv_set_default_isa_spec (const char *s)
187 {
188 enum riscv_spec_class class = ISA_SPEC_CLASS_NONE;
189 RISCV_GET_ISA_SPEC_CLASS (s, class);
190 if (class == ISA_SPEC_CLASS_NONE)
191 {
192 as_bad ("unknown default ISA spec `%s' set by "
193 "-misa-spec or --with-isa-spec", s);
194 return 0;
195 }
196 else
197 default_isa_spec = class;
198 return 1;
199 }
200
201 /* Set the default_priv_spec. Find the privileged elf attributes when
202 the input string is NULL. Return 0 if the spec isn't supported.
203 Otherwise, return 1. */
204
205 static int
206 riscv_set_default_priv_spec (const char *s)
207 {
208 enum riscv_spec_class class = PRIV_SPEC_CLASS_NONE;
209 unsigned major, minor, revision;
210 obj_attribute *attr;
211
212 RISCV_GET_PRIV_SPEC_CLASS (s, class);
213 if (class != PRIV_SPEC_CLASS_NONE)
214 {
215 default_priv_spec = class;
216 return 1;
217 }
218
219 if (s != NULL)
220 {
221 as_bad (_("unknown default privileged spec `%s' set by "
222 "-mpriv-spec or --with-priv-spec"), s);
223 return 0;
224 }
225
226 /* Set the default_priv_spec by the privileged elf attributes. */
227 attr = elf_known_obj_attributes_proc (stdoutput);
228 major = (unsigned) attr[Tag_RISCV_priv_spec].i;
229 minor = (unsigned) attr[Tag_RISCV_priv_spec_minor].i;
230 revision = (unsigned) attr[Tag_RISCV_priv_spec_revision].i;
231 /* Version 0.0.0 is the default value and meningless. */
232 if (major == 0 && minor == 0 && revision == 0)
233 return 1;
234
235 riscv_get_priv_spec_class_from_numbers (major, minor, revision, &class);
236 if (class != PRIV_SPEC_CLASS_NONE)
237 {
238 default_priv_spec = class;
239 return 1;
240 }
241
242 /* Still can not find the privileged spec class. */
243 as_bad (_("unknown default privileged spec `%d.%d.%d' set by "
244 "privileged elf attributes"), major, minor, revision);
245 return 0;
246 }
247
248 /* This is the set of options which the .option pseudo-op may modify. */
249 struct riscv_set_options
250 {
251 int pic; /* Generate position-independent code. */
252 int rvc; /* Generate RVC code. */
253 int relax; /* Emit relocs the linker is allowed to relax. */
254 int arch_attr; /* Emit architecture and privileged elf attributes. */
255 int csr_check; /* Enable the CSR checking. */
256 };
257
258 static struct riscv_set_options riscv_opts =
259 {
260 0, /* pic */
261 0, /* rvc */
262 1, /* relax */
263 DEFAULT_RISCV_ATTR, /* arch_attr */
264 0, /* csr_check */
265 };
266
267 /* Enable or disable the rvc flags for riscv_opts. Turn on the rvc flag
268 for elf_flags once we have enabled c extension. */
269
270 static void
271 riscv_set_rvc (bool rvc_value)
272 {
273 if (rvc_value)
274 elf_flags |= EF_RISCV_RVC;
275
276 riscv_opts.rvc = rvc_value;
277 }
278
279 /* Turn on the tso flag for elf_flags once we have enabled ztso extension. */
280
281 static void
282 riscv_set_tso (void)
283 {
284 elf_flags |= EF_RISCV_TSO;
285 }
286
287 /* The linked list hanging off of .subsets_list records all enabled extensions,
288 which are parsed from the architecture string. The architecture string can
289 be set by the -march option, the elf architecture attributes, and the
290 --with-arch configure option. */
291 static riscv_parse_subset_t riscv_rps_as =
292 {
293 NULL, /* subset_list, we will set it later once
294 riscv_opts_stack is created or updated. */
295 as_bad, /* error_handler. */
296 &xlen, /* xlen. */
297 &default_isa_spec, /* isa_spec. */
298 true, /* check_unknown_prefixed_ext. */
299 };
300
301 /* Update the architecture string in the subset_list. */
302
303 static void
304 riscv_reset_subsets_list_arch_str (void)
305 {
306 riscv_subset_list_t *subsets = riscv_rps_as.subset_list;
307 if (subsets->arch_str != NULL)
308 free ((void *) subsets->arch_str);
309 subsets->arch_str = riscv_arch_str (xlen, subsets);
310 }
311
312 /* This structure is used to hold a stack of .option values. */
313 struct riscv_option_stack
314 {
315 struct riscv_option_stack *next;
316 struct riscv_set_options options;
317 riscv_subset_list_t *subset_list;
318 };
319
320 static struct riscv_option_stack *riscv_opts_stack = NULL;
321
322 /* Set which ISA and extensions are available. */
323
324 static void
325 riscv_set_arch (const char *s)
326 {
327 if (s != NULL && strcmp (s, "") == 0)
328 {
329 as_bad (_("the architecture string of -march and elf architecture "
330 "attributes cannot be empty"));
331 return;
332 }
333
334 if (riscv_rps_as.subset_list == NULL)
335 {
336 riscv_rps_as.subset_list = XNEW (riscv_subset_list_t);
337 riscv_rps_as.subset_list->head = NULL;
338 riscv_rps_as.subset_list->tail = NULL;
339 riscv_rps_as.subset_list->arch_str = NULL;
340 }
341 riscv_release_subset_list (riscv_rps_as.subset_list);
342 riscv_parse_subset (&riscv_rps_as, s);
343 riscv_reset_subsets_list_arch_str ();
344
345 riscv_set_rvc (false);
346 if (riscv_subset_supports (&riscv_rps_as, "c")
347 || riscv_subset_supports (&riscv_rps_as, "zca"))
348 riscv_set_rvc (true);
349
350 if (riscv_subset_supports (&riscv_rps_as, "ztso"))
351 riscv_set_tso ();
352 }
353
354 /* Indicate -mabi option is explictly set. */
355 static bool explicit_mabi = false;
356
357 /* Set the abi information. */
358
359 static void
360 riscv_set_abi (unsigned new_xlen, enum float_abi new_float_abi, bool rve)
361 {
362 abi_xlen = new_xlen;
363 float_abi = new_float_abi;
364 rve_abi = rve;
365 }
366
367 /* If the -mabi option isn't set, then set the abi according to the
368 ISA string. Otherwise, check if there is any conflict. */
369
370 static void
371 riscv_set_abi_by_arch (void)
372 {
373 if (!explicit_mabi)
374 {
375 if (riscv_subset_supports (&riscv_rps_as, "q"))
376 riscv_set_abi (xlen, FLOAT_ABI_QUAD, false);
377 else if (riscv_subset_supports (&riscv_rps_as, "d"))
378 riscv_set_abi (xlen, FLOAT_ABI_DOUBLE, false);
379 else if (riscv_subset_supports (&riscv_rps_as, "e"))
380 riscv_set_abi (xlen, FLOAT_ABI_SOFT, true);
381 else
382 riscv_set_abi (xlen, FLOAT_ABI_SOFT, false);
383 }
384 else
385 {
386 gas_assert (abi_xlen != 0 && xlen != 0 && float_abi != FLOAT_ABI_DEFAULT);
387 if (abi_xlen > xlen)
388 as_bad ("can't have %d-bit ABI on %d-bit ISA", abi_xlen, xlen);
389 else if (abi_xlen < xlen)
390 as_bad ("%d-bit ABI not yet supported on %d-bit ISA", abi_xlen, xlen);
391
392 if (riscv_subset_supports (&riscv_rps_as, "e") && !rve_abi)
393 as_bad ("only ilp32e/lp64e ABI are supported for e extension");
394
395 if (float_abi == FLOAT_ABI_SINGLE
396 && !riscv_subset_supports (&riscv_rps_as, "f"))
397 as_bad ("ilp32f/lp64f ABI can't be used when f extension "
398 "isn't supported");
399 else if (float_abi == FLOAT_ABI_DOUBLE
400 && !riscv_subset_supports (&riscv_rps_as, "d"))
401 as_bad ("ilp32d/lp64d ABI can't be used when d extension "
402 "isn't supported");
403 else if (float_abi == FLOAT_ABI_QUAD
404 && !riscv_subset_supports (&riscv_rps_as, "q"))
405 as_bad ("ilp32q/lp64q ABI can't be used when q extension "
406 "isn't supported");
407 }
408
409 /* Update the EF_RISCV_FLOAT_ABI field of elf_flags. */
410 elf_flags &= ~EF_RISCV_FLOAT_ABI;
411 elf_flags |= float_abi << 1;
412
413 if (rve_abi)
414 elf_flags |= EF_RISCV_RVE;
415 }
416
417 /* Handle of the OPCODE hash table. */
418 static htab_t op_hash = NULL;
419
420 /* Handle of the type of .insn hash table. */
421 static htab_t insn_type_hash = NULL;
422
423 /* This array holds the chars that always start a comment. If the
424 pre-processor is disabled, these aren't very useful. */
425 const char comment_chars[] = "#";
426
427 /* This array holds the chars that only start a comment at the beginning of
428 a line. If the line seems to have the form '# 123 filename'
429 .line and .file directives will appear in the pre-processed output
430
431 Note that input_file.c hand checks for '#' at the beginning of the
432 first line of the input file. This is because the compiler outputs
433 #NO_APP at the beginning of its output.
434
435 Also note that C style comments are always supported. */
436 const char line_comment_chars[] = "#";
437
438 /* This array holds machine specific line separator characters. */
439 const char line_separator_chars[] = ";";
440
441 /* Chars that can be used to separate mant from exp in floating point nums. */
442 const char EXP_CHARS[] = "eE";
443
444 /* Chars that mean this number is a floating point constant.
445 As in 0f12.456 or 0d1.2345e12. */
446 const char FLT_CHARS[] = "rRsSfFdDxXpPhH";
447
448 /* Indicate we are already assemble any instructions or not. */
449 static bool start_assemble = false;
450
451 /* Indicate ELF attributes are explicitly set. */
452 static bool explicit_attr = false;
453
454 /* Indicate CSR or priv instructions are explicitly used. */
455 static bool explicit_priv_attr = false;
456
457 static char *expr_parse_end;
458
459 /* Macros for encoding relaxation state for RVC branches and far jumps. */
460 #define RELAX_BRANCH_ENCODE(uncond, rvc, length) \
461 ((relax_substateT) \
462 (0xc0000000 \
463 | ((uncond) ? 1 : 0) \
464 | ((rvc) ? 2 : 0) \
465 | ((length) << 2)))
466 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
467 #define RELAX_BRANCH_LENGTH(i) (((i) >> 2) & 0xF)
468 #define RELAX_BRANCH_RVC(i) (((i) & 2) != 0)
469 #define RELAX_BRANCH_UNCOND(i) (((i) & 1) != 0)
470
471 /* Is the given value a sign-extended 32-bit value? */
472 #define IS_SEXT_32BIT_NUM(x) \
473 (((x) &~ (offsetT) 0x7fffffff) == 0 \
474 || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
475
476 /* Is the given value a zero-extended 32-bit value? Or a negated one? */
477 #define IS_ZEXT_32BIT_NUM(x) \
478 (((x) &~ (offsetT) 0xffffffff) == 0 \
479 || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
480
481 /* Change INSN's opcode so that the operand given by FIELD has value VALUE.
482 INSN is a riscv_cl_insn structure and VALUE is evaluated exactly once. */
483 #define INSERT_OPERAND(FIELD, INSN, VALUE) \
484 INSERT_BITS ((INSN).insn_opcode, VALUE, OP_MASK_##FIELD, OP_SH_##FIELD)
485
486 #define INSERT_IMM(n, s, INSN, VALUE) \
487 INSERT_BITS ((INSN).insn_opcode, VALUE, (1ULL<<n) - 1, s)
488
489 /* Determine if an instruction matches an opcode. */
490 #define OPCODE_MATCHES(OPCODE, OP) \
491 (((OPCODE) & MASK_##OP) == MATCH_##OP)
492
493 /* Create a new mapping symbol for the transition to STATE. */
494
495 static void
496 make_mapping_symbol (enum riscv_seg_mstate state,
497 valueT value,
498 fragS *frag,
499 const char *arch_str,
500 bool odd_data_padding)
501 {
502 const char *name;
503 char *buff = NULL;
504 switch (state)
505 {
506 case MAP_DATA:
507 name = "$d";
508 break;
509 case MAP_INSN:
510 if (arch_str != NULL)
511 {
512 size_t size = strlen (arch_str) + 3; /* "$x" + '\0' */
513 buff = xmalloc (size);
514 snprintf (buff, size, "$x%s", arch_str);
515 name = buff;
516 }
517 else
518 name = "$x";
519 break;
520 default:
521 abort ();
522 }
523
524 symbolS *symbol = symbol_new (name, now_seg, frag, value);
525 symbol_get_bfdsym (symbol)->flags |= (BSF_NO_FLAGS | BSF_LOCAL);
526 if (arch_str != NULL)
527 {
528 /* Store current $x+arch into tc_segment_info. */
529 seg_info (now_seg)->tc_segment_info_data.arch_map_symbol = symbol;
530 xfree ((void *) buff);
531 }
532
533 /* If .fill or other data filling directive generates zero sized data,
534 then mapping symbol for the following code will have the same value.
535
536 Please see gas/testsuite/gas/riscv/mapping.s: .text.zero.fill.first
537 and .text.zero.fill.last. */
538 symbolS *first = frag->tc_frag_data.first_map_symbol;
539 symbolS *last = frag->tc_frag_data.last_map_symbol;
540 symbolS *removed = NULL;
541 if (value == 0)
542 {
543 if (first != NULL)
544 {
545 know (S_GET_VALUE (first) == S_GET_VALUE (symbol)
546 && first == last);
547 /* Remove the old one. */
548 removed = first;
549 }
550 frag->tc_frag_data.first_map_symbol = symbol;
551 }
552 else if (last != NULL)
553 {
554 /* The mapping symbols should be added in offset order. */
555 know (S_GET_VALUE (last) <= S_GET_VALUE (symbol));
556 /* Remove the old one. */
557 if (S_GET_VALUE (last) == S_GET_VALUE (symbol))
558 removed = last;
559 }
560 frag->tc_frag_data.last_map_symbol = symbol;
561
562 if (removed == NULL)
563 return;
564
565 if (odd_data_padding)
566 {
567 /* If the removed mapping symbol is $x+arch, then add it back to
568 the next $x. */
569 const char *str = strncmp (S_GET_NAME (removed), "$xrv", 4) == 0
570 ? S_GET_NAME (removed) + 2 : NULL;
571 make_mapping_symbol (MAP_INSN, frag->fr_fix + 1, frag, str,
572 false/* odd_data_padding */);
573 }
574 symbol_remove (removed, &symbol_rootP, &symbol_lastP);
575 }
576
577 /* Set the mapping state for frag_now. */
578
579 void
580 riscv_mapping_state (enum riscv_seg_mstate to_state,
581 int max_chars,
582 bool fr_align_code)
583 {
584 enum riscv_seg_mstate from_state =
585 seg_info (now_seg)->tc_segment_info_data.map_state;
586 bool reset_seg_arch_str = false;
587
588 if (!SEG_NORMAL (now_seg)
589 /* For now we only add the mapping symbols to text sections.
590 Therefore, the dis-assembler only show the actual contents
591 distribution for text. Other sections will be shown as
592 data without the details. */
593 || !subseg_text_p (now_seg))
594 return;
595
596 /* The mapping symbol should be emitted if not in the right
597 mapping state. */
598 symbolS *seg_arch_symbol =
599 seg_info (now_seg)->tc_segment_info_data.arch_map_symbol;
600 if (to_state == MAP_INSN && seg_arch_symbol == 0)
601 {
602 /* Always add $x+arch at the first instruction of section. */
603 reset_seg_arch_str = true;
604 }
605 else if (seg_arch_symbol != 0
606 && to_state == MAP_INSN
607 && !fr_align_code
608 && strcmp (riscv_rps_as.subset_list->arch_str,
609 S_GET_NAME (seg_arch_symbol) + 2) != 0)
610 {
611 reset_seg_arch_str = true;
612 }
613 else if (from_state == to_state)
614 return;
615
616 valueT value = (valueT) (frag_now_fix () - max_chars);
617 seg_info (now_seg)->tc_segment_info_data.map_state = to_state;
618 const char *arch_str = reset_seg_arch_str
619 ? riscv_rps_as.subset_list->arch_str : NULL;
620 make_mapping_symbol (to_state, value, frag_now, arch_str,
621 false/* odd_data_padding */);
622 }
623
624 /* Add the odd bytes of paddings for riscv_handle_align. */
625
626 static void
627 riscv_add_odd_padding_symbol (fragS *frag)
628 {
629 /* If there was already a mapping symbol, it should be
630 removed in the make_mapping_symbol.
631
632 Please see gas/testsuite/gas/riscv/mapping.s: .text.odd.align.*. */
633 make_mapping_symbol (MAP_DATA, frag->fr_fix, frag,
634 NULL/* arch_str */, true/* odd_data_padding */);
635 }
636
637 /* Remove any excess mapping symbols generated for alignment frags in
638 SEC. We may have created a mapping symbol before a zero byte
639 alignment; remove it if there's a mapping symbol after the
640 alignment. */
641
642 static void
643 riscv_check_mapping_symbols (bfd *abfd ATTRIBUTE_UNUSED,
644 asection *sec,
645 void *dummy ATTRIBUTE_UNUSED)
646 {
647 segment_info_type *seginfo = seg_info (sec);
648 fragS *fragp;
649
650 if (seginfo == NULL || seginfo->frchainP == NULL)
651 return;
652
653 for (fragp = seginfo->frchainP->frch_root;
654 fragp != NULL;
655 fragp = fragp->fr_next)
656 {
657 symbolS *last = fragp->tc_frag_data.last_map_symbol;
658 fragS *next = fragp->fr_next;
659
660 if (last == NULL || next == NULL)
661 continue;
662
663 /* Check the last mapping symbol if it is at the boundary of
664 fragment. */
665 if (S_GET_VALUE (last) < next->fr_address)
666 continue;
667 know (S_GET_VALUE (last) == next->fr_address);
668
669 do
670 {
671 symbolS *next_first = next->tc_frag_data.first_map_symbol;
672 if (next_first != NULL)
673 {
674 /* The last mapping symbol overlaps with another one
675 which at the start of the next frag.
676
677 Please see the gas/testsuite/gas/riscv/mapping.s:
678 .text.zero.fill.align.A and .text.zero.fill.align.B. */
679 know (S_GET_VALUE (last) == S_GET_VALUE (next_first));
680 symbolS *removed = last;
681 if (strncmp (S_GET_NAME (last), "$xrv", 4) == 0
682 && strcmp (S_GET_NAME (next_first), "$x") == 0)
683 removed = next_first;
684 symbol_remove (removed, &symbol_rootP, &symbol_lastP);
685 break;
686 }
687
688 if (next->fr_next == NULL)
689 {
690 /* The last mapping symbol is at the end of the section.
691
692 Please see the gas/testsuite/gas/riscv/mapping.s:
693 .text.last.section. */
694 know (next->fr_fix == 0 && next->fr_var == 0);
695 symbol_remove (last, &symbol_rootP, &symbol_lastP);
696 break;
697 }
698
699 /* Since we may have empty frags without any mapping symbols,
700 keep looking until the non-empty frag. */
701 if (next->fr_address != next->fr_next->fr_address)
702 break;
703
704 next = next->fr_next;
705 }
706 while (next != NULL);
707 }
708 }
709
710 /* The default target format to use. */
711
712 const char *
713 riscv_target_format (void)
714 {
715 if (target_big_endian)
716 return xlen == 64 ? "elf64-bigriscv" : "elf32-bigriscv";
717 else
718 return xlen == 64 ? "elf64-littleriscv" : "elf32-littleriscv";
719 }
720
721 /* Return the length of instruction INSN. */
722
723 static inline unsigned int
724 insn_length (const struct riscv_cl_insn *insn)
725 {
726 return riscv_insn_length (insn->insn_opcode);
727 }
728
729 /* Initialise INSN from opcode entry MO. Leave its position unspecified. */
730
731 static void
732 create_insn (struct riscv_cl_insn *insn, const struct riscv_opcode *mo)
733 {
734 insn->insn_mo = mo;
735 insn->insn_opcode = mo->match;
736 insn->insn_long_opcode[0] = 0;
737 insn->frag = NULL;
738 insn->where = 0;
739 insn->fixp = NULL;
740 }
741
742 /* Install INSN at the location specified by its "frag" and "where" fields. */
743
744 static void
745 install_insn (const struct riscv_cl_insn *insn)
746 {
747 char *f = insn->frag->fr_literal + insn->where;
748 if (insn->insn_long_opcode[0] != 0)
749 memcpy (f, insn->insn_long_opcode, insn_length (insn));
750 else
751 number_to_chars_littleendian (f, insn->insn_opcode, insn_length (insn));
752 }
753
754 /* Move INSN to offset WHERE in FRAG. Adjust the fixups accordingly
755 and install the opcode in the new location. */
756
757 static void
758 move_insn (struct riscv_cl_insn *insn, fragS *frag, long where)
759 {
760 insn->frag = frag;
761 insn->where = where;
762 if (insn->fixp != NULL)
763 {
764 insn->fixp->fx_frag = frag;
765 insn->fixp->fx_where = where;
766 }
767 install_insn (insn);
768 }
769
770 /* Add INSN to the end of the output. */
771
772 static void
773 add_fixed_insn (struct riscv_cl_insn *insn)
774 {
775 char *f = frag_more (insn_length (insn));
776 move_insn (insn, frag_now, f - frag_now->fr_literal);
777 }
778
779 static void
780 add_relaxed_insn (struct riscv_cl_insn *insn, int max_chars, int var,
781 relax_substateT subtype, symbolS *symbol, offsetT offset)
782 {
783 frag_grow (max_chars);
784 move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
785 frag_var (rs_machine_dependent, max_chars, var,
786 subtype, symbol, offset, NULL);
787 }
788
789 /* Compute the length of a branch sequence, and adjust the stored length
790 accordingly. If FRAGP is NULL, the worst-case length is returned. */
791
792 static unsigned
793 relaxed_branch_length (fragS *fragp, asection *sec, int update)
794 {
795 int jump, rvc, length = 8;
796
797 if (!fragp)
798 return length;
799
800 jump = RELAX_BRANCH_UNCOND (fragp->fr_subtype);
801 rvc = RELAX_BRANCH_RVC (fragp->fr_subtype);
802 length = RELAX_BRANCH_LENGTH (fragp->fr_subtype);
803
804 /* Assume jumps are in range; the linker will catch any that aren't. */
805 length = jump ? 4 : 8;
806
807 if (fragp->fr_symbol != NULL
808 && S_IS_DEFINED (fragp->fr_symbol)
809 && !S_IS_WEAK (fragp->fr_symbol)
810 && sec == S_GET_SEGMENT (fragp->fr_symbol))
811 {
812 offsetT val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
813 bfd_vma rvc_range = jump ? RVC_JUMP_REACH : RVC_BRANCH_REACH;
814 val -= fragp->fr_address + fragp->fr_fix;
815
816 if (rvc && (bfd_vma)(val + rvc_range/2) < rvc_range)
817 length = 2;
818 else if ((bfd_vma)(val + RISCV_BRANCH_REACH/2) < RISCV_BRANCH_REACH)
819 length = 4;
820 else if (!jump && rvc)
821 length = 6;
822 }
823
824 if (update)
825 fragp->fr_subtype = RELAX_BRANCH_ENCODE (jump, rvc, length);
826
827 return length;
828 }
829
830 /* Information about an opcode name, mnemonics and its value. */
831 struct opcode_name_t
832 {
833 const char *name;
834 unsigned int val;
835 };
836
837 /* List for all supported opcode name. */
838 static const struct opcode_name_t opcode_name_list[] =
839 {
840 {"C0", 0x0},
841 {"C1", 0x1},
842 {"C2", 0x2},
843
844 {"LOAD", 0x03},
845 {"LOAD_FP", 0x07},
846 {"CUSTOM_0", 0x0b},
847 {"MISC_MEM", 0x0f},
848 {"OP_IMM", 0x13},
849 {"AUIPC", 0x17},
850 {"OP_IMM_32", 0x1b},
851 /* 48b 0x1f. */
852
853 {"STORE", 0x23},
854 {"STORE_FP", 0x27},
855 {"CUSTOM_1", 0x2b},
856 {"AMO", 0x2f},
857 {"OP", 0x33},
858 {"LUI", 0x37},
859 {"OP_32", 0x3b},
860 /* 64b 0x3f. */
861
862 {"MADD", 0x43},
863 {"MSUB", 0x47},
864 {"NMADD", 0x4f},
865 {"NMSUB", 0x4b},
866 {"OP_FP", 0x53},
867 {"OP_V", 0x57},
868 {"CUSTOM_2", 0x5b},
869 /* 48b 0x5f. */
870
871 {"BRANCH", 0x63},
872 {"JALR", 0x67},
873 /*reserved 0x5b. */
874 {"JAL", 0x6f},
875 {"SYSTEM", 0x73},
876 /*reserved 0x77. */
877 {"CUSTOM_3", 0x7b},
878 /* >80b 0x7f. */
879
880 {NULL, 0}
881 };
882
883 /* Hash table for lookup opcode name. */
884 static htab_t opcode_names_hash = NULL;
885
886 /* Initialization for hash table of opcode name. */
887
888 static void
889 init_opcode_names_hash (void)
890 {
891 const struct opcode_name_t *opcode;
892
893 for (opcode = &opcode_name_list[0]; opcode->name != NULL; ++opcode)
894 if (str_hash_insert (opcode_names_hash, opcode->name, opcode, 0) != NULL)
895 as_fatal (_("internal: duplicate %s"), opcode->name);
896 }
897
898 /* Find `s` is a valid opcode name or not, return the opcode name info
899 if found. */
900
901 static const struct opcode_name_t *
902 opcode_name_lookup (char **s)
903 {
904 char *e;
905 char save_c;
906 struct opcode_name_t *o;
907
908 /* Find end of name. */
909 e = *s;
910 if (is_name_beginner (*e))
911 ++e;
912 while (is_part_of_name (*e))
913 ++e;
914
915 /* Terminate name. */
916 save_c = *e;
917 *e = '\0';
918
919 o = (struct opcode_name_t *) str_hash_find (opcode_names_hash, *s);
920
921 /* Advance to next token if one was recognized. */
922 if (o)
923 *s = e;
924
925 *e = save_c;
926 expr_parse_end = e;
927
928 return o;
929 }
930
931 /* All RISC-V registers belong to one of these classes. */
932 enum reg_class
933 {
934 RCLASS_GPR,
935 RCLASS_FPR,
936 RCLASS_VECR,
937 RCLASS_VECM,
938 RCLASS_MAX,
939
940 RCLASS_CSR
941 };
942
943 static htab_t reg_names_hash = NULL;
944 static htab_t csr_extra_hash = NULL;
945
946 #define ENCODE_REG_HASH(cls, n) \
947 ((void *)(uintptr_t)((n) * RCLASS_MAX + (cls) + 1))
948 #define DECODE_REG_CLASS(hash) (((uintptr_t)(hash) - 1) % RCLASS_MAX)
949 #define DECODE_REG_NUM(hash) (((uintptr_t)(hash) - 1) / RCLASS_MAX)
950
951 static void
952 hash_reg_name (enum reg_class class, const char *name, unsigned n)
953 {
954 void *hash = ENCODE_REG_HASH (class, n);
955 if (str_hash_insert (reg_names_hash, name, hash, 0) != NULL)
956 as_fatal (_("internal: duplicate %s"), name);
957 }
958
959 static void
960 hash_reg_names (enum reg_class class, const char names[][NRC], unsigned n)
961 {
962 unsigned i;
963
964 for (i = 0; i < n; i++)
965 hash_reg_name (class, names[i], i);
966 }
967
968 /* Init hash table csr_extra_hash to handle CSR. */
969
970 static void
971 riscv_init_csr_hash (const char *name,
972 unsigned address,
973 enum riscv_csr_class class,
974 enum riscv_spec_class define_version,
975 enum riscv_spec_class abort_version)
976 {
977 struct riscv_csr_extra *entry, *pre_entry;
978 bool need_enrty = true;
979
980 pre_entry = NULL;
981 entry = (struct riscv_csr_extra *) str_hash_find (csr_extra_hash, name);
982 while (need_enrty && entry != NULL)
983 {
984 if (entry->csr_class == class
985 && entry->address == address
986 && entry->define_version == define_version
987 && entry->abort_version == abort_version)
988 need_enrty = false;
989 pre_entry = entry;
990 entry = entry->next;
991 }
992
993 /* Duplicate CSR. */
994 if (!need_enrty)
995 return;
996
997 entry = notes_alloc (sizeof (*entry));
998 entry->csr_class = class;
999 entry->address = address;
1000 entry->define_version = define_version;
1001 entry->abort_version = abort_version;
1002 entry->next = NULL;
1003
1004 if (pre_entry == NULL)
1005 str_hash_insert (csr_extra_hash, name, entry, 0);
1006 else
1007 pre_entry->next = entry;
1008 }
1009
1010 /* Return the CSR address after checking the ISA dependency and
1011 the privileged spec version.
1012
1013 There are one warning and two errors for CSR,
1014
1015 Invalid CSR: the CSR was defined, but isn't allowed for the current ISA
1016 or the privileged spec, report warning only if -mcsr-check is set.
1017 Unknown CSR: the CSR has never been defined, report error.
1018 Improper CSR: the CSR number over the range (> 0xfff), report error. */
1019
1020 static unsigned int
1021 riscv_csr_address (const char *csr_name,
1022 struct riscv_csr_extra *entry)
1023 {
1024 struct riscv_csr_extra *saved_entry = entry;
1025 enum riscv_csr_class csr_class = entry->csr_class;
1026 bool need_check_version = false;
1027 bool is_rv32_only = false;
1028 bool is_h_required = false;
1029 const char* extension = NULL;
1030
1031 switch (csr_class)
1032 {
1033 case CSR_CLASS_I_32:
1034 is_rv32_only = true;
1035 /* Fall through. */
1036 case CSR_CLASS_I:
1037 need_check_version = true;
1038 extension = "i";
1039 break;
1040 case CSR_CLASS_H_32:
1041 is_rv32_only = true;
1042 /* Fall through. */
1043 case CSR_CLASS_H:
1044 extension = "h";
1045 break;
1046 case CSR_CLASS_F:
1047 extension = "f";
1048 break;
1049 case CSR_CLASS_ZKR:
1050 extension = "zkr";
1051 break;
1052 case CSR_CLASS_V:
1053 extension = "zve32x";
1054 break;
1055 case CSR_CLASS_SMAIA_32:
1056 is_rv32_only = true;
1057 /* Fall through. */
1058 case CSR_CLASS_SMAIA:
1059 extension = "smaia";
1060 break;
1061 case CSR_CLASS_SMCNTRPMF_32:
1062 is_rv32_only = true;
1063 /* Fall through. */
1064 case CSR_CLASS_SMCNTRPMF:
1065 need_check_version = true;
1066 extension = "smcntrpmf";
1067 break;
1068 case CSR_CLASS_SMSTATEEN_32:
1069 is_rv32_only = true;
1070 /* Fall through. */
1071 case CSR_CLASS_SMSTATEEN:
1072 extension = "smstateen";
1073 break;
1074 case CSR_CLASS_SSAIA:
1075 case CSR_CLASS_SSAIA_AND_H:
1076 case CSR_CLASS_SSAIA_32:
1077 case CSR_CLASS_SSAIA_AND_H_32:
1078 is_rv32_only = (csr_class == CSR_CLASS_SSAIA_32
1079 || csr_class == CSR_CLASS_SSAIA_AND_H_32);
1080 is_h_required = (csr_class == CSR_CLASS_SSAIA_AND_H
1081 || csr_class == CSR_CLASS_SSAIA_AND_H_32);
1082 extension = "ssaia";
1083 break;
1084 case CSR_CLASS_SSSTATEEN_AND_H_32:
1085 is_rv32_only = true;
1086 /* Fall through. */
1087 case CSR_CLASS_SSSTATEEN_AND_H:
1088 is_h_required = true;
1089 /* Fall through. */
1090 case CSR_CLASS_SSSTATEEN:
1091 extension = "ssstateen";
1092 break;
1093 case CSR_CLASS_SSCOFPMF_32:
1094 is_rv32_only = true;
1095 /* Fall through. */
1096 case CSR_CLASS_SSCOFPMF:
1097 extension = "sscofpmf";
1098 break;
1099 case CSR_CLASS_SSTC:
1100 case CSR_CLASS_SSTC_AND_H:
1101 case CSR_CLASS_SSTC_32:
1102 case CSR_CLASS_SSTC_AND_H_32:
1103 is_rv32_only = (csr_class == CSR_CLASS_SSTC_32
1104 || csr_class == CSR_CLASS_SSTC_AND_H_32);
1105 is_h_required = (csr_class == CSR_CLASS_SSTC_AND_H
1106 || csr_class == CSR_CLASS_SSTC_AND_H_32);
1107 extension = "sstc";
1108 break;
1109 case CSR_CLASS_DEBUG:
1110 break;
1111 case CSR_CLASS_XTHEADVECTOR:
1112 extension = "xtheadvector";
1113 break;
1114 default:
1115 as_bad (_("internal: bad RISC-V CSR class (0x%x)"), csr_class);
1116 }
1117
1118 if (riscv_opts.csr_check)
1119 {
1120 if (is_rv32_only && xlen != 32)
1121 as_warn (_("invalid CSR `%s', needs rv32i extension"), csr_name);
1122 if (is_h_required && !riscv_subset_supports (&riscv_rps_as, "h"))
1123 as_warn (_("invalid CSR `%s', needs `h' extension"), csr_name);
1124
1125 if (extension != NULL
1126 && !riscv_subset_supports (&riscv_rps_as, extension))
1127 as_warn (_("invalid CSR `%s', needs `%s' extension"),
1128 csr_name, extension);
1129 }
1130
1131 while (entry != NULL)
1132 {
1133 if (!need_check_version
1134 || (default_priv_spec >= entry->define_version
1135 && default_priv_spec < entry->abort_version))
1136 {
1137 /* Find the CSR according to the specific version. */
1138 return entry->address;
1139 }
1140 entry = entry->next;
1141 }
1142
1143 /* Can not find the CSR address from the chosen privileged version,
1144 so use the newly defined value. */
1145 if (riscv_opts.csr_check)
1146 {
1147 const char *priv_name = NULL;
1148 RISCV_GET_PRIV_SPEC_NAME (priv_name, default_priv_spec);
1149 if (priv_name != NULL)
1150 as_warn (_("invalid CSR `%s' for the privileged spec `%s'"),
1151 csr_name, priv_name);
1152 }
1153
1154 return saved_entry->address;
1155 }
1156
1157 /* Return -1 if the CSR has never been defined. Otherwise, return
1158 the address. */
1159
1160 static unsigned int
1161 reg_csr_lookup_internal (const char *s)
1162 {
1163 struct riscv_csr_extra *r =
1164 (struct riscv_csr_extra *) str_hash_find (csr_extra_hash, s);
1165
1166 if (r == NULL)
1167 return -1U;
1168
1169 return riscv_csr_address (s, r);
1170 }
1171
1172 static unsigned int
1173 reg_lookup_internal (const char *s, enum reg_class class)
1174 {
1175 void *r;
1176
1177 if (class == RCLASS_CSR)
1178 return reg_csr_lookup_internal (s);
1179
1180 r = str_hash_find (reg_names_hash, s);
1181 if (r == NULL || DECODE_REG_CLASS (r) != class)
1182 return -1;
1183
1184 if (riscv_subset_supports (&riscv_rps_as, "e")
1185 && class == RCLASS_GPR
1186 && DECODE_REG_NUM (r) > 15)
1187 return -1;
1188
1189 return DECODE_REG_NUM (r);
1190 }
1191
1192 static bool
1193 reg_lookup (char **s, enum reg_class class, unsigned int *regnop)
1194 {
1195 char *e;
1196 char save_c;
1197 int reg = -1;
1198
1199 /* Find end of name. */
1200 e = *s;
1201 if (is_name_beginner (*e))
1202 ++e;
1203 while (is_part_of_name (*e))
1204 ++e;
1205
1206 /* Terminate name. */
1207 save_c = *e;
1208 *e = '\0';
1209
1210 /* Look for the register. Advance to next token if one was recognized. */
1211 if ((reg = reg_lookup_internal (*s, class)) >= 0)
1212 *s = e;
1213
1214 *e = save_c;
1215 if (regnop)
1216 *regnop = reg;
1217 return reg >= 0;
1218 }
1219
1220 static bool
1221 arg_lookup (char **s, const char *const *array, size_t size, unsigned *regnop)
1222 {
1223 const char *p = strchr (*s, ',');
1224 size_t i, len = p ? (size_t)(p - *s) : strlen (*s);
1225
1226 if (len == 0)
1227 return false;
1228
1229 for (i = 0; i < size; i++)
1230 if (array[i] != NULL && strncmp (array[i], *s, len) == 0
1231 && array[i][len] == '\0')
1232 {
1233 *regnop = i;
1234 *s += len;
1235 return true;
1236 }
1237
1238 return false;
1239 }
1240
1241 static bool
1242 flt_lookup (float f, const float *array, size_t size, unsigned *regnop)
1243 {
1244 size_t i;
1245
1246 for (i = 0; i < size; i++)
1247 if (array[i] == f)
1248 {
1249 *regnop = i;
1250 return true;
1251 }
1252
1253 return false;
1254 }
1255
1256 #define USE_BITS(mask,shift) (used_bits |= ((insn_t)(mask) << (shift)))
1257 #define USE_IMM(n, s) \
1258 (used_bits |= ((insn_t)((1ull<<n)-1) << (s)))
1259
1260 /* For consistency checking, verify that all bits are specified either
1261 by the match/mask part of the instruction definition, or by the
1262 operand list. The `length` could be the actual instruction length or
1263 0 for auto-detection. */
1264
1265 static bool
1266 validate_riscv_insn (const struct riscv_opcode *opc, int length)
1267 {
1268 const char *oparg, *opargStart;
1269 insn_t used_bits = opc->mask;
1270 int insn_width;
1271 insn_t required_bits;
1272
1273 if (length == 0)
1274 length = riscv_insn_length (opc->match);
1275 /* We don't support instructions longer than 64-bits yet. */
1276 if (length > 8)
1277 length = 8;
1278 insn_width = 8 * length;
1279
1280 required_bits = ((insn_t)~0ULL) >> (64 - insn_width);
1281
1282 if ((used_bits & opc->match) != (opc->match & required_bits))
1283 {
1284 as_bad (_("internal: bad RISC-V opcode (mask error): %s %s"),
1285 opc->name, opc->args);
1286 return false;
1287 }
1288
1289 for (oparg = opc->args; *oparg; ++oparg)
1290 {
1291 opargStart = oparg;
1292 switch (*oparg)
1293 {
1294 case 'C': /* RVC */
1295 switch (*++oparg)
1296 {
1297 case 'U': break; /* CRS1, constrained to equal RD. */
1298 case 'c': break; /* CRS1, constrained to equal sp. */
1299 case 'T': /* CRS2, floating point. */
1300 case 'V': USE_BITS (OP_MASK_CRS2, OP_SH_CRS2); break;
1301 case 'S': /* CRS1S, floating point. */
1302 case 's': USE_BITS (OP_MASK_CRS1S, OP_SH_CRS1S); break;
1303 case 'w': break; /* CRS1S, constrained to equal RD. */
1304 case 'D': /* CRS2S, floating point. */
1305 case 't': USE_BITS (OP_MASK_CRS2S, OP_SH_CRS2S); break;
1306 case 'x': break; /* CRS2S, constrained to equal RD. */
1307 case 'z': break; /* CRS2S, constrained to be x0. */
1308 case '>': /* CITYPE immediate, compressed shift. */
1309 case 'u': /* CITYPE immediate, compressed lui. */
1310 case 'v': /* CITYPE immediate, li to compressed lui. */
1311 case 'o': /* CITYPE immediate, allow zero. */
1312 case 'j': used_bits |= ENCODE_CITYPE_IMM (-1U); break;
1313 case 'L': used_bits |= ENCODE_CITYPE_ADDI16SP_IMM (-1U); break;
1314 case 'm': used_bits |= ENCODE_CITYPE_LWSP_IMM (-1U); break;
1315 case 'n': used_bits |= ENCODE_CITYPE_LDSP_IMM (-1U); break;
1316 case '6': used_bits |= ENCODE_CSSTYPE_IMM (-1U); break;
1317 case 'M': used_bits |= ENCODE_CSSTYPE_SWSP_IMM (-1U); break;
1318 case 'N': used_bits |= ENCODE_CSSTYPE_SDSP_IMM (-1U); break;
1319 case '8': used_bits |= ENCODE_CIWTYPE_IMM (-1U); break;
1320 case 'K': used_bits |= ENCODE_CIWTYPE_ADDI4SPN_IMM (-1U); break;
1321 /* CLTYPE and CSTYPE have the same immediate encoding. */
1322 case '5': used_bits |= ENCODE_CLTYPE_IMM (-1U); break;
1323 case 'k': used_bits |= ENCODE_CLTYPE_LW_IMM (-1U); break;
1324 case 'l': used_bits |= ENCODE_CLTYPE_LD_IMM (-1U); break;
1325 case 'p': used_bits |= ENCODE_CBTYPE_IMM (-1U); break;
1326 case 'a': used_bits |= ENCODE_CJTYPE_IMM (-1U); break;
1327 case 'F': /* Compressed funct for .insn directive. */
1328 switch (*++oparg)
1329 {
1330 case '6': USE_BITS (OP_MASK_CFUNCT6, OP_SH_CFUNCT6); break;
1331 case '4': USE_BITS (OP_MASK_CFUNCT4, OP_SH_CFUNCT4); break;
1332 case '3': USE_BITS (OP_MASK_CFUNCT3, OP_SH_CFUNCT3); break;
1333 case '2': USE_BITS (OP_MASK_CFUNCT2, OP_SH_CFUNCT2); break;
1334 default:
1335 goto unknown_validate_operand;
1336 }
1337 break;
1338 default:
1339 goto unknown_validate_operand;
1340 }
1341 break; /* end RVC */
1342 case 'V': /* RVV */
1343 switch (*++oparg)
1344 {
1345 case 'd':
1346 case 'f': USE_BITS (OP_MASK_VD, OP_SH_VD); break;
1347 case 'e': USE_BITS (OP_MASK_VWD, OP_SH_VWD); break;
1348 case 's': USE_BITS (OP_MASK_VS1, OP_SH_VS1); break;
1349 case 't': USE_BITS (OP_MASK_VS2, OP_SH_VS2); break;
1350 case 'u': USE_BITS (OP_MASK_VS1, OP_SH_VS1);
1351 USE_BITS (OP_MASK_VS2, OP_SH_VS2); break;
1352 case 'v': USE_BITS (OP_MASK_VD, OP_SH_VD);
1353 USE_BITS (OP_MASK_VS1, OP_SH_VS1);
1354 USE_BITS (OP_MASK_VS2, OP_SH_VS2); break;
1355 case '0': break;
1356 case 'b': used_bits |= ENCODE_RVV_VB_IMM (-1U); break;
1357 case 'c': used_bits |= ENCODE_RVV_VC_IMM (-1U); break;
1358 case 'i':
1359 case 'j':
1360 case 'k': USE_BITS (OP_MASK_VIMM, OP_SH_VIMM); break;
1361 case 'l': used_bits |= ENCODE_RVV_VI_UIMM6 (-1U); break;
1362 case 'm': USE_BITS (OP_MASK_VMASK, OP_SH_VMASK); break;
1363 case 'M': break; /* Macro operand, must be a mask register. */
1364 case 'T': break; /* Macro operand, must be a vector register. */
1365 default:
1366 goto unknown_validate_operand;
1367 }
1368 break; /* end RVV */
1369 case ',': break;
1370 case '(': break;
1371 case ')': break;
1372 case '<': USE_BITS (OP_MASK_SHAMTW, OP_SH_SHAMTW); break;
1373 case '>': USE_BITS (OP_MASK_SHAMT, OP_SH_SHAMT); break;
1374 case 'A': break; /* Macro operand, must be symbol. */
1375 case 'B': break; /* Macro operand, must be symbol or constant. */
1376 case 'c': break; /* Macro operand, must be symbol or constant. */
1377 case 'I': break; /* Macro operand, must be constant. */
1378 case 'D': /* RD, floating point. */
1379 case 'd': USE_BITS (OP_MASK_RD, OP_SH_RD); break;
1380 case 'y': USE_BITS (OP_MASK_BS, OP_SH_BS); break;
1381 case 'Y': USE_BITS (OP_MASK_RNUM, OP_SH_RNUM); break;
1382 case 'Z': /* RS1, CSR number. */
1383 case 'S': /* RS1, floating point. */
1384 case 's': USE_BITS (OP_MASK_RS1, OP_SH_RS1); break;
1385 case 'U': /* RS1 and RS2 are the same, floating point. */
1386 USE_BITS (OP_MASK_RS1, OP_SH_RS1);
1387 /* Fall through. */
1388 case 'T': /* RS2, floating point. */
1389 case 't': USE_BITS (OP_MASK_RS2, OP_SH_RS2); break;
1390 case 'R': /* RS3, floating point. */
1391 case 'r': USE_BITS (OP_MASK_RS3, OP_SH_RS3); break;
1392 case 'm': USE_BITS (OP_MASK_RM, OP_SH_RM); break;
1393 case 'E': USE_BITS (OP_MASK_CSR, OP_SH_CSR); break;
1394 case 'P': USE_BITS (OP_MASK_PRED, OP_SH_PRED); break;
1395 case 'Q': USE_BITS (OP_MASK_SUCC, OP_SH_SUCC); break;
1396 case 'o': /* ITYPE immediate, load displacement. */
1397 case 'j': used_bits |= ENCODE_ITYPE_IMM (-1U); break;
1398 case 'a': used_bits |= ENCODE_JTYPE_IMM (-1U); break;
1399 case 'p': used_bits |= ENCODE_BTYPE_IMM (-1U); break;
1400 case 'q': used_bits |= ENCODE_STYPE_IMM (-1U); break;
1401 case 'u': used_bits |= ENCODE_UTYPE_IMM (-1U); break;
1402 case 'z': break; /* Zero immediate. */
1403 case '[': break; /* Unused operand. */
1404 case ']': break; /* Unused operand. */
1405 case '0': break; /* AMO displacement, must to zero. */
1406 case '1': break; /* Relaxation operand. */
1407 case 'F': /* Funct for .insn directive. */
1408 switch (*++oparg)
1409 {
1410 case '7': USE_BITS (OP_MASK_FUNCT7, OP_SH_FUNCT7); break;
1411 case '3': USE_BITS (OP_MASK_FUNCT3, OP_SH_FUNCT3); break;
1412 case '2': USE_BITS (OP_MASK_FUNCT2, OP_SH_FUNCT2); break;
1413 default:
1414 goto unknown_validate_operand;
1415 }
1416 break;
1417 case 'O': /* Opcode for .insn directive. */
1418 switch (*++oparg)
1419 {
1420 case '4': USE_BITS (OP_MASK_OP, OP_SH_OP); break;
1421 case '2': USE_BITS (OP_MASK_OP2, OP_SH_OP2); break;
1422 default:
1423 goto unknown_validate_operand;
1424 }
1425 break;
1426 case 'W': /* Various operands for standard z extensions. */
1427 switch (*++oparg)
1428 {
1429 case 'i':
1430 switch (*++oparg)
1431 {
1432 case 'f': used_bits |= ENCODE_STYPE_IMM (-1U); break;
1433 default:
1434 goto unknown_validate_operand;
1435 }
1436 break;
1437 case 'f':
1438 switch (*++oparg)
1439 {
1440 case 'v': USE_BITS (OP_MASK_RS1, OP_SH_RS1); break;
1441 default:
1442 goto unknown_validate_operand;
1443 }
1444 break;
1445 case 'c':
1446 switch (*++oparg)
1447 {
1448 /* byte immediate operators, load/store byte insns. */
1449 case 'h': used_bits |= ENCODE_ZCB_HALFWORD_UIMM (-1U); break;
1450 /* halfword immediate operators, load/store halfword insns. */
1451 case 'b': used_bits |= ENCODE_ZCB_BYTE_UIMM (-1U); break;
1452 case 'f': break;
1453 default:
1454 goto unknown_validate_operand;
1455 }
1456 break;
1457 default:
1458 goto unknown_validate_operand;
1459 }
1460 break;
1461 case 'X': /* Vendor-specific operands. */
1462 switch (*++oparg)
1463 {
1464 case 't': /* Vendor-specific (T-head) operands. */
1465 {
1466 size_t n;
1467 size_t s;
1468 switch (*++oparg)
1469 {
1470 case 'l': /* Integer immediate, literal. */
1471 oparg += strcspn(oparg, ",") - 1;
1472 break;
1473 case 's': /* Integer immediate, 'XtsN@S' ... N-bit signed immediate at bit S. */
1474 goto use_imm;
1475 case 'u': /* Integer immediate, 'XtuN@S' ... N-bit unsigned immediate at bit S. */
1476 goto use_imm;
1477 use_imm:
1478 n = strtol (oparg + 1, (char **)&oparg, 10);
1479 if (*oparg != '@')
1480 goto unknown_validate_operand;
1481 s = strtol (oparg + 1, (char **)&oparg, 10);
1482 oparg--;
1483
1484 USE_IMM (n, s);
1485 break;
1486 default:
1487 goto unknown_validate_operand;
1488 }
1489 }
1490 break;
1491 case 'c': /* Vendor-specific (CORE-V) operands. */
1492 switch (*++oparg)
1493 {
1494 case '2':
1495 /* ls2[4:0] */
1496 used_bits |= ENCODE_CV_IS2_UIMM5 (-1U);
1497 break;
1498 case '3':
1499 used_bits |= ENCODE_CV_IS3_UIMM5 (-1U);
1500 break;
1501 default:
1502 goto unknown_validate_operand;
1503 }
1504 break;
1505 case 's': /* Vendor-specific (SiFive) operands. */
1506 switch (*++oparg)
1507 {
1508 case 'd': USE_BITS (OP_MASK_RD, OP_SH_RD); break;
1509 case 't': USE_BITS (OP_MASK_RS2, OP_SH_RS2); break;
1510 case 'O':
1511 switch (*++oparg)
1512 {
1513 case '2': USE_BITS (OP_MASK_XSO2, OP_SH_XSO2); break;
1514 case '1': USE_BITS (OP_MASK_XSO1, OP_SH_XSO1); break;
1515 default:
1516 goto unknown_validate_operand;
1517 }
1518 break;
1519 default:
1520 goto unknown_validate_operand;
1521 }
1522 break;
1523 default:
1524 goto unknown_validate_operand;
1525 }
1526 break;
1527 default:
1528 unknown_validate_operand:
1529 as_bad (_("internal: bad RISC-V opcode "
1530 "(unknown operand type `%s'): %s %s"),
1531 opargStart, opc->name, opc->args);
1532 return false;
1533 }
1534 }
1535
1536 if (used_bits != required_bits)
1537 {
1538 as_bad (_("internal: bad RISC-V opcode "
1539 "(bits %#llx undefined or invalid): %s %s"),
1540 (unsigned long long)(used_bits ^ required_bits),
1541 opc->name, opc->args);
1542 return false;
1543 }
1544 return true;
1545 }
1546
1547 #undef USE_BITS
1548
1549 struct percent_op_match
1550 {
1551 const char *str;
1552 bfd_reloc_code_real_type reloc;
1553 };
1554
1555 /* Common hash table initialization function for instruction and .insn
1556 directive. */
1557
1558 static htab_t
1559 init_opcode_hash (const struct riscv_opcode *opcodes,
1560 bool insn_directive_p)
1561 {
1562 int i = 0;
1563 int length;
1564 htab_t hash = str_htab_create ();
1565 while (opcodes[i].name)
1566 {
1567 const char *name = opcodes[i].name;
1568 if (str_hash_insert (hash, name, &opcodes[i], 0) != NULL)
1569 as_fatal (_("internal: duplicate %s"), name);
1570
1571 do
1572 {
1573 if (opcodes[i].pinfo != INSN_MACRO)
1574 {
1575 if (insn_directive_p)
1576 length = ((name[0] == 'c') ? 2 : 4);
1577 else
1578 length = 0; /* Let assembler determine the length. */
1579 if (!validate_riscv_insn (&opcodes[i], length))
1580 as_fatal (_("internal: broken assembler. "
1581 "No assembly attempted"));
1582 }
1583 else
1584 gas_assert (!insn_directive_p);
1585 ++i;
1586 }
1587 while (opcodes[i].name && !strcmp (opcodes[i].name, name));
1588 }
1589
1590 return hash;
1591 }
1592
1593 /* Record all PC-relative high-part relocation that we have encountered to
1594 help us resolve the corresponding low-part relocation later. */
1595 typedef struct
1596 {
1597 bfd_vma address;
1598 symbolS *symbol;
1599 bfd_vma target;
1600 } riscv_pcrel_hi_fixup;
1601
1602 /* Handle of the pcrel_hi hash table. */
1603 static htab_t riscv_pcrel_hi_fixup_hash;
1604
1605 /* Get the key of a entry from the pcrel_hi hash table. */
1606
1607 static hashval_t
1608 riscv_pcrel_fixup_hash (const void *entry)
1609 {
1610 const riscv_pcrel_hi_fixup *e = entry;
1611 return (hashval_t) (e->address);
1612 }
1613
1614 /* Compare the keys between two entries fo the pcrel_hi hash table. */
1615
1616 static int
1617 riscv_pcrel_fixup_eq (const void *entry1, const void *entry2)
1618 {
1619 const riscv_pcrel_hi_fixup *e1 = entry1, *e2 = entry2;
1620 return e1->address == e2->address;
1621 }
1622
1623 /* Record the pcrel_hi relocation. */
1624
1625 static bool
1626 riscv_record_pcrel_fixup (htab_t p, bfd_vma address, symbolS *symbol,
1627 bfd_vma target)
1628 {
1629 riscv_pcrel_hi_fixup entry = {address, symbol, target};
1630 riscv_pcrel_hi_fixup **slot =
1631 (riscv_pcrel_hi_fixup **) htab_find_slot (p, &entry, INSERT);
1632 if (slot == NULL)
1633 return false;
1634
1635 *slot = (riscv_pcrel_hi_fixup *) xmalloc (sizeof (riscv_pcrel_hi_fixup));
1636 if (*slot == NULL)
1637 return false;
1638 **slot = entry;
1639 return true;
1640 }
1641
1642 /* This function is called once, at assembler startup time. It should set up
1643 all the tables, etc. that the MD part of the assembler will need. */
1644
1645 void
1646 md_begin (void)
1647 {
1648 unsigned long mach = xlen == 64 ? bfd_mach_riscv64 : bfd_mach_riscv32;
1649
1650 if (! bfd_set_arch_mach (stdoutput, bfd_arch_riscv, mach))
1651 as_warn (_("could not set architecture and machine"));
1652
1653 op_hash = init_opcode_hash (riscv_opcodes, false);
1654 insn_type_hash = init_opcode_hash (riscv_insn_types, true);
1655
1656 reg_names_hash = str_htab_create ();
1657 hash_reg_names (RCLASS_GPR, riscv_gpr_names_numeric, NGPR);
1658 hash_reg_names (RCLASS_GPR, riscv_gpr_names_abi, NGPR);
1659 hash_reg_names (RCLASS_FPR, riscv_fpr_names_numeric, NFPR);
1660 hash_reg_names (RCLASS_FPR, riscv_fpr_names_abi, NFPR);
1661 hash_reg_names (RCLASS_VECR, riscv_vecr_names_numeric, NVECR);
1662 hash_reg_names (RCLASS_VECM, riscv_vecm_names_numeric, NVECM);
1663 /* Add "fp" as an alias for "s0". */
1664 hash_reg_name (RCLASS_GPR, "fp", 8);
1665
1666 /* Create and insert CSR hash tables. */
1667 csr_extra_hash = str_htab_create ();
1668 #define DECLARE_CSR(name, num, class, define_version, abort_version) \
1669 riscv_init_csr_hash (#name, num, class, define_version, abort_version);
1670 #define DECLARE_CSR_ALIAS(name, num, class, define_version, abort_version) \
1671 DECLARE_CSR(name, num, class, define_version, abort_version);
1672 #include "opcode/riscv-opc.h"
1673 #undef DECLARE_CSR
1674
1675 opcode_names_hash = str_htab_create ();
1676 init_opcode_names_hash ();
1677
1678 /* Create pcrel_hi hash table to resolve the relocation while with
1679 -mno-relax. */
1680 riscv_pcrel_hi_fixup_hash = htab_create (1024, riscv_pcrel_fixup_hash,
1681 riscv_pcrel_fixup_eq, free);
1682
1683 /* Set the default alignment for the text section. */
1684 record_alignment (text_section, riscv_opts.rvc ? 1 : 2);
1685 }
1686
1687 static insn_t
1688 riscv_apply_const_reloc (bfd_reloc_code_real_type reloc_type, bfd_vma value)
1689 {
1690 switch (reloc_type)
1691 {
1692 case BFD_RELOC_32:
1693 return value;
1694
1695 case BFD_RELOC_RISCV_HI20:
1696 return ENCODE_UTYPE_IMM (RISCV_CONST_HIGH_PART (value));
1697
1698 case BFD_RELOC_RISCV_LO12_S:
1699 return ENCODE_STYPE_IMM (value);
1700
1701 case BFD_RELOC_RISCV_LO12_I:
1702 return ENCODE_ITYPE_IMM (value);
1703
1704 default:
1705 abort ();
1706 }
1707 }
1708
1709 /* Output an instruction. IP is the instruction information.
1710 ADDRESS_EXPR is an operand of the instruction to be used with
1711 RELOC_TYPE. */
1712
1713 static void
1714 append_insn (struct riscv_cl_insn *ip, expressionS *address_expr,
1715 bfd_reloc_code_real_type reloc_type)
1716 {
1717 dwarf2_emit_insn (0);
1718
1719 if (reloc_type != BFD_RELOC_UNUSED)
1720 {
1721 reloc_howto_type *howto;
1722
1723 gas_assert (address_expr);
1724 if (reloc_type == BFD_RELOC_12_PCREL
1725 || reloc_type == BFD_RELOC_RISCV_JMP)
1726 {
1727 int j = reloc_type == BFD_RELOC_RISCV_JMP;
1728 int best_case = insn_length (ip);
1729 unsigned worst_case = relaxed_branch_length (NULL, NULL, 0);
1730
1731 if (now_seg == absolute_section)
1732 {
1733 as_bad (_("relaxable branches not supported in absolute section"));
1734 return;
1735 }
1736
1737 add_relaxed_insn (ip, worst_case, best_case,
1738 RELAX_BRANCH_ENCODE (j, best_case == 2, worst_case),
1739 address_expr->X_add_symbol,
1740 address_expr->X_add_number);
1741 return;
1742 }
1743 else
1744 {
1745 howto = bfd_reloc_type_lookup (stdoutput, reloc_type);
1746 if (howto == NULL)
1747 as_bad (_("internal: unsupported RISC-V relocation number %d"),
1748 reloc_type);
1749
1750 ip->fixp = fix_new_exp (ip->frag, ip->where,
1751 bfd_get_reloc_size (howto),
1752 address_expr, false, reloc_type);
1753
1754 ip->fixp->fx_tcbit = riscv_opts.relax;
1755 ip->fixp->tc_fix_data.source_macro = source_macro;
1756 }
1757 }
1758
1759 add_fixed_insn (ip);
1760
1761 /* We need to start a new frag after any instruction that can be
1762 optimized away or compressed by the linker during relaxation, to prevent
1763 the assembler from computing static offsets across such an instruction.
1764 This is necessary to get correct EH info. */
1765 if (reloc_type == BFD_RELOC_RISCV_HI20
1766 || reloc_type == BFD_RELOC_RISCV_PCREL_HI20
1767 || reloc_type == BFD_RELOC_RISCV_TPREL_HI20
1768 || reloc_type == BFD_RELOC_RISCV_TPREL_ADD)
1769 {
1770 frag_wane (frag_now);
1771 frag_new (0);
1772 }
1773 }
1774
1775 /* Build an instruction created by a macro expansion. This is passed
1776 a pointer to the count of instructions created so far, an expression,
1777 the name of the instruction to build, an operand format string, and
1778 corresponding arguments. */
1779
1780 static void
1781 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
1782 {
1783 const struct riscv_opcode *mo;
1784 struct riscv_cl_insn insn;
1785 bfd_reloc_code_real_type r;
1786 va_list args;
1787 const char *fmtStart;
1788
1789 va_start (args, fmt);
1790
1791 r = BFD_RELOC_UNUSED;
1792 mo = (struct riscv_opcode *) str_hash_find (op_hash, name);
1793 gas_assert (mo);
1794
1795 /* Find a non-RVC variant of the instruction. append_insn will compress
1796 it if possible. */
1797 while (riscv_insn_length (mo->match) < 4)
1798 mo++;
1799 gas_assert (strcmp (name, mo->name) == 0);
1800
1801 create_insn (&insn, mo);
1802 for (;; ++fmt)
1803 {
1804 fmtStart = fmt;
1805 switch (*fmt)
1806 {
1807 case 'V': /* RVV */
1808 switch (*++fmt)
1809 {
1810 case 'd':
1811 INSERT_OPERAND (VD, insn, va_arg (args, int));
1812 continue;
1813 case 's':
1814 INSERT_OPERAND (VS1, insn, va_arg (args, int));
1815 continue;
1816 case 't':
1817 INSERT_OPERAND (VS2, insn, va_arg (args, int));
1818 continue;
1819 case 'm':
1820 {
1821 int reg = va_arg (args, int);
1822 if (reg == -1)
1823 {
1824 INSERT_OPERAND (VMASK, insn, 1);
1825 continue;
1826 }
1827 else if (reg == 0)
1828 {
1829 INSERT_OPERAND (VMASK, insn, 0);
1830 continue;
1831 }
1832 else
1833 goto unknown_macro_argument;
1834 }
1835 default:
1836 goto unknown_macro_argument;
1837 }
1838 break;
1839
1840 case 'd':
1841 INSERT_OPERAND (RD, insn, va_arg (args, int));
1842 continue;
1843 case 's':
1844 INSERT_OPERAND (RS1, insn, va_arg (args, int));
1845 continue;
1846 case 't':
1847 INSERT_OPERAND (RS2, insn, va_arg (args, int));
1848 continue;
1849
1850 case 'j':
1851 case 'u':
1852 case 'q':
1853 gas_assert (ep != NULL);
1854 r = va_arg (args, int);
1855 continue;
1856
1857 case '\0':
1858 break;
1859 case ',':
1860 continue;
1861 default:
1862 unknown_macro_argument:
1863 as_fatal (_("internal: invalid macro argument `%s'"), fmtStart);
1864 }
1865 break;
1866 }
1867 va_end (args);
1868 gas_assert (r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
1869
1870 append_insn (&insn, ep, r);
1871 }
1872
1873 /* Build an instruction created by a macro expansion. Like md_assemble but
1874 accept a printf-style format string and arguments. */
1875
1876 static void
1877 md_assemblef (const char *format, ...)
1878 {
1879 char *buf = NULL;
1880 va_list ap;
1881 int r;
1882
1883 va_start (ap, format);
1884
1885 r = vasprintf (&buf, format, ap);
1886
1887 if (r < 0)
1888 as_fatal (_("internal: vasprintf failed"));
1889
1890 md_assemble (buf);
1891 free(buf);
1892
1893 va_end (ap);
1894 }
1895
1896 /* Sign-extend 32-bit mode constants that have bit 31 set and all higher bits
1897 unset. */
1898
1899 static void
1900 normalize_constant_expr (expressionS *ex)
1901 {
1902 if (xlen > 32)
1903 return;
1904 if ((ex->X_op == O_constant || ex->X_op == O_symbol)
1905 && IS_ZEXT_32BIT_NUM (ex->X_add_number))
1906 ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
1907 - 0x80000000);
1908 }
1909
1910 /* Fail if an expression EX is not a constant. IP is the instruction using EX.
1911 MAYBE_CSR is true if the symbol may be an unrecognized CSR name. */
1912
1913 static void
1914 check_absolute_expr (struct riscv_cl_insn *ip, expressionS *ex,
1915 bool maybe_csr)
1916 {
1917 if (ex->X_op == O_big)
1918 as_bad (_("unsupported large constant"));
1919 else if (maybe_csr && ex->X_op == O_symbol)
1920 as_bad (_("unknown CSR `%s'"),
1921 S_GET_NAME (ex->X_add_symbol));
1922 else if (ex->X_op != O_constant)
1923 as_bad (_("instruction %s requires absolute expression"),
1924 ip->insn_mo->name);
1925 normalize_constant_expr (ex);
1926 }
1927
1928 static symbolS *
1929 make_internal_label (void)
1930 {
1931 return (symbolS *) local_symbol_make (FAKE_LABEL_NAME, now_seg, frag_now,
1932 frag_now_fix ());
1933 }
1934
1935 /* Load an entry from the GOT. */
1936
1937 static void
1938 pcrel_access (int destreg, int tempreg, expressionS *ep,
1939 const char *lo_insn, const char *lo_pattern,
1940 bfd_reloc_code_real_type hi_reloc,
1941 bfd_reloc_code_real_type lo_reloc)
1942 {
1943 expressionS ep2;
1944 ep2.X_op = O_symbol;
1945 ep2.X_add_symbol = make_internal_label ();
1946 ep2.X_add_number = 0;
1947
1948 macro_build (ep, "auipc", "d,u", tempreg, hi_reloc);
1949 macro_build (&ep2, lo_insn, lo_pattern, destreg, tempreg, lo_reloc);
1950 }
1951
1952 static void
1953 pcrel_load (int destreg, int tempreg, expressionS *ep, const char *lo_insn,
1954 bfd_reloc_code_real_type hi_reloc,
1955 bfd_reloc_code_real_type lo_reloc)
1956 {
1957 pcrel_access (destreg, tempreg, ep, lo_insn, "d,s,j", hi_reloc, lo_reloc);
1958 }
1959
1960 static void
1961 pcrel_store (int srcreg, int tempreg, expressionS *ep, const char *lo_insn,
1962 bfd_reloc_code_real_type hi_reloc,
1963 bfd_reloc_code_real_type lo_reloc)
1964 {
1965 pcrel_access (srcreg, tempreg, ep, lo_insn, "t,s,q", hi_reloc, lo_reloc);
1966 }
1967
1968 /* PC-relative function call using AUIPC/JALR, relaxed to JAL. */
1969
1970 static void
1971 riscv_call (int destreg, int tempreg, expressionS *ep,
1972 bfd_reloc_code_real_type reloc)
1973 {
1974 /* Ensure the jalr is emitted to the same frag as the auipc. */
1975 frag_grow (8);
1976 macro_build (ep, "auipc", "d,u", tempreg, reloc);
1977 macro_build (NULL, "jalr", "d,s", destreg, tempreg);
1978 /* See comment at end of append_insn. */
1979 frag_wane (frag_now);
1980 frag_new (0);
1981 }
1982
1983 /* Load an integer constant into a register. */
1984
1985 static void
1986 load_const (int reg, expressionS *ep)
1987 {
1988 int shift = RISCV_IMM_BITS;
1989 bfd_vma upper_imm, sign = (bfd_vma) 1 << (RISCV_IMM_BITS - 1);
1990 expressionS upper = *ep, lower = *ep;
1991 lower.X_add_number = ((ep->X_add_number & (sign + sign - 1)) ^ sign) - sign;
1992 upper.X_add_number -= lower.X_add_number;
1993
1994 if (ep->X_op != O_constant)
1995 {
1996 as_bad (_("unsupported large constant"));
1997 return;
1998 }
1999
2000 if (xlen > 32 && !IS_SEXT_32BIT_NUM (ep->X_add_number))
2001 {
2002 /* Reduce to a signed 32-bit constant using SLLI and ADDI. */
2003 while (((upper.X_add_number >> shift) & 1) == 0)
2004 shift++;
2005
2006 upper.X_add_number = (int64_t) upper.X_add_number >> shift;
2007 load_const (reg, &upper);
2008
2009 md_assemblef ("slli x%d, x%d, 0x%x", reg, reg, shift);
2010 if (lower.X_add_number != 0)
2011 md_assemblef ("addi x%d, x%d, %" PRId64, reg, reg,
2012 (int64_t) lower.X_add_number);
2013 }
2014 else
2015 {
2016 /* Simply emit LUI and/or ADDI to build a 32-bit signed constant. */
2017 int hi_reg = 0;
2018
2019 if (upper.X_add_number != 0)
2020 {
2021 /* Discard low part and zero-extend upper immediate. */
2022 upper_imm = ((uint32_t)upper.X_add_number >> shift);
2023
2024 md_assemblef ("lui x%d, 0x%" PRIx64, reg, (uint64_t) upper_imm);
2025 hi_reg = reg;
2026 }
2027
2028 if (lower.X_add_number != 0 || hi_reg == 0)
2029 md_assemblef ("%s x%d, x%d, %" PRId64, ADD32_INSN, reg, hi_reg,
2030 (int64_t) lower.X_add_number);
2031 }
2032 }
2033
2034 /* Zero extend and sign extend byte/half-word/word. */
2035
2036 static void
2037 riscv_ext (int destreg, int srcreg, unsigned shift, bool sign)
2038 {
2039 md_assemblef ("slli x%d, x%d, %#x", destreg, srcreg, shift);
2040 md_assemblef ("sr%ci x%d, x%d, %#x",
2041 sign ? 'a' : 'l', destreg, destreg, shift);
2042 }
2043
2044 /* Expand RISC-V Vector macros into one or more instructions. */
2045
2046 static void
2047 vector_macro (struct riscv_cl_insn *ip)
2048 {
2049 int vd = (ip->insn_opcode >> OP_SH_VD) & OP_MASK_VD;
2050 int vs1 = (ip->insn_opcode >> OP_SH_VS1) & OP_MASK_VS1;
2051 int vs2 = (ip->insn_opcode >> OP_SH_VS2) & OP_MASK_VS2;
2052 int vm = (ip->insn_opcode >> OP_SH_VMASK) & OP_MASK_VMASK;
2053 int vtemp = (ip->insn_opcode >> OP_SH_VFUNCT6) & OP_MASK_VFUNCT6;
2054 const char *vmslt_vx = ip->insn_mo->match ? "vmsltu.vx" : "vmslt.vx";
2055 int mask = ip->insn_mo->mask;
2056
2057 switch (mask)
2058 {
2059 case M_VMSGE:
2060 if (vm)
2061 {
2062 /* Unmasked. */
2063 macro_build (NULL, vmslt_vx, "Vd,Vt,sVm", vd, vs2, vs1, -1);
2064 macro_build (NULL, "vmnand.mm", "Vd,Vt,Vs", vd, vd, vd);
2065 break;
2066 }
2067 if (vtemp != 0)
2068 {
2069 /* Masked. Have vtemp to avoid overlap constraints. */
2070 if (vd == vm)
2071 {
2072 macro_build (NULL, vmslt_vx, "Vd,Vt,sVm", vtemp, vs2, vs1, -1);
2073 macro_build (NULL, "vmandnot.mm", "Vd,Vt,Vs", vd, vm, vtemp);
2074 }
2075 else
2076 {
2077 /* Preserve the value of vd if not updating by vm. */
2078 macro_build (NULL, vmslt_vx, "Vd,Vt,sVm", vtemp, vs2, vs1, -1);
2079 macro_build (NULL, "vmandnot.mm", "Vd,Vt,Vs", vtemp, vm, vtemp);
2080 macro_build (NULL, "vmandnot.mm", "Vd,Vt,Vs", vd, vd, vm);
2081 macro_build (NULL, "vmor.mm", "Vd,Vt,Vs", vd, vtemp, vd);
2082 }
2083 }
2084 else if (vd != vm)
2085 {
2086 /* Masked. This may cause the vd overlaps vs2, when LMUL > 1. */
2087 macro_build (NULL, vmslt_vx, "Vd,Vt,sVm", vd, vs2, vs1, vm);
2088 macro_build (NULL, "vmxor.mm", "Vd,Vt,Vs", vd, vd, vm);
2089 }
2090 else
2091 as_bad (_("must provide temp if destination overlaps mask"));
2092 break;
2093
2094 default:
2095 break;
2096 }
2097 }
2098
2099 /* Expand RISC-V assembly macros into one or more instructions. */
2100
2101 static void
2102 macro (struct riscv_cl_insn *ip, expressionS *imm_expr,
2103 bfd_reloc_code_real_type *imm_reloc)
2104 {
2105 int rd = (ip->insn_opcode >> OP_SH_RD) & OP_MASK_RD;
2106 int rs1 = (ip->insn_opcode >> OP_SH_RS1) & OP_MASK_RS1;
2107 int rs2 = (ip->insn_opcode >> OP_SH_RS2) & OP_MASK_RS2;
2108 int mask = ip->insn_mo->mask;
2109
2110 source_macro = mask;
2111
2112 switch (mask)
2113 {
2114 case M_LI:
2115 load_const (rd, imm_expr);
2116 break;
2117
2118 case M_LA:
2119 case M_LLA:
2120 case M_LGA:
2121 /* Load the address of a symbol into a register. */
2122 if (!IS_SEXT_32BIT_NUM (imm_expr->X_add_number))
2123 as_bad (_("offset too large"));
2124
2125 if (imm_expr->X_op == O_constant)
2126 load_const (rd, imm_expr);
2127 /* Global PIC symbol. */
2128 else if ((riscv_opts.pic && mask == M_LA)
2129 || mask == M_LGA)
2130 pcrel_load (rd, rd, imm_expr, LOAD_ADDRESS_INSN,
2131 BFD_RELOC_RISCV_GOT_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
2132 /* Local PIC symbol, or any non-PIC symbol. */
2133 else
2134 pcrel_load (rd, rd, imm_expr, "addi",
2135 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
2136 break;
2137
2138 case M_LA_TLS_GD:
2139 pcrel_load (rd, rd, imm_expr, "addi",
2140 BFD_RELOC_RISCV_TLS_GD_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
2141 break;
2142
2143 case M_LA_TLS_IE:
2144 pcrel_load (rd, rd, imm_expr, LOAD_ADDRESS_INSN,
2145 BFD_RELOC_RISCV_TLS_GOT_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
2146 break;
2147
2148 case M_Lx:
2149 pcrel_load (rd, rd, imm_expr, ip->insn_mo->name,
2150 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
2151 break;
2152
2153 case M_FLx:
2154 pcrel_load (rd, rs1, imm_expr, ip->insn_mo->name,
2155 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
2156 break;
2157
2158 case M_Sx_FSx:
2159 pcrel_store (rs2, rs1, imm_expr, ip->insn_mo->name,
2160 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
2161 break;
2162
2163 case M_CALL:
2164 riscv_call (rd, rs1, imm_expr, *imm_reloc);
2165 break;
2166
2167 case M_EXTH:
2168 riscv_ext (rd, rs1, xlen - 16, *ip->insn_mo->name == 's');
2169 break;
2170
2171 case M_ZEXTW:
2172 riscv_ext (rd, rs1, xlen - 32, false);
2173 break;
2174
2175 case M_SEXTB:
2176 riscv_ext (rd, rs1, xlen - 8, true);
2177 break;
2178
2179 case M_VMSGE:
2180 vector_macro (ip);
2181 break;
2182
2183 default:
2184 as_bad (_("internal: macro %s not implemented"), ip->insn_mo->name);
2185 break;
2186 }
2187
2188 source_macro = -1;
2189 }
2190
2191 static const struct percent_op_match percent_op_utype[] =
2192 {
2193 {"tprel_hi", BFD_RELOC_RISCV_TPREL_HI20},
2194 {"pcrel_hi", BFD_RELOC_RISCV_PCREL_HI20},
2195 {"got_pcrel_hi", BFD_RELOC_RISCV_GOT_HI20},
2196 {"tls_ie_pcrel_hi", BFD_RELOC_RISCV_TLS_GOT_HI20},
2197 {"tls_gd_pcrel_hi", BFD_RELOC_RISCV_TLS_GD_HI20},
2198 {"hi", BFD_RELOC_RISCV_HI20},
2199 {0, 0}
2200 };
2201
2202 static const struct percent_op_match percent_op_itype[] =
2203 {
2204 {"lo", BFD_RELOC_RISCV_LO12_I},
2205 {"tprel_lo", BFD_RELOC_RISCV_TPREL_LO12_I},
2206 {"pcrel_lo", BFD_RELOC_RISCV_PCREL_LO12_I},
2207 {0, 0}
2208 };
2209
2210 static const struct percent_op_match percent_op_stype[] =
2211 {
2212 {"lo", BFD_RELOC_RISCV_LO12_S},
2213 {"tprel_lo", BFD_RELOC_RISCV_TPREL_LO12_S},
2214 {"pcrel_lo", BFD_RELOC_RISCV_PCREL_LO12_S},
2215 {0, 0}
2216 };
2217
2218 static const struct percent_op_match percent_op_rtype[] =
2219 {
2220 {"tprel_add", BFD_RELOC_RISCV_TPREL_ADD},
2221 {0, 0}
2222 };
2223
2224 static const struct percent_op_match percent_op_null[] =
2225 {
2226 {0, 0}
2227 };
2228
2229 /* Return true if *STR points to a relocation operator. When returning true,
2230 move *STR over the operator and store its relocation code in *RELOC.
2231 Leave both *STR and *RELOC alone when returning false. */
2232
2233 static bool
2234 parse_relocation (char **str, bfd_reloc_code_real_type *reloc,
2235 const struct percent_op_match *percent_op)
2236 {
2237 for ( ; percent_op->str; percent_op++)
2238 if (strncasecmp (*str + 1, percent_op->str, strlen (percent_op->str)) == 0)
2239 {
2240 size_t len = 1 + strlen (percent_op->str);
2241
2242 while (ISSPACE ((*str)[len]))
2243 ++len;
2244 if ((*str)[len] != '(')
2245 continue;
2246
2247 *str += len;
2248 *reloc = percent_op->reloc;
2249
2250 /* Check whether the output BFD supports this relocation.
2251 If not, issue an error and fall back on something safe. */
2252 if (*reloc != BFD_RELOC_UNUSED
2253 && !bfd_reloc_type_lookup (stdoutput, *reloc))
2254 {
2255 as_bad ("internal: relocation %s isn't supported by the "
2256 "current ABI", percent_op->str);
2257 *reloc = BFD_RELOC_UNUSED;
2258 }
2259 return true;
2260 }
2261 return false;
2262 }
2263
2264 static void
2265 my_getExpression (expressionS *ep, char *str)
2266 {
2267 char *save_in;
2268
2269 save_in = input_line_pointer;
2270 input_line_pointer = str;
2271 expression (ep);
2272 expr_parse_end = input_line_pointer;
2273 input_line_pointer = save_in;
2274 }
2275
2276 /* Parse string STR as a 16-bit relocatable operand. Store the
2277 expression in *EP and the relocation, if any, in RELOC.
2278 Return the number of relocation operators used (0 or 1).
2279
2280 On exit, EXPR_PARSE_END points to the first character after the
2281 expression. */
2282
2283 static size_t
2284 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
2285 char *str, const struct percent_op_match *percent_op)
2286 {
2287 size_t reloc_index;
2288 unsigned crux_depth, str_depth;
2289 bool orig_probing = probing_insn_operands;
2290 char *crux;
2291
2292 /* Search for the start of the main expression.
2293
2294 End the loop with CRUX pointing to the start of the main expression and
2295 with CRUX_DEPTH containing the number of open brackets at that point. */
2296 reloc_index = -1;
2297 str_depth = 0;
2298 do
2299 {
2300 reloc_index++;
2301 crux = str;
2302 crux_depth = str_depth;
2303
2304 /* Skip over whitespace and brackets, keeping count of the number
2305 of brackets. */
2306 while (*str == ' ' || *str == '\t' || *str == '(')
2307 if (*str++ == '(')
2308 str_depth++;
2309 }
2310 while (*str == '%'
2311 && reloc_index < 1
2312 && parse_relocation (&str, reloc, percent_op));
2313
2314 if (*str == '%')
2315 {
2316 /* expression() will choke on anything looking like an (unrecognized)
2317 relocation specifier. Don't even call it, avoiding multiple (and
2318 perhaps redundant) error messages; our caller will issue one. */
2319 ep->X_op = O_illegal;
2320 return 0;
2321 }
2322
2323 /* Anything inside parentheses or subject to a relocation operator cannot
2324 be a register and hence can be treated the same as operands to
2325 directives (other than .insn). */
2326 if (str_depth || reloc_index)
2327 probing_insn_operands = false;
2328
2329 my_getExpression (ep, crux);
2330 str = expr_parse_end;
2331
2332 probing_insn_operands = orig_probing;
2333
2334 /* Match every open bracket. */
2335 while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
2336 if (*str++ == ')')
2337 crux_depth--;
2338
2339 if (crux_depth > 0)
2340 as_bad ("unclosed '('");
2341
2342 expr_parse_end = str;
2343
2344 return reloc_index;
2345 }
2346
2347 /* Parse opcode name, could be an mnemonics or number. */
2348
2349 static size_t
2350 my_getOpcodeExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
2351 char *str)
2352 {
2353 const struct opcode_name_t *o = opcode_name_lookup (&str);
2354
2355 if (o != NULL)
2356 {
2357 ep->X_op = O_constant;
2358 ep->X_add_number = o->val;
2359 return 0;
2360 }
2361
2362 return my_getSmallExpression (ep, reloc, str, percent_op_null);
2363 }
2364
2365 /* Parse string STR as a vsetvli operand. Store the expression in *EP.
2366 On exit, EXPR_PARSE_END points to the first character after the
2367 expression. */
2368
2369 static void
2370 my_getVsetvliExpression (expressionS *ep, char *str)
2371 {
2372 unsigned int vsew_value = 0, vlmul_value = 0;
2373 unsigned int vta_value = 0, vma_value = 0;
2374 bfd_boolean vsew_found = FALSE, vlmul_found = FALSE;
2375 bfd_boolean vta_found = FALSE, vma_found = FALSE;
2376
2377 if (arg_lookup (&str, riscv_vsew, ARRAY_SIZE (riscv_vsew), &vsew_value))
2378 {
2379 if (*str == ',')
2380 ++str;
2381 if (vsew_found)
2382 as_bad (_("multiple vsew constants"));
2383 vsew_found = TRUE;
2384 }
2385 if (arg_lookup (&str, riscv_vlmul, ARRAY_SIZE (riscv_vlmul), &vlmul_value))
2386 {
2387 if (*str == ',')
2388 ++str;
2389 if (vlmul_found)
2390 as_bad (_("multiple vlmul constants"));
2391 vlmul_found = TRUE;
2392 }
2393 if (arg_lookup (&str, riscv_vta, ARRAY_SIZE (riscv_vta), &vta_value))
2394 {
2395 if (*str == ',')
2396 ++str;
2397 if (vta_found)
2398 as_bad (_("multiple vta constants"));
2399 vta_found = TRUE;
2400 }
2401 if (arg_lookup (&str, riscv_vma, ARRAY_SIZE (riscv_vma), &vma_value))
2402 {
2403 if (*str == ',')
2404 ++str;
2405 if (vma_found)
2406 as_bad (_("multiple vma constants"));
2407 vma_found = TRUE;
2408 }
2409
2410 if (vsew_found || vlmul_found || vta_found || vma_found)
2411 {
2412 ep->X_op = O_constant;
2413 ep->X_add_number = (vlmul_value << OP_SH_VLMUL)
2414 | (vsew_value << OP_SH_VSEW)
2415 | (vta_value << OP_SH_VTA)
2416 | (vma_value << OP_SH_VMA);
2417 expr_parse_end = str;
2418 }
2419 else
2420 {
2421 my_getExpression (ep, str);
2422 str = expr_parse_end;
2423 }
2424 }
2425
2426 /* Detect and handle implicitly zero load-store offsets. For example,
2427 "lw t0, (t1)" is shorthand for "lw t0, 0(t1)". Return true if such
2428 an implicit offset was detected. */
2429
2430 static bool
2431 riscv_handle_implicit_zero_offset (expressionS *ep, const char *s)
2432 {
2433 /* Check whether there is only a single bracketed expression left.
2434 If so, it must be the base register and the constant must be zero. */
2435 if (*s == '(' && strchr (s + 1, '(') == 0)
2436 {
2437 ep->X_op = O_constant;
2438 ep->X_add_number = 0;
2439 return true;
2440 }
2441
2442 return false;
2443 }
2444
2445 /* All RISC-V CSR instructions belong to one of these classes. */
2446 enum csr_insn_type
2447 {
2448 INSN_NOT_CSR,
2449 INSN_CSRRW,
2450 INSN_CSRRS,
2451 INSN_CSRRC
2452 };
2453
2454 /* Return which CSR instruction is checking. */
2455
2456 static enum csr_insn_type
2457 riscv_csr_insn_type (insn_t insn)
2458 {
2459 if (((insn ^ MATCH_CSRRW) & MASK_CSRRW) == 0
2460 || ((insn ^ MATCH_CSRRWI) & MASK_CSRRWI) == 0)
2461 return INSN_CSRRW;
2462 else if (((insn ^ MATCH_CSRRS) & MASK_CSRRS) == 0
2463 || ((insn ^ MATCH_CSRRSI) & MASK_CSRRSI) == 0)
2464 return INSN_CSRRS;
2465 else if (((insn ^ MATCH_CSRRC) & MASK_CSRRC) == 0
2466 || ((insn ^ MATCH_CSRRCI) & MASK_CSRRCI) == 0)
2467 return INSN_CSRRC;
2468 else
2469 return INSN_NOT_CSR;
2470 }
2471
2472 /* CSRRW and CSRRWI always write CSR. CSRRS, CSRRC, CSRRSI and CSRRCI write
2473 CSR when RS1 isn't zero. The CSR is read only if the [11:10] bits of
2474 CSR address is 0x3. */
2475
2476 static bool
2477 riscv_csr_read_only_check (insn_t insn)
2478 {
2479 int csr = (insn & (OP_MASK_CSR << OP_SH_CSR)) >> OP_SH_CSR;
2480 int rs1 = (insn & (OP_MASK_RS1 << OP_SH_RS1)) >> OP_SH_RS1;
2481 int readonly = (((csr & (0x3 << 10)) >> 10) == 0x3);
2482 enum csr_insn_type csr_insn = riscv_csr_insn_type (insn);
2483
2484 if (readonly
2485 && (((csr_insn == INSN_CSRRS
2486 || csr_insn == INSN_CSRRC)
2487 && rs1 != 0)
2488 || csr_insn == INSN_CSRRW))
2489 return false;
2490
2491 return true;
2492 }
2493
2494 /* Return true if it is a privileged instruction. Otherwise, return false.
2495
2496 uret is actually a N-ext instruction. So it is better to regard it as
2497 an user instruction rather than the priv instruction.
2498
2499 hret is used to return from traps in H-mode. H-mode is removed since
2500 the v1.10 priv spec, but probably be added in the new hypervisor spec.
2501 Therefore, hret should be controlled by the hypervisor spec rather than
2502 priv spec in the future.
2503
2504 dret is defined in the debug spec, so it should be checked in the future,
2505 too. */
2506
2507 static bool
2508 riscv_is_priv_insn (insn_t insn)
2509 {
2510 return (((insn ^ MATCH_SRET) & MASK_SRET) == 0
2511 || ((insn ^ MATCH_MRET) & MASK_MRET) == 0
2512 || ((insn ^ MATCH_SFENCE_VMA) & MASK_SFENCE_VMA) == 0
2513 || ((insn ^ MATCH_WFI) & MASK_WFI) == 0
2514 /* The sfence.vm is dropped in the v1.10 priv specs, but we still need to
2515 check it here to keep the compatible. */
2516 || ((insn ^ MATCH_SFENCE_VM) & MASK_SFENCE_VM) == 0);
2517 }
2518
2519 static symbolS *deferred_sym_rootP;
2520 static symbolS *deferred_sym_lastP;
2521 /* Since symbols can't easily be freed, try to recycle ones which weren't
2522 committed. */
2523 static symbolS *orphan_sym_rootP;
2524 static symbolS *orphan_sym_lastP;
2525
2526 /* This routine assembles an instruction into its binary format. As a
2527 side effect, it sets the global variable imm_reloc to the type of
2528 relocation to do if one of the operands is an address expression. */
2529
2530 static struct riscv_ip_error
2531 riscv_ip (char *str, struct riscv_cl_insn *ip, expressionS *imm_expr,
2532 bfd_reloc_code_real_type *imm_reloc, htab_t hash)
2533 {
2534 /* The operand string defined in the riscv_opcodes. */
2535 const char *oparg, *opargStart;
2536 /* The parsed operands from assembly. */
2537 char *asarg, *asargStart;
2538 char save_c = 0;
2539 struct riscv_opcode *insn;
2540 unsigned int regno;
2541 const struct percent_op_match *p;
2542 struct riscv_ip_error error;
2543 error.msg = "unrecognized opcode";
2544 error.statement = str;
2545 error.missing_ext = NULL;
2546 /* Indicate we are assembling instruction with CSR. */
2547 bool insn_with_csr = false;
2548
2549 /* Parse the name of the instruction. Terminate the string if whitespace
2550 is found so that str_hash_find only sees the name part of the string. */
2551 for (asarg = str; *asarg!= '\0'; ++asarg)
2552 if (ISSPACE (*asarg))
2553 {
2554 save_c = *asarg;
2555 *asarg++ = '\0';
2556 break;
2557 }
2558
2559 insn = (struct riscv_opcode *) str_hash_find (hash, str);
2560
2561 probing_insn_operands = true;
2562
2563 asargStart = asarg;
2564 for ( ; insn && insn->name && strcmp (insn->name, str) == 0; insn++)
2565 {
2566 if ((insn->xlen_requirement != 0) && (xlen != insn->xlen_requirement))
2567 continue;
2568
2569 if (!riscv_multi_subset_supports (&riscv_rps_as, insn->insn_class))
2570 {
2571 error.missing_ext = riscv_multi_subset_supports_ext (&riscv_rps_as,
2572 insn->insn_class);
2573 continue;
2574 }
2575
2576 /* Reset error message of the previous round. */
2577 error.msg = _("illegal operands");
2578 error.missing_ext = NULL;
2579
2580 /* Purge deferred symbols from the previous round, if any. */
2581 while (deferred_sym_rootP)
2582 {
2583 symbolS *sym = deferred_sym_rootP;
2584
2585 symbol_remove (sym, &deferred_sym_rootP, &deferred_sym_lastP);
2586 symbol_append (sym, orphan_sym_lastP, &orphan_sym_rootP,
2587 &orphan_sym_lastP);
2588 }
2589
2590 create_insn (ip, insn);
2591
2592 imm_expr->X_op = O_absent;
2593 *imm_reloc = BFD_RELOC_UNUSED;
2594 p = percent_op_null;
2595
2596 for (oparg = insn->args;; ++oparg)
2597 {
2598 opargStart = oparg;
2599 asarg += strspn (asarg, " \t");
2600 switch (*oparg)
2601 {
2602 case '\0': /* End of args. */
2603 if (insn->match_func && !insn->match_func (insn, ip->insn_opcode))
2604 break;
2605
2606 if (insn->pinfo != INSN_MACRO)
2607 {
2608 /* For .insn, insn->match and insn->mask are 0. */
2609 if (riscv_insn_length ((insn->match == 0 && insn->mask == 0)
2610 ? ip->insn_opcode
2611 : insn->match) == 2
2612 && !riscv_opts.rvc)
2613 break;
2614
2615 if (riscv_is_priv_insn (ip->insn_opcode))
2616 explicit_priv_attr = true;
2617
2618 /* Check if we write a read-only CSR by the CSR
2619 instruction. */
2620 if (insn_with_csr
2621 && riscv_opts.csr_check
2622 && !riscv_csr_read_only_check (ip->insn_opcode))
2623 {
2624 /* Restore the character in advance, since we want to
2625 report the detailed warning message here. */
2626 if (save_c)
2627 *(asargStart - 1) = save_c;
2628 as_warn (_("read-only CSR is written `%s'"), str);
2629 insn_with_csr = false;
2630 }
2631
2632 /* The (segmant) load and store with EEW 64 cannot be used
2633 when zve32x is enabled. */
2634 if (ip->insn_mo->pinfo & INSN_V_EEW64
2635 && riscv_subset_supports (&riscv_rps_as, "zve32x")
2636 && !riscv_subset_supports (&riscv_rps_as, "zve64x"))
2637 {
2638 error.msg = _("illegal opcode for zve32x");
2639 break;
2640 }
2641 }
2642 if (*asarg != '\0')
2643 break;
2644
2645 /* Successful assembly. */
2646 error.msg = NULL;
2647 insn_with_csr = false;
2648
2649 /* Commit deferred symbols, if any. */
2650 while (deferred_sym_rootP)
2651 {
2652 symbolS *sym = deferred_sym_rootP;
2653
2654 symbol_remove (sym, &deferred_sym_rootP,
2655 &deferred_sym_lastP);
2656 symbol_append (sym, symbol_lastP, &symbol_rootP,
2657 &symbol_lastP);
2658 symbol_table_insert (sym);
2659 }
2660 goto out;
2661
2662 case 'C': /* RVC */
2663 switch (*++oparg)
2664 {
2665 case 's': /* RS1 x8-x15. */
2666 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2667 || !(regno >= 8 && regno <= 15))
2668 break;
2669 INSERT_OPERAND (CRS1S, *ip, regno % 8);
2670 continue;
2671 case 'w': /* RS1 x8-x15, constrained to equal RD x8-x15. */
2672 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2673 || EXTRACT_OPERAND (CRS1S, ip->insn_opcode) + 8 != regno)
2674 break;
2675 continue;
2676 case 't': /* RS2 x8-x15. */
2677 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2678 || !(regno >= 8 && regno <= 15))
2679 break;
2680 INSERT_OPERAND (CRS2S, *ip, regno % 8);
2681 continue;
2682 case 'x': /* RS2 x8-x15, constrained to equal RD x8-x15. */
2683 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2684 || EXTRACT_OPERAND (CRS2S, ip->insn_opcode) + 8 != regno)
2685 break;
2686 continue;
2687 case 'U': /* RS1, constrained to equal RD. */
2688 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2689 || EXTRACT_OPERAND (RD, ip->insn_opcode) != regno)
2690 break;
2691 continue;
2692 case 'V': /* RS2 */
2693 if (!reg_lookup (&asarg, RCLASS_GPR, &regno))
2694 break;
2695 INSERT_OPERAND (CRS2, *ip, regno);
2696 continue;
2697 case 'c': /* RS1, constrained to equal sp. */
2698 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2699 || regno != X_SP)
2700 break;
2701 continue;
2702 case 'z': /* RS2, constrained to equal x0. */
2703 if (!reg_lookup (&asarg, RCLASS_GPR, &regno)
2704 || regno != 0)
2705 break;
2706 continue;
2707 case '>': /* Shift amount, 0 - (XLEN-1). */
2708 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2709 || imm_expr->X_op != O_constant
2710 || (unsigned long) imm_expr->X_add_number >= xlen)
2711 break;
2712 ip->insn_opcode |= ENCODE_CITYPE_IMM (imm_expr->X_add_number);
2713 rvc_imm_done:
2714 asarg = expr_parse_end;
2715 imm_expr->X_op = O_absent;
2716 continue;
2717 case '5':
2718 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2719 || imm_expr->X_op != O_constant
2720 || imm_expr->X_add_number < 0
2721 || imm_expr->X_add_number >= 32
2722 || !VALID_CLTYPE_IMM ((valueT) imm_expr->X_add_number))
2723 break;
2724 ip->insn_opcode |= ENCODE_CLTYPE_IMM (imm_expr->X_add_number);
2725 goto rvc_imm_done;
2726 case '6':
2727 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2728 || imm_expr->X_op != O_constant
2729 || imm_expr->X_add_number < 0
2730 || imm_expr->X_add_number >= 64
2731 || !VALID_CSSTYPE_IMM ((valueT) imm_expr->X_add_number))
2732 break;
2733 ip->insn_opcode |= ENCODE_CSSTYPE_IMM (imm_expr->X_add_number);
2734 goto rvc_imm_done;
2735 case '8':
2736 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2737 || imm_expr->X_op != O_constant
2738 || imm_expr->X_add_number < 0
2739 || imm_expr->X_add_number >= 256
2740 || !VALID_CIWTYPE_IMM ((valueT) imm_expr->X_add_number))
2741 break;
2742 ip->insn_opcode |= ENCODE_CIWTYPE_IMM (imm_expr->X_add_number);
2743 goto rvc_imm_done;
2744 case 'j':
2745 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2746 || imm_expr->X_op != O_constant
2747 || imm_expr->X_add_number == 0
2748 || !VALID_CITYPE_IMM ((valueT) imm_expr->X_add_number))
2749 break;
2750 ip->insn_opcode |= ENCODE_CITYPE_IMM (imm_expr->X_add_number);
2751 goto rvc_imm_done;
2752 case 'k':
2753 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
2754 continue;
2755 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2756 || imm_expr->X_op != O_constant
2757 || !VALID_CLTYPE_LW_IMM ((valueT) imm_expr->X_add_number))
2758 break;
2759 ip->insn_opcode |= ENCODE_CLTYPE_LW_IMM (imm_expr->X_add_number);
2760 goto rvc_imm_done;
2761 case 'l':
2762 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
2763 continue;
2764 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2765 || imm_expr->X_op != O_constant
2766 || !VALID_CLTYPE_LD_IMM ((valueT) imm_expr->X_add_number))
2767 break;
2768 ip->insn_opcode |= ENCODE_CLTYPE_LD_IMM (imm_expr->X_add_number);
2769 goto rvc_imm_done;
2770 case 'm':
2771 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
2772 continue;
2773 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2774 || imm_expr->X_op != O_constant
2775 || !VALID_CITYPE_LWSP_IMM ((valueT) imm_expr->X_add_number))
2776 break;
2777 ip->insn_opcode |=
2778 ENCODE_CITYPE_LWSP_IMM (imm_expr->X_add_number);
2779 goto rvc_imm_done;
2780 case 'n':
2781 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
2782 continue;
2783 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2784 || imm_expr->X_op != O_constant
2785 || !VALID_CITYPE_LDSP_IMM ((valueT) imm_expr->X_add_number))
2786 break;
2787 ip->insn_opcode |=
2788 ENCODE_CITYPE_LDSP_IMM (imm_expr->X_add_number);
2789 goto rvc_imm_done;
2790 case 'o':
2791 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2792 || imm_expr->X_op != O_constant
2793 /* C.addiw, c.li, and c.andi allow zero immediate.
2794 C.addi allows zero immediate as hint. Otherwise this
2795 is same as 'j'. */
2796 || !VALID_CITYPE_IMM ((valueT) imm_expr->X_add_number))
2797 break;
2798 ip->insn_opcode |= ENCODE_CITYPE_IMM (imm_expr->X_add_number);
2799 goto rvc_imm_done;
2800 case 'K':
2801 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2802 || imm_expr->X_op != O_constant
2803 || imm_expr->X_add_number == 0
2804 || !VALID_CIWTYPE_ADDI4SPN_IMM ((valueT) imm_expr->X_add_number))
2805 break;
2806 ip->insn_opcode |=
2807 ENCODE_CIWTYPE_ADDI4SPN_IMM (imm_expr->X_add_number);
2808 goto rvc_imm_done;
2809 case 'L':
2810 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2811 || imm_expr->X_op != O_constant
2812 || !VALID_CITYPE_ADDI16SP_IMM ((valueT) imm_expr->X_add_number))
2813 break;
2814 ip->insn_opcode |=
2815 ENCODE_CITYPE_ADDI16SP_IMM (imm_expr->X_add_number);
2816 goto rvc_imm_done;
2817 case 'M':
2818 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
2819 continue;
2820 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2821 || imm_expr->X_op != O_constant
2822 || !VALID_CSSTYPE_SWSP_IMM ((valueT) imm_expr->X_add_number))
2823 break;
2824 ip->insn_opcode |=
2825 ENCODE_CSSTYPE_SWSP_IMM (imm_expr->X_add_number);
2826 goto rvc_imm_done;
2827 case 'N':
2828 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
2829 continue;
2830 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2831 || imm_expr->X_op != O_constant
2832 || !VALID_CSSTYPE_SDSP_IMM ((valueT) imm_expr->X_add_number))
2833 break;
2834 ip->insn_opcode |=
2835 ENCODE_CSSTYPE_SDSP_IMM (imm_expr->X_add_number);
2836 goto rvc_imm_done;
2837 case 'u':
2838 p = percent_op_utype;
2839 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p))
2840 break;
2841 rvc_lui:
2842 if (imm_expr->X_op != O_constant
2843 || imm_expr->X_add_number <= 0
2844 || imm_expr->X_add_number >= RISCV_BIGIMM_REACH
2845 || (imm_expr->X_add_number >= RISCV_RVC_IMM_REACH / 2
2846 && (imm_expr->X_add_number <
2847 RISCV_BIGIMM_REACH - RISCV_RVC_IMM_REACH / 2)))
2848 break;
2849 ip->insn_opcode |= ENCODE_CITYPE_IMM (imm_expr->X_add_number);
2850 goto rvc_imm_done;
2851 case 'v':
2852 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2853 || (imm_expr->X_add_number & (RISCV_IMM_REACH - 1))
2854 || ((int32_t)imm_expr->X_add_number
2855 != imm_expr->X_add_number))
2856 break;
2857 imm_expr->X_add_number =
2858 ((uint32_t) imm_expr->X_add_number) >> RISCV_IMM_BITS;
2859 goto rvc_lui;
2860 case 'p':
2861 goto branch;
2862 case 'a':
2863 goto jump;
2864 case 'S': /* Floating-point RS1 x8-x15. */
2865 if (!reg_lookup (&asarg, RCLASS_FPR, &regno)
2866 || !(regno >= 8 && regno <= 15))
2867 break;
2868 INSERT_OPERAND (CRS1S, *ip, regno % 8);
2869 continue;
2870 case 'D': /* Floating-point RS2 x8-x15. */
2871 if (!reg_lookup (&asarg, RCLASS_FPR, &regno)
2872 || !(regno >= 8 && regno <= 15))
2873 break;
2874 INSERT_OPERAND (CRS2S, *ip, regno % 8);
2875 continue;
2876 case 'T': /* Floating-point RS2. */
2877 if (!reg_lookup (&asarg, RCLASS_FPR, &regno))
2878 break;
2879 INSERT_OPERAND (CRS2, *ip, regno);
2880 continue;
2881 case 'F':
2882 switch (*++oparg)
2883 {
2884 case '6':
2885 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2886 || imm_expr->X_op != O_constant
2887 || imm_expr->X_add_number < 0
2888 || imm_expr->X_add_number >= 64)
2889 {
2890 as_bad (_("bad value for compressed funct6 "
2891 "field, value must be 0...63"));
2892 break;
2893 }
2894 INSERT_OPERAND (CFUNCT6, *ip, imm_expr->X_add_number);
2895 imm_expr->X_op = O_absent;
2896 asarg = expr_parse_end;
2897 continue;
2898
2899 case '4':
2900 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2901 || imm_expr->X_op != O_constant
2902 || imm_expr->X_add_number < 0
2903 || imm_expr->X_add_number >= 16)
2904 {
2905 as_bad (_("bad value for compressed funct4 "
2906 "field, value must be 0...15"));
2907 break;
2908 }
2909 INSERT_OPERAND (CFUNCT4, *ip, imm_expr->X_add_number);
2910 imm_expr->X_op = O_absent;
2911 asarg = expr_parse_end;
2912 continue;
2913
2914 case '3':
2915 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2916 || imm_expr->X_op != O_constant
2917 || imm_expr->X_add_number < 0
2918 || imm_expr->X_add_number >= 8)
2919 {
2920 as_bad (_("bad value for compressed funct3 "
2921 "field, value must be 0...7"));
2922 break;
2923 }
2924 INSERT_OPERAND (CFUNCT3, *ip, imm_expr->X_add_number);
2925 imm_expr->X_op = O_absent;
2926 asarg = expr_parse_end;
2927 continue;
2928
2929 case '2':
2930 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
2931 || imm_expr->X_op != O_constant
2932 || imm_expr->X_add_number < 0
2933 || imm_expr->X_add_number >= 4)
2934 {
2935 as_bad (_("bad value for compressed funct2 "
2936 "field, value must be 0...3"));
2937 break;
2938 }
2939 INSERT_OPERAND (CFUNCT2, *ip, imm_expr->X_add_number);
2940 imm_expr->X_op = O_absent;
2941 asarg = expr_parse_end;
2942 continue;
2943
2944 default:
2945 goto unknown_riscv_ip_operand;
2946 }
2947 break;
2948
2949 default:
2950 goto unknown_riscv_ip_operand;
2951 }
2952 break; /* end RVC */
2953
2954 case 'V': /* RVV */
2955 switch (*++oparg)
2956 {
2957 case 'd': /* VD */
2958 if (!reg_lookup (&asarg, RCLASS_VECR, &regno))
2959 break;
2960 INSERT_OPERAND (VD, *ip, regno);
2961 continue;
2962
2963 case 'e': /* AMO VD */
2964 if (reg_lookup (&asarg, RCLASS_GPR, &regno) && regno == 0)
2965 INSERT_OPERAND (VWD, *ip, 0);
2966 else if (reg_lookup (&asarg, RCLASS_VECR, &regno))
2967 {
2968 INSERT_OPERAND (VWD, *ip, 1);
2969 INSERT_OPERAND (VD, *ip, regno);
2970 }
2971 else
2972 break;
2973 continue;
2974
2975 case 'f': /* AMO VS3 */
2976 if (!reg_lookup (&asarg, RCLASS_VECR, &regno))
2977 break;
2978 if (!EXTRACT_OPERAND (VWD, ip->insn_opcode))
2979 INSERT_OPERAND (VD, *ip, regno);
2980 else
2981 {
2982 /* VS3 must match VD. */
2983 if (EXTRACT_OPERAND (VD, ip->insn_opcode) != regno)
2984 break;
2985 }
2986 continue;
2987
2988 case 's': /* VS1 */
2989 if (!reg_lookup (&asarg, RCLASS_VECR, &regno))
2990 break;
2991 INSERT_OPERAND (VS1, *ip, regno);
2992 continue;
2993
2994 case 't': /* VS2 */
2995 if (!reg_lookup (&asarg, RCLASS_VECR, &regno))
2996 break;
2997 INSERT_OPERAND (VS2, *ip, regno);
2998 continue;
2999
3000 case 'u': /* VS1 == VS2 */
3001 if (!reg_lookup (&asarg, RCLASS_VECR, &regno))
3002 break;
3003 INSERT_OPERAND (VS1, *ip, regno);
3004 INSERT_OPERAND (VS2, *ip, regno);
3005 continue;
3006
3007 case 'v': /* VD == VS1 == VS2 */
3008 if (!reg_lookup (&asarg, RCLASS_VECR, &regno))
3009 break;
3010 INSERT_OPERAND (VD, *ip, regno);
3011 INSERT_OPERAND (VS1, *ip, regno);
3012 INSERT_OPERAND (VS2, *ip, regno);
3013 continue;
3014
3015 /* The `V0` is carry-in register for v[m]adc and v[m]sbc,
3016 and is used to choose vs1/rs1/frs1/imm or vs2 for
3017 v[f]merge. It use the same encoding as the vector mask
3018 register. */
3019 case '0':
3020 if (reg_lookup (&asarg, RCLASS_VECR, &regno) && regno == 0)
3021 continue;
3022 break;
3023
3024 case 'b': /* vtypei for vsetivli */
3025 my_getVsetvliExpression (imm_expr, asarg);
3026 check_absolute_expr (ip, imm_expr, FALSE);
3027 if (!VALID_RVV_VB_IMM (imm_expr->X_add_number))
3028 as_bad (_("bad value for vsetivli immediate field, "
3029 "value must be 0..1023"));
3030 ip->insn_opcode
3031 |= ENCODE_RVV_VB_IMM (imm_expr->X_add_number);
3032 imm_expr->X_op = O_absent;
3033 asarg = expr_parse_end;
3034 continue;
3035
3036 case 'c': /* vtypei for vsetvli */
3037 my_getVsetvliExpression (imm_expr, asarg);
3038 check_absolute_expr (ip, imm_expr, FALSE);
3039 if (!VALID_RVV_VC_IMM (imm_expr->X_add_number))
3040 as_bad (_("bad value for vsetvli immediate field, "
3041 "value must be 0..2047"));
3042 ip->insn_opcode
3043 |= ENCODE_RVV_VC_IMM (imm_expr->X_add_number);
3044 imm_expr->X_op = O_absent;
3045 asarg = expr_parse_end;
3046 continue;
3047
3048 case 'i': /* vector arith signed immediate */
3049 my_getExpression (imm_expr, asarg);
3050 check_absolute_expr (ip, imm_expr, FALSE);
3051 if (imm_expr->X_add_number > 15
3052 || imm_expr->X_add_number < -16)
3053 as_bad (_("bad value for vector immediate field, "
3054 "value must be -16...15"));
3055 INSERT_OPERAND (VIMM, *ip, imm_expr->X_add_number);
3056 imm_expr->X_op = O_absent;
3057 asarg = expr_parse_end;
3058 continue;
3059
3060 case 'j': /* vector arith unsigned immediate */
3061 my_getExpression (imm_expr, asarg);
3062 check_absolute_expr (ip, imm_expr, FALSE);
3063 if (imm_expr->X_add_number < 0
3064 || imm_expr->X_add_number >= 32)
3065 as_bad (_("bad value for vector immediate field, "
3066 "value must be 0...31"));
3067 INSERT_OPERAND (VIMM, *ip, imm_expr->X_add_number);
3068 imm_expr->X_op = O_absent;
3069 asarg = expr_parse_end;
3070 continue;
3071
3072 case 'k': /* vector arith signed immediate, minus 1 */
3073 my_getExpression (imm_expr, asarg);
3074 check_absolute_expr (ip, imm_expr, FALSE);
3075 if (imm_expr->X_add_number > 16
3076 || imm_expr->X_add_number < -15)
3077 as_bad (_("bad value for vector immediate field, "
3078 "value must be -15...16"));
3079 INSERT_OPERAND (VIMM, *ip, imm_expr->X_add_number - 1);
3080 imm_expr->X_op = O_absent;
3081 asarg = expr_parse_end;
3082 continue;
3083
3084 case 'l': /* 6-bit vector arith unsigned immediate */
3085 my_getExpression (imm_expr, asarg);
3086 check_absolute_expr (ip, imm_expr, FALSE);
3087 if (imm_expr->X_add_number < 0
3088 || imm_expr->X_add_number >= 64)
3089 as_bad (_("bad value for vector immediate field, "
3090 "value must be 0...63"));
3091 ip->insn_opcode |= ENCODE_RVV_VI_UIMM6 (imm_expr->X_add_number);
3092 imm_expr->X_op = O_absent;
3093 asarg = expr_parse_end;
3094 continue;
3095
3096 case 'm': /* optional vector mask */
3097 if (*asarg == '\0')
3098 {
3099 INSERT_OPERAND (VMASK, *ip, 1);
3100 continue;
3101 }
3102 else if (*asarg == ',' && asarg++
3103 && reg_lookup (&asarg, RCLASS_VECM, &regno)
3104 && regno == 0)
3105 {
3106 INSERT_OPERAND (VMASK, *ip, 0);
3107 continue;
3108 }
3109 break;
3110
3111 case 'M': /* required vector mask */
3112 if (reg_lookup (&asarg, RCLASS_VECM, &regno) && regno == 0)
3113 {
3114 INSERT_OPERAND (VMASK, *ip, 0);
3115 continue;
3116 }
3117 break;
3118
3119 case 'T': /* vector macro temporary register */
3120 if (!reg_lookup (&asarg, RCLASS_VECR, &regno) || regno == 0)
3121 break;
3122 /* Store it in the FUNCT6 field as we don't have anyplace
3123 else to store it. */
3124 INSERT_OPERAND (VFUNCT6, *ip, regno);
3125 continue;
3126
3127 default:
3128 goto unknown_riscv_ip_operand;
3129 }
3130 break; /* end RVV */
3131
3132 case ',':
3133 if (*asarg++ == *oparg)
3134 continue;
3135 asarg--;
3136 break;
3137
3138 case '(':
3139 case ')':
3140 case '[':
3141 case ']':
3142 if (*asarg++ == *oparg)
3143 continue;
3144 break;
3145
3146 case '<': /* Shift amount, 0 - 31. */
3147 my_getExpression (imm_expr, asarg);
3148 check_absolute_expr (ip, imm_expr, false);
3149 if ((unsigned long) imm_expr->X_add_number > 31)
3150 as_bad (_("improper shift amount (%"PRIu64")"),
3151 imm_expr->X_add_number);
3152 INSERT_OPERAND (SHAMTW, *ip, imm_expr->X_add_number);
3153 imm_expr->X_op = O_absent;
3154 asarg = expr_parse_end;
3155 continue;
3156
3157 case '>': /* Shift amount, 0 - (XLEN-1). */
3158 my_getExpression (imm_expr, asarg);
3159 check_absolute_expr (ip, imm_expr, false);
3160 if ((unsigned long) imm_expr->X_add_number >= xlen)
3161 as_bad (_("improper shift amount (%"PRIu64")"),
3162 imm_expr->X_add_number);
3163 INSERT_OPERAND (SHAMT, *ip, imm_expr->X_add_number);
3164 imm_expr->X_op = O_absent;
3165 asarg = expr_parse_end;
3166 continue;
3167
3168 case 'Z': /* CSRRxI immediate. */
3169 my_getExpression (imm_expr, asarg);
3170 check_absolute_expr (ip, imm_expr, false);
3171 if ((unsigned long) imm_expr->X_add_number > 31)
3172 as_bad (_("improper CSRxI immediate (%"PRIu64")"),
3173 imm_expr->X_add_number);
3174 INSERT_OPERAND (RS1, *ip, imm_expr->X_add_number);
3175 imm_expr->X_op = O_absent;
3176 asarg = expr_parse_end;
3177 continue;
3178
3179 case 'E': /* Control register. */
3180 insn_with_csr = true;
3181 explicit_priv_attr = true;
3182 if (reg_lookup (&asarg, RCLASS_CSR, &regno))
3183 INSERT_OPERAND (CSR, *ip, regno);
3184 else
3185 {
3186 my_getExpression (imm_expr, asarg);
3187 check_absolute_expr (ip, imm_expr, true);
3188 if ((unsigned long) imm_expr->X_add_number > 0xfff)
3189 as_bad (_("improper CSR address (%"PRIu64")"),
3190 imm_expr->X_add_number);
3191 INSERT_OPERAND (CSR, *ip, imm_expr->X_add_number);
3192 imm_expr->X_op = O_absent;
3193 asarg = expr_parse_end;
3194 }
3195 continue;
3196
3197 case 'm': /* Rounding mode. */
3198 if (arg_lookup (&asarg, riscv_rm,
3199 ARRAY_SIZE (riscv_rm), &regno))
3200 {
3201 INSERT_OPERAND (RM, *ip, regno);
3202 continue;
3203 }
3204 break;
3205
3206 case 'P':
3207 case 'Q': /* Fence predecessor/successor. */
3208 if (arg_lookup (&asarg, riscv_pred_succ,
3209 ARRAY_SIZE (riscv_pred_succ), &regno))
3210 {
3211 if (*oparg == 'P')
3212 INSERT_OPERAND (PRED, *ip, regno);
3213 else
3214 INSERT_OPERAND (SUCC, *ip, regno);
3215 continue;
3216 }
3217 break;
3218
3219 case 'd': /* Destination register. */
3220 case 's': /* Source register. */
3221 case 't': /* Target register. */
3222 case 'r': /* RS3 */
3223 if (reg_lookup (&asarg, RCLASS_GPR, &regno))
3224 {
3225 char c = *oparg;
3226 if (*asarg == ' ')
3227 ++asarg;
3228
3229 /* Now that we have assembled one operand, we use the args
3230 string to figure out where it goes in the instruction. */
3231 switch (c)
3232 {
3233 case 's':
3234 INSERT_OPERAND (RS1, *ip, regno);
3235 break;
3236 case 'd':
3237 INSERT_OPERAND (RD, *ip, regno);
3238 break;
3239 case 't':
3240 INSERT_OPERAND (RS2, *ip, regno);
3241 break;
3242 case 'r':
3243 INSERT_OPERAND (RS3, *ip, regno);
3244 break;
3245 }
3246 continue;
3247 }
3248 break;
3249
3250 case 'D': /* Floating point RD. */
3251 case 'S': /* Floating point RS1. */
3252 case 'T': /* Floating point RS2. */
3253 case 'U': /* Floating point RS1 and RS2. */
3254 case 'R': /* Floating point RS3. */
3255 if (reg_lookup (&asarg,
3256 (riscv_subset_supports (&riscv_rps_as, "zfinx")
3257 ? RCLASS_GPR : RCLASS_FPR), &regno))
3258 {
3259 char c = *oparg;
3260 if (*asarg == ' ')
3261 ++asarg;
3262 switch (c)
3263 {
3264 case 'D':
3265 INSERT_OPERAND (RD, *ip, regno);
3266 break;
3267 case 'S':
3268 INSERT_OPERAND (RS1, *ip, regno);
3269 break;
3270 case 'U':
3271 INSERT_OPERAND (RS1, *ip, regno);
3272 /* Fall through. */
3273 case 'T':
3274 INSERT_OPERAND (RS2, *ip, regno);
3275 break;
3276 case 'R':
3277 INSERT_OPERAND (RS3, *ip, regno);
3278 break;
3279 }
3280 continue;
3281 }
3282 break;
3283
3284 case 'I':
3285 my_getExpression (imm_expr, asarg);
3286 if (imm_expr->X_op != O_big
3287 && imm_expr->X_op != O_constant)
3288 break;
3289 normalize_constant_expr (imm_expr);
3290 asarg = expr_parse_end;
3291 continue;
3292
3293 case 'A':
3294 my_getExpression (imm_expr, asarg);
3295 normalize_constant_expr (imm_expr);
3296 /* The 'A' format specifier must be a symbol. */
3297 if (imm_expr->X_op != O_symbol)
3298 break;
3299 *imm_reloc = BFD_RELOC_32;
3300 asarg = expr_parse_end;
3301 continue;
3302
3303 case 'B':
3304 my_getExpression (imm_expr, asarg);
3305 normalize_constant_expr (imm_expr);
3306 /* The 'B' format specifier must be a symbol or a constant. */
3307 if (imm_expr->X_op != O_symbol && imm_expr->X_op != O_constant)
3308 break;
3309 if (imm_expr->X_op == O_symbol)
3310 *imm_reloc = BFD_RELOC_32;
3311 asarg = expr_parse_end;
3312 continue;
3313
3314 case 'j': /* Sign-extended immediate. */
3315 p = percent_op_itype;
3316 *imm_reloc = BFD_RELOC_RISCV_LO12_I;
3317 goto alu_op;
3318 case 'q': /* Store displacement. */
3319 p = percent_op_stype;
3320 *imm_reloc = BFD_RELOC_RISCV_LO12_S;
3321 goto load_store;
3322 case 'o': /* Load displacement. */
3323 p = percent_op_itype;
3324 *imm_reloc = BFD_RELOC_RISCV_LO12_I;
3325 goto load_store;
3326 case '1':
3327 /* This is used for TLS, where the fourth operand is
3328 %tprel_add, to get a relocation applied to an add
3329 instruction, for relaxation to use. */
3330 p = percent_op_rtype;
3331 goto alu_op;
3332 case '0': /* AMO displacement, which must be zero. */
3333 load_store:
3334 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
3335 continue;
3336 alu_op:
3337 /* If this value won't fit into a 16 bit offset, then go
3338 find a macro that will generate the 32 bit offset
3339 code pattern. */
3340 if (!my_getSmallExpression (imm_expr, imm_reloc, asarg, p))
3341 {
3342 normalize_constant_expr (imm_expr);
3343 if (imm_expr->X_op != O_constant
3344 || (*oparg == '0' && imm_expr->X_add_number != 0)
3345 || (*oparg == '1')
3346 || imm_expr->X_add_number >= (signed)RISCV_IMM_REACH/2
3347 || imm_expr->X_add_number < -(signed)RISCV_IMM_REACH/2)
3348 break;
3349 }
3350 asarg = expr_parse_end;
3351 continue;
3352
3353 case 'p': /* PC-relative offset. */
3354 branch:
3355 *imm_reloc = BFD_RELOC_12_PCREL;
3356 my_getExpression (imm_expr, asarg);
3357 asarg = expr_parse_end;
3358 continue;
3359
3360 case 'u': /* Upper 20 bits. */
3361 p = percent_op_utype;
3362 if (!my_getSmallExpression (imm_expr, imm_reloc, asarg, p))
3363 {
3364 if (imm_expr->X_op != O_constant)
3365 break;
3366
3367 if (imm_expr->X_add_number < 0
3368 || imm_expr->X_add_number >= (signed)RISCV_BIGIMM_REACH)
3369 as_bad (_("lui expression not in range 0..1048575"));
3370
3371 *imm_reloc = BFD_RELOC_RISCV_HI20;
3372 imm_expr->X_add_number <<= RISCV_IMM_BITS;
3373 }
3374 asarg = expr_parse_end;
3375 continue;
3376
3377 case 'a': /* 20-bit PC-relative offset. */
3378 jump:
3379 my_getExpression (imm_expr, asarg);
3380 asarg = expr_parse_end;
3381 *imm_reloc = BFD_RELOC_RISCV_JMP;
3382 continue;
3383
3384 case 'c':
3385 my_getExpression (imm_expr, asarg);
3386 asarg = expr_parse_end;
3387 if (strcmp (asarg, "@plt") == 0)
3388 asarg += 4;
3389 *imm_reloc = BFD_RELOC_RISCV_CALL_PLT;
3390 continue;
3391
3392 case 'O':
3393 switch (*++oparg)
3394 {
3395 case '4':
3396 if (my_getOpcodeExpression (imm_expr, imm_reloc, asarg)
3397 || imm_expr->X_op != O_constant
3398 || imm_expr->X_add_number < 0
3399 || imm_expr->X_add_number >= 128
3400 || (imm_expr->X_add_number & 0x3) != 3)
3401 {
3402 as_bad (_("bad value for opcode field, "
3403 "value must be 0...127 and "
3404 "lower 2 bits must be 0x3"));
3405 break;
3406 }
3407 INSERT_OPERAND (OP, *ip, imm_expr->X_add_number);
3408 imm_expr->X_op = O_absent;
3409 asarg = expr_parse_end;
3410 continue;
3411
3412 case '2':
3413 if (my_getOpcodeExpression (imm_expr, imm_reloc, asarg)
3414 || imm_expr->X_op != O_constant
3415 || imm_expr->X_add_number < 0
3416 || imm_expr->X_add_number >= 3)
3417 {
3418 as_bad (_("bad value for opcode field, "
3419 "value must be 0...2"));
3420 break;
3421 }
3422 INSERT_OPERAND (OP2, *ip, imm_expr->X_add_number);
3423 imm_expr->X_op = O_absent;
3424 asarg = expr_parse_end;
3425 continue;
3426
3427 default:
3428 goto unknown_riscv_ip_operand;
3429 }
3430 break;
3431
3432 case 'F':
3433 switch (*++oparg)
3434 {
3435 case '7':
3436 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
3437 || imm_expr->X_op != O_constant
3438 || imm_expr->X_add_number < 0
3439 || imm_expr->X_add_number >= 128)
3440 {
3441 as_bad (_("bad value for funct7 field, "
3442 "value must be 0...127"));
3443 break;
3444 }
3445 INSERT_OPERAND (FUNCT7, *ip, imm_expr->X_add_number);
3446 imm_expr->X_op = O_absent;
3447 asarg = expr_parse_end;
3448 continue;
3449
3450 case '3':
3451 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
3452 || imm_expr->X_op != O_constant
3453 || imm_expr->X_add_number < 0
3454 || imm_expr->X_add_number >= 8)
3455 {
3456 as_bad (_("bad value for funct3 field, "
3457 "value must be 0...7"));
3458 break;
3459 }
3460 INSERT_OPERAND (FUNCT3, *ip, imm_expr->X_add_number);
3461 imm_expr->X_op = O_absent;
3462 asarg = expr_parse_end;
3463 continue;
3464
3465 case '2':
3466 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
3467 || imm_expr->X_op != O_constant
3468 || imm_expr->X_add_number < 0
3469 || imm_expr->X_add_number >= 4)
3470 {
3471 as_bad (_("bad value for funct2 field, "
3472 "value must be 0...3"));
3473 break;
3474 }
3475 INSERT_OPERAND (FUNCT2, *ip, imm_expr->X_add_number);
3476 imm_expr->X_op = O_absent;
3477 asarg = expr_parse_end;
3478 continue;
3479
3480 default:
3481 goto unknown_riscv_ip_operand;
3482 }
3483 break;
3484
3485 case 'y': /* bs immediate */
3486 my_getExpression (imm_expr, asarg);
3487 check_absolute_expr (ip, imm_expr, FALSE);
3488 if ((unsigned long)imm_expr->X_add_number > 3)
3489 as_bad(_("Improper bs immediate (%lu)"),
3490 (unsigned long)imm_expr->X_add_number);
3491 INSERT_OPERAND(BS, *ip, imm_expr->X_add_number);
3492 imm_expr->X_op = O_absent;
3493 asarg = expr_parse_end;
3494 continue;
3495
3496 case 'Y': /* rnum immediate */
3497 my_getExpression (imm_expr, asarg);
3498 check_absolute_expr (ip, imm_expr, FALSE);
3499 if ((unsigned long)imm_expr->X_add_number > 10)
3500 as_bad(_("Improper rnum immediate (%lu)"),
3501 (unsigned long)imm_expr->X_add_number);
3502 INSERT_OPERAND(RNUM, *ip, imm_expr->X_add_number);
3503 imm_expr->X_op = O_absent;
3504 asarg = expr_parse_end;
3505 continue;
3506
3507 case 'z':
3508 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
3509 || imm_expr->X_op != O_constant
3510 || imm_expr->X_add_number != 0)
3511 break;
3512 asarg = expr_parse_end;
3513 imm_expr->X_op = O_absent;
3514 continue;
3515
3516 case 'W': /* Various operands for standard z extensions. */
3517 switch (*++oparg)
3518 {
3519 case 'i':
3520 switch (*++oparg)
3521 {
3522 case 'f':
3523 /* Prefetch offset for 'Zicbop' extension.
3524 pseudo S-type but lower 5-bits zero. */
3525 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
3526 continue;
3527 my_getExpression (imm_expr, asarg);
3528 check_absolute_expr (ip, imm_expr, false);
3529 if (((unsigned) (imm_expr->X_add_number) & 0x1fU)
3530 || imm_expr->X_add_number >= RISCV_IMM_REACH / 2
3531 || imm_expr->X_add_number < -RISCV_IMM_REACH / 2)
3532 as_bad (_ ("improper prefetch offset (%ld)"),
3533 (long) imm_expr->X_add_number);
3534 ip->insn_opcode |= ENCODE_STYPE_IMM (
3535 (unsigned) (imm_expr->X_add_number) & ~0x1fU);
3536 imm_expr->X_op = O_absent;
3537 asarg = expr_parse_end;
3538 continue;
3539 default:
3540 goto unknown_riscv_ip_operand;
3541 }
3542 break;
3543
3544 case 'f':
3545 switch (*++oparg)
3546 {
3547 case 'v':
3548 /* FLI.[HSDQ] value field for 'Zfa' extension. */
3549 if (!arg_lookup (&asarg, riscv_fli_symval,
3550 ARRAY_SIZE (riscv_fli_symval), &regno))
3551 {
3552 /* 0.0 is not a valid entry in riscv_fli_numval. */
3553 errno = 0;
3554 float f = strtof (asarg, &asarg);
3555 if (errno != 0 || f == 0.0
3556 || !flt_lookup (f, riscv_fli_numval,
3557 ARRAY_SIZE(riscv_fli_numval),
3558 &regno))
3559 {
3560 as_bad (_("bad fli constant operand, "
3561 "supported constants must be in "
3562 "decimal or hexadecimal floating-point "
3563 "literal form"));
3564 break;
3565 }
3566 }
3567 INSERT_OPERAND (RS1, *ip, regno);
3568 continue;
3569 default:
3570 goto unknown_riscv_ip_operand;
3571 }
3572 break;
3573
3574 case 'c':
3575 switch (*++oparg)
3576 {
3577 case 'h': /* Immediate field for c.lh/c.lhu/c.sh. */
3578 /* Handle cases, such as c.sh rs2', (rs1'). */
3579 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
3580 continue;
3581 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
3582 || imm_expr->X_op != O_constant
3583 || !VALID_ZCB_HALFWORD_UIMM ((valueT) imm_expr->X_add_number))
3584 break;
3585 ip->insn_opcode |= ENCODE_ZCB_HALFWORD_UIMM (imm_expr->X_add_number);
3586 goto rvc_imm_done;
3587 case 'b': /* Immediate field for c.lbu/c.sb. */
3588 /* Handle cases, such as c.lbu rd', (rs1'). */
3589 if (riscv_handle_implicit_zero_offset (imm_expr, asarg))
3590 continue;
3591 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
3592 || imm_expr->X_op != O_constant
3593 || !VALID_ZCB_BYTE_UIMM ((valueT) imm_expr->X_add_number))
3594 break;
3595 ip->insn_opcode |= ENCODE_ZCB_BYTE_UIMM (imm_expr->X_add_number);
3596 goto rvc_imm_done;
3597 case 'f': /* Operand for matching immediate 255. */
3598 if (my_getSmallExpression (imm_expr, imm_reloc, asarg, p)
3599 || imm_expr->X_op != O_constant
3600 || imm_expr->X_add_number != 255)
3601 break;
3602 /* This operand is used for matching immediate 255, and
3603 we do not write anything to encoding by this operand. */
3604 asarg = expr_parse_end;
3605 imm_expr->X_op = O_absent;
3606 continue;
3607 default:
3608 goto unknown_riscv_ip_operand;
3609 }
3610 break;
3611
3612 default:
3613 goto unknown_riscv_ip_operand;
3614 }
3615 break;
3616
3617 case 'X': /* Vendor-specific operands. */
3618 switch (*++oparg)
3619 {
3620 case 't': /* Vendor-specific (T-head) operands. */
3621 {
3622 size_t n;
3623 size_t s;
3624 bool sign;
3625 switch (*++oparg)
3626 {
3627 case 'l': /* Integer immediate, literal. */
3628 n = strcspn (++oparg, ",");
3629 if (strncmp (oparg, asarg, n))
3630 as_bad (_("unexpected literal (%s)"), asarg);
3631 oparg += n - 1;
3632 asarg += n;
3633 continue;
3634 case 's': /* Integer immediate, 'XsN@S' ... N-bit signed immediate at bit S. */
3635 sign = true;
3636 goto parse_imm;
3637 case 'u': /* Integer immediate, 'XuN@S' ... N-bit unsigned immediate at bit S. */
3638 sign = false;
3639 goto parse_imm;
3640 parse_imm:
3641 n = strtol (oparg + 1, (char **)&oparg, 10);
3642 if (*oparg != '@')
3643 goto unknown_riscv_ip_operand;
3644 s = strtol (oparg + 1, (char **)&oparg, 10);
3645 oparg--;
3646
3647 my_getExpression (imm_expr, asarg);
3648 check_absolute_expr (ip, imm_expr, false);
3649 if (!sign)
3650 {
3651 if (!VALIDATE_U_IMM (imm_expr->X_add_number, n))
3652 as_bad (_("improper immediate value (%"PRIu64")"),
3653 imm_expr->X_add_number);
3654 }
3655 else
3656 {
3657 if (!VALIDATE_S_IMM (imm_expr->X_add_number, n))
3658 as_bad (_("improper immediate value (%"PRIi64")"),
3659 imm_expr->X_add_number);
3660 }
3661 INSERT_IMM (n, s, *ip, imm_expr->X_add_number);
3662 imm_expr->X_op = O_absent;
3663 asarg = expr_parse_end;
3664 continue;
3665 default:
3666 goto unknown_riscv_ip_operand;
3667 }
3668 }
3669 break;
3670
3671 case 'c': /* Vendor-specific (CORE-V) operands. */
3672 switch (*++oparg)
3673 {
3674 case '2':
3675 my_getExpression (imm_expr, asarg);
3676 check_absolute_expr (ip, imm_expr, FALSE);
3677 asarg = expr_parse_end;
3678 if (imm_expr->X_add_number<0
3679 || imm_expr->X_add_number>31)
3680 break;
3681 ip->insn_opcode
3682 |= ENCODE_CV_IS2_UIMM5 (imm_expr->X_add_number);
3683 continue;
3684 case '3':
3685 my_getExpression (imm_expr, asarg);
3686 check_absolute_expr (ip, imm_expr, FALSE);
3687 asarg = expr_parse_end;
3688 if (imm_expr->X_add_number < 0
3689 || imm_expr->X_add_number > 31)
3690 break;
3691 ip->insn_opcode
3692 |= ENCODE_CV_IS3_UIMM5 (imm_expr->X_add_number);
3693 continue;
3694 default:
3695 goto unknown_riscv_ip_operand;
3696 }
3697 break;
3698
3699 case 's': /* Vendor-specific (SiFive) operands. */
3700 #define UIMM_BITFIELD_VAL(S, E) (1 << ((E) - (S) + 1))
3701 #define ENCODE_UIMM_BIT_FIELD(NAME, IP, EXPR, RELOC, ASARG, \
3702 START, END) \
3703 do \
3704 { \
3705 if (my_getOpcodeExpression (EXPR, RELOC, ASARG) \
3706 || EXPR->X_op != O_constant \
3707 || EXPR->X_add_number < 0 \
3708 || EXPR->X_add_number >= UIMM_BITFIELD_VAL (START, END)) \
3709 { \
3710 as_bad (_("bad value for <bit-%s-%s> " \
3711 "field, value must be 0...%d"), \
3712 #START, #END, UIMM_BITFIELD_VAL (START, END)); \
3713 break; \
3714 } \
3715 INSERT_OPERAND (NAME, *IP, EXPR->X_add_number); \
3716 EXPR->X_op = O_absent; \
3717 ASARG = expr_parse_end; \
3718 } \
3719 while (0);
3720 switch (*++oparg)
3721 {
3722 case 'd': /* Xsd */
3723 ENCODE_UIMM_BIT_FIELD
3724 (RD, ip, imm_expr, imm_reloc, asarg, 7, 11);
3725 continue;
3726 case 't': /* Xst */
3727 ENCODE_UIMM_BIT_FIELD
3728 (RS2, ip, imm_expr, imm_reloc, asarg, 20, 24)
3729 continue;
3730 case 'O':
3731 switch (*++oparg)
3732 {
3733 case '2': /* XsO2 */
3734 ENCODE_UIMM_BIT_FIELD
3735 (XSO2, ip, imm_expr, imm_reloc, asarg, 26, 27);
3736 continue;
3737 case '1': /* XsO1 */
3738 ENCODE_UIMM_BIT_FIELD
3739 (XSO1, ip, imm_expr, imm_reloc, asarg, 26, 26);
3740 continue;
3741 }
3742 default:
3743 goto unknown_riscv_ip_operand;
3744 }
3745 #undef UIMM_BITFIELD_VAL
3746 #undef ENCODE_UIMM_BIT_FIELD
3747 break;
3748
3749 default:
3750 goto unknown_riscv_ip_operand;
3751 }
3752 break;
3753
3754 default:
3755 unknown_riscv_ip_operand:
3756 as_fatal (_("internal: unknown argument type `%s'"),
3757 opargStart);
3758 }
3759 break;
3760 }
3761 asarg = asargStart;
3762 insn_with_csr = false;
3763 }
3764
3765 out:
3766 /* Restore the character we might have clobbered above. */
3767 if (save_c)
3768 *(asargStart - 1) = save_c;
3769
3770 probing_insn_operands = false;
3771
3772 return error;
3773 }
3774
3775 /* Similar to riscv_ip, but assembles an instruction according to the
3776 hardcode values of .insn directive. */
3777
3778 static const char *
3779 riscv_ip_hardcode (char *str,
3780 struct riscv_cl_insn *ip,
3781 expressionS *imm_expr,
3782 const char *error)
3783 {
3784 struct riscv_opcode *insn;
3785 insn_t values[2] = {0, 0};
3786 unsigned int num = 0;
3787
3788 input_line_pointer = str;
3789 do
3790 {
3791 expression (imm_expr);
3792 switch (imm_expr->X_op)
3793 {
3794 case O_constant:
3795 values[num++] = (insn_t) imm_expr->X_add_number;
3796 break;
3797 case O_big:
3798 /* Extract lower 32-bits of a big number.
3799 Assume that generic_bignum_to_int32 work on such number. */
3800 values[num++] = (insn_t) generic_bignum_to_int32 ();
3801 break;
3802 default:
3803 /* The first value isn't constant, so it should be
3804 .insn <type> <operands>. We have been parsed it
3805 in the riscv_ip. */
3806 if (num == 0)
3807 return error;
3808 return _("values must be constant");
3809 }
3810 }
3811 while (*input_line_pointer++ == ',' && num < 2 && imm_expr->X_op != O_big);
3812
3813 input_line_pointer--;
3814 if (*input_line_pointer != '\0')
3815 return _("unrecognized values");
3816
3817 insn = XCNEW (struct riscv_opcode);
3818 insn->match = values[num - 1];
3819 create_insn (ip, insn);
3820 unsigned int bytes = riscv_insn_length (insn->match);
3821
3822 if (num == 2 && values[0] != bytes)
3823 return _("value conflicts with instruction length");
3824
3825 if (imm_expr->X_op == O_big)
3826 {
3827 unsigned int llen = 0;
3828 for (LITTLENUM_TYPE lval = generic_bignum[imm_expr->X_add_number - 1];
3829 lval != 0; llen++)
3830 lval >>= BITS_PER_CHAR;
3831 unsigned int repr_bytes
3832 = (imm_expr->X_add_number - 1) * CHARS_PER_LITTLENUM + llen;
3833 if (bytes < repr_bytes)
3834 return _("value conflicts with instruction length");
3835 for (num = 0; num < imm_expr->X_add_number - 1; ++num)
3836 number_to_chars_littleendian (
3837 ip->insn_long_opcode + num * CHARS_PER_LITTLENUM,
3838 generic_bignum[num],
3839 CHARS_PER_LITTLENUM);
3840 if (llen != 0)
3841 number_to_chars_littleendian (
3842 ip->insn_long_opcode + num * CHARS_PER_LITTLENUM,
3843 generic_bignum[num],
3844 llen);
3845 memset(ip->insn_long_opcode + repr_bytes, 0, bytes - repr_bytes);
3846 return NULL;
3847 }
3848
3849 if (bytes < sizeof(values[0]) && values[num - 1] >> (8 * bytes) != 0)
3850 return _("value conflicts with instruction length");
3851
3852 return NULL;
3853 }
3854
3855 void
3856 md_assemble (char *str)
3857 {
3858 struct riscv_cl_insn insn;
3859 expressionS imm_expr;
3860 bfd_reloc_code_real_type imm_reloc = BFD_RELOC_UNUSED;
3861
3862 /* The architecture and privileged elf attributes should be set
3863 before assembling. */
3864 if (!start_assemble)
3865 {
3866 start_assemble = true;
3867
3868 riscv_set_abi_by_arch ();
3869 if (!riscv_set_default_priv_spec (NULL))
3870 return;
3871 }
3872
3873 riscv_mapping_state (MAP_INSN, 0, false/* fr_align_code */);
3874
3875 const struct riscv_ip_error error = riscv_ip (str, &insn, &imm_expr,
3876 &imm_reloc, op_hash);
3877
3878 if (error.msg)
3879 {
3880 if (error.missing_ext)
3881 as_bad ("%s `%s', extension `%s' required", error.msg,
3882 error.statement, error.missing_ext);
3883 else
3884 as_bad ("%s `%s'", error.msg, error.statement);
3885 return;
3886 }
3887
3888 if (insn.insn_mo->pinfo == INSN_MACRO)
3889 macro (&insn, &imm_expr, &imm_reloc);
3890 else
3891 append_insn (&insn, &imm_expr, imm_reloc);
3892 }
3893
3894 const char *
3895 md_atof (int type, char *litP, int *sizeP)
3896 {
3897 return ieee_md_atof (type, litP, sizeP, target_big_endian);
3898 }
3899
3900 void
3901 md_number_to_chars (char *buf, valueT val, int n)
3902 {
3903 if (target_big_endian)
3904 number_to_chars_bigendian (buf, val, n);
3905 else
3906 number_to_chars_littleendian (buf, val, n);
3907 }
3908
3909 const char *md_shortopts = "O::g::G:";
3910
3911 enum options
3912 {
3913 OPTION_MARCH = OPTION_MD_BASE,
3914 OPTION_PIC,
3915 OPTION_NO_PIC,
3916 OPTION_MABI,
3917 OPTION_RELAX,
3918 OPTION_NO_RELAX,
3919 OPTION_ARCH_ATTR,
3920 OPTION_NO_ARCH_ATTR,
3921 OPTION_CSR_CHECK,
3922 OPTION_NO_CSR_CHECK,
3923 OPTION_MISA_SPEC,
3924 OPTION_MPRIV_SPEC,
3925 OPTION_BIG_ENDIAN,
3926 OPTION_LITTLE_ENDIAN,
3927 OPTION_END_OF_ENUM
3928 };
3929
3930 struct option md_longopts[] =
3931 {
3932 {"march", required_argument, NULL, OPTION_MARCH},
3933 {"fPIC", no_argument, NULL, OPTION_PIC},
3934 {"fpic", no_argument, NULL, OPTION_PIC},
3935 {"fno-pic", no_argument, NULL, OPTION_NO_PIC},
3936 {"mabi", required_argument, NULL, OPTION_MABI},
3937 {"mrelax", no_argument, NULL, OPTION_RELAX},
3938 {"mno-relax", no_argument, NULL, OPTION_NO_RELAX},
3939 {"march-attr", no_argument, NULL, OPTION_ARCH_ATTR},
3940 {"mno-arch-attr", no_argument, NULL, OPTION_NO_ARCH_ATTR},
3941 {"mcsr-check", no_argument, NULL, OPTION_CSR_CHECK},
3942 {"mno-csr-check", no_argument, NULL, OPTION_NO_CSR_CHECK},
3943 {"misa-spec", required_argument, NULL, OPTION_MISA_SPEC},
3944 {"mpriv-spec", required_argument, NULL, OPTION_MPRIV_SPEC},
3945 {"mbig-endian", no_argument, NULL, OPTION_BIG_ENDIAN},
3946 {"mlittle-endian", no_argument, NULL, OPTION_LITTLE_ENDIAN},
3947
3948 {NULL, no_argument, NULL, 0}
3949 };
3950 size_t md_longopts_size = sizeof (md_longopts);
3951
3952 int
3953 md_parse_option (int c, const char *arg)
3954 {
3955 switch (c)
3956 {
3957 case OPTION_MARCH:
3958 default_arch_with_ext = arg;
3959 break;
3960
3961 case OPTION_NO_PIC:
3962 riscv_opts.pic = false;
3963 break;
3964
3965 case OPTION_PIC:
3966 riscv_opts.pic = true;
3967 break;
3968
3969 case OPTION_MABI:
3970 if (strcmp (arg, "ilp32") == 0)
3971 riscv_set_abi (32, FLOAT_ABI_SOFT, false);
3972 else if (strcmp (arg, "ilp32e") == 0)
3973 riscv_set_abi (32, FLOAT_ABI_SOFT, true);
3974 else if (strcmp (arg, "ilp32f") == 0)
3975 riscv_set_abi (32, FLOAT_ABI_SINGLE, false);
3976 else if (strcmp (arg, "ilp32d") == 0)
3977 riscv_set_abi (32, FLOAT_ABI_DOUBLE, false);
3978 else if (strcmp (arg, "ilp32q") == 0)
3979 riscv_set_abi (32, FLOAT_ABI_QUAD, false);
3980 else if (strcmp (arg, "lp64") == 0)
3981 riscv_set_abi (64, FLOAT_ABI_SOFT, false);
3982 else if (strcmp (arg, "lp64e") == 0)
3983 riscv_set_abi (64, FLOAT_ABI_SOFT, true);
3984 else if (strcmp (arg, "lp64f") == 0)
3985 riscv_set_abi (64, FLOAT_ABI_SINGLE, false);
3986 else if (strcmp (arg, "lp64d") == 0)
3987 riscv_set_abi (64, FLOAT_ABI_DOUBLE, false);
3988 else if (strcmp (arg, "lp64q") == 0)
3989 riscv_set_abi (64, FLOAT_ABI_QUAD, false);
3990 else
3991 return 0;
3992 explicit_mabi = true;
3993 break;
3994
3995 case OPTION_RELAX:
3996 riscv_opts.relax = true;
3997 break;
3998
3999 case OPTION_NO_RELAX:
4000 riscv_opts.relax = false;
4001 break;
4002
4003 case OPTION_ARCH_ATTR:
4004 riscv_opts.arch_attr = true;
4005 break;
4006
4007 case OPTION_NO_ARCH_ATTR:
4008 riscv_opts.arch_attr = false;
4009 break;
4010
4011 case OPTION_CSR_CHECK:
4012 riscv_opts.csr_check = true;
4013 break;
4014
4015 case OPTION_NO_CSR_CHECK:
4016 riscv_opts.csr_check = false;
4017 break;
4018
4019 case OPTION_MISA_SPEC:
4020 return riscv_set_default_isa_spec (arg);
4021
4022 case OPTION_MPRIV_SPEC:
4023 return riscv_set_default_priv_spec (arg);
4024
4025 case OPTION_BIG_ENDIAN:
4026 target_big_endian = 1;
4027 break;
4028
4029 case OPTION_LITTLE_ENDIAN:
4030 target_big_endian = 0;
4031 break;
4032
4033 default:
4034 return 0;
4035 }
4036
4037 return 1;
4038 }
4039
4040 void
4041 riscv_after_parse_args (void)
4042 {
4043 /* The --with-arch is optional for now, so we still need to set the xlen
4044 according to the default_arch, which is set by the --target. */
4045 if (xlen == 0)
4046 {
4047 if (strcmp (default_arch, "riscv32") == 0)
4048 xlen = 32;
4049 else if (strcmp (default_arch, "riscv64") == 0)
4050 xlen = 64;
4051 else
4052 as_bad ("unknown default architecture `%s'", default_arch);
4053 }
4054
4055 /* Set default specs. */
4056 if (default_isa_spec == ISA_SPEC_CLASS_NONE)
4057 riscv_set_default_isa_spec (DEFAULT_RISCV_ISA_SPEC);
4058 if (default_priv_spec == PRIV_SPEC_CLASS_NONE)
4059 riscv_set_default_priv_spec (DEFAULT_RISCV_PRIV_SPEC);
4060
4061 riscv_set_arch (default_arch_with_ext);
4062
4063 /* If the CIE to be produced has not been overridden on the command line,
4064 then produce version 3 by default. This allows us to use the full
4065 range of registers in a .cfi_return_column directive. */
4066 if (flag_dwarf_cie_version == -1)
4067 flag_dwarf_cie_version = 3;
4068 }
4069
4070 bool riscv_parse_name (const char *name, struct expressionS *ep,
4071 enum expr_mode mode)
4072 {
4073 unsigned int regno;
4074 symbolS *sym;
4075
4076 if (!probing_insn_operands)
4077 return false;
4078
4079 gas_assert (mode == expr_normal);
4080
4081 regno = reg_lookup_internal (name, RCLASS_GPR);
4082 if (regno == (unsigned int)-1)
4083 return false;
4084
4085 if (symbol_find (name) != NULL)
4086 return false;
4087
4088 /* Create a symbol without adding it to the symbol table yet.
4089 Insertion will happen only once we commit to using the insn
4090 we're probing operands for. */
4091 for (sym = deferred_sym_rootP; sym; sym = symbol_next (sym))
4092 if (strcmp (name, S_GET_NAME (sym)) == 0)
4093 break;
4094 if (!sym)
4095 {
4096 for (sym = orphan_sym_rootP; sym; sym = symbol_next (sym))
4097 if (strcmp (name, S_GET_NAME (sym)) == 0)
4098 {
4099 symbol_remove (sym, &orphan_sym_rootP, &orphan_sym_lastP);
4100 break;
4101 }
4102 if (!sym)
4103 sym = symbol_create (name, undefined_section,
4104 &zero_address_frag, 0);
4105
4106 symbol_append (sym, deferred_sym_lastP, &deferred_sym_rootP,
4107 &deferred_sym_lastP);
4108 }
4109
4110 ep->X_op = O_symbol;
4111 ep->X_add_symbol = sym;
4112 ep->X_add_number = 0;
4113
4114 return true;
4115 }
4116
4117 long
4118 md_pcrel_from (fixS *fixP)
4119 {
4120 return fixP->fx_where + fixP->fx_frag->fr_address;
4121 }
4122
4123 /* Apply a fixup to the object file. */
4124
4125 void
4126 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
4127 {
4128 unsigned int subtype;
4129 bfd_byte *buf = (bfd_byte *) (fixP->fx_frag->fr_literal + fixP->fx_where);
4130 bool relaxable = false;
4131 offsetT loc;
4132 segT sub_segment;
4133
4134 /* Remember value for tc_gen_reloc. */
4135 fixP->fx_addnumber = *valP;
4136
4137 switch (fixP->fx_r_type)
4138 {
4139 case BFD_RELOC_RISCV_HI20:
4140 case BFD_RELOC_RISCV_LO12_I:
4141 case BFD_RELOC_RISCV_LO12_S:
4142 bfd_putl32 (riscv_apply_const_reloc (fixP->fx_r_type, *valP)
4143 | bfd_getl32 (buf), buf);
4144 if (fixP->fx_addsy == NULL)
4145 fixP->fx_done = true;
4146 relaxable = true;
4147 break;
4148
4149 case BFD_RELOC_RISCV_GOT_HI20:
4150 /* R_RISCV_GOT_HI20 and the following R_RISCV_LO12_I are relaxable
4151 only if it is created as a result of la or lga assembler macros. */
4152 if (fixP->tc_fix_data.source_macro == M_LA
4153 || fixP->tc_fix_data.source_macro == M_LGA)
4154 relaxable = true;
4155 break;
4156
4157 case BFD_RELOC_RISCV_ADD8:
4158 case BFD_RELOC_RISCV_ADD16:
4159 case BFD_RELOC_RISCV_ADD32:
4160 case BFD_RELOC_RISCV_ADD64:
4161 case BFD_RELOC_RISCV_SUB6:
4162 case BFD_RELOC_RISCV_SUB8:
4163 case BFD_RELOC_RISCV_SUB16:
4164 case BFD_RELOC_RISCV_SUB32:
4165 case BFD_RELOC_RISCV_SUB64:
4166 case BFD_RELOC_RISCV_RELAX:
4167 /* cvt_frag_to_fill () has called output_leb128 (). */
4168 case BFD_RELOC_RISCV_SET_ULEB128:
4169 case BFD_RELOC_RISCV_SUB_ULEB128:
4170 break;
4171
4172 case BFD_RELOC_RISCV_TPREL_HI20:
4173 case BFD_RELOC_RISCV_TPREL_LO12_I:
4174 case BFD_RELOC_RISCV_TPREL_LO12_S:
4175 case BFD_RELOC_RISCV_TPREL_ADD:
4176 relaxable = true;
4177 /* Fall through. */
4178
4179 case BFD_RELOC_RISCV_TLS_GOT_HI20:
4180 case BFD_RELOC_RISCV_TLS_GD_HI20:
4181 case BFD_RELOC_RISCV_TLS_DTPREL32:
4182 case BFD_RELOC_RISCV_TLS_DTPREL64:
4183 if (fixP->fx_addsy != NULL)
4184 S_SET_THREAD_LOCAL (fixP->fx_addsy);
4185 else
4186 as_bad_where (fixP->fx_file, fixP->fx_line,
4187 _("TLS relocation against a constant"));
4188 break;
4189
4190 case BFD_RELOC_32:
4191 /* Use pc-relative relocation for FDE initial location.
4192 The symbol address in .eh_frame may be adjusted in
4193 _bfd_elf_discard_section_eh_frame, and the content of
4194 .eh_frame will be adjusted in _bfd_elf_write_section_eh_frame.
4195 Therefore, we cannot insert a relocation whose addend symbol is
4196 in .eh_frame. Othrewise, the value may be adjusted twice. */
4197 if (fixP->fx_addsy && fixP->fx_subsy
4198 && (sub_segment = S_GET_SEGMENT (fixP->fx_subsy))
4199 && strcmp (sub_segment->name, ".eh_frame") == 0
4200 && S_GET_VALUE (fixP->fx_subsy)
4201 == fixP->fx_frag->fr_address + fixP->fx_where)
4202 {
4203 fixP->fx_r_type = BFD_RELOC_RISCV_32_PCREL;
4204 fixP->fx_subsy = NULL;
4205 break;
4206 }
4207 /* Fall through. */
4208 case BFD_RELOC_64:
4209 case BFD_RELOC_16:
4210 case BFD_RELOC_8:
4211 case BFD_RELOC_RISCV_CFA:
4212 if (fixP->fx_addsy && fixP->fx_subsy)
4213 {
4214 fixP->fx_next = xmemdup (fixP, sizeof (*fixP), sizeof (*fixP));
4215 fixP->fx_next->fx_addsy = fixP->fx_subsy;
4216 fixP->fx_next->fx_subsy = NULL;
4217 fixP->fx_next->fx_offset = 0;
4218 fixP->fx_subsy = NULL;
4219
4220 switch (fixP->fx_r_type)
4221 {
4222 case BFD_RELOC_64:
4223 fixP->fx_r_type = BFD_RELOC_RISCV_ADD64;
4224 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB64;
4225 break;
4226
4227 case BFD_RELOC_32:
4228 fixP->fx_r_type = BFD_RELOC_RISCV_ADD32;
4229 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB32;
4230 break;
4231
4232 case BFD_RELOC_16:
4233 fixP->fx_r_type = BFD_RELOC_RISCV_ADD16;
4234 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB16;
4235 break;
4236
4237 case BFD_RELOC_8:
4238 fixP->fx_r_type = BFD_RELOC_RISCV_ADD8;
4239 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB8;
4240 break;
4241
4242 case BFD_RELOC_RISCV_CFA:
4243 /* Load the byte to get the subtype. */
4244 subtype = bfd_get_8 (NULL, &((fragS *) (fixP->fx_frag->fr_opcode))->fr_literal[fixP->fx_where]);
4245 loc = fixP->fx_frag->fr_fix - (subtype & 7);
4246 switch (subtype)
4247 {
4248 case DW_CFA_advance_loc1:
4249 fixP->fx_where = loc + 1;
4250 fixP->fx_next->fx_where = loc + 1;
4251 fixP->fx_r_type = BFD_RELOC_RISCV_SET8;
4252 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB8;
4253 break;
4254
4255 case DW_CFA_advance_loc2:
4256 fixP->fx_size = 2;
4257 fixP->fx_next->fx_size = 2;
4258 fixP->fx_where = loc + 1;
4259 fixP->fx_next->fx_where = loc + 1;
4260 fixP->fx_r_type = BFD_RELOC_RISCV_SET16;
4261 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB16;
4262 break;
4263
4264 case DW_CFA_advance_loc4:
4265 fixP->fx_size = 4;
4266 fixP->fx_next->fx_size = 4;
4267 fixP->fx_where = loc;
4268 fixP->fx_next->fx_where = loc;
4269 fixP->fx_r_type = BFD_RELOC_RISCV_SET32;
4270 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB32;
4271 break;
4272
4273 default:
4274 if (subtype < 0x80 && (subtype & 0x40))
4275 {
4276 /* DW_CFA_advance_loc */
4277 fixP->fx_frag = (fragS *) fixP->fx_frag->fr_opcode;
4278 fixP->fx_next->fx_frag = fixP->fx_frag;
4279 fixP->fx_r_type = BFD_RELOC_RISCV_SET6;
4280 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB6;
4281 }
4282 else
4283 as_fatal (_("internal: bad CFA value #%d"), subtype);
4284 break;
4285 }
4286 break;
4287
4288 default:
4289 /* This case is unreachable. */
4290 abort ();
4291 }
4292 }
4293 /* Fall through. */
4294
4295 case BFD_RELOC_RVA:
4296 /* If we are deleting this reloc entry, we must fill in the
4297 value now. This can happen if we have a .word which is not
4298 resolved when it appears but is later defined. */
4299 if (fixP->fx_addsy == NULL)
4300 {
4301 gas_assert (fixP->fx_size <= sizeof (valueT));
4302 md_number_to_chars ((char *) buf, *valP, fixP->fx_size);
4303 fixP->fx_done = 1;
4304 }
4305 break;
4306
4307 case BFD_RELOC_RISCV_JMP:
4308 if (fixP->fx_addsy)
4309 {
4310 /* Fill in a tentative value to improve objdump readability. */
4311 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
4312 bfd_vma delta = target - md_pcrel_from (fixP);
4313 bfd_putl32 (bfd_getl32 (buf) | ENCODE_JTYPE_IMM (delta), buf);
4314 }
4315 break;
4316
4317 case BFD_RELOC_12_PCREL:
4318 if (fixP->fx_addsy)
4319 {
4320 /* Fill in a tentative value to improve objdump readability. */
4321 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
4322 bfd_vma delta = target - md_pcrel_from (fixP);
4323 bfd_putl32 (bfd_getl32 (buf) | ENCODE_BTYPE_IMM (delta), buf);
4324 }
4325 break;
4326
4327 case BFD_RELOC_RISCV_RVC_BRANCH:
4328 if (fixP->fx_addsy)
4329 {
4330 /* Fill in a tentative value to improve objdump readability. */
4331 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
4332 bfd_vma delta = target - md_pcrel_from (fixP);
4333 bfd_putl16 (bfd_getl16 (buf) | ENCODE_CBTYPE_IMM (delta), buf);
4334 }
4335 break;
4336
4337 case BFD_RELOC_RISCV_RVC_JUMP:
4338 if (fixP->fx_addsy)
4339 {
4340 /* Fill in a tentative value to improve objdump readability. */
4341 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
4342 bfd_vma delta = target - md_pcrel_from (fixP);
4343 bfd_putl16 (bfd_getl16 (buf) | ENCODE_CJTYPE_IMM (delta), buf);
4344 }
4345 break;
4346
4347 case BFD_RELOC_RISCV_CALL:
4348 case BFD_RELOC_RISCV_CALL_PLT:
4349 relaxable = true;
4350 break;
4351
4352 case BFD_RELOC_RISCV_PCREL_HI20:
4353 /* Record and evaluate the pcrel_hi relocation with local symbol.
4354 Fill in a tentative value to improve objdump readability for -mrelax,
4355 and set fx_done for -mno-relax. */
4356 if (fixP->fx_addsy
4357 && S_IS_LOCAL (fixP->fx_addsy)
4358 && S_GET_SEGMENT (fixP->fx_addsy) == seg)
4359 {
4360 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
4361 bfd_vma value = target - md_pcrel_from (fixP);
4362
4363 /* Record PCREL_HI20. */
4364 if (!riscv_record_pcrel_fixup (riscv_pcrel_hi_fixup_hash,
4365 md_pcrel_from (fixP),
4366 fixP->fx_addsy,
4367 target))
4368 as_warn (_("too many pcrel_hi"));
4369
4370 bfd_putl32 (bfd_getl32 (buf)
4371 | ENCODE_UTYPE_IMM (RISCV_CONST_HIGH_PART (value)),
4372 buf);
4373 if (!riscv_opts.relax)
4374 fixP->fx_done = 1;
4375 }
4376 relaxable = true;
4377 break;
4378
4379 case BFD_RELOC_RISCV_PCREL_LO12_S:
4380 case BFD_RELOC_RISCV_PCREL_LO12_I:
4381 /* Resolve the pcrel_lo relocation with local symbol.
4382 Fill in a tentative value to improve objdump readability for -mrelax,
4383 and set fx_done for -mno-relax. */
4384 {
4385 bfd_vma location_pcrel_hi = S_GET_VALUE (fixP->fx_addsy) + *valP;
4386 riscv_pcrel_hi_fixup search = {location_pcrel_hi, 0, 0};
4387 riscv_pcrel_hi_fixup *entry = htab_find (riscv_pcrel_hi_fixup_hash,
4388 &search);
4389 if (entry && entry->symbol
4390 && S_IS_LOCAL (entry->symbol)
4391 && S_GET_SEGMENT (entry->symbol) == seg)
4392 {
4393 bfd_vma target = entry->target;
4394 bfd_vma value = target - entry->address;
4395 bfd_putl32 (bfd_getl32 (buf) | ENCODE_ITYPE_IMM (value), buf);
4396 /* Relaxations should never be enabled by `.option relax'. */
4397 if (!riscv_opts.relax)
4398 fixP->fx_done = 1;
4399 }
4400 }
4401 relaxable = true;
4402 break;
4403
4404 case BFD_RELOC_RISCV_ALIGN:
4405 break;
4406
4407 default:
4408 /* We ignore generic BFD relocations we don't know about. */
4409 if (bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type) != NULL)
4410 as_fatal (_("internal: bad relocation #%d"), fixP->fx_r_type);
4411 }
4412
4413 if (fixP->fx_subsy != NULL)
4414 as_bad_subtract (fixP);
4415
4416 /* Add an R_RISCV_RELAX reloc if the reloc is relaxable. */
4417 if (relaxable && fixP->fx_tcbit && fixP->fx_addsy != NULL)
4418 {
4419 fixP->fx_next = xmemdup (fixP, sizeof (*fixP), sizeof (*fixP));
4420 fixP->fx_next->fx_addsy = fixP->fx_next->fx_subsy = NULL;
4421 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_RELAX;
4422 fixP->fx_next->fx_size = 0;
4423 }
4424 }
4425
4426 /* Because the value of .cfi_remember_state may changed after relaxation,
4427 we insert a fix to relocate it again in link-time. */
4428
4429 void
4430 riscv_pre_output_hook (void)
4431 {
4432 const frchainS *frch;
4433 segT s;
4434
4435 /* Save the current segment info. */
4436 segT seg = now_seg;
4437 subsegT subseg = now_subseg;
4438
4439 for (s = stdoutput->sections; s; s = s->next)
4440 for (frch = seg_info (s)->frchainP; frch; frch = frch->frch_next)
4441 {
4442 fragS *frag;
4443
4444 for (frag = frch->frch_root; frag; frag = frag->fr_next)
4445 {
4446 if (frag->fr_type == rs_cfa)
4447 {
4448 expressionS exp;
4449 expressionS *symval;
4450
4451 symval = symbol_get_value_expression (frag->fr_symbol);
4452 exp.X_op = O_subtract;
4453 exp.X_add_symbol = symval->X_add_symbol;
4454 exp.X_add_number = 0;
4455 exp.X_op_symbol = symval->X_op_symbol;
4456
4457 /* We must set the segment before creating a frag after all
4458 frag chains have been chained together. */
4459 subseg_set (s, frch->frch_subseg);
4460
4461 fix_new_exp (frag, (int) frag->fr_offset, 1, &exp, 0,
4462 BFD_RELOC_RISCV_CFA);
4463 }
4464 }
4465 }
4466
4467 /* Restore the original segment info. */
4468 subseg_set (seg, subseg);
4469 }
4470
4471 /* Handle the .option pseudo-op. */
4472
4473 static void
4474 s_riscv_option (int x ATTRIBUTE_UNUSED)
4475 {
4476 char *name = input_line_pointer, ch;
4477
4478 while (!is_end_of_line[(unsigned char) *input_line_pointer])
4479 ++input_line_pointer;
4480 ch = *input_line_pointer;
4481 *input_line_pointer = '\0';
4482
4483 if (strcmp (name, "rvc") == 0)
4484 {
4485 riscv_update_subset (&riscv_rps_as, "+c");
4486 riscv_reset_subsets_list_arch_str ();
4487 riscv_set_rvc (true);
4488 }
4489 else if (strcmp (name, "norvc") == 0)
4490 {
4491 riscv_update_subset (&riscv_rps_as, "-c");
4492 riscv_reset_subsets_list_arch_str ();
4493 riscv_set_rvc (false);
4494 }
4495 else if (strcmp (name, "pic") == 0)
4496 riscv_opts.pic = true;
4497 else if (strcmp (name, "nopic") == 0)
4498 riscv_opts.pic = false;
4499 else if (strcmp (name, "relax") == 0)
4500 riscv_opts.relax = true;
4501 else if (strcmp (name, "norelax") == 0)
4502 riscv_opts.relax = false;
4503 else if (strcmp (name, "csr-check") == 0)
4504 riscv_opts.csr_check = true;
4505 else if (strcmp (name, "no-csr-check") == 0)
4506 riscv_opts.csr_check = false;
4507 else if (strncmp (name, "arch,", 5) == 0)
4508 {
4509 name += 5;
4510 if (ISSPACE (*name) && *name != '\0')
4511 name++;
4512 riscv_update_subset (&riscv_rps_as, name);
4513 riscv_reset_subsets_list_arch_str ();
4514
4515 riscv_set_rvc (false);
4516 if (riscv_subset_supports (&riscv_rps_as, "c")
4517 || riscv_subset_supports (&riscv_rps_as, "zca"))
4518 riscv_set_rvc (true);
4519
4520 if (riscv_subset_supports (&riscv_rps_as, "ztso"))
4521 riscv_set_tso ();
4522 }
4523 else if (strcmp (name, "push") == 0)
4524 {
4525 struct riscv_option_stack *s;
4526
4527 s = XNEW (struct riscv_option_stack);
4528 s->next = riscv_opts_stack;
4529 s->options = riscv_opts;
4530 s->subset_list = riscv_rps_as.subset_list;
4531 riscv_opts_stack = s;
4532 riscv_rps_as.subset_list = riscv_copy_subset_list (s->subset_list);
4533 }
4534 else if (strcmp (name, "pop") == 0)
4535 {
4536 struct riscv_option_stack *s;
4537
4538 s = riscv_opts_stack;
4539 if (s == NULL)
4540 as_bad (_(".option pop with no .option push"));
4541 else
4542 {
4543 riscv_subset_list_t *release_subsets = riscv_rps_as.subset_list;
4544 riscv_opts_stack = s->next;
4545 riscv_opts = s->options;
4546 riscv_rps_as.subset_list = s->subset_list;
4547 riscv_release_subset_list (release_subsets);
4548 free (s);
4549 }
4550 }
4551 else
4552 {
4553 as_warn (_("unrecognized .option directive: %s"), name);
4554 }
4555 *input_line_pointer = ch;
4556 demand_empty_rest_of_line ();
4557 }
4558
4559 /* Handle the .dtprelword and .dtpreldword pseudo-ops. They generate
4560 a 32-bit or 64-bit DTP-relative relocation (BYTES says which) for
4561 use in DWARF debug information. */
4562
4563 static void
4564 s_dtprel (int bytes)
4565 {
4566 expressionS ex;
4567 char *p;
4568
4569 expression (&ex);
4570
4571 if (ex.X_op != O_symbol)
4572 {
4573 as_bad (_("unsupported use of %s"), (bytes == 8
4574 ? ".dtpreldword"
4575 : ".dtprelword"));
4576 ignore_rest_of_line ();
4577 }
4578
4579 p = frag_more (bytes);
4580 md_number_to_chars (p, 0, bytes);
4581 fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, false,
4582 (bytes == 8
4583 ? BFD_RELOC_RISCV_TLS_DTPREL64
4584 : BFD_RELOC_RISCV_TLS_DTPREL32));
4585
4586 demand_empty_rest_of_line ();
4587 }
4588
4589 /* Handle the .bss pseudo-op. */
4590
4591 static void
4592 s_bss (int ignore ATTRIBUTE_UNUSED)
4593 {
4594 subseg_set (bss_section, 0);
4595 demand_empty_rest_of_line ();
4596 }
4597
4598 static void
4599 riscv_make_nops (char *buf, bfd_vma bytes)
4600 {
4601 bfd_vma i = 0;
4602
4603 /* RISC-V instructions cannot begin or end on odd addresses, so this case
4604 means we are not within a valid instruction sequence. It is thus safe
4605 to use a zero byte, even though that is not a valid instruction. */
4606 if (bytes % 2 == 1)
4607 buf[i++] = 0;
4608
4609 /* Use at most one 2-byte NOP. */
4610 if ((bytes - i) % 4 == 2)
4611 {
4612 number_to_chars_littleendian (buf + i, RVC_NOP, 2);
4613 i += 2;
4614 }
4615
4616 /* Fill the remainder with 4-byte NOPs. */
4617 for ( ; i < bytes; i += 4)
4618 number_to_chars_littleendian (buf + i, RISCV_NOP, 4);
4619 }
4620
4621 /* Called from md_do_align. Used to create an alignment frag in a
4622 code section by emitting a worst-case NOP sequence that the linker
4623 will later relax to the correct number of NOPs. We can't compute
4624 the correct alignment now because of other linker relaxations. */
4625
4626 bool
4627 riscv_frag_align_code (int n)
4628 {
4629 bfd_vma bytes = (bfd_vma) 1 << n;
4630 bfd_vma insn_alignment = riscv_opts.rvc ? 2 : 4;
4631 bfd_vma worst_case_bytes = bytes - insn_alignment;
4632 char *nops;
4633 expressionS ex;
4634
4635 /* If we are moving to a smaller alignment than the instruction size, then no
4636 alignment is required. */
4637 if (bytes <= insn_alignment)
4638 return true;
4639
4640 /* When not relaxing, riscv_handle_align handles code alignment. */
4641 if (!riscv_opts.relax)
4642 return false;
4643
4644 /* Maybe we should use frag_var to create a new rs_align_code fragment,
4645 rather than just use frag_more to handle an alignment here? So that we
4646 don't need to call riscv_mapping_state again later, and then only need
4647 to check frag->fr_type to see if it is frag_align_code. */
4648 nops = frag_more (worst_case_bytes);
4649
4650 ex.X_op = O_constant;
4651 ex.X_add_number = worst_case_bytes;
4652
4653 riscv_make_nops (nops, worst_case_bytes);
4654
4655 fix_new_exp (frag_now, nops - frag_now->fr_literal, 0,
4656 &ex, false, BFD_RELOC_RISCV_ALIGN);
4657
4658 riscv_mapping_state (MAP_INSN, worst_case_bytes, true/* fr_align_code */);
4659
4660 /* We need to start a new frag after the alignment which may be removed by
4661 the linker, to prevent the assembler from computing static offsets.
4662 This is necessary to get correct EH info. */
4663 frag_wane (frag_now);
4664 frag_new (0);
4665
4666 return true;
4667 }
4668
4669 /* Implement HANDLE_ALIGN. */
4670
4671 void
4672 riscv_handle_align (fragS *fragP)
4673 {
4674 switch (fragP->fr_type)
4675 {
4676 case rs_align_code:
4677 /* When relaxing, riscv_frag_align_code handles code alignment. */
4678 if (!riscv_opts.relax)
4679 {
4680 bfd_signed_vma bytes = (fragP->fr_next->fr_address
4681 - fragP->fr_address - fragP->fr_fix);
4682 /* We have 4 byte uncompressed nops. */
4683 bfd_signed_vma size = 4;
4684 bfd_signed_vma excess = bytes % size;
4685 bfd_boolean odd_padding = (excess % 2 == 1);
4686 char *p = fragP->fr_literal + fragP->fr_fix;
4687
4688 if (bytes <= 0)
4689 break;
4690
4691 /* Insert zeros or compressed nops to get 4 byte alignment. */
4692 if (excess)
4693 {
4694 if (odd_padding)
4695 riscv_add_odd_padding_symbol (fragP);
4696 riscv_make_nops (p, excess);
4697 fragP->fr_fix += excess;
4698 p += excess;
4699 }
4700
4701 /* The frag will be changed to `rs_fill` later. The function
4702 `write_contents` will try to fill the remaining spaces
4703 according to the patterns we give. In this case, we give
4704 a 4 byte uncompressed nop as the pattern, and set the size
4705 of the pattern into `fr_var`. The nop will be output to the
4706 file `fr_offset` times. However, `fr_offset` could be zero
4707 if we don't need to pad the boundary finally. */
4708 riscv_make_nops (p, size);
4709 fragP->fr_var = size;
4710 }
4711 break;
4712
4713 default:
4714 break;
4715 }
4716 }
4717
4718 /* This usually called from frag_var. */
4719
4720 void
4721 riscv_init_frag (fragS * fragP, int max_chars)
4722 {
4723 /* Do not add mapping symbol to debug sections. */
4724 if (bfd_section_flags (now_seg) & SEC_DEBUGGING)
4725 return;
4726
4727 switch (fragP->fr_type)
4728 {
4729 case rs_fill:
4730 case rs_align:
4731 case rs_align_test:
4732 riscv_mapping_state (MAP_DATA, max_chars, false/* fr_align_code */);
4733 break;
4734 case rs_align_code:
4735 riscv_mapping_state (MAP_INSN, max_chars, true/* fr_align_code */);
4736 break;
4737 default:
4738 break;
4739 }
4740 }
4741
4742 int
4743 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
4744 {
4745 return (fragp->fr_var = relaxed_branch_length (fragp, segtype, false));
4746 }
4747
4748 /* Translate internal representation of relocation info to BFD target
4749 format. */
4750
4751 arelent *
4752 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
4753 {
4754 arelent *reloc = (arelent *) xmalloc (sizeof (arelent));
4755
4756 reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
4757 *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
4758 reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
4759 reloc->addend = fixp->fx_addnumber;
4760
4761 reloc->howto = bfd_reloc_type_lookup (stdoutput, fixp->fx_r_type);
4762 if (reloc->howto == NULL)
4763 {
4764 if ((fixp->fx_r_type == BFD_RELOC_16 || fixp->fx_r_type == BFD_RELOC_8)
4765 && fixp->fx_addsy != NULL && fixp->fx_subsy != NULL)
4766 {
4767 /* We don't have R_RISCV_8/16, but for this special case,
4768 we can use R_RISCV_ADD8/16 with R_RISCV_SUB8/16. */
4769 return reloc;
4770 }
4771
4772 as_bad_where (fixp->fx_file, fixp->fx_line,
4773 _("cannot represent %s relocation in object file"),
4774 bfd_get_reloc_code_name (fixp->fx_r_type));
4775 return NULL;
4776 }
4777
4778 return reloc;
4779 }
4780
4781 int
4782 riscv_relax_frag (asection *sec, fragS *fragp, long stretch ATTRIBUTE_UNUSED)
4783 {
4784 if (RELAX_BRANCH_P (fragp->fr_subtype))
4785 {
4786 offsetT old_var = fragp->fr_var;
4787 fragp->fr_var = relaxed_branch_length (fragp, sec, true);
4788 return fragp->fr_var - old_var;
4789 }
4790
4791 return 0;
4792 }
4793
4794 /* Expand far branches to multi-instruction sequences. */
4795
4796 static void
4797 md_convert_frag_branch (fragS *fragp)
4798 {
4799 bfd_byte *buf;
4800 expressionS exp;
4801 fixS *fixp;
4802 insn_t insn;
4803 int rs1, reloc;
4804
4805 buf = (bfd_byte *)fragp->fr_literal + fragp->fr_fix;
4806
4807 exp.X_op = O_symbol;
4808 exp.X_add_symbol = fragp->fr_symbol;
4809 exp.X_add_number = fragp->fr_offset;
4810
4811 gas_assert (fragp->fr_var == RELAX_BRANCH_LENGTH (fragp->fr_subtype));
4812
4813 if (RELAX_BRANCH_RVC (fragp->fr_subtype))
4814 {
4815 switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
4816 {
4817 case 8:
4818 case 4:
4819 /* Expand the RVC branch into a RISC-V one. */
4820 insn = bfd_getl16 (buf);
4821 rs1 = 8 + ((insn >> OP_SH_CRS1S) & OP_MASK_CRS1S);
4822 if ((insn & MASK_C_J) == MATCH_C_J)
4823 insn = MATCH_JAL;
4824 else if ((insn & MASK_C_JAL) == MATCH_C_JAL)
4825 insn = MATCH_JAL | (X_RA << OP_SH_RD);
4826 else if ((insn & MASK_C_BEQZ) == MATCH_C_BEQZ)
4827 insn = MATCH_BEQ | (rs1 << OP_SH_RS1);
4828 else if ((insn & MASK_C_BNEZ) == MATCH_C_BNEZ)
4829 insn = MATCH_BNE | (rs1 << OP_SH_RS1);
4830 else
4831 abort ();
4832 bfd_putl32 (insn, buf);
4833 break;
4834
4835 case 6:
4836 /* Invert the branch condition. Branch over the jump. */
4837 insn = bfd_getl16 (buf);
4838 insn ^= MATCH_C_BEQZ ^ MATCH_C_BNEZ;
4839 insn |= ENCODE_CBTYPE_IMM (6);
4840 bfd_putl16 (insn, buf);
4841 buf += 2;
4842 goto jump;
4843
4844 case 2:
4845 /* Just keep the RVC branch. */
4846 reloc = RELAX_BRANCH_UNCOND (fragp->fr_subtype)
4847 ? BFD_RELOC_RISCV_RVC_JUMP : BFD_RELOC_RISCV_RVC_BRANCH;
4848 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
4849 2, &exp, false, reloc);
4850 buf += 2;
4851 goto done;
4852
4853 default:
4854 abort ();
4855 }
4856 }
4857
4858 switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
4859 {
4860 case 8:
4861 gas_assert (!RELAX_BRANCH_UNCOND (fragp->fr_subtype));
4862
4863 /* Invert the branch condition. Branch over the jump. */
4864 insn = bfd_getl32 (buf);
4865 insn ^= MATCH_BEQ ^ MATCH_BNE;
4866 insn |= ENCODE_BTYPE_IMM (8);
4867 bfd_putl32 (insn, buf);
4868 buf += 4;
4869
4870 jump:
4871 /* Jump to the target. */
4872 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
4873 4, &exp, false, BFD_RELOC_RISCV_JMP);
4874 bfd_putl32 (MATCH_JAL, buf);
4875 buf += 4;
4876 break;
4877
4878 case 4:
4879 reloc = RELAX_BRANCH_UNCOND (fragp->fr_subtype)
4880 ? BFD_RELOC_RISCV_JMP : BFD_RELOC_12_PCREL;
4881 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
4882 4, &exp, false, reloc);
4883 buf += 4;
4884 break;
4885
4886 default:
4887 abort ();
4888 }
4889
4890 done:
4891 fixp->fx_file = fragp->fr_file;
4892 fixp->fx_line = fragp->fr_line;
4893
4894 gas_assert (buf == (bfd_byte *)fragp->fr_literal
4895 + fragp->fr_fix + fragp->fr_var);
4896
4897 fragp->fr_fix += fragp->fr_var;
4898 }
4899
4900 /* Relax a machine dependent frag. This returns the amount by which
4901 the current size of the frag should change. */
4902
4903 void
4904 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec ATTRIBUTE_UNUSED,
4905 fragS *fragp)
4906 {
4907 gas_assert (RELAX_BRANCH_P (fragp->fr_subtype));
4908 md_convert_frag_branch (fragp);
4909 }
4910
4911 void
4912 md_show_usage (FILE *stream)
4913 {
4914 fprintf (stream, _("\
4915 RISC-V options:\n\
4916 -fpic or -fPIC generate position-independent code\n\
4917 -fno-pic don't generate position-independent code (default)\n\
4918 -march=ISA set the RISC-V architecture\n\
4919 -misa-spec=ISAspec set the RISC-V ISA spec (2.2, 20190608, 20191213)\n\
4920 -mpriv-spec=PRIVspec set the RISC-V privilege spec (1.9.1, 1.10, 1.11, 1.12)\n\
4921 -mabi=ABI set the RISC-V ABI\n\
4922 -mrelax enable relax (default)\n\
4923 -mno-relax disable relax\n\
4924 -march-attr generate RISC-V arch attribute\n\
4925 -mno-arch-attr don't generate RISC-V arch attribute\n\
4926 -mcsr-check enable the csr ISA and privilege spec version checks\n\
4927 -mno-csr-check disable the csr ISA and privilege spec version checks (default)\n\
4928 -mbig-endian assemble for big-endian\n\
4929 -mlittle-endian assemble for little-endian\n\
4930 "));
4931 }
4932
4933 /* Standard calling conventions leave the CFA at SP on entry. */
4934
4935 void
4936 riscv_cfi_frame_initial_instructions (void)
4937 {
4938 cfi_add_CFA_def_cfa_register (X_SP);
4939 }
4940
4941 int
4942 tc_riscv_regname_to_dw2regnum (char *regname)
4943 {
4944 int reg;
4945
4946 if ((reg = reg_lookup_internal (regname, RCLASS_GPR)) >= 0)
4947 return reg;
4948
4949 if ((reg = reg_lookup_internal (regname, RCLASS_FPR)) >= 0)
4950 return reg + 32;
4951
4952 if ((reg = reg_lookup_internal (regname, RCLASS_VECR)) >= 0)
4953 return reg + 96;
4954
4955 /* CSRs are numbered 4096 -> 8191. */
4956 if ((reg = reg_lookup_internal (regname, RCLASS_CSR)) >= 0)
4957 return reg + 4096;
4958
4959 as_bad (_("unknown register `%s'"), regname);
4960 return -1;
4961 }
4962
4963 void
4964 riscv_elf_final_processing (void)
4965 {
4966 riscv_set_abi_by_arch ();
4967 riscv_release_subset_list (riscv_rps_as.subset_list);
4968 elf_elfheader (stdoutput)->e_flags |= elf_flags;
4969 }
4970
4971 /* Parse the .sleb128 and .uleb128 pseudos. Only allow constant expressions,
4972 since these directives break relaxation when used with symbol deltas. */
4973
4974 static void
4975 s_riscv_leb128 (int sign)
4976 {
4977 expressionS exp;
4978 char *save_in = input_line_pointer;
4979
4980 expression (&exp);
4981 if (sign && exp.X_op != O_constant)
4982 as_bad (_("non-constant .sleb128 is not supported"));
4983 else if (!sign && exp.X_op != O_constant && exp.X_op != O_subtract)
4984 as_bad (_(".uleb128 only supports constant or subtract expressions"));
4985
4986 demand_empty_rest_of_line ();
4987
4988 input_line_pointer = save_in;
4989 return s_leb128 (sign);
4990 }
4991
4992 /* Parse the .insn directive. There are three formats,
4993 Format 1: .insn <type> <operand1>, <operand2>, ...
4994 Format 2: .insn <length>, <value>
4995 Format 3: .insn <value>. */
4996
4997 static void
4998 s_riscv_insn (int x ATTRIBUTE_UNUSED)
4999 {
5000 char *str = input_line_pointer;
5001 struct riscv_cl_insn insn;
5002 expressionS imm_expr;
5003 bfd_reloc_code_real_type imm_reloc = BFD_RELOC_UNUSED;
5004 char save_c;
5005
5006 while (!is_end_of_line[(unsigned char) *input_line_pointer])
5007 ++input_line_pointer;
5008
5009 save_c = *input_line_pointer;
5010 *input_line_pointer = '\0';
5011
5012 riscv_mapping_state (MAP_INSN, 0, false/* fr_align_code */);
5013
5014 struct riscv_ip_error error = riscv_ip (str, &insn, &imm_expr,
5015 &imm_reloc, insn_type_hash);
5016 if (error.msg)
5017 {
5018 char *save_in = input_line_pointer;
5019 error.msg = riscv_ip_hardcode (str, &insn, &imm_expr, error.msg);
5020 input_line_pointer = save_in;
5021 }
5022
5023 if (error.msg)
5024 {
5025 if (error.missing_ext)
5026 as_bad ("%s `%s', extension `%s' required", error.msg, error.statement,
5027 error.missing_ext);
5028 else
5029 as_bad ("%s `%s'", error.msg, error.statement);
5030 }
5031 else
5032 {
5033 gas_assert (insn.insn_mo->pinfo != INSN_MACRO);
5034 append_insn (&insn, &imm_expr, imm_reloc);
5035 }
5036
5037 *input_line_pointer = save_c;
5038 demand_empty_rest_of_line ();
5039 }
5040
5041 /* Update architecture and privileged elf attributes. If we don't set
5042 them, then try to output the default ones. */
5043
5044 static void
5045 riscv_write_out_attrs (void)
5046 {
5047 const char *arch_str, *priv_str, *p;
5048 /* versions[0]: major version.
5049 versions[1]: minor version.
5050 versions[2]: revision version. */
5051 unsigned versions[3] = {0}, number = 0;
5052 unsigned int i;
5053
5054 /* Re-write architecture elf attribute. */
5055 arch_str = riscv_rps_as.subset_list->arch_str;
5056 if (!bfd_elf_add_proc_attr_string (stdoutput, Tag_RISCV_arch, arch_str))
5057 as_fatal (_("error adding attribute: %s"),
5058 bfd_errmsg (bfd_get_error ()));
5059
5060 /* For the file without any instruction, we don't set the default_priv_spec
5061 according to the privileged elf attributes since the md_assemble isn't
5062 called. */
5063 if (!start_assemble
5064 && !riscv_set_default_priv_spec (NULL))
5065 return;
5066
5067 /* If we already have set privileged elf attributes, then no need to do
5068 anything. Otherwise, don't generate or update them when no CSR and
5069 privileged instructions are used. */
5070 if (!explicit_priv_attr)
5071 return;
5072
5073 RISCV_GET_PRIV_SPEC_NAME (priv_str, default_priv_spec);
5074 p = priv_str;
5075 for (i = 0; *p; ++p)
5076 {
5077 if (*p == '.' && i < 3)
5078 {
5079 versions[i++] = number;
5080 number = 0;
5081 }
5082 else if (ISDIGIT (*p))
5083 number = (number * 10) + (*p - '0');
5084 else
5085 {
5086 as_bad (_("internal: bad RISC-V privileged spec (%s)"), priv_str);
5087 return;
5088 }
5089 }
5090 versions[i] = number;
5091
5092 /* Re-write privileged elf attributes. */
5093 if (!bfd_elf_add_proc_attr_int (stdoutput, Tag_RISCV_priv_spec,
5094 versions[0])
5095 || !bfd_elf_add_proc_attr_int (stdoutput, Tag_RISCV_priv_spec_minor,
5096 versions[1])
5097 || !bfd_elf_add_proc_attr_int (stdoutput, Tag_RISCV_priv_spec_revision,
5098 versions[2]))
5099 as_fatal (_("error adding attribute: %s"),
5100 bfd_errmsg (bfd_get_error ()));
5101 }
5102
5103 /* Add the default contents for the .riscv.attributes section. */
5104
5105 static void
5106 riscv_set_public_attributes (void)
5107 {
5108 if (riscv_opts.arch_attr || explicit_attr)
5109 riscv_write_out_attrs ();
5110 }
5111
5112 /* Scan uleb128 subtraction expressions and insert fixups for them.
5113 e.g., .uleb128 .L1 - .L0
5114 Because relaxation may change the value of the subtraction, we
5115 must resolve them at link-time. */
5116
5117 static void
5118 riscv_insert_uleb128_fixes (bfd *abfd ATTRIBUTE_UNUSED,
5119 asection *sec, void *xxx ATTRIBUTE_UNUSED)
5120 {
5121 segment_info_type *seginfo = seg_info (sec);
5122 struct frag *fragP;
5123
5124 subseg_set (sec, 0);
5125
5126 for (fragP = seginfo->frchainP->frch_root;
5127 fragP; fragP = fragP->fr_next)
5128 {
5129 expressionS *exp, *exp_dup;
5130
5131 if (fragP->fr_type != rs_leb128 || fragP->fr_symbol == NULL)
5132 continue;
5133
5134 exp = symbol_get_value_expression (fragP->fr_symbol);
5135
5136 if (exp->X_op != O_subtract)
5137 continue;
5138
5139 /* Only unsigned leb128 can be handled. */
5140 gas_assert (fragP->fr_subtype == 0);
5141 exp_dup = xmemdup (exp, sizeof (*exp), sizeof (*exp));
5142 exp_dup->X_op = O_symbol;
5143 exp_dup->X_op_symbol = NULL;
5144
5145 /* Insert relocations to resolve the subtraction at link-time.
5146 Emit the SET relocation first in riscv. */
5147 exp_dup->X_add_symbol = exp->X_add_symbol;
5148 fix_new_exp (fragP, fragP->fr_fix, 0,
5149 exp_dup, 0, BFD_RELOC_RISCV_SET_ULEB128);
5150 exp_dup->X_add_symbol = exp->X_op_symbol;
5151 exp_dup->X_add_number = 0; /* Set addend of SUB_ULEB128 to zero. */
5152 fix_new_exp (fragP, fragP->fr_fix, 0,
5153 exp_dup, 0, BFD_RELOC_RISCV_SUB_ULEB128);
5154 free ((void *) exp_dup);
5155 }
5156 }
5157
5158 /* Called after all assembly has been done. */
5159
5160 void
5161 riscv_md_finish (void)
5162 {
5163 riscv_set_public_attributes ();
5164 if (riscv_opts.relax)
5165 bfd_map_over_sections (stdoutput, riscv_insert_uleb128_fixes, NULL);
5166 }
5167
5168 /* Called just before the assembler exits. */
5169
5170 void
5171 riscv_md_end (void)
5172 {
5173 htab_delete (riscv_pcrel_hi_fixup_hash);
5174 }
5175
5176 /* Adjust the symbol table. */
5177
5178 void
5179 riscv_adjust_symtab (void)
5180 {
5181 bfd_map_over_sections (stdoutput, riscv_check_mapping_symbols, (char *) 0);
5182 elf_adjust_symtab ();
5183 }
5184
5185 /* Given a symbolic attribute NAME, return the proper integer value.
5186 Returns -1 if the attribute is not known. */
5187
5188 int
5189 riscv_convert_symbolic_attribute (const char *name)
5190 {
5191 static const struct
5192 {
5193 const char *name;
5194 const int tag;
5195 }
5196 attribute_table[] =
5197 {
5198 /* When you modify this table you should
5199 also modify the list in doc/c-riscv.texi. */
5200 #define T(tag) {#tag, Tag_RISCV_##tag}, {"Tag_RISCV_" #tag, Tag_RISCV_##tag}
5201 T(arch),
5202 T(priv_spec),
5203 T(priv_spec_minor),
5204 T(priv_spec_revision),
5205 T(unaligned_access),
5206 T(stack_align),
5207 #undef T
5208 };
5209
5210 if (name == NULL)
5211 return -1;
5212
5213 unsigned int i;
5214 for (i = 0; i < ARRAY_SIZE (attribute_table); i++)
5215 if (strcmp (name, attribute_table[i].name) == 0)
5216 return attribute_table[i].tag;
5217
5218 return -1;
5219 }
5220
5221 /* Parse a .attribute directive. */
5222
5223 static void
5224 s_riscv_attribute (int ignored ATTRIBUTE_UNUSED)
5225 {
5226 int tag = obj_elf_vendor_attribute (OBJ_ATTR_PROC);
5227 unsigned old_xlen;
5228 obj_attribute *attr;
5229
5230 explicit_attr = true;
5231 switch (tag)
5232 {
5233 case Tag_RISCV_arch:
5234 old_xlen = xlen;
5235 attr = elf_known_obj_attributes_proc (stdoutput);
5236 if (!start_assemble)
5237 riscv_set_arch (attr[Tag_RISCV_arch].s);
5238 else
5239 as_fatal (_("architecture elf attributes must set before "
5240 "any instructions"));
5241
5242 if (old_xlen != xlen)
5243 {
5244 /* We must re-init bfd again if xlen is changed. */
5245 unsigned long mach = xlen == 64 ? bfd_mach_riscv64 : bfd_mach_riscv32;
5246 bfd_find_target (riscv_target_format (), stdoutput);
5247
5248 if (! bfd_set_arch_mach (stdoutput, bfd_arch_riscv, mach))
5249 as_warn (_("could not set architecture and machine"));
5250 }
5251 break;
5252
5253 case Tag_RISCV_priv_spec:
5254 case Tag_RISCV_priv_spec_minor:
5255 case Tag_RISCV_priv_spec_revision:
5256 if (start_assemble)
5257 as_fatal (_("privileged elf attributes must set before "
5258 "any instructions"));
5259 break;
5260
5261 default:
5262 break;
5263 }
5264 }
5265
5266 /* Mark symbol that it follows a variant CC convention. */
5267
5268 static void
5269 s_variant_cc (int ignored ATTRIBUTE_UNUSED)
5270 {
5271 char *name;
5272 char c;
5273 symbolS *sym;
5274 asymbol *bfdsym;
5275 elf_symbol_type *elfsym;
5276
5277 c = get_symbol_name (&name);
5278 if (!*name)
5279 as_bad (_("missing symbol name for .variant_cc directive"));
5280 sym = symbol_find_or_make (name);
5281 restore_line_pointer (c);
5282 demand_empty_rest_of_line ();
5283
5284 bfdsym = symbol_get_bfdsym (sym);
5285 elfsym = elf_symbol_from (bfdsym);
5286 gas_assert (elfsym);
5287 elfsym->internal_elf_sym.st_other |= STO_RISCV_VARIANT_CC;
5288 }
5289
5290 /* Same as elf_copy_symbol_attributes, but without copying st_other.
5291 This is needed so RISC-V specific st_other values can be independently
5292 specified for an IFUNC resolver (that is called by the dynamic linker)
5293 and the symbol it resolves (aliased to the resolver). In particular,
5294 if a function symbol has special st_other value set via directives,
5295 then attaching an IFUNC resolver to that symbol should not override
5296 the st_other setting. Requiring the directive on the IFUNC resolver
5297 symbol would be unexpected and problematic in C code, where the two
5298 symbols appear as two independent function declarations. */
5299
5300 void
5301 riscv_elf_copy_symbol_attributes (symbolS *dest, symbolS *src)
5302 {
5303 struct elf_obj_sy *srcelf = symbol_get_obj (src);
5304 struct elf_obj_sy *destelf = symbol_get_obj (dest);
5305 /* If size is unset, copy size from src. Because we don't track whether
5306 .size has been used, we can't differentiate .size dest, 0 from the case
5307 where dest's size is unset. */
5308 if (!destelf->size && S_GET_SIZE (dest) == 0)
5309 {
5310 if (srcelf->size)
5311 {
5312 destelf->size = XNEW (expressionS);
5313 *destelf->size = *srcelf->size;
5314 }
5315 S_SET_SIZE (dest, S_GET_SIZE (src));
5316 }
5317 }
5318
5319 /* RISC-V pseudo-ops table. */
5320 static const pseudo_typeS riscv_pseudo_table[] =
5321 {
5322 {"option", s_riscv_option, 0},
5323 {"half", cons, 2},
5324 {"word", cons, 4},
5325 {"dword", cons, 8},
5326 {"dtprelword", s_dtprel, 4},
5327 {"dtpreldword", s_dtprel, 8},
5328 {"bss", s_bss, 0},
5329 {"uleb128", s_riscv_leb128, 0},
5330 {"sleb128", s_riscv_leb128, 1},
5331 {"insn", s_riscv_insn, 0},
5332 {"attribute", s_riscv_attribute, 0},
5333 {"variant_cc", s_variant_cc, 0},
5334 {"float16", float_cons, 'h'},
5335
5336 { NULL, NULL, 0 },
5337 };
5338
5339 void
5340 riscv_pop_insert (void)
5341 {
5342 extern void pop_insert (const pseudo_typeS *);
5343
5344 pop_insert (riscv_pseudo_table);
5345 }