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