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