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