]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gas/config/tc-riscv.c
RISC-V: Error for relaxable branch in absolute section.
[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
1110 if (now_seg == absolute_section)
1111 {
1112 as_bad (_("relaxable branches not supported in absolute section"));
1113 return;
1114 }
1115
1116 add_relaxed_insn (ip, worst_case, best_case,
1117 RELAX_BRANCH_ENCODE (j, best_case == 2, worst_case),
1118 address_expr->X_add_symbol,
1119 address_expr->X_add_number);
1120 return;
1121 }
1122 else
1123 {
1124 howto = bfd_reloc_type_lookup (stdoutput, reloc_type);
1125 if (howto == NULL)
1126 as_bad (_("Unsupported RISC-V relocation number %d"), reloc_type);
1127
1128 ip->fixp = fix_new_exp (ip->frag, ip->where,
1129 bfd_get_reloc_size (howto),
1130 address_expr, FALSE, reloc_type);
1131
1132 ip->fixp->fx_tcbit = riscv_opts.relax;
1133 }
1134 }
1135
1136 add_fixed_insn (ip);
1137 install_insn (ip);
1138
1139 /* We need to start a new frag after any instruction that can be
1140 optimized away or compressed by the linker during relaxation, to prevent
1141 the assembler from computing static offsets across such an instruction.
1142 This is necessary to get correct EH info. */
1143 if (reloc_type == BFD_RELOC_RISCV_HI20
1144 || reloc_type == BFD_RELOC_RISCV_PCREL_HI20
1145 || reloc_type == BFD_RELOC_RISCV_TPREL_HI20
1146 || reloc_type == BFD_RELOC_RISCV_TPREL_ADD)
1147 {
1148 frag_wane (frag_now);
1149 frag_new (0);
1150 }
1151 }
1152
1153 /* Build an instruction created by a macro expansion. This is passed
1154 a pointer to the count of instructions created so far, an
1155 expression, the name of the instruction to build, an operand format
1156 string, and corresponding arguments. */
1157
1158 static void
1159 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
1160 {
1161 const struct riscv_opcode *mo;
1162 struct riscv_cl_insn insn;
1163 bfd_reloc_code_real_type r;
1164 va_list args;
1165
1166 va_start (args, fmt);
1167
1168 r = BFD_RELOC_UNUSED;
1169 mo = (struct riscv_opcode *) str_hash_find (op_hash, name);
1170 gas_assert (mo);
1171
1172 /* Find a non-RVC variant of the instruction. append_insn will compress
1173 it if possible. */
1174 while (riscv_insn_length (mo->match) < 4)
1175 mo++;
1176 gas_assert (strcmp (name, mo->name) == 0);
1177
1178 create_insn (&insn, mo);
1179 for (;;)
1180 {
1181 switch (*fmt++)
1182 {
1183 case 'd':
1184 INSERT_OPERAND (RD, insn, va_arg (args, int));
1185 continue;
1186
1187 case 's':
1188 INSERT_OPERAND (RS1, insn, va_arg (args, int));
1189 continue;
1190
1191 case 't':
1192 INSERT_OPERAND (RS2, insn, va_arg (args, int));
1193 continue;
1194
1195 case '>':
1196 INSERT_OPERAND (SHAMT, insn, va_arg (args, int));
1197 continue;
1198
1199 case 'j':
1200 case 'u':
1201 case 'q':
1202 gas_assert (ep != NULL);
1203 r = va_arg (args, int);
1204 continue;
1205
1206 case '\0':
1207 break;
1208 case ',':
1209 continue;
1210 default:
1211 as_fatal (_("internal error: invalid macro"));
1212 }
1213 break;
1214 }
1215 va_end (args);
1216 gas_assert (r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
1217
1218 append_insn (&insn, ep, r);
1219 }
1220
1221 /* Build an instruction created by a macro expansion. Like md_assemble but
1222 accept a printf-style format string and arguments. */
1223
1224 static void
1225 md_assemblef (const char *format, ...)
1226 {
1227 char *buf = NULL;
1228 va_list ap;
1229 int r;
1230
1231 va_start (ap, format);
1232
1233 r = vasprintf (&buf, format, ap);
1234
1235 if (r < 0)
1236 as_fatal (_("internal error: vasprintf failed"));
1237
1238 md_assemble (buf);
1239 free(buf);
1240
1241 va_end (ap);
1242 }
1243
1244 /* Sign-extend 32-bit mode constants that have bit 31 set and all higher bits
1245 unset. */
1246 static void
1247 normalize_constant_expr (expressionS *ex)
1248 {
1249 if (xlen > 32)
1250 return;
1251 if ((ex->X_op == O_constant || ex->X_op == O_symbol)
1252 && IS_ZEXT_32BIT_NUM (ex->X_add_number))
1253 ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
1254 - 0x80000000);
1255 }
1256
1257 /* Fail if an expression EX is not a constant. IP is the instruction using EX.
1258 MAYBE_CSR is true if the symbol may be an unrecognized CSR name. */
1259
1260 static void
1261 check_absolute_expr (struct riscv_cl_insn *ip, expressionS *ex,
1262 bfd_boolean maybe_csr)
1263 {
1264 if (ex->X_op == O_big)
1265 as_bad (_("unsupported large constant"));
1266 else if (maybe_csr && ex->X_op == O_symbol)
1267 as_bad (_("unknown CSR `%s'"),
1268 S_GET_NAME (ex->X_add_symbol));
1269 else if (ex->X_op != O_constant)
1270 as_bad (_("Instruction %s requires absolute expression"),
1271 ip->insn_mo->name);
1272 normalize_constant_expr (ex);
1273 }
1274
1275 static symbolS *
1276 make_internal_label (void)
1277 {
1278 return (symbolS *) local_symbol_make (FAKE_LABEL_NAME, now_seg, frag_now,
1279 frag_now_fix ());
1280 }
1281
1282 /* Load an entry from the GOT. */
1283 static void
1284 pcrel_access (int destreg, int tempreg, expressionS *ep,
1285 const char *lo_insn, const char *lo_pattern,
1286 bfd_reloc_code_real_type hi_reloc,
1287 bfd_reloc_code_real_type lo_reloc)
1288 {
1289 expressionS ep2;
1290 ep2.X_op = O_symbol;
1291 ep2.X_add_symbol = make_internal_label ();
1292 ep2.X_add_number = 0;
1293
1294 macro_build (ep, "auipc", "d,u", tempreg, hi_reloc);
1295 macro_build (&ep2, lo_insn, lo_pattern, destreg, tempreg, lo_reloc);
1296 }
1297
1298 static void
1299 pcrel_load (int destreg, int tempreg, expressionS *ep, const char *lo_insn,
1300 bfd_reloc_code_real_type hi_reloc,
1301 bfd_reloc_code_real_type lo_reloc)
1302 {
1303 pcrel_access (destreg, tempreg, ep, lo_insn, "d,s,j", hi_reloc, lo_reloc);
1304 }
1305
1306 static void
1307 pcrel_store (int srcreg, int tempreg, expressionS *ep, const char *lo_insn,
1308 bfd_reloc_code_real_type hi_reloc,
1309 bfd_reloc_code_real_type lo_reloc)
1310 {
1311 pcrel_access (srcreg, tempreg, ep, lo_insn, "t,s,q", hi_reloc, lo_reloc);
1312 }
1313
1314 /* PC-relative function call using AUIPC/JALR, relaxed to JAL. */
1315 static void
1316 riscv_call (int destreg, int tempreg, expressionS *ep,
1317 bfd_reloc_code_real_type reloc)
1318 {
1319 /* Ensure the jalr is emitted to the same frag as the auipc. */
1320 frag_grow (8);
1321 macro_build (ep, "auipc", "d,u", tempreg, reloc);
1322 macro_build (NULL, "jalr", "d,s", destreg, tempreg);
1323 /* See comment at end of append_insn. */
1324 frag_wane (frag_now);
1325 frag_new (0);
1326 }
1327
1328 /* Load an integer constant into a register. */
1329
1330 static void
1331 load_const (int reg, expressionS *ep)
1332 {
1333 int shift = RISCV_IMM_BITS;
1334 bfd_vma upper_imm, sign = (bfd_vma) 1 << (RISCV_IMM_BITS - 1);
1335 expressionS upper = *ep, lower = *ep;
1336 lower.X_add_number = ((ep->X_add_number & (sign + sign - 1)) ^ sign) - sign;
1337 upper.X_add_number -= lower.X_add_number;
1338
1339 if (ep->X_op != O_constant)
1340 {
1341 as_bad (_("unsupported large constant"));
1342 return;
1343 }
1344
1345 if (xlen > 32 && !IS_SEXT_32BIT_NUM (ep->X_add_number))
1346 {
1347 /* Reduce to a signed 32-bit constant using SLLI and ADDI. */
1348 while (((upper.X_add_number >> shift) & 1) == 0)
1349 shift++;
1350
1351 upper.X_add_number = (int64_t) upper.X_add_number >> shift;
1352 load_const (reg, &upper);
1353
1354 md_assemblef ("slli x%d, x%d, 0x%x", reg, reg, shift);
1355 if (lower.X_add_number != 0)
1356 md_assemblef ("addi x%d, x%d, %" BFD_VMA_FMT "d", reg, reg,
1357 lower.X_add_number);
1358 }
1359 else
1360 {
1361 /* Simply emit LUI and/or ADDI to build a 32-bit signed constant. */
1362 int hi_reg = 0;
1363
1364 if (upper.X_add_number != 0)
1365 {
1366 /* Discard low part and zero-extend upper immediate. */
1367 upper_imm = ((uint32_t)upper.X_add_number >> shift);
1368
1369 md_assemblef ("lui x%d, 0x%" BFD_VMA_FMT "x", reg, upper_imm);
1370 hi_reg = reg;
1371 }
1372
1373 if (lower.X_add_number != 0 || hi_reg == 0)
1374 md_assemblef ("%s x%d, x%d, %" BFD_VMA_FMT "d", ADD32_INSN, reg, hi_reg,
1375 lower.X_add_number);
1376 }
1377 }
1378
1379 /* Expand RISC-V assembly macros into one or more instructions. */
1380 static void
1381 macro (struct riscv_cl_insn *ip, expressionS *imm_expr,
1382 bfd_reloc_code_real_type *imm_reloc)
1383 {
1384 int rd = (ip->insn_opcode >> OP_SH_RD) & OP_MASK_RD;
1385 int rs1 = (ip->insn_opcode >> OP_SH_RS1) & OP_MASK_RS1;
1386 int rs2 = (ip->insn_opcode >> OP_SH_RS2) & OP_MASK_RS2;
1387 int mask = ip->insn_mo->mask;
1388
1389 switch (mask)
1390 {
1391 case M_LI:
1392 load_const (rd, imm_expr);
1393 break;
1394
1395 case M_LA:
1396 case M_LLA:
1397 /* Load the address of a symbol into a register. */
1398 if (!IS_SEXT_32BIT_NUM (imm_expr->X_add_number))
1399 as_bad (_("offset too large"));
1400
1401 if (imm_expr->X_op == O_constant)
1402 load_const (rd, imm_expr);
1403 else if (riscv_opts.pic && mask == M_LA) /* Global PIC symbol */
1404 pcrel_load (rd, rd, imm_expr, LOAD_ADDRESS_INSN,
1405 BFD_RELOC_RISCV_GOT_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1406 else /* Local PIC symbol, or any non-PIC symbol */
1407 pcrel_load (rd, rd, imm_expr, "addi",
1408 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1409 break;
1410
1411 case M_LA_TLS_GD:
1412 pcrel_load (rd, rd, imm_expr, "addi",
1413 BFD_RELOC_RISCV_TLS_GD_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1414 break;
1415
1416 case M_LA_TLS_IE:
1417 pcrel_load (rd, rd, imm_expr, LOAD_ADDRESS_INSN,
1418 BFD_RELOC_RISCV_TLS_GOT_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1419 break;
1420
1421 case M_LB:
1422 pcrel_load (rd, rd, imm_expr, "lb",
1423 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1424 break;
1425
1426 case M_LBU:
1427 pcrel_load (rd, rd, imm_expr, "lbu",
1428 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1429 break;
1430
1431 case M_LH:
1432 pcrel_load (rd, rd, imm_expr, "lh",
1433 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1434 break;
1435
1436 case M_LHU:
1437 pcrel_load (rd, rd, imm_expr, "lhu",
1438 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1439 break;
1440
1441 case M_LW:
1442 pcrel_load (rd, rd, imm_expr, "lw",
1443 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1444 break;
1445
1446 case M_LWU:
1447 pcrel_load (rd, rd, imm_expr, "lwu",
1448 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1449 break;
1450
1451 case M_LD:
1452 pcrel_load (rd, rd, imm_expr, "ld",
1453 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1454 break;
1455
1456 case M_FLW:
1457 pcrel_load (rd, rs1, imm_expr, "flw",
1458 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1459 break;
1460
1461 case M_FLD:
1462 pcrel_load (rd, rs1, imm_expr, "fld",
1463 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
1464 break;
1465
1466 case M_SB:
1467 pcrel_store (rs2, rs1, imm_expr, "sb",
1468 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1469 break;
1470
1471 case M_SH:
1472 pcrel_store (rs2, rs1, imm_expr, "sh",
1473 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1474 break;
1475
1476 case M_SW:
1477 pcrel_store (rs2, rs1, imm_expr, "sw",
1478 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1479 break;
1480
1481 case M_SD:
1482 pcrel_store (rs2, rs1, imm_expr, "sd",
1483 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1484 break;
1485
1486 case M_FSW:
1487 pcrel_store (rs2, rs1, imm_expr, "fsw",
1488 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1489 break;
1490
1491 case M_FSD:
1492 pcrel_store (rs2, rs1, imm_expr, "fsd",
1493 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1494 break;
1495
1496 case M_CALL:
1497 riscv_call (rd, rs1, imm_expr, *imm_reloc);
1498 break;
1499
1500 default:
1501 as_bad (_("Macro %s not implemented"), ip->insn_mo->name);
1502 break;
1503 }
1504 }
1505
1506 static const struct percent_op_match percent_op_utype[] =
1507 {
1508 {"%tprel_hi", BFD_RELOC_RISCV_TPREL_HI20},
1509 {"%pcrel_hi", BFD_RELOC_RISCV_PCREL_HI20},
1510 {"%got_pcrel_hi", BFD_RELOC_RISCV_GOT_HI20},
1511 {"%tls_ie_pcrel_hi", BFD_RELOC_RISCV_TLS_GOT_HI20},
1512 {"%tls_gd_pcrel_hi", BFD_RELOC_RISCV_TLS_GD_HI20},
1513 {"%hi", BFD_RELOC_RISCV_HI20},
1514 {0, 0}
1515 };
1516
1517 static const struct percent_op_match percent_op_itype[] =
1518 {
1519 {"%lo", BFD_RELOC_RISCV_LO12_I},
1520 {"%tprel_lo", BFD_RELOC_RISCV_TPREL_LO12_I},
1521 {"%pcrel_lo", BFD_RELOC_RISCV_PCREL_LO12_I},
1522 {0, 0}
1523 };
1524
1525 static const struct percent_op_match percent_op_stype[] =
1526 {
1527 {"%lo", BFD_RELOC_RISCV_LO12_S},
1528 {"%tprel_lo", BFD_RELOC_RISCV_TPREL_LO12_S},
1529 {"%pcrel_lo", BFD_RELOC_RISCV_PCREL_LO12_S},
1530 {0, 0}
1531 };
1532
1533 static const struct percent_op_match percent_op_rtype[] =
1534 {
1535 {"%tprel_add", BFD_RELOC_RISCV_TPREL_ADD},
1536 {0, 0}
1537 };
1538
1539 static const struct percent_op_match percent_op_null[] =
1540 {
1541 {0, 0}
1542 };
1543
1544 /* Return true if *STR points to a relocation operator. When returning true,
1545 move *STR over the operator and store its relocation code in *RELOC.
1546 Leave both *STR and *RELOC alone when returning false. */
1547
1548 static bfd_boolean
1549 parse_relocation (char **str, bfd_reloc_code_real_type *reloc,
1550 const struct percent_op_match *percent_op)
1551 {
1552 for ( ; percent_op->str; percent_op++)
1553 if (strncasecmp (*str, percent_op->str, strlen (percent_op->str)) == 0)
1554 {
1555 int len = strlen (percent_op->str);
1556
1557 if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
1558 continue;
1559
1560 *str += strlen (percent_op->str);
1561 *reloc = percent_op->reloc;
1562
1563 /* Check whether the output BFD supports this relocation.
1564 If not, issue an error and fall back on something safe. */
1565 if (*reloc != BFD_RELOC_UNUSED
1566 && !bfd_reloc_type_lookup (stdoutput, *reloc))
1567 {
1568 as_bad ("relocation %s isn't supported by the current ABI",
1569 percent_op->str);
1570 *reloc = BFD_RELOC_UNUSED;
1571 }
1572 return TRUE;
1573 }
1574 return FALSE;
1575 }
1576
1577 static void
1578 my_getExpression (expressionS *ep, char *str)
1579 {
1580 char *save_in;
1581
1582 save_in = input_line_pointer;
1583 input_line_pointer = str;
1584 expression (ep);
1585 expr_end = input_line_pointer;
1586 input_line_pointer = save_in;
1587 }
1588
1589 /* Parse string STR as a 16-bit relocatable operand. Store the
1590 expression in *EP and the relocation, if any, in RELOC.
1591 Return the number of relocation operators used (0 or 1).
1592
1593 On exit, EXPR_END points to the first character after the expression. */
1594
1595 static size_t
1596 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
1597 char *str, const struct percent_op_match *percent_op)
1598 {
1599 size_t reloc_index;
1600 unsigned crux_depth, str_depth, regno;
1601 char *crux;
1602
1603 /* First, check for integer registers. No callers can accept a reg, but
1604 we need to avoid accidentally creating a useless undefined symbol below,
1605 if this is an instruction pattern that can't match. A glibc build fails
1606 if this is removed. */
1607 if (reg_lookup (&str, RCLASS_GPR, &regno))
1608 {
1609 ep->X_op = O_register;
1610 ep->X_add_number = regno;
1611 expr_end = str;
1612 return 0;
1613 }
1614
1615 /* Search for the start of the main expression.
1616 End the loop with CRUX pointing to the start
1617 of the main expression and with CRUX_DEPTH containing the number
1618 of open brackets at that point. */
1619 reloc_index = -1;
1620 str_depth = 0;
1621 do
1622 {
1623 reloc_index++;
1624 crux = str;
1625 crux_depth = str_depth;
1626
1627 /* Skip over whitespace and brackets, keeping count of the number
1628 of brackets. */
1629 while (*str == ' ' || *str == '\t' || *str == '(')
1630 if (*str++ == '(')
1631 str_depth++;
1632 }
1633 while (*str == '%'
1634 && reloc_index < 1
1635 && parse_relocation (&str, reloc, percent_op));
1636
1637 my_getExpression (ep, crux);
1638 str = expr_end;
1639
1640 /* Match every open bracket. */
1641 while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
1642 if (*str++ == ')')
1643 crux_depth--;
1644
1645 if (crux_depth > 0)
1646 as_bad ("unclosed '('");
1647
1648 expr_end = str;
1649
1650 return reloc_index;
1651 }
1652
1653 /* Parse opcode name, could be an mnemonics or number. */
1654 static size_t
1655 my_getOpcodeExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
1656 char *str, const struct percent_op_match *percent_op)
1657 {
1658 const struct opcode_name_t *o = opcode_name_lookup (&str);
1659
1660 if (o != NULL)
1661 {
1662 ep->X_op = O_constant;
1663 ep->X_add_number = o->val;
1664 return 0;
1665 }
1666
1667 return my_getSmallExpression (ep, reloc, str, percent_op);
1668 }
1669
1670 /* Detect and handle implicitly zero load-store offsets. For example,
1671 "lw t0, (t1)" is shorthand for "lw t0, 0(t1)". Return TRUE iff such
1672 an implicit offset was detected. */
1673
1674 static bfd_boolean
1675 riscv_handle_implicit_zero_offset (expressionS *ep, const char *s)
1676 {
1677 /* Check whether there is only a single bracketed expression left.
1678 If so, it must be the base register and the constant must be zero. */
1679 if (*s == '(' && strchr (s + 1, '(') == 0)
1680 {
1681 ep->X_op = O_constant;
1682 ep->X_add_number = 0;
1683 return TRUE;
1684 }
1685
1686 return FALSE;
1687 }
1688
1689 /* All RISC-V CSR instructions belong to one of these classes. */
1690
1691 enum csr_insn_type
1692 {
1693 INSN_NOT_CSR,
1694 INSN_CSRRW,
1695 INSN_CSRRS,
1696 INSN_CSRRC
1697 };
1698
1699 /* Return which CSR instruction is checking. */
1700
1701 static enum csr_insn_type
1702 riscv_csr_insn_type (insn_t insn)
1703 {
1704 if (((insn ^ MATCH_CSRRW) & MASK_CSRRW) == 0
1705 || ((insn ^ MATCH_CSRRWI) & MASK_CSRRWI) == 0)
1706 return INSN_CSRRW;
1707 else if (((insn ^ MATCH_CSRRS) & MASK_CSRRS) == 0
1708 || ((insn ^ MATCH_CSRRSI) & MASK_CSRRSI) == 0)
1709 return INSN_CSRRS;
1710 else if (((insn ^ MATCH_CSRRC) & MASK_CSRRC) == 0
1711 || ((insn ^ MATCH_CSRRCI) & MASK_CSRRCI) == 0)
1712 return INSN_CSRRC;
1713 else
1714 return INSN_NOT_CSR;
1715 }
1716
1717 /* CSRRW and CSRRWI always write CSR. CSRRS, CSRRC, CSRRSI and CSRRCI write
1718 CSR when RS1 isn't zero. The CSR is read only if the [11:10] bits of
1719 CSR address is 0x3. */
1720
1721 static bfd_boolean
1722 riscv_csr_read_only_check (insn_t insn)
1723 {
1724 int csr = (insn & (OP_MASK_CSR << OP_SH_CSR)) >> OP_SH_CSR;
1725 int rs1 = (insn & (OP_MASK_RS1 << OP_SH_RS1)) >> OP_SH_RS1;
1726 int readonly = (((csr & (0x3 << 10)) >> 10) == 0x3);
1727 enum csr_insn_type csr_insn = riscv_csr_insn_type (insn);
1728
1729 if (readonly
1730 && (((csr_insn == INSN_CSRRS
1731 || csr_insn == INSN_CSRRC)
1732 && rs1 != 0)
1733 || csr_insn == INSN_CSRRW))
1734 return FALSE;
1735
1736 return TRUE;
1737 }
1738
1739 /* Return True if it is a privileged instruction. Otherwise, return FALSE.
1740
1741 uret is actually a N-ext instruction. So it is better to regard it as
1742 an user instruction rather than the priv instruction.
1743
1744 hret is used to return from traps in H-mode. H-mode is removed since
1745 the v1.10 priv spec, but probably be added in the new hypervisor spec.
1746 Therefore, hret should be controlled by the hypervisor spec rather than
1747 priv spec in the future.
1748
1749 dret is defined in the debug spec, so it should be checked in the future,
1750 too. */
1751
1752 static bfd_boolean
1753 riscv_is_priv_insn (insn_t insn)
1754 {
1755 return (((insn ^ MATCH_SRET) & MASK_SRET) == 0
1756 || ((insn ^ MATCH_MRET) & MASK_MRET) == 0
1757 || ((insn ^ MATCH_SFENCE_VMA) & MASK_SFENCE_VMA) == 0
1758 || ((insn ^ MATCH_WFI) & MASK_WFI) == 0
1759 /* The sfence.vm is dropped in the v1.10 priv specs, but we still need to
1760 check it here to keep the compatible. Maybe we should issue warning
1761 if sfence.vm is used, but the priv spec newer than v1.10 is chosen.
1762 We already have a similar check for CSR, but not yet for instructions.
1763 It would be good if we could check the spec versions both for CSR and
1764 instructions, but not here. */
1765 || ((insn ^ MATCH_SFENCE_VM) & MASK_SFENCE_VM) == 0);
1766 }
1767
1768 /* This routine assembles an instruction into its binary format. As a
1769 side effect, it sets the global variable imm_reloc to the type of
1770 relocation to do if one of the operands is an address expression. */
1771
1772 static const char *
1773 riscv_ip (char *str, struct riscv_cl_insn *ip, expressionS *imm_expr,
1774 bfd_reloc_code_real_type *imm_reloc, htab_t hash)
1775 {
1776 char *s;
1777 const char *args;
1778 char c = 0;
1779 struct riscv_opcode *insn;
1780 char *argsStart;
1781 unsigned int regno;
1782 char save_c = 0;
1783 int argnum;
1784 const struct percent_op_match *p;
1785 const char *error = "unrecognized opcode";
1786 /* Indicate we are assembling instruction with CSR. */
1787 bfd_boolean insn_with_csr = FALSE;
1788
1789 /* Parse the name of the instruction. Terminate the string if whitespace
1790 is found so that str_hash_find only sees the name part of the string. */
1791 for (s = str; *s != '\0'; ++s)
1792 if (ISSPACE (*s))
1793 {
1794 save_c = *s;
1795 *s++ = '\0';
1796 break;
1797 }
1798
1799 insn = (struct riscv_opcode *) str_hash_find (hash, str);
1800
1801 argsStart = s;
1802 for ( ; insn && insn->name && strcmp (insn->name, str) == 0; insn++)
1803 {
1804 if ((insn->xlen_requirement != 0) && (xlen != insn->xlen_requirement))
1805 continue;
1806
1807 if (!riscv_multi_subset_supports (insn->insn_class))
1808 continue;
1809
1810 create_insn (ip, insn);
1811 argnum = 1;
1812
1813 imm_expr->X_op = O_absent;
1814 *imm_reloc = BFD_RELOC_UNUSED;
1815 p = percent_op_itype;
1816
1817 for (args = insn->args;; ++args)
1818 {
1819 s += strspn (s, " \t");
1820 switch (*args)
1821 {
1822 case '\0': /* End of args. */
1823 if (insn->pinfo != INSN_MACRO)
1824 {
1825 if (!insn->match_func (insn, ip->insn_opcode))
1826 break;
1827
1828 /* For .insn, insn->match and insn->mask are 0. */
1829 if (riscv_insn_length ((insn->match == 0 && insn->mask == 0)
1830 ? ip->insn_opcode
1831 : insn->match) == 2
1832 && !riscv_opts.rvc)
1833 break;
1834
1835 if (riscv_is_priv_insn (ip->insn_opcode))
1836 explicit_priv_attr = TRUE;
1837
1838 /* Check if we write a read-only CSR by the CSR
1839 instruction. */
1840 if (insn_with_csr
1841 && riscv_opts.csr_check
1842 && !riscv_csr_read_only_check (ip->insn_opcode))
1843 {
1844 /* Restore the character in advance, since we want to
1845 report the detailed warning message here. */
1846 if (save_c)
1847 *(argsStart - 1) = save_c;
1848 as_warn (_("Read-only CSR is written `%s'"), str);
1849 insn_with_csr = FALSE;
1850 }
1851 }
1852 if (*s != '\0')
1853 break;
1854 /* Successful assembly. */
1855 error = NULL;
1856 insn_with_csr = FALSE;
1857 goto out;
1858
1859 case 'C': /* RVC */
1860 switch (*++args)
1861 {
1862 case 's': /* RS1 x8-x15 */
1863 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1864 || !(regno >= 8 && regno <= 15))
1865 break;
1866 INSERT_OPERAND (CRS1S, *ip, regno % 8);
1867 continue;
1868 case 'w': /* RS1 x8-x15, constrained to equal RD x8-x15. */
1869 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1870 || EXTRACT_OPERAND (CRS1S, ip->insn_opcode) + 8 != regno)
1871 break;
1872 continue;
1873 case 't': /* RS2 x8-x15 */
1874 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1875 || !(regno >= 8 && regno <= 15))
1876 break;
1877 INSERT_OPERAND (CRS2S, *ip, regno % 8);
1878 continue;
1879 case 'x': /* RS2 x8-x15, constrained to equal RD x8-x15. */
1880 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1881 || EXTRACT_OPERAND (CRS2S, ip->insn_opcode) + 8 != regno)
1882 break;
1883 continue;
1884 case 'U': /* RS1, constrained to equal RD. */
1885 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1886 || EXTRACT_OPERAND (RD, ip->insn_opcode) != regno)
1887 break;
1888 continue;
1889 case 'V': /* RS2 */
1890 if (!reg_lookup (&s, RCLASS_GPR, &regno))
1891 break;
1892 INSERT_OPERAND (CRS2, *ip, regno);
1893 continue;
1894 case 'c': /* RS1, constrained to equal sp. */
1895 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1896 || regno != X_SP)
1897 break;
1898 continue;
1899 case 'z': /* RS2, contrained to equal x0. */
1900 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1901 || regno != 0)
1902 break;
1903 continue;
1904 case '>':
1905 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1906 || imm_expr->X_op != O_constant
1907 || imm_expr->X_add_number <= 0
1908 || imm_expr->X_add_number >= 64)
1909 break;
1910 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1911 rvc_imm_done:
1912 s = expr_end;
1913 imm_expr->X_op = O_absent;
1914 continue;
1915 case '<':
1916 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1917 || imm_expr->X_op != O_constant
1918 || imm_expr->X_add_number <= 0
1919 || imm_expr->X_add_number >= 32
1920 || !VALID_RVC_IMM ((valueT) imm_expr->X_add_number))
1921 break;
1922 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1923 goto rvc_imm_done;
1924 case '8':
1925 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1926 || imm_expr->X_op != O_constant
1927 || imm_expr->X_add_number < 0
1928 || imm_expr->X_add_number >= 256
1929 || !VALID_RVC_UIMM8 ((valueT) imm_expr->X_add_number))
1930 break;
1931 ip->insn_opcode |= ENCODE_RVC_UIMM8 (imm_expr->X_add_number);
1932 goto rvc_imm_done;
1933 case 'i':
1934 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1935 || imm_expr->X_op != O_constant
1936 || imm_expr->X_add_number == 0
1937 || !VALID_RVC_SIMM3 ((valueT) imm_expr->X_add_number))
1938 break;
1939 ip->insn_opcode |= ENCODE_RVC_SIMM3 (imm_expr->X_add_number);
1940 goto rvc_imm_done;
1941 case 'j':
1942 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1943 || imm_expr->X_op != O_constant
1944 || imm_expr->X_add_number == 0
1945 || !VALID_RVC_IMM ((valueT) imm_expr->X_add_number))
1946 break;
1947 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1948 goto rvc_imm_done;
1949 case 'k':
1950 if (riscv_handle_implicit_zero_offset (imm_expr, s))
1951 continue;
1952 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1953 || imm_expr->X_op != O_constant
1954 || !VALID_RVC_LW_IMM ((valueT) imm_expr->X_add_number))
1955 break;
1956 ip->insn_opcode |= ENCODE_RVC_LW_IMM (imm_expr->X_add_number);
1957 goto rvc_imm_done;
1958 case 'l':
1959 if (riscv_handle_implicit_zero_offset (imm_expr, s))
1960 continue;
1961 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1962 || imm_expr->X_op != O_constant
1963 || !VALID_RVC_LD_IMM ((valueT) imm_expr->X_add_number))
1964 break;
1965 ip->insn_opcode |= ENCODE_RVC_LD_IMM (imm_expr->X_add_number);
1966 goto rvc_imm_done;
1967 case 'm':
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_LWSP_IMM ((valueT) imm_expr->X_add_number))
1973 break;
1974 ip->insn_opcode |=
1975 ENCODE_RVC_LWSP_IMM (imm_expr->X_add_number);
1976 goto rvc_imm_done;
1977 case 'n':
1978 if (riscv_handle_implicit_zero_offset (imm_expr, s))
1979 continue;
1980 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1981 || imm_expr->X_op != O_constant
1982 || !VALID_RVC_LDSP_IMM ((valueT) imm_expr->X_add_number))
1983 break;
1984 ip->insn_opcode |=
1985 ENCODE_RVC_LDSP_IMM (imm_expr->X_add_number);
1986 goto rvc_imm_done;
1987 case 'o':
1988 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1989 || imm_expr->X_op != O_constant
1990 /* C.addiw, c.li, and c.andi allow zero immediate.
1991 C.addi allows zero immediate as hint. Otherwise this
1992 is same as 'j'. */
1993 || !VALID_RVC_IMM ((valueT) imm_expr->X_add_number))
1994 break;
1995 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1996 goto rvc_imm_done;
1997 case 'K':
1998 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1999 || imm_expr->X_op != O_constant
2000 || imm_expr->X_add_number == 0
2001 || !VALID_RVC_ADDI4SPN_IMM ((valueT) imm_expr->X_add_number))
2002 break;
2003 ip->insn_opcode |=
2004 ENCODE_RVC_ADDI4SPN_IMM (imm_expr->X_add_number);
2005 goto rvc_imm_done;
2006 case 'L':
2007 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2008 || imm_expr->X_op != O_constant
2009 || imm_expr->X_add_number == 0
2010 || !VALID_RVC_ADDI16SP_IMM ((valueT) imm_expr->X_add_number))
2011 break;
2012 ip->insn_opcode |=
2013 ENCODE_RVC_ADDI16SP_IMM (imm_expr->X_add_number);
2014 goto rvc_imm_done;
2015 case 'M':
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_SWSP_IMM ((valueT) imm_expr->X_add_number))
2021 break;
2022 ip->insn_opcode |=
2023 ENCODE_RVC_SWSP_IMM (imm_expr->X_add_number);
2024 goto rvc_imm_done;
2025 case 'N':
2026 if (riscv_handle_implicit_zero_offset (imm_expr, s))
2027 continue;
2028 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2029 || imm_expr->X_op != O_constant
2030 || !VALID_RVC_SDSP_IMM ((valueT) imm_expr->X_add_number))
2031 break;
2032 ip->insn_opcode |=
2033 ENCODE_RVC_SDSP_IMM (imm_expr->X_add_number);
2034 goto rvc_imm_done;
2035 case 'u':
2036 p = percent_op_utype;
2037 if (my_getSmallExpression (imm_expr, imm_reloc, s, p))
2038 break;
2039 rvc_lui:
2040 if (imm_expr->X_op != O_constant
2041 || imm_expr->X_add_number <= 0
2042 || imm_expr->X_add_number >= RISCV_BIGIMM_REACH
2043 || (imm_expr->X_add_number >= RISCV_RVC_IMM_REACH / 2
2044 && (imm_expr->X_add_number <
2045 RISCV_BIGIMM_REACH - RISCV_RVC_IMM_REACH / 2)))
2046 break;
2047 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
2048 goto rvc_imm_done;
2049 case 'v':
2050 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2051 || (imm_expr->X_add_number & (RISCV_IMM_REACH - 1))
2052 || ((int32_t)imm_expr->X_add_number
2053 != imm_expr->X_add_number))
2054 break;
2055 imm_expr->X_add_number =
2056 ((uint32_t) imm_expr->X_add_number) >> RISCV_IMM_BITS;
2057 goto rvc_lui;
2058 case 'p':
2059 goto branch;
2060 case 'a':
2061 goto jump;
2062 case 'S': /* Floating-point RS1 x8-x15. */
2063 if (!reg_lookup (&s, RCLASS_FPR, &regno)
2064 || !(regno >= 8 && regno <= 15))
2065 break;
2066 INSERT_OPERAND (CRS1S, *ip, regno % 8);
2067 continue;
2068 case 'D': /* Floating-point RS2 x8-x15. */
2069 if (!reg_lookup (&s, RCLASS_FPR, &regno)
2070 || !(regno >= 8 && regno <= 15))
2071 break;
2072 INSERT_OPERAND (CRS2S, *ip, regno % 8);
2073 continue;
2074 case 'T': /* Floating-point RS2. */
2075 if (!reg_lookup (&s, RCLASS_FPR, &regno))
2076 break;
2077 INSERT_OPERAND (CRS2, *ip, regno);
2078 continue;
2079 case 'F':
2080 switch (*++args)
2081 {
2082 case '6':
2083 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2084 || imm_expr->X_op != O_constant
2085 || imm_expr->X_add_number < 0
2086 || imm_expr->X_add_number >= 64)
2087 {
2088 as_bad (_("bad value for funct6 field, "
2089 "value must be 0...64"));
2090 break;
2091 }
2092
2093 INSERT_OPERAND (CFUNCT6, *ip, imm_expr->X_add_number);
2094 imm_expr->X_op = O_absent;
2095 s = expr_end;
2096 continue;
2097 case '4':
2098 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2099 || imm_expr->X_op != O_constant
2100 || imm_expr->X_add_number < 0
2101 || imm_expr->X_add_number >= 16)
2102 {
2103 as_bad (_("bad value for funct4 field, "
2104 "value must be 0...15"));
2105 break;
2106 }
2107
2108 INSERT_OPERAND (CFUNCT4, *ip, imm_expr->X_add_number);
2109 imm_expr->X_op = O_absent;
2110 s = expr_end;
2111 continue;
2112 case '3':
2113 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2114 || imm_expr->X_op != O_constant
2115 || imm_expr->X_add_number < 0
2116 || imm_expr->X_add_number >= 8)
2117 {
2118 as_bad (_("bad value for funct3 field, "
2119 "value must be 0...7"));
2120 break;
2121 }
2122 INSERT_OPERAND (CFUNCT3, *ip, imm_expr->X_add_number);
2123 imm_expr->X_op = O_absent;
2124 s = expr_end;
2125 continue;
2126 case '2':
2127 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2128 || imm_expr->X_op != O_constant
2129 || imm_expr->X_add_number < 0
2130 || imm_expr->X_add_number >= 4)
2131 {
2132 as_bad (_("bad value for funct2 field, "
2133 "value must be 0...3"));
2134 break;
2135 }
2136 INSERT_OPERAND (CFUNCT2, *ip, imm_expr->X_add_number);
2137 imm_expr->X_op = O_absent;
2138 s = expr_end;
2139 continue;
2140 default:
2141 as_bad (_("bad compressed FUNCT field"
2142 " specifier 'CF%c'\n"),
2143 *args);
2144 }
2145 break;
2146
2147 default:
2148 as_bad (_("bad RVC field specifier 'C%c'\n"), *args);
2149 }
2150 break;
2151
2152 case ',':
2153 ++argnum;
2154 if (*s++ == *args)
2155 continue;
2156 s--;
2157 break;
2158
2159 case '(':
2160 case ')':
2161 case '[':
2162 case ']':
2163 if (*s++ == *args)
2164 continue;
2165 break;
2166
2167 case '<': /* Shift amount, 0 - 31. */
2168 my_getExpression (imm_expr, s);
2169 check_absolute_expr (ip, imm_expr, FALSE);
2170 if ((unsigned long) imm_expr->X_add_number > 31)
2171 as_bad (_("Improper shift amount (%lu)"),
2172 (unsigned long) imm_expr->X_add_number);
2173 INSERT_OPERAND (SHAMTW, *ip, imm_expr->X_add_number);
2174 imm_expr->X_op = O_absent;
2175 s = expr_end;
2176 continue;
2177
2178 case '>': /* Shift amount, 0 - (XLEN-1). */
2179 my_getExpression (imm_expr, s);
2180 check_absolute_expr (ip, imm_expr, FALSE);
2181 if ((unsigned long) imm_expr->X_add_number >= xlen)
2182 as_bad (_("Improper shift amount (%lu)"),
2183 (unsigned long) imm_expr->X_add_number);
2184 INSERT_OPERAND (SHAMT, *ip, imm_expr->X_add_number);
2185 imm_expr->X_op = O_absent;
2186 s = expr_end;
2187 continue;
2188
2189 case 'Z': /* CSRRxI immediate. */
2190 my_getExpression (imm_expr, s);
2191 check_absolute_expr (ip, imm_expr, FALSE);
2192 if ((unsigned long) imm_expr->X_add_number > 31)
2193 as_bad (_("Improper CSRxI immediate (%lu)"),
2194 (unsigned long) imm_expr->X_add_number);
2195 INSERT_OPERAND (RS1, *ip, imm_expr->X_add_number);
2196 imm_expr->X_op = O_absent;
2197 s = expr_end;
2198 continue;
2199
2200 case 'E': /* Control register. */
2201 insn_with_csr = TRUE;
2202 explicit_priv_attr = TRUE;
2203 if (reg_lookup (&s, RCLASS_CSR, &regno))
2204 INSERT_OPERAND (CSR, *ip, regno);
2205 else
2206 {
2207 my_getExpression (imm_expr, s);
2208 check_absolute_expr (ip, imm_expr, TRUE);
2209 if ((unsigned long) imm_expr->X_add_number > 0xfff)
2210 as_bad (_("Improper CSR address (%lu)"),
2211 (unsigned long) imm_expr->X_add_number);
2212 INSERT_OPERAND (CSR, *ip, imm_expr->X_add_number);
2213 imm_expr->X_op = O_absent;
2214 s = expr_end;
2215 }
2216 continue;
2217
2218 case 'm': /* Rounding mode. */
2219 if (arg_lookup (&s, riscv_rm, ARRAY_SIZE (riscv_rm), &regno))
2220 {
2221 INSERT_OPERAND (RM, *ip, regno);
2222 continue;
2223 }
2224 break;
2225
2226 case 'P':
2227 case 'Q': /* Fence predecessor/successor. */
2228 if (arg_lookup (&s, riscv_pred_succ, ARRAY_SIZE (riscv_pred_succ),
2229 &regno))
2230 {
2231 if (*args == 'P')
2232 INSERT_OPERAND (PRED, *ip, regno);
2233 else
2234 INSERT_OPERAND (SUCC, *ip, regno);
2235 continue;
2236 }
2237 break;
2238
2239 case 'd': /* Destination register. */
2240 case 's': /* Source register. */
2241 case 't': /* Target register. */
2242 case 'r': /* rs3. */
2243 if (reg_lookup (&s, RCLASS_GPR, &regno))
2244 {
2245 c = *args;
2246 if (*s == ' ')
2247 ++s;
2248
2249 /* Now that we have assembled one operand, we use the args
2250 string to figure out where it goes in the instruction. */
2251 switch (c)
2252 {
2253 case 's':
2254 INSERT_OPERAND (RS1, *ip, regno);
2255 break;
2256 case 'd':
2257 INSERT_OPERAND (RD, *ip, regno);
2258 break;
2259 case 't':
2260 INSERT_OPERAND (RS2, *ip, regno);
2261 break;
2262 case 'r':
2263 INSERT_OPERAND (RS3, *ip, regno);
2264 break;
2265 }
2266 continue;
2267 }
2268 break;
2269
2270 case 'D': /* Floating point rd. */
2271 case 'S': /* Floating point rs1. */
2272 case 'T': /* Floating point rs2. */
2273 case 'U': /* Floating point rs1 and rs2. */
2274 case 'R': /* Floating point rs3. */
2275 if (reg_lookup (&s, RCLASS_FPR, &regno))
2276 {
2277 c = *args;
2278 if (*s == ' ')
2279 ++s;
2280 switch (c)
2281 {
2282 case 'D':
2283 INSERT_OPERAND (RD, *ip, regno);
2284 break;
2285 case 'S':
2286 INSERT_OPERAND (RS1, *ip, regno);
2287 break;
2288 case 'U':
2289 INSERT_OPERAND (RS1, *ip, regno);
2290 /* fallthru */
2291 case 'T':
2292 INSERT_OPERAND (RS2, *ip, regno);
2293 break;
2294 case 'R':
2295 INSERT_OPERAND (RS3, *ip, regno);
2296 break;
2297 }
2298 continue;
2299 }
2300
2301 break;
2302
2303 case 'I':
2304 my_getExpression (imm_expr, s);
2305 if (imm_expr->X_op != O_big
2306 && imm_expr->X_op != O_constant)
2307 break;
2308 normalize_constant_expr (imm_expr);
2309 s = expr_end;
2310 continue;
2311
2312 case 'A':
2313 my_getExpression (imm_expr, s);
2314 normalize_constant_expr (imm_expr);
2315 /* The 'A' format specifier must be a symbol. */
2316 if (imm_expr->X_op != O_symbol)
2317 break;
2318 *imm_reloc = BFD_RELOC_32;
2319 s = expr_end;
2320 continue;
2321
2322 case 'B':
2323 my_getExpression (imm_expr, s);
2324 normalize_constant_expr (imm_expr);
2325 /* The 'B' format specifier must be a symbol or a constant. */
2326 if (imm_expr->X_op != O_symbol && imm_expr->X_op != O_constant)
2327 break;
2328 if (imm_expr->X_op == O_symbol)
2329 *imm_reloc = BFD_RELOC_32;
2330 s = expr_end;
2331 continue;
2332
2333 case 'j': /* Sign-extended immediate. */
2334 p = percent_op_itype;
2335 *imm_reloc = BFD_RELOC_RISCV_LO12_I;
2336 goto alu_op;
2337 case 'q': /* Store displacement. */
2338 p = percent_op_stype;
2339 *imm_reloc = BFD_RELOC_RISCV_LO12_S;
2340 goto load_store;
2341 case 'o': /* Load displacement. */
2342 p = percent_op_itype;
2343 *imm_reloc = BFD_RELOC_RISCV_LO12_I;
2344 goto load_store;
2345 case '1': /* 4-operand add, must be %tprel_add. */
2346 p = percent_op_rtype;
2347 goto alu_op;
2348 case '0': /* AMO "displacement," which must be zero. */
2349 p = percent_op_null;
2350 load_store:
2351 if (riscv_handle_implicit_zero_offset (imm_expr, s))
2352 continue;
2353 alu_op:
2354 /* If this value won't fit into a 16 bit offset, then go
2355 find a macro that will generate the 32 bit offset
2356 code pattern. */
2357 if (!my_getSmallExpression (imm_expr, imm_reloc, s, p))
2358 {
2359 normalize_constant_expr (imm_expr);
2360 if (imm_expr->X_op != O_constant
2361 || (*args == '0' && imm_expr->X_add_number != 0)
2362 || (*args == '1')
2363 || imm_expr->X_add_number >= (signed)RISCV_IMM_REACH/2
2364 || imm_expr->X_add_number < -(signed)RISCV_IMM_REACH/2)
2365 break;
2366 }
2367
2368 s = expr_end;
2369 continue;
2370
2371 case 'p': /* PC-relative offset. */
2372 branch:
2373 *imm_reloc = BFD_RELOC_12_PCREL;
2374 my_getExpression (imm_expr, s);
2375 s = expr_end;
2376 continue;
2377
2378 case 'u': /* Upper 20 bits. */
2379 p = percent_op_utype;
2380 if (!my_getSmallExpression (imm_expr, imm_reloc, s, p))
2381 {
2382 if (imm_expr->X_op != O_constant)
2383 break;
2384
2385 if (imm_expr->X_add_number < 0
2386 || imm_expr->X_add_number >= (signed)RISCV_BIGIMM_REACH)
2387 as_bad (_("lui expression not in range 0..1048575"));
2388
2389 *imm_reloc = BFD_RELOC_RISCV_HI20;
2390 imm_expr->X_add_number <<= RISCV_IMM_BITS;
2391 }
2392 s = expr_end;
2393 continue;
2394
2395 case 'a': /* 20-bit PC-relative offset. */
2396 jump:
2397 my_getExpression (imm_expr, s);
2398 s = expr_end;
2399 *imm_reloc = BFD_RELOC_RISCV_JMP;
2400 continue;
2401
2402 case 'c':
2403 my_getExpression (imm_expr, s);
2404 s = expr_end;
2405 if (strcmp (s, "@plt") == 0)
2406 {
2407 *imm_reloc = BFD_RELOC_RISCV_CALL_PLT;
2408 s += 4;
2409 }
2410 else
2411 *imm_reloc = BFD_RELOC_RISCV_CALL;
2412 continue;
2413 case 'O':
2414 switch (*++args)
2415 {
2416 case '4':
2417 if (my_getOpcodeExpression (imm_expr, imm_reloc, s, p)
2418 || imm_expr->X_op != O_constant
2419 || imm_expr->X_add_number < 0
2420 || imm_expr->X_add_number >= 128
2421 || (imm_expr->X_add_number & 0x3) != 3)
2422 {
2423 as_bad (_("bad value for opcode field, "
2424 "value must be 0...127 and "
2425 "lower 2 bits must be 0x3"));
2426 break;
2427 }
2428
2429 INSERT_OPERAND (OP, *ip, imm_expr->X_add_number);
2430 imm_expr->X_op = O_absent;
2431 s = expr_end;
2432 continue;
2433 case '2':
2434 if (my_getOpcodeExpression (imm_expr, imm_reloc, s, p)
2435 || imm_expr->X_op != O_constant
2436 || imm_expr->X_add_number < 0
2437 || imm_expr->X_add_number >= 3)
2438 {
2439 as_bad (_("bad value for opcode field, "
2440 "value must be 0...2"));
2441 break;
2442 }
2443
2444 INSERT_OPERAND (OP2, *ip, imm_expr->X_add_number);
2445 imm_expr->X_op = O_absent;
2446 s = expr_end;
2447 continue;
2448 default:
2449 as_bad (_("bad Opcode field specifier 'O%c'\n"), *args);
2450 }
2451 break;
2452
2453 case 'F':
2454 switch (*++args)
2455 {
2456 case '7':
2457 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2458 || imm_expr->X_op != O_constant
2459 || imm_expr->X_add_number < 0
2460 || imm_expr->X_add_number >= 128)
2461 {
2462 as_bad (_("bad value for funct7 field, "
2463 "value must be 0...127"));
2464 break;
2465 }
2466
2467 INSERT_OPERAND (FUNCT7, *ip, imm_expr->X_add_number);
2468 imm_expr->X_op = O_absent;
2469 s = expr_end;
2470 continue;
2471 case '3':
2472 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2473 || imm_expr->X_op != O_constant
2474 || imm_expr->X_add_number < 0
2475 || imm_expr->X_add_number >= 8)
2476 {
2477 as_bad (_("bad value for funct3 field, "
2478 "value must be 0...7"));
2479 break;
2480 }
2481
2482 INSERT_OPERAND (FUNCT3, *ip, imm_expr->X_add_number);
2483 imm_expr->X_op = O_absent;
2484 s = expr_end;
2485 continue;
2486 case '2':
2487 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2488 || imm_expr->X_op != O_constant
2489 || imm_expr->X_add_number < 0
2490 || imm_expr->X_add_number >= 4)
2491 {
2492 as_bad (_("bad value for funct2 field, "
2493 "value must be 0...3"));
2494 break;
2495 }
2496
2497 INSERT_OPERAND (FUNCT2, *ip, imm_expr->X_add_number);
2498 imm_expr->X_op = O_absent;
2499 s = expr_end;
2500 continue;
2501
2502 default:
2503 as_bad (_("bad FUNCT field specifier 'F%c'\n"), *args);
2504 }
2505 break;
2506
2507 case 'z':
2508 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
2509 || imm_expr->X_op != O_constant
2510 || imm_expr->X_add_number != 0)
2511 break;
2512 s = expr_end;
2513 imm_expr->X_op = O_absent;
2514 continue;
2515
2516 default:
2517 as_fatal (_("internal error: bad argument type %c"), *args);
2518 }
2519 break;
2520 }
2521 s = argsStart;
2522 error = _("illegal operands");
2523 insn_with_csr = FALSE;
2524 }
2525
2526 out:
2527 /* Restore the character we might have clobbered above. */
2528 if (save_c)
2529 *(argsStart - 1) = save_c;
2530
2531 return error;
2532 }
2533
2534 void
2535 md_assemble (char *str)
2536 {
2537 struct riscv_cl_insn insn;
2538 expressionS imm_expr;
2539 bfd_reloc_code_real_type imm_reloc = BFD_RELOC_UNUSED;
2540
2541 /* The arch and priv attributes should be set before assembling. */
2542 if (!start_assemble)
2543 {
2544 start_assemble = TRUE;
2545
2546 /* Set the default_priv_spec according to the priv attributes. */
2547 if (!riscv_set_default_priv_spec (NULL))
2548 return;
2549 }
2550
2551 const char *error = riscv_ip (str, &insn, &imm_expr, &imm_reloc, op_hash);
2552
2553 if (error)
2554 {
2555 as_bad ("%s `%s'", error, str);
2556 return;
2557 }
2558
2559 if (insn.insn_mo->pinfo == INSN_MACRO)
2560 macro (&insn, &imm_expr, &imm_reloc);
2561 else
2562 append_insn (&insn, &imm_expr, imm_reloc);
2563 }
2564
2565 const char *
2566 md_atof (int type, char *litP, int *sizeP)
2567 {
2568 return ieee_md_atof (type, litP, sizeP, TARGET_BYTES_BIG_ENDIAN);
2569 }
2570
2571 void
2572 md_number_to_chars (char *buf, valueT val, int n)
2573 {
2574 number_to_chars_littleendian (buf, val, n);
2575 }
2576
2577 const char *md_shortopts = "O::g::G:";
2578
2579 enum options
2580 {
2581 OPTION_MARCH = OPTION_MD_BASE,
2582 OPTION_PIC,
2583 OPTION_NO_PIC,
2584 OPTION_MABI,
2585 OPTION_RELAX,
2586 OPTION_NO_RELAX,
2587 OPTION_ARCH_ATTR,
2588 OPTION_NO_ARCH_ATTR,
2589 OPTION_CSR_CHECK,
2590 OPTION_NO_CSR_CHECK,
2591 OPTION_MISA_SPEC,
2592 OPTION_MPRIV_SPEC,
2593 OPTION_END_OF_ENUM
2594 };
2595
2596 struct option md_longopts[] =
2597 {
2598 {"march", required_argument, NULL, OPTION_MARCH},
2599 {"fPIC", no_argument, NULL, OPTION_PIC},
2600 {"fpic", no_argument, NULL, OPTION_PIC},
2601 {"fno-pic", no_argument, NULL, OPTION_NO_PIC},
2602 {"mabi", required_argument, NULL, OPTION_MABI},
2603 {"mrelax", no_argument, NULL, OPTION_RELAX},
2604 {"mno-relax", no_argument, NULL, OPTION_NO_RELAX},
2605 {"march-attr", no_argument, NULL, OPTION_ARCH_ATTR},
2606 {"mno-arch-attr", no_argument, NULL, OPTION_NO_ARCH_ATTR},
2607 {"mcsr-check", no_argument, NULL, OPTION_CSR_CHECK},
2608 {"mno-csr-check", no_argument, NULL, OPTION_NO_CSR_CHECK},
2609 {"misa-spec", required_argument, NULL, OPTION_MISA_SPEC},
2610 {"mpriv-spec", required_argument, NULL, OPTION_MPRIV_SPEC},
2611
2612 {NULL, no_argument, NULL, 0}
2613 };
2614 size_t md_longopts_size = sizeof (md_longopts);
2615
2616 enum float_abi {
2617 FLOAT_ABI_DEFAULT = -1,
2618 FLOAT_ABI_SOFT,
2619 FLOAT_ABI_SINGLE,
2620 FLOAT_ABI_DOUBLE,
2621 FLOAT_ABI_QUAD
2622 };
2623 static enum float_abi float_abi = FLOAT_ABI_DEFAULT;
2624
2625 static void
2626 riscv_set_abi (unsigned new_xlen, enum float_abi new_float_abi, bfd_boolean rve)
2627 {
2628 abi_xlen = new_xlen;
2629 float_abi = new_float_abi;
2630 rve_abi = rve;
2631 }
2632
2633 int
2634 md_parse_option (int c, const char *arg)
2635 {
2636 switch (c)
2637 {
2638 case OPTION_MARCH:
2639 /* riscv_after_parse_args will call riscv_set_arch to parse
2640 the architecture. */
2641 default_arch_with_ext = arg;
2642 break;
2643
2644 case OPTION_NO_PIC:
2645 riscv_opts.pic = FALSE;
2646 break;
2647
2648 case OPTION_PIC:
2649 riscv_opts.pic = TRUE;
2650 break;
2651
2652 case OPTION_MABI:
2653 if (strcmp (arg, "ilp32") == 0)
2654 riscv_set_abi (32, FLOAT_ABI_SOFT, FALSE);
2655 else if (strcmp (arg, "ilp32e") == 0)
2656 riscv_set_abi (32, FLOAT_ABI_SOFT, TRUE);
2657 else if (strcmp (arg, "ilp32f") == 0)
2658 riscv_set_abi (32, FLOAT_ABI_SINGLE, FALSE);
2659 else if (strcmp (arg, "ilp32d") == 0)
2660 riscv_set_abi (32, FLOAT_ABI_DOUBLE, FALSE);
2661 else if (strcmp (arg, "ilp32q") == 0)
2662 riscv_set_abi (32, FLOAT_ABI_QUAD, FALSE);
2663 else if (strcmp (arg, "lp64") == 0)
2664 riscv_set_abi (64, FLOAT_ABI_SOFT, FALSE);
2665 else if (strcmp (arg, "lp64f") == 0)
2666 riscv_set_abi (64, FLOAT_ABI_SINGLE, FALSE);
2667 else if (strcmp (arg, "lp64d") == 0)
2668 riscv_set_abi (64, FLOAT_ABI_DOUBLE, FALSE);
2669 else if (strcmp (arg, "lp64q") == 0)
2670 riscv_set_abi (64, FLOAT_ABI_QUAD, FALSE);
2671 else
2672 return 0;
2673 break;
2674
2675 case OPTION_RELAX:
2676 riscv_opts.relax = TRUE;
2677 break;
2678
2679 case OPTION_NO_RELAX:
2680 riscv_opts.relax = FALSE;
2681 break;
2682
2683 case OPTION_ARCH_ATTR:
2684 riscv_opts.arch_attr = TRUE;
2685 break;
2686
2687 case OPTION_NO_ARCH_ATTR:
2688 riscv_opts.arch_attr = FALSE;
2689 break;
2690
2691 case OPTION_CSR_CHECK:
2692 riscv_opts.csr_check = TRUE;
2693 break;
2694
2695 case OPTION_NO_CSR_CHECK:
2696 riscv_opts.csr_check = FALSE;
2697 break;
2698
2699 case OPTION_MISA_SPEC:
2700 return riscv_set_default_isa_spec (arg);
2701
2702 case OPTION_MPRIV_SPEC:
2703 return riscv_set_default_priv_spec (arg);
2704
2705 default:
2706 return 0;
2707 }
2708
2709 return 1;
2710 }
2711
2712 void
2713 riscv_after_parse_args (void)
2714 {
2715 /* The --with-arch is optional for now, so we have to set the xlen
2716 according to the default_arch, which is set by the --targte, first.
2717 Then, we use the xlen to set the default_arch_with_ext if the
2718 -march and --with-arch are not set. */
2719 if (xlen == 0)
2720 {
2721 if (strcmp (default_arch, "riscv32") == 0)
2722 xlen = 32;
2723 else if (strcmp (default_arch, "riscv64") == 0)
2724 xlen = 64;
2725 else
2726 as_bad ("unknown default architecture `%s'", default_arch);
2727 }
2728 if (default_arch_with_ext == NULL)
2729 default_arch_with_ext = xlen == 64 ? "rv64g" : "rv32g";
2730
2731 /* Initialize the hash table for extensions with default version. */
2732 ext_version_hash = init_ext_version_hash (riscv_ext_version_table);
2733
2734 /* If the -misa-spec isn't set, then we set the default ISA spec according
2735 to DEFAULT_RISCV_ISA_SPEC. */
2736 if (default_isa_spec == ISA_SPEC_CLASS_NONE)
2737 riscv_set_default_isa_spec (DEFAULT_RISCV_ISA_SPEC);
2738
2739 /* Set the architecture according to -march or or --with-arch. */
2740 riscv_set_arch (default_arch_with_ext);
2741
2742 /* Add the RVC extension, regardless of -march, to support .option rvc. */
2743 riscv_set_rvc (FALSE);
2744 if (riscv_subset_supports ("c"))
2745 riscv_set_rvc (TRUE);
2746
2747 /* Enable RVE if specified by the -march option. */
2748 riscv_set_rve (FALSE);
2749 if (riscv_subset_supports ("e"))
2750 riscv_set_rve (TRUE);
2751
2752 /* If the -mpriv-spec isn't set, then we set the default privilege spec
2753 according to DEFAULT_PRIV_SPEC. */
2754 if (default_priv_spec == PRIV_SPEC_CLASS_NONE)
2755 riscv_set_default_priv_spec (DEFAULT_RISCV_PRIV_SPEC);
2756
2757 /* Infer ABI from ISA if not specified on command line. */
2758 if (abi_xlen == 0)
2759 abi_xlen = xlen;
2760 else if (abi_xlen > xlen)
2761 as_bad ("can't have %d-bit ABI on %d-bit ISA", abi_xlen, xlen);
2762 else if (abi_xlen < xlen)
2763 as_bad ("%d-bit ABI not yet supported on %d-bit ISA", abi_xlen, xlen);
2764
2765 if (float_abi == FLOAT_ABI_DEFAULT)
2766 {
2767 riscv_subset_t *subset;
2768
2769 /* Assume soft-float unless D extension is present. */
2770 float_abi = FLOAT_ABI_SOFT;
2771
2772 for (subset = riscv_subsets.head; subset != NULL; subset = subset->next)
2773 {
2774 if (strcasecmp (subset->name, "D") == 0)
2775 float_abi = FLOAT_ABI_DOUBLE;
2776 if (strcasecmp (subset->name, "Q") == 0)
2777 float_abi = FLOAT_ABI_QUAD;
2778 }
2779 }
2780
2781 if (rve_abi)
2782 elf_flags |= EF_RISCV_RVE;
2783
2784 /* Insert float_abi into the EF_RISCV_FLOAT_ABI field of elf_flags. */
2785 elf_flags |= float_abi * (EF_RISCV_FLOAT_ABI & ~(EF_RISCV_FLOAT_ABI << 1));
2786
2787 /* If the CIE to be produced has not been overridden on the command line,
2788 then produce version 3 by default. This allows us to use the full
2789 range of registers in a .cfi_return_column directive. */
2790 if (flag_dwarf_cie_version == -1)
2791 flag_dwarf_cie_version = 3;
2792 }
2793
2794 long
2795 md_pcrel_from (fixS *fixP)
2796 {
2797 return fixP->fx_where + fixP->fx_frag->fr_address;
2798 }
2799
2800 /* Apply a fixup to the object file. */
2801
2802 void
2803 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
2804 {
2805 unsigned int subtype;
2806 bfd_byte *buf = (bfd_byte *) (fixP->fx_frag->fr_literal + fixP->fx_where);
2807 bfd_boolean relaxable = FALSE;
2808 offsetT loc;
2809 segT sub_segment;
2810
2811 /* Remember value for tc_gen_reloc. */
2812 fixP->fx_addnumber = *valP;
2813
2814 switch (fixP->fx_r_type)
2815 {
2816 case BFD_RELOC_RISCV_HI20:
2817 case BFD_RELOC_RISCV_LO12_I:
2818 case BFD_RELOC_RISCV_LO12_S:
2819 bfd_putl32 (riscv_apply_const_reloc (fixP->fx_r_type, *valP)
2820 | bfd_getl32 (buf), buf);
2821 if (fixP->fx_addsy == NULL)
2822 fixP->fx_done = TRUE;
2823 relaxable = TRUE;
2824 break;
2825
2826 case BFD_RELOC_RISCV_GOT_HI20:
2827 case BFD_RELOC_RISCV_ADD8:
2828 case BFD_RELOC_RISCV_ADD16:
2829 case BFD_RELOC_RISCV_ADD32:
2830 case BFD_RELOC_RISCV_ADD64:
2831 case BFD_RELOC_RISCV_SUB6:
2832 case BFD_RELOC_RISCV_SUB8:
2833 case BFD_RELOC_RISCV_SUB16:
2834 case BFD_RELOC_RISCV_SUB32:
2835 case BFD_RELOC_RISCV_SUB64:
2836 case BFD_RELOC_RISCV_RELAX:
2837 break;
2838
2839 case BFD_RELOC_RISCV_TPREL_HI20:
2840 case BFD_RELOC_RISCV_TPREL_LO12_I:
2841 case BFD_RELOC_RISCV_TPREL_LO12_S:
2842 case BFD_RELOC_RISCV_TPREL_ADD:
2843 relaxable = TRUE;
2844 /* Fall through. */
2845
2846 case BFD_RELOC_RISCV_TLS_GOT_HI20:
2847 case BFD_RELOC_RISCV_TLS_GD_HI20:
2848 case BFD_RELOC_RISCV_TLS_DTPREL32:
2849 case BFD_RELOC_RISCV_TLS_DTPREL64:
2850 if (fixP->fx_addsy != NULL)
2851 S_SET_THREAD_LOCAL (fixP->fx_addsy);
2852 else
2853 as_bad_where (fixP->fx_file, fixP->fx_line,
2854 _("TLS relocation against a constant"));
2855 break;
2856
2857 case BFD_RELOC_32:
2858 /* Use pc-relative relocation for FDE initial location.
2859 The symbol address in .eh_frame may be adjusted in
2860 _bfd_elf_discard_section_eh_frame, and the content of
2861 .eh_frame will be adjusted in _bfd_elf_write_section_eh_frame.
2862 Therefore, we cannot insert a relocation whose addend symbol is
2863 in .eh_frame. Othrewise, the value may be adjusted twice.*/
2864 if (fixP->fx_addsy && fixP->fx_subsy
2865 && (sub_segment = S_GET_SEGMENT (fixP->fx_subsy))
2866 && strcmp (sub_segment->name, ".eh_frame") == 0
2867 && S_GET_VALUE (fixP->fx_subsy)
2868 == fixP->fx_frag->fr_address + fixP->fx_where)
2869 {
2870 fixP->fx_r_type = BFD_RELOC_RISCV_32_PCREL;
2871 fixP->fx_subsy = NULL;
2872 break;
2873 }
2874 /* Fall through. */
2875 case BFD_RELOC_64:
2876 case BFD_RELOC_16:
2877 case BFD_RELOC_8:
2878 case BFD_RELOC_RISCV_CFA:
2879 if (fixP->fx_addsy && fixP->fx_subsy)
2880 {
2881 fixP->fx_next = xmemdup (fixP, sizeof (*fixP), sizeof (*fixP));
2882 fixP->fx_next->fx_addsy = fixP->fx_subsy;
2883 fixP->fx_next->fx_subsy = NULL;
2884 fixP->fx_next->fx_offset = 0;
2885 fixP->fx_subsy = NULL;
2886
2887 switch (fixP->fx_r_type)
2888 {
2889 case BFD_RELOC_64:
2890 fixP->fx_r_type = BFD_RELOC_RISCV_ADD64;
2891 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB64;
2892 break;
2893
2894 case BFD_RELOC_32:
2895 fixP->fx_r_type = BFD_RELOC_RISCV_ADD32;
2896 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB32;
2897 break;
2898
2899 case BFD_RELOC_16:
2900 fixP->fx_r_type = BFD_RELOC_RISCV_ADD16;
2901 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB16;
2902 break;
2903
2904 case BFD_RELOC_8:
2905 fixP->fx_r_type = BFD_RELOC_RISCV_ADD8;
2906 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB8;
2907 break;
2908
2909 case BFD_RELOC_RISCV_CFA:
2910 /* Load the byte to get the subtype. */
2911 subtype = bfd_get_8 (NULL, &((fragS *) (fixP->fx_frag->fr_opcode))->fr_literal[fixP->fx_where]);
2912 loc = fixP->fx_frag->fr_fix - (subtype & 7);
2913 switch (subtype)
2914 {
2915 case DW_CFA_advance_loc1:
2916 fixP->fx_where = loc + 1;
2917 fixP->fx_next->fx_where = loc + 1;
2918 fixP->fx_r_type = BFD_RELOC_RISCV_SET8;
2919 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB8;
2920 break;
2921
2922 case DW_CFA_advance_loc2:
2923 fixP->fx_size = 2;
2924 fixP->fx_next->fx_size = 2;
2925 fixP->fx_where = loc + 1;
2926 fixP->fx_next->fx_where = loc + 1;
2927 fixP->fx_r_type = BFD_RELOC_RISCV_SET16;
2928 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB16;
2929 break;
2930
2931 case DW_CFA_advance_loc4:
2932 fixP->fx_size = 4;
2933 fixP->fx_next->fx_size = 4;
2934 fixP->fx_where = loc;
2935 fixP->fx_next->fx_where = loc;
2936 fixP->fx_r_type = BFD_RELOC_RISCV_SET32;
2937 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB32;
2938 break;
2939
2940 default:
2941 if (subtype < 0x80 && (subtype & 0x40))
2942 {
2943 /* DW_CFA_advance_loc */
2944 fixP->fx_frag = (fragS *) fixP->fx_frag->fr_opcode;
2945 fixP->fx_next->fx_frag = fixP->fx_frag;
2946 fixP->fx_r_type = BFD_RELOC_RISCV_SET6;
2947 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB6;
2948 }
2949 else
2950 as_fatal (_("internal error: bad CFA value #%d"), subtype);
2951 break;
2952 }
2953 break;
2954
2955 default:
2956 /* This case is unreachable. */
2957 abort ();
2958 }
2959 }
2960 /* Fall through. */
2961
2962 case BFD_RELOC_RVA:
2963 /* If we are deleting this reloc entry, we must fill in the
2964 value now. This can happen if we have a .word which is not
2965 resolved when it appears but is later defined. */
2966 if (fixP->fx_addsy == NULL)
2967 {
2968 gas_assert (fixP->fx_size <= sizeof (valueT));
2969 md_number_to_chars ((char *) buf, *valP, fixP->fx_size);
2970 fixP->fx_done = 1;
2971 }
2972 break;
2973
2974 case BFD_RELOC_RISCV_JMP:
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_UJTYPE_IMM (delta), buf);
2981 }
2982 break;
2983
2984 case BFD_RELOC_12_PCREL:
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_putl32 (bfd_getl32 (buf) | ENCODE_SBTYPE_IMM (delta), buf);
2991 }
2992 break;
2993
2994 case BFD_RELOC_RISCV_RVC_BRANCH:
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_B_IMM (delta), buf);
3001 }
3002 break;
3003
3004 case BFD_RELOC_RISCV_RVC_JUMP:
3005 if (fixP->fx_addsy)
3006 {
3007 /* Fill in a tentative value to improve objdump readability. */
3008 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
3009 bfd_vma delta = target - md_pcrel_from (fixP);
3010 bfd_putl16 (bfd_getl16 (buf) | ENCODE_RVC_J_IMM (delta), buf);
3011 }
3012 break;
3013
3014 case BFD_RELOC_RISCV_CALL:
3015 case BFD_RELOC_RISCV_CALL_PLT:
3016 relaxable = TRUE;
3017 break;
3018
3019 case BFD_RELOC_RISCV_PCREL_HI20:
3020 case BFD_RELOC_RISCV_PCREL_LO12_S:
3021 case BFD_RELOC_RISCV_PCREL_LO12_I:
3022 relaxable = riscv_opts.relax;
3023 break;
3024
3025 case BFD_RELOC_RISCV_ALIGN:
3026 break;
3027
3028 default:
3029 /* We ignore generic BFD relocations we don't know about. */
3030 if (bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type) != NULL)
3031 as_fatal (_("internal error: bad relocation #%d"), fixP->fx_r_type);
3032 }
3033
3034 if (fixP->fx_subsy != NULL)
3035 as_bad_where (fixP->fx_file, fixP->fx_line,
3036 _("unsupported symbol subtraction"));
3037
3038 /* Add an R_RISCV_RELAX reloc if the reloc is relaxable. */
3039 if (relaxable && fixP->fx_tcbit && fixP->fx_addsy != NULL)
3040 {
3041 fixP->fx_next = xmemdup (fixP, sizeof (*fixP), sizeof (*fixP));
3042 fixP->fx_next->fx_addsy = fixP->fx_next->fx_subsy = NULL;
3043 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_RELAX;
3044 fixP->fx_next->fx_size = 0;
3045 }
3046 }
3047
3048 /* Because the value of .cfi_remember_state may changed after relaxation,
3049 we insert a fix to relocate it again in link-time. */
3050
3051 void
3052 riscv_pre_output_hook (void)
3053 {
3054 const frchainS *frch;
3055 segT s;
3056
3057 /* Save the current segment info. */
3058 segT seg = now_seg;
3059 subsegT subseg = now_subseg;
3060
3061 for (s = stdoutput->sections; s; s = s->next)
3062 for (frch = seg_info (s)->frchainP; frch; frch = frch->frch_next)
3063 {
3064 fragS *frag;
3065
3066 for (frag = frch->frch_root; frag; frag = frag->fr_next)
3067 {
3068 if (frag->fr_type == rs_cfa)
3069 {
3070 expressionS exp;
3071 expressionS *symval;
3072
3073 symval = symbol_get_value_expression (frag->fr_symbol);
3074 exp.X_op = O_subtract;
3075 exp.X_add_symbol = symval->X_add_symbol;
3076 exp.X_add_number = 0;
3077 exp.X_op_symbol = symval->X_op_symbol;
3078
3079 /* We must set the segment before creating a frag after all
3080 frag chains have been chained together. */
3081 subseg_set (s, frch->frch_subseg);
3082
3083 fix_new_exp (frag, (int) frag->fr_offset, 1, &exp, 0,
3084 BFD_RELOC_RISCV_CFA);
3085 }
3086 }
3087 }
3088
3089 /* Restore the original segment info. */
3090 subseg_set (seg, subseg);
3091 }
3092
3093
3094 /* This structure is used to hold a stack of .option values. */
3095
3096 struct riscv_option_stack
3097 {
3098 struct riscv_option_stack *next;
3099 struct riscv_set_options options;
3100 };
3101
3102 static struct riscv_option_stack *riscv_opts_stack;
3103
3104 /* Handle the .option pseudo-op. */
3105
3106 static void
3107 s_riscv_option (int x ATTRIBUTE_UNUSED)
3108 {
3109 char *name = input_line_pointer, ch;
3110
3111 while (!is_end_of_line[(unsigned char) *input_line_pointer])
3112 ++input_line_pointer;
3113 ch = *input_line_pointer;
3114 *input_line_pointer = '\0';
3115
3116 if (strcmp (name, "rvc") == 0)
3117 riscv_set_rvc (TRUE);
3118 else if (strcmp (name, "norvc") == 0)
3119 riscv_set_rvc (FALSE);
3120 else if (strcmp (name, "pic") == 0)
3121 riscv_opts.pic = TRUE;
3122 else if (strcmp (name, "nopic") == 0)
3123 riscv_opts.pic = FALSE;
3124 else if (strcmp (name, "relax") == 0)
3125 riscv_opts.relax = TRUE;
3126 else if (strcmp (name, "norelax") == 0)
3127 riscv_opts.relax = FALSE;
3128 else if (strcmp (name, "csr-check") == 0)
3129 riscv_opts.csr_check = TRUE;
3130 else if (strcmp (name, "no-csr-check") == 0)
3131 riscv_opts.csr_check = FALSE;
3132 else if (strcmp (name, "push") == 0)
3133 {
3134 struct riscv_option_stack *s;
3135
3136 s = (struct riscv_option_stack *) xmalloc (sizeof *s);
3137 s->next = riscv_opts_stack;
3138 s->options = riscv_opts;
3139 riscv_opts_stack = s;
3140 }
3141 else if (strcmp (name, "pop") == 0)
3142 {
3143 struct riscv_option_stack *s;
3144
3145 s = riscv_opts_stack;
3146 if (s == NULL)
3147 as_bad (_(".option pop with no .option push"));
3148 else
3149 {
3150 riscv_opts = s->options;
3151 riscv_opts_stack = s->next;
3152 free (s);
3153 }
3154 }
3155 else
3156 {
3157 as_warn (_("Unrecognized .option directive: %s\n"), name);
3158 }
3159 *input_line_pointer = ch;
3160 demand_empty_rest_of_line ();
3161 }
3162
3163 /* Handle the .dtprelword and .dtpreldword pseudo-ops. They generate
3164 a 32-bit or 64-bit DTP-relative relocation (BYTES says which) for
3165 use in DWARF debug information. */
3166
3167 static void
3168 s_dtprel (int bytes)
3169 {
3170 expressionS ex;
3171 char *p;
3172
3173 expression (&ex);
3174
3175 if (ex.X_op != O_symbol)
3176 {
3177 as_bad (_("Unsupported use of %s"), (bytes == 8
3178 ? ".dtpreldword"
3179 : ".dtprelword"));
3180 ignore_rest_of_line ();
3181 }
3182
3183 p = frag_more (bytes);
3184 md_number_to_chars (p, 0, bytes);
3185 fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE,
3186 (bytes == 8
3187 ? BFD_RELOC_RISCV_TLS_DTPREL64
3188 : BFD_RELOC_RISCV_TLS_DTPREL32));
3189
3190 demand_empty_rest_of_line ();
3191 }
3192
3193 /* Handle the .bss pseudo-op. */
3194
3195 static void
3196 s_bss (int ignore ATTRIBUTE_UNUSED)
3197 {
3198 subseg_set (bss_section, 0);
3199 demand_empty_rest_of_line ();
3200 }
3201
3202 static void
3203 riscv_make_nops (char *buf, bfd_vma bytes)
3204 {
3205 bfd_vma i = 0;
3206
3207 /* RISC-V instructions cannot begin or end on odd addresses, so this case
3208 means we are not within a valid instruction sequence. It is thus safe
3209 to use a zero byte, even though that is not a valid instruction. */
3210 if (bytes % 2 == 1)
3211 buf[i++] = 0;
3212
3213 /* Use at most one 2-byte NOP. */
3214 if ((bytes - i) % 4 == 2)
3215 {
3216 md_number_to_chars (buf + i, RVC_NOP, 2);
3217 i += 2;
3218 }
3219
3220 /* Fill the remainder with 4-byte NOPs. */
3221 for ( ; i < bytes; i += 4)
3222 md_number_to_chars (buf + i, RISCV_NOP, 4);
3223 }
3224
3225 /* Called from md_do_align. Used to create an alignment frag in a
3226 code section by emitting a worst-case NOP sequence that the linker
3227 will later relax to the correct number of NOPs. We can't compute
3228 the correct alignment now because of other linker relaxations. */
3229
3230 bfd_boolean
3231 riscv_frag_align_code (int n)
3232 {
3233 bfd_vma bytes = (bfd_vma) 1 << n;
3234 bfd_vma insn_alignment = riscv_opts.rvc ? 2 : 4;
3235 bfd_vma worst_case_bytes = bytes - insn_alignment;
3236 char *nops;
3237 expressionS ex;
3238
3239 /* If we are moving to a smaller alignment than the instruction size, then no
3240 alignment is required. */
3241 if (bytes <= insn_alignment)
3242 return TRUE;
3243
3244 /* When not relaxing, riscv_handle_align handles code alignment. */
3245 if (!riscv_opts.relax)
3246 return FALSE;
3247
3248 nops = frag_more (worst_case_bytes);
3249
3250 ex.X_op = O_constant;
3251 ex.X_add_number = worst_case_bytes;
3252
3253 riscv_make_nops (nops, worst_case_bytes);
3254
3255 fix_new_exp (frag_now, nops - frag_now->fr_literal, 0,
3256 &ex, FALSE, BFD_RELOC_RISCV_ALIGN);
3257
3258 return TRUE;
3259 }
3260
3261 /* Implement HANDLE_ALIGN. */
3262
3263 void
3264 riscv_handle_align (fragS *fragP)
3265 {
3266 switch (fragP->fr_type)
3267 {
3268 case rs_align_code:
3269 /* When relaxing, riscv_frag_align_code handles code alignment. */
3270 if (!riscv_opts.relax)
3271 {
3272 bfd_signed_vma bytes = (fragP->fr_next->fr_address
3273 - fragP->fr_address - fragP->fr_fix);
3274 /* We have 4 byte uncompressed nops. */
3275 bfd_signed_vma size = 4;
3276 bfd_signed_vma excess = bytes % size;
3277 char *p = fragP->fr_literal + fragP->fr_fix;
3278
3279 if (bytes <= 0)
3280 break;
3281
3282 /* Insert zeros or compressed nops to get 4 byte alignment. */
3283 if (excess)
3284 {
3285 riscv_make_nops (p, excess);
3286 fragP->fr_fix += excess;
3287 p += excess;
3288 }
3289
3290 /* Insert variable number of 4 byte uncompressed nops. */
3291 riscv_make_nops (p, size);
3292 fragP->fr_var = size;
3293 }
3294 break;
3295
3296 default:
3297 break;
3298 }
3299 }
3300
3301 int
3302 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
3303 {
3304 return (fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE));
3305 }
3306
3307 /* Translate internal representation of relocation info to BFD target
3308 format. */
3309
3310 arelent *
3311 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
3312 {
3313 arelent *reloc = (arelent *) xmalloc (sizeof (arelent));
3314
3315 reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
3316 *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
3317 reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
3318 reloc->addend = fixp->fx_addnumber;
3319
3320 reloc->howto = bfd_reloc_type_lookup (stdoutput, fixp->fx_r_type);
3321 if (reloc->howto == NULL)
3322 {
3323 if ((fixp->fx_r_type == BFD_RELOC_16 || fixp->fx_r_type == BFD_RELOC_8)
3324 && fixp->fx_addsy != NULL && fixp->fx_subsy != NULL)
3325 {
3326 /* We don't have R_RISCV_8/16, but for this special case,
3327 we can use R_RISCV_ADD8/16 with R_RISCV_SUB8/16. */
3328 return reloc;
3329 }
3330
3331 as_bad_where (fixp->fx_file, fixp->fx_line,
3332 _("cannot represent %s relocation in object file"),
3333 bfd_get_reloc_code_name (fixp->fx_r_type));
3334 return NULL;
3335 }
3336
3337 return reloc;
3338 }
3339
3340 int
3341 riscv_relax_frag (asection *sec, fragS *fragp, long stretch ATTRIBUTE_UNUSED)
3342 {
3343 if (RELAX_BRANCH_P (fragp->fr_subtype))
3344 {
3345 offsetT old_var = fragp->fr_var;
3346 fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
3347 return fragp->fr_var - old_var;
3348 }
3349
3350 return 0;
3351 }
3352
3353 /* Expand far branches to multi-instruction sequences. */
3354
3355 static void
3356 md_convert_frag_branch (fragS *fragp)
3357 {
3358 bfd_byte *buf;
3359 expressionS exp;
3360 fixS *fixp;
3361 insn_t insn;
3362 int rs1, reloc;
3363
3364 buf = (bfd_byte *)fragp->fr_literal + fragp->fr_fix;
3365
3366 exp.X_op = O_symbol;
3367 exp.X_add_symbol = fragp->fr_symbol;
3368 exp.X_add_number = fragp->fr_offset;
3369
3370 gas_assert (fragp->fr_var == RELAX_BRANCH_LENGTH (fragp->fr_subtype));
3371
3372 if (RELAX_BRANCH_RVC (fragp->fr_subtype))
3373 {
3374 switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
3375 {
3376 case 8:
3377 case 4:
3378 /* Expand the RVC branch into a RISC-V one. */
3379 insn = bfd_getl16 (buf);
3380 rs1 = 8 + ((insn >> OP_SH_CRS1S) & OP_MASK_CRS1S);
3381 if ((insn & MASK_C_J) == MATCH_C_J)
3382 insn = MATCH_JAL;
3383 else if ((insn & MASK_C_JAL) == MATCH_C_JAL)
3384 insn = MATCH_JAL | (X_RA << OP_SH_RD);
3385 else if ((insn & MASK_C_BEQZ) == MATCH_C_BEQZ)
3386 insn = MATCH_BEQ | (rs1 << OP_SH_RS1);
3387 else if ((insn & MASK_C_BNEZ) == MATCH_C_BNEZ)
3388 insn = MATCH_BNE | (rs1 << OP_SH_RS1);
3389 else
3390 abort ();
3391 bfd_putl32 (insn, buf);
3392 break;
3393
3394 case 6:
3395 /* Invert the branch condition. Branch over the jump. */
3396 insn = bfd_getl16 (buf);
3397 insn ^= MATCH_C_BEQZ ^ MATCH_C_BNEZ;
3398 insn |= ENCODE_RVC_B_IMM (6);
3399 bfd_putl16 (insn, buf);
3400 buf += 2;
3401 goto jump;
3402
3403 case 2:
3404 /* Just keep the RVC branch. */
3405 reloc = RELAX_BRANCH_UNCOND (fragp->fr_subtype)
3406 ? BFD_RELOC_RISCV_RVC_JUMP : BFD_RELOC_RISCV_RVC_BRANCH;
3407 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
3408 2, &exp, FALSE, reloc);
3409 buf += 2;
3410 goto done;
3411
3412 default:
3413 abort ();
3414 }
3415 }
3416
3417 switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
3418 {
3419 case 8:
3420 gas_assert (!RELAX_BRANCH_UNCOND (fragp->fr_subtype));
3421
3422 /* Invert the branch condition. Branch over the jump. */
3423 insn = bfd_getl32 (buf);
3424 insn ^= MATCH_BEQ ^ MATCH_BNE;
3425 insn |= ENCODE_SBTYPE_IMM (8);
3426 md_number_to_chars ((char *) buf, insn, 4);
3427 buf += 4;
3428
3429 jump:
3430 /* Jump to the target. */
3431 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
3432 4, &exp, FALSE, BFD_RELOC_RISCV_JMP);
3433 md_number_to_chars ((char *) buf, MATCH_JAL, 4);
3434 buf += 4;
3435 break;
3436
3437 case 4:
3438 reloc = RELAX_BRANCH_UNCOND (fragp->fr_subtype)
3439 ? BFD_RELOC_RISCV_JMP : BFD_RELOC_12_PCREL;
3440 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
3441 4, &exp, FALSE, reloc);
3442 buf += 4;
3443 break;
3444
3445 default:
3446 abort ();
3447 }
3448
3449 done:
3450 fixp->fx_file = fragp->fr_file;
3451 fixp->fx_line = fragp->fr_line;
3452
3453 gas_assert (buf == (bfd_byte *)fragp->fr_literal
3454 + fragp->fr_fix + fragp->fr_var);
3455
3456 fragp->fr_fix += fragp->fr_var;
3457 }
3458
3459 /* Relax a machine dependent frag. This returns the amount by which
3460 the current size of the frag should change. */
3461
3462 void
3463 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec ATTRIBUTE_UNUSED,
3464 fragS *fragp)
3465 {
3466 gas_assert (RELAX_BRANCH_P (fragp->fr_subtype));
3467 md_convert_frag_branch (fragp);
3468 }
3469
3470 void
3471 md_show_usage (FILE *stream)
3472 {
3473 fprintf (stream, _("\
3474 RISC-V options:\n\
3475 -fpic generate position-independent code\n\
3476 -fno-pic don't generate position-independent code (default)\n\
3477 -march=ISA set the RISC-V architecture\n\
3478 -misa-spec=ISAspec set the RISC-V ISA spec (2.2, 20190608, 20191213)\n\
3479 -mpriv-spec=PRIVspec set the RISC-V privilege spec (1.9, 1.9.1, 1.10, 1.11)\n\
3480 -mabi=ABI set the RISC-V ABI\n\
3481 -mrelax enable relax (default)\n\
3482 -mno-relax disable relax\n\
3483 -march-attr generate RISC-V arch attribute\n\
3484 -mno-arch-attr don't generate RISC-V arch attribute\n\
3485 "));
3486 }
3487
3488 /* Standard calling conventions leave the CFA at SP on entry. */
3489 void
3490 riscv_cfi_frame_initial_instructions (void)
3491 {
3492 cfi_add_CFA_def_cfa_register (X_SP);
3493 }
3494
3495 int
3496 tc_riscv_regname_to_dw2regnum (char *regname)
3497 {
3498 int reg;
3499
3500 if ((reg = reg_lookup_internal (regname, RCLASS_GPR)) >= 0)
3501 return reg;
3502
3503 if ((reg = reg_lookup_internal (regname, RCLASS_FPR)) >= 0)
3504 return reg + 32;
3505
3506 /* CSRs are numbered 4096 -> 8191. */
3507 if ((reg = reg_lookup_internal (regname, RCLASS_CSR)) >= 0)
3508 return reg + 4096;
3509
3510 as_bad (_("unknown register `%s'"), regname);
3511 return -1;
3512 }
3513
3514 void
3515 riscv_elf_final_processing (void)
3516 {
3517 elf_elfheader (stdoutput)->e_flags |= elf_flags;
3518 }
3519
3520 /* Parse the .sleb128 and .uleb128 pseudos. Only allow constant expressions,
3521 since these directives break relaxation when used with symbol deltas. */
3522
3523 static void
3524 s_riscv_leb128 (int sign)
3525 {
3526 expressionS exp;
3527 char *save_in = input_line_pointer;
3528
3529 expression (&exp);
3530 if (exp.X_op != O_constant)
3531 as_bad (_("non-constant .%cleb128 is not supported"), sign ? 's' : 'u');
3532 demand_empty_rest_of_line ();
3533
3534 input_line_pointer = save_in;
3535 return s_leb128 (sign);
3536 }
3537
3538 /* Parse the .insn directive. */
3539
3540 static void
3541 s_riscv_insn (int x ATTRIBUTE_UNUSED)
3542 {
3543 char *str = input_line_pointer;
3544 struct riscv_cl_insn insn;
3545 expressionS imm_expr;
3546 bfd_reloc_code_real_type imm_reloc = BFD_RELOC_UNUSED;
3547 char save_c;
3548
3549 while (!is_end_of_line[(unsigned char) *input_line_pointer])
3550 ++input_line_pointer;
3551
3552 save_c = *input_line_pointer;
3553 *input_line_pointer = '\0';
3554
3555 const char *error = riscv_ip (str, &insn, &imm_expr,
3556 &imm_reloc, insn_type_hash);
3557
3558 if (error)
3559 {
3560 as_bad ("%s `%s'", error, str);
3561 }
3562 else
3563 {
3564 gas_assert (insn.insn_mo->pinfo != INSN_MACRO);
3565 append_insn (&insn, &imm_expr, imm_reloc);
3566 }
3567
3568 *input_line_pointer = save_c;
3569 demand_empty_rest_of_line ();
3570 }
3571
3572 /* Update arch and priv attributes. If we don't set the corresponding ELF
3573 attributes, then try to output the default ones. */
3574
3575 static void
3576 riscv_write_out_attrs (void)
3577 {
3578 const char *arch_str, *priv_str, *p;
3579 /* versions[0] is major, versions[1] is minor,
3580 and versions[3] is revision. */
3581 unsigned versions[3] = {0}, number = 0;
3582 unsigned int i;
3583
3584 /* Re-write arch attribute to normalize the arch string. */
3585 arch_str = riscv_arch_str (xlen, &riscv_subsets);
3586 bfd_elf_add_proc_attr_string (stdoutput, Tag_RISCV_arch, arch_str);
3587 xfree ((void *)arch_str);
3588
3589 /* For the file without any instruction, we don't set the default_priv_spec
3590 according to the priv attributes since the md_assemble isn't called.
3591 Call riscv_set_default_priv_spec here for the above case, although
3592 it seems strange. */
3593 if (!start_assemble
3594 && !riscv_set_default_priv_spec (NULL))
3595 return;
3596
3597 /* If we already have set elf priv attributes, then no need to do anything,
3598 assembler will generate them according to what you set. Otherwise, don't
3599 generate or update them when no CSR and priv instructions are used.
3600 Generate the priv attributes according to default_priv_spec, which can be
3601 set by -mpriv-spec and --with-priv-spec, and be updated by the original
3602 priv attribute sets. */
3603 if (!explicit_priv_attr)
3604 return;
3605
3606 /* Re-write priv attributes by default_priv_spec. */
3607 priv_str = riscv_get_priv_spec_name (default_priv_spec);
3608 p = priv_str;
3609 for (i = 0; *p; ++p)
3610 {
3611 if (*p == '.' && i < 3)
3612 {
3613 versions[i++] = number;
3614 number = 0;
3615 }
3616 else if (ISDIGIT (*p))
3617 number = (number * 10) + (*p - '0');
3618 else
3619 {
3620 as_bad (_("internal: bad RISC-V priv spec string (%s)"), priv_str);
3621 return;
3622 }
3623 }
3624 versions[i] = number;
3625
3626 /* Set the priv attributes. */
3627 bfd_elf_add_proc_attr_int (stdoutput, Tag_RISCV_priv_spec, versions[0]);
3628 bfd_elf_add_proc_attr_int (stdoutput, Tag_RISCV_priv_spec_minor, versions[1]);
3629 bfd_elf_add_proc_attr_int (stdoutput, Tag_RISCV_priv_spec_revision, versions[2]);
3630 }
3631
3632 /* Add the default contents for the .riscv.attributes section. If any
3633 ELF attribute or -march-attr options is set, call riscv_write_out_attrs
3634 to update the arch and priv attributes. */
3635
3636 static void
3637 riscv_set_public_attributes (void)
3638 {
3639 if (riscv_opts.arch_attr || explicit_attr)
3640 riscv_write_out_attrs ();
3641 }
3642
3643 /* Called after all assembly has been done. */
3644
3645 void
3646 riscv_md_end (void)
3647 {
3648 riscv_set_public_attributes ();
3649 }
3650
3651 /* Given a symbolic attribute NAME, return the proper integer value.
3652 Returns -1 if the attribute is not known. */
3653
3654 int
3655 riscv_convert_symbolic_attribute (const char *name)
3656 {
3657 static const struct
3658 {
3659 const char * name;
3660 const int tag;
3661 }
3662 attribute_table[] =
3663 {
3664 /* When you modify this table you should
3665 also modify the list in doc/c-riscv.texi. */
3666 #define T(tag) {#tag, Tag_RISCV_##tag}, {"Tag_RISCV_" #tag, Tag_RISCV_##tag}
3667 T(arch),
3668 T(priv_spec),
3669 T(priv_spec_minor),
3670 T(priv_spec_revision),
3671 T(unaligned_access),
3672 T(stack_align),
3673 #undef T
3674 };
3675
3676 unsigned int i;
3677
3678 if (name == NULL)
3679 return -1;
3680
3681 for (i = 0; i < ARRAY_SIZE (attribute_table); i++)
3682 if (strcmp (name, attribute_table[i].name) == 0)
3683 return attribute_table[i].tag;
3684
3685 return -1;
3686 }
3687
3688 /* Parse a .attribute directive. */
3689
3690 static void
3691 s_riscv_attribute (int ignored ATTRIBUTE_UNUSED)
3692 {
3693 int tag = obj_elf_vendor_attribute (OBJ_ATTR_PROC);
3694 unsigned old_xlen;
3695 obj_attribute *attr;
3696
3697 explicit_attr = TRUE;
3698 switch (tag)
3699 {
3700 case Tag_RISCV_arch:
3701 old_xlen = xlen;
3702 attr = elf_known_obj_attributes_proc (stdoutput);
3703 if (!start_assemble)
3704 riscv_set_arch (attr[Tag_RISCV_arch].s);
3705 else
3706 as_fatal (_(".attribute arch must set before any instructions"));
3707
3708 if (old_xlen != xlen)
3709 {
3710 /* We must re-init bfd again if xlen is changed. */
3711 unsigned long mach = xlen == 64 ? bfd_mach_riscv64 : bfd_mach_riscv32;
3712 bfd_find_target (riscv_target_format (), stdoutput);
3713
3714 if (! bfd_set_arch_mach (stdoutput, bfd_arch_riscv, mach))
3715 as_warn (_("Could not set architecture and machine"));
3716 }
3717 break;
3718
3719 case Tag_RISCV_priv_spec:
3720 case Tag_RISCV_priv_spec_minor:
3721 case Tag_RISCV_priv_spec_revision:
3722 if (start_assemble)
3723 as_fatal (_(".attribute priv spec must set before any instructions"));
3724 break;
3725
3726 default:
3727 break;
3728 }
3729 }
3730
3731 /* Pseudo-op table. */
3732
3733 static const pseudo_typeS riscv_pseudo_table[] =
3734 {
3735 /* RISC-V-specific pseudo-ops. */
3736 {"option", s_riscv_option, 0},
3737 {"half", cons, 2},
3738 {"word", cons, 4},
3739 {"dword", cons, 8},
3740 {"dtprelword", s_dtprel, 4},
3741 {"dtpreldword", s_dtprel, 8},
3742 {"bss", s_bss, 0},
3743 {"uleb128", s_riscv_leb128, 0},
3744 {"sleb128", s_riscv_leb128, 1},
3745 {"insn", s_riscv_insn, 0},
3746 {"attribute", s_riscv_attribute, 0},
3747
3748 { NULL, NULL, 0 },
3749 };
3750
3751 void
3752 riscv_pop_insert (void)
3753 {
3754 extern void pop_insert (const pseudo_typeS *);
3755
3756 pop_insert (riscv_pseudo_table);
3757 }