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