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