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