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