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