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