1 /* tc-riscv.c -- RISC-V assembler
2 Copyright 2011-2016 Free Software Foundation, Inc.
4 Contributed by Andrew Waterman (andrew@sifive.com).
7 This file is part of GAS.
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)
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.
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/>. */
26 #include "safe-ctype.h"
29 #include "dwarf2dbg.h"
30 #include "dw2gencfi.h"
32 #include "elf/riscv.h"
33 #include "opcode/riscv.h"
37 /* Information about an instruction, including its format, operands
41 /* The opcode's entry in riscv_opcodes. */
42 const struct riscv_opcode *insn_mo;
44 /* The encoded instruction bits. */
47 /* The frag that contains the instruction. */
50 /* The offset into FRAG of the first instruction byte. */
53 /* The relocs associated with the instruction, if any. */
58 #define DEFAULT_ARCH "riscv64"
61 static const char default_arch[] = DEFAULT_ARCH;
63 unsigned xlen = 0; /* width of an x-register */
65 #define LOAD_ADDRESS_INSN (xlen == 64 ? "ld" : "lw")
66 #define ADD32_INSN (xlen == 64 ? "addiw" : "addi")
68 static unsigned elf_flags = 0;
70 /* This is the set of options which the .option pseudo-op may modify. */
72 struct riscv_set_options
74 int pic; /* Generate position-independent code. */
75 int rvc; /* Generate RVC code. */
78 static struct riscv_set_options riscv_opts =
85 riscv_set_rvc (bfd_boolean rvc_value)
88 elf_flags |= EF_RISCV_RVC;
90 riscv_opts.rvc = rvc_value;
97 struct riscv_subset *next;
100 static struct riscv_subset *riscv_subsets;
103 riscv_subset_supports (const char *feature)
105 struct riscv_subset *s;
107 unsigned xlen_required = strtoul (feature, &p, 10);
109 if (xlen_required && xlen != xlen_required)
112 for (s = riscv_subsets; s != NULL; s = s->next)
113 if (strcasecmp (s->name, p) == 0)
120 riscv_add_subset (const char *subset)
122 struct riscv_subset *s = xmalloc (sizeof *s);
124 s->name = xstrdup (subset);
125 s->next = riscv_subsets;
129 /* Set which ISA and extensions are available. Formally, ISA strings must
130 begin with RV32 or RV64, but we allow the prefix to be omitted.
132 FIXME: Version numbers are not supported yet. */
134 riscv_set_arch (const char *p)
136 const char *all_subsets = "IMAFDC";
137 const char *extension = NULL;
141 if (strncasecmp (p, "RV32", 4) == 0)
146 else if (strncasecmp (p, "RV64", 4) == 0)
151 else if (strncasecmp (p, "RV", 2) == 0)
164 for (i = 0; all_subsets[i] != '\0'; i++)
166 const char subset[] = {all_subsets[i], '\0'};
167 riscv_add_subset (subset);
172 as_fatal ("`I' must be the first ISA subset name specified (got %c)",
178 if (TOUPPER(*p) == 'X')
180 char *subset = xstrdup (p), *q = subset;
182 while (*++q != '\0' && *q != '_')
187 as_fatal ("only one eXtension is supported (found %s and %s)",
190 riscv_add_subset (subset);
191 p += strlen (subset);
196 else if ((all_subsets = strchr (all_subsets, *p)) != NULL)
198 const char subset[] = {*p, 0};
199 riscv_add_subset (subset);
200 if (TOUPPER(*p) == 'C')
206 as_fatal ("unsupported ISA subset %c", *p);
211 /* Override -m[no-]rvc setting if C was explicitly listed. */
212 riscv_set_rvc (TRUE);
216 /* Add RVC anyway. -m[no-]rvc toggles its availability. */
217 riscv_add_subset ("C");
221 /* Handle of the OPCODE hash table. */
222 static struct hash_control *op_hash = NULL;
224 /* This array holds the chars that always start a comment. If the
225 pre-processor is disabled, these aren't very useful */
226 const char comment_chars[] = "#";
228 /* This array holds the chars that only start a comment at the beginning of
229 a line. If the line seems to have the form '# 123 filename'
230 .line and .file directives will appear in the pre-processed output */
231 /* Note that input_file.c hand checks for '#' at the beginning of the
232 first line of the input file. This is because the compiler outputs
233 #NO_APP at the beginning of its output. */
234 /* Also note that C style comments are always supported. */
235 const char line_comment_chars[] = "#";
237 /* This array holds machine specific line separator characters. */
238 const char line_separator_chars[] = ";";
240 /* Chars that can be used to separate mant from exp in floating point nums */
241 const char EXP_CHARS[] = "eE";
243 /* Chars that mean this number is a floating point constant */
246 const char FLT_CHARS[] = "rRsSfFdDxXpP";
248 /* Macros for encoding relaxation state for RVC branches and far jumps. */
249 #define RELAX_BRANCH_ENCODE(uncond, rvc, length) \
252 | ((uncond) ? 1 : 0) \
255 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
256 #define RELAX_BRANCH_LENGTH(i) (((i) >> 2) & 0xF)
257 #define RELAX_BRANCH_RVC(i) (((i) & 2) != 0)
258 #define RELAX_BRANCH_UNCOND(i) (((i) & 1) != 0)
260 /* Is the given value a sign-extended 32-bit value? */
261 #define IS_SEXT_32BIT_NUM(x) \
262 (((x) &~ (offsetT) 0x7fffffff) == 0 \
263 || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
265 /* Is the given value a zero-extended 32-bit value? Or a negated one? */
266 #define IS_ZEXT_32BIT_NUM(x) \
267 (((x) &~ (offsetT) 0xffffffff) == 0 \
268 || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
270 /* Change INSN's opcode so that the operand given by FIELD has value VALUE.
271 INSN is a riscv_cl_insn structure and VALUE is evaluated exactly once. */
272 #define INSERT_OPERAND(FIELD, INSN, VALUE) \
273 INSERT_BITS ((INSN).insn_opcode, VALUE, OP_MASK_##FIELD, OP_SH_##FIELD)
275 /* Determine if an instruction matches an opcode. */
276 #define OPCODE_MATCHES(OPCODE, OP) \
277 (((OPCODE) & MASK_##OP) == MATCH_##OP)
279 static char *expr_end;
281 /* The default target format to use. */
284 riscv_target_format (void)
286 return xlen == 64 ? "elf64-littleriscv" : "elf32-littleriscv";
289 /* Return the length of instruction INSN. */
291 static inline unsigned int
292 insn_length (const struct riscv_cl_insn *insn)
294 return riscv_insn_length (insn->insn_opcode);
297 /* Initialise INSN from opcode entry MO. Leave its position unspecified. */
300 create_insn (struct riscv_cl_insn *insn, const struct riscv_opcode *mo)
303 insn->insn_opcode = mo->match;
309 /* Install INSN at the location specified by its "frag" and "where" fields. */
312 install_insn (const struct riscv_cl_insn *insn)
314 char *f = insn->frag->fr_literal + insn->where;
315 md_number_to_chars (f, insn->insn_opcode, insn_length (insn));
318 /* Move INSN to offset WHERE in FRAG. Adjust the fixups accordingly
319 and install the opcode in the new location. */
322 move_insn (struct riscv_cl_insn *insn, fragS *frag, long where)
326 if (insn->fixp != NULL)
328 insn->fixp->fx_frag = frag;
329 insn->fixp->fx_where = where;
334 /* Add INSN to the end of the output. */
337 add_fixed_insn (struct riscv_cl_insn *insn)
339 char *f = frag_more (insn_length (insn));
340 move_insn (insn, frag_now, f - frag_now->fr_literal);
344 add_relaxed_insn (struct riscv_cl_insn *insn, int max_chars, int var,
345 relax_substateT subtype, symbolS *symbol, offsetT offset)
347 frag_grow (max_chars);
348 move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
349 frag_var (rs_machine_dependent, max_chars, var,
350 subtype, symbol, offset, NULL);
353 /* Compute the length of a branch sequence, and adjust the stored length
354 accordingly. If FRAGP is NULL, the worst-case length is returned. */
357 relaxed_branch_length (fragS *fragp, asection *sec, int update)
359 int jump, rvc, length = 8;
364 jump = RELAX_BRANCH_UNCOND (fragp->fr_subtype);
365 rvc = RELAX_BRANCH_RVC (fragp->fr_subtype);
366 length = RELAX_BRANCH_LENGTH (fragp->fr_subtype);
368 /* Assume jumps are in range; the linker will catch any that aren't. */
369 length = jump ? 4 : 8;
371 if (fragp->fr_symbol != NULL
372 && S_IS_DEFINED (fragp->fr_symbol)
373 && sec == S_GET_SEGMENT (fragp->fr_symbol))
375 offsetT val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
376 bfd_vma rvc_range = jump ? RVC_JUMP_REACH : RVC_BRANCH_REACH;
377 val -= fragp->fr_address + fragp->fr_fix;
379 if (rvc && (bfd_vma)(val + rvc_range/2) < rvc_range)
381 else if ((bfd_vma)(val + RISCV_BRANCH_REACH/2) < RISCV_BRANCH_REACH)
383 else if (!jump && rvc)
388 fragp->fr_subtype = RELAX_BRANCH_ENCODE (jump, rvc, length);
407 static struct hash_control *reg_names_hash = NULL;
409 #define ENCODE_REG_HASH(cls, n) \
410 ((void *)(uintptr_t)((n) * RCLASS_MAX + (cls) + 1))
411 #define DECODE_REG_CLASS(hash) (((uintptr_t)(hash) - 1) % RCLASS_MAX)
412 #define DECODE_REG_NUM(hash) (((uintptr_t)(hash) - 1) / RCLASS_MAX)
415 hash_reg_name (enum reg_class class, const char *name, unsigned n)
417 void *hash = ENCODE_REG_HASH (class, n);
418 const char *retval = hash_insert (reg_names_hash, name, hash);
421 as_fatal (_("internal error: can't hash `%s': %s"), name, retval);
425 hash_reg_names (enum reg_class class, const char * const names[], unsigned n)
429 for (i = 0; i < n; i++)
430 hash_reg_name (class, names[i], i);
434 reg_lookup_internal (const char *s, enum reg_class class)
436 struct regname *r = (struct regname *) hash_find (reg_names_hash, s);
438 if (r == NULL || DECODE_REG_CLASS (r) != class)
440 return DECODE_REG_NUM (r);
444 reg_lookup (char **s, enum reg_class class, unsigned int *regnop)
450 /* Find end of name. */
452 if (is_name_beginner (*e))
454 while (is_part_of_name (*e))
457 /* Terminate name. */
461 /* Look for the register. Advance to next token if one was recognized. */
462 if ((reg = reg_lookup_internal (*s, class)) >= 0)
472 arg_lookup (char **s, const char *const *array, size_t size, unsigned *regnop)
474 const char *p = strchr (*s, ',');
475 size_t i, len = p ? (size_t)(p - *s) : strlen (*s);
477 for (i = 0; i < size; i++)
478 if (array[i] != NULL && strncmp (array[i], *s, len) == 0)
488 /* For consistency checking, verify that all bits are specified either
489 by the match/mask part of the instruction definition, or by the
492 validate_riscv_insn (const struct riscv_opcode *opc)
494 const char *p = opc->args;
496 insn_t used_bits = opc->mask;
497 int insn_width = 8 * riscv_insn_length (opc->match);
498 insn_t required_bits = ~0ULL >> (64 - insn_width);
500 if ((used_bits & opc->match) != (opc->match & required_bits))
502 as_bad (_("internal: bad RISC-V opcode (mask error): %s %s"),
503 opc->name, opc->args);
507 #define USE_BITS(mask,shift) (used_bits |= ((insn_t)(mask) << (shift)))
514 case 'a': used_bits |= ENCODE_RVC_J_IMM(-1U); break;
515 case 'c': break; /* RS1, constrained to equal sp */
516 case 'i': used_bits |= ENCODE_RVC_SIMM3(-1U); break;
517 case 'j': used_bits |= ENCODE_RVC_IMM(-1U); break;
518 case 'k': used_bits |= ENCODE_RVC_LW_IMM(-1U); break;
519 case 'l': used_bits |= ENCODE_RVC_LD_IMM(-1U); break;
520 case 'm': used_bits |= ENCODE_RVC_LWSP_IMM(-1U); break;
521 case 'n': used_bits |= ENCODE_RVC_LDSP_IMM(-1U); break;
522 case 'p': used_bits |= ENCODE_RVC_B_IMM(-1U); break;
523 case 's': USE_BITS (OP_MASK_CRS1S, OP_SH_CRS1S); break;
524 case 't': USE_BITS (OP_MASK_CRS2S, OP_SH_CRS2S); break;
525 case 'u': used_bits |= ENCODE_RVC_IMM(-1U); break;
526 case 'v': used_bits |= ENCODE_RVC_IMM(-1U); break;
527 case 'w': break; /* RS1S, constrained to equal RD */
528 case 'x': break; /* RS2S, constrained to equal RD */
529 case 'K': used_bits |= ENCODE_RVC_ADDI4SPN_IMM(-1U); break;
530 case 'L': used_bits |= ENCODE_RVC_ADDI16SP_IMM(-1U); break;
531 case 'M': used_bits |= ENCODE_RVC_SWSP_IMM(-1U); break;
532 case 'N': used_bits |= ENCODE_RVC_SDSP_IMM(-1U); break;
533 case 'U': break; /* RS1, constrained to equal RD */
534 case 'V': USE_BITS (OP_MASK_CRS2, OP_SH_CRS2); break;
535 case '<': used_bits |= ENCODE_RVC_IMM(-1U); break;
536 case '>': used_bits |= ENCODE_RVC_IMM(-1U); break;
537 case 'T': USE_BITS (OP_MASK_CRS2, OP_SH_CRS2); break;
538 case 'D': USE_BITS (OP_MASK_CRS2S, OP_SH_CRS2S); break;
540 as_bad (_("internal: bad RISC-V opcode (unknown operand type `C%c'): %s %s"),
541 c, opc->name, opc->args);
548 case '<': USE_BITS (OP_MASK_SHAMTW, OP_SH_SHAMTW); break;
549 case '>': USE_BITS (OP_MASK_SHAMT, OP_SH_SHAMT); break;
551 case 'D': USE_BITS (OP_MASK_RD, OP_SH_RD); break;
552 case 'Z': USE_BITS (OP_MASK_RS1, OP_SH_RS1); break;
553 case 'E': USE_BITS (OP_MASK_CSR, OP_SH_CSR); break;
555 case 'R': USE_BITS (OP_MASK_RS3, OP_SH_RS3); break;
556 case 'S': USE_BITS (OP_MASK_RS1, OP_SH_RS1); break;
557 case 'U': USE_BITS (OP_MASK_RS1, OP_SH_RS1); /* fallthru */
558 case 'T': USE_BITS (OP_MASK_RS2, OP_SH_RS2); break;
559 case 'd': USE_BITS (OP_MASK_RD, OP_SH_RD); break;
560 case 'm': USE_BITS (OP_MASK_RM, OP_SH_RM); break;
561 case 's': USE_BITS (OP_MASK_RS1, OP_SH_RS1); break;
562 case 't': USE_BITS (OP_MASK_RS2, OP_SH_RS2); break;
563 case 'P': USE_BITS (OP_MASK_PRED, OP_SH_PRED); break;
564 case 'Q': USE_BITS (OP_MASK_SUCC, OP_SH_SUCC); break;
566 case 'j': used_bits |= ENCODE_ITYPE_IMM(-1U); break;
567 case 'a': used_bits |= ENCODE_UJTYPE_IMM(-1U); break;
568 case 'p': used_bits |= ENCODE_SBTYPE_IMM(-1U); break;
569 case 'q': used_bits |= ENCODE_STYPE_IMM(-1U); break;
570 case 'u': used_bits |= ENCODE_UTYPE_IMM(-1U); break;
575 as_bad (_("internal: bad RISC-V opcode "
576 "(unknown operand type `%c'): %s %s"),
577 c, opc->name, opc->args);
581 if (used_bits != required_bits)
583 as_bad (_("internal: bad RISC-V opcode (bits 0x%lx undefined): %s %s"),
584 ~(unsigned long)(used_bits & required_bits),
585 opc->name, opc->args);
591 struct percent_op_match
594 bfd_reloc_code_real_type reloc;
597 /* This function is called once, at assembler startup time. It should set up
598 all the tables, etc. that the MD part of the assembler will need. */
605 if (! bfd_set_arch_mach (stdoutput, bfd_arch_riscv, 0))
606 as_warn (_("Could not set architecture and machine"));
608 op_hash = hash_new ();
610 while (riscv_opcodes[i].name)
612 const char *name = riscv_opcodes[i].name;
613 const char *hash_error =
614 hash_insert (op_hash, name, (void *) &riscv_opcodes[i]);
618 fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
619 riscv_opcodes[i].name, hash_error);
620 /* Probably a memory allocation problem? Give up now. */
621 as_fatal (_("Broken assembler. No assembly attempted."));
626 if (riscv_opcodes[i].pinfo != INSN_MACRO)
628 if (!validate_riscv_insn (&riscv_opcodes[i]))
629 as_fatal (_("Broken assembler. No assembly attempted."));
633 while (riscv_opcodes[i].name && !strcmp (riscv_opcodes[i].name, name));
636 reg_names_hash = hash_new ();
637 hash_reg_names (RCLASS_GPR, riscv_gpr_names_numeric, NGPR);
638 hash_reg_names (RCLASS_GPR, riscv_gpr_names_abi, NGPR);
639 hash_reg_names (RCLASS_FPR, riscv_fpr_names_numeric, NFPR);
640 hash_reg_names (RCLASS_FPR, riscv_fpr_names_abi, NFPR);
642 #define DECLARE_CSR(name, num) hash_reg_name (RCLASS_CSR, #name, num);
643 #include "opcode/riscv-opc.h"
646 /* Set the default alignment for the text section. */
647 record_alignment (text_section, riscv_opts.rvc ? 1 : 2);
650 /* Output an instruction. IP is the instruction information.
651 ADDRESS_EXPR is an operand of the instruction to be used with
655 append_insn (struct riscv_cl_insn *ip, expressionS *address_expr,
656 bfd_reloc_code_real_type reloc_type)
658 dwarf2_emit_insn (0);
660 if (reloc_type != BFD_RELOC_UNUSED)
662 reloc_howto_type *howto;
664 gas_assert(address_expr);
665 if (reloc_type == BFD_RELOC_12_PCREL
666 || reloc_type == BFD_RELOC_RISCV_JMP)
668 int j = reloc_type == BFD_RELOC_RISCV_JMP;
669 int best_case = riscv_insn_length (ip->insn_opcode);
670 unsigned worst_case = relaxed_branch_length (NULL, NULL, 0);
671 add_relaxed_insn (ip, worst_case, best_case,
672 RELAX_BRANCH_ENCODE (j, best_case == 2, worst_case),
673 address_expr->X_add_symbol,
674 address_expr->X_add_number);
677 else if (address_expr->X_op == O_constant)
682 ip->insn_opcode |= address_expr->X_add_number;
685 case BFD_RELOC_RISCV_HI20:
687 insn_t imm = RISCV_CONST_HIGH_PART (address_expr->X_add_number);
688 ip->insn_opcode |= ENCODE_UTYPE_IMM (imm);
692 case BFD_RELOC_RISCV_LO12_S:
693 ip->insn_opcode |= ENCODE_STYPE_IMM (address_expr->X_add_number);
696 case BFD_RELOC_RISCV_LO12_I:
697 ip->insn_opcode |= ENCODE_ITYPE_IMM (address_expr->X_add_number);
705 howto = bfd_reloc_type_lookup (stdoutput, reloc_type);
707 as_bad (_("Unsupported RISC-V relocation number %d"), reloc_type);
709 ip->fixp = fix_new_exp (ip->frag, ip->where,
710 bfd_get_reloc_size (howto),
711 address_expr, FALSE, reloc_type);
719 /* Build an instruction created by a macro expansion. This is passed
720 a pointer to the count of instructions created so far, an
721 expression, the name of the instruction to build, an operand format
722 string, and corresponding arguments. */
725 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
727 const struct riscv_opcode *mo;
728 struct riscv_cl_insn insn;
729 bfd_reloc_code_real_type r;
732 va_start (args, fmt);
734 r = BFD_RELOC_UNUSED;
735 mo = (struct riscv_opcode *) hash_find (op_hash, name);
738 /* Find a non-RVC variant of the instruction. append_insn will compress
740 while (riscv_insn_length (mo->match) < 4)
742 gas_assert (strcmp (name, mo->name) == 0);
744 create_insn (&insn, mo);
750 INSERT_OPERAND (RD, insn, va_arg (args, int));
754 INSERT_OPERAND (RS1, insn, va_arg (args, int));
758 INSERT_OPERAND (RS2, insn, va_arg (args, int));
762 INSERT_OPERAND (SHAMT, insn, va_arg (args, int));
768 gas_assert (ep != NULL);
769 r = va_arg (args, int);
777 as_fatal (_("internal error: invalid macro"));
782 gas_assert (r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
784 append_insn (&insn, ep, r);
787 /* Sign-extend 32-bit mode constants that have bit 31 set and all higher bits
790 normalize_constant_expr (expressionS *ex)
794 if ((ex->X_op == O_constant || ex->X_op == O_symbol)
795 && IS_ZEXT_32BIT_NUM (ex->X_add_number))
796 ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
800 /* Fail if an expression is not a constant. */
803 check_absolute_expr (struct riscv_cl_insn *ip, expressionS *ex)
805 if (ex->X_op == O_big)
806 as_bad (_("unsupported large constant"));
807 else if (ex->X_op != O_constant)
808 as_bad (_("Instruction %s requires absolute expression"),
810 normalize_constant_expr (ex);
814 make_internal_label (void)
816 return (symbolS *) local_symbol_make (FAKE_LABEL_NAME, now_seg,
817 (valueT) frag_now_fix(), frag_now);
820 /* Load an entry from the GOT. */
822 pcrel_access (int destreg, int tempreg, expressionS *ep,
823 const char *lo_insn, const char *lo_pattern,
824 bfd_reloc_code_real_type hi_reloc,
825 bfd_reloc_code_real_type lo_reloc)
829 ep2.X_add_symbol = make_internal_label ();
830 ep2.X_add_number = 0;
832 macro_build (ep, "auipc", "d,u", tempreg, hi_reloc);
833 macro_build (&ep2, lo_insn, lo_pattern, destreg, tempreg, lo_reloc);
837 pcrel_load (int destreg, int tempreg, expressionS *ep, const char *lo_insn,
838 bfd_reloc_code_real_type hi_reloc,
839 bfd_reloc_code_real_type lo_reloc)
841 pcrel_access (destreg, tempreg, ep, lo_insn, "d,s,j", hi_reloc, lo_reloc);
845 pcrel_store (int srcreg, int tempreg, expressionS *ep, const char *lo_insn,
846 bfd_reloc_code_real_type hi_reloc,
847 bfd_reloc_code_real_type lo_reloc)
849 pcrel_access (srcreg, tempreg, ep, lo_insn, "t,s,q", hi_reloc, lo_reloc);
852 /* PC-relative function call using AUIPC/JALR, relaxed to JAL. */
854 riscv_call (int destreg, int tempreg, expressionS *ep,
855 bfd_reloc_code_real_type reloc)
857 macro_build (ep, "auipc", "d,u", tempreg, reloc);
858 macro_build (NULL, "jalr", "d,s", destreg, tempreg);
861 /* Load an integer constant into a register. */
864 load_const (int reg, expressionS *ep)
866 int shift = RISCV_IMM_BITS;
867 expressionS upper = *ep, lower = *ep;
868 lower.X_add_number = (int32_t) ep->X_add_number << (32-shift) >> (32-shift);
869 upper.X_add_number -= lower.X_add_number;
871 if (ep->X_op != O_constant)
873 as_bad (_("unsupported large constant"));
877 if (xlen > 32 && !IS_SEXT_32BIT_NUM(ep->X_add_number))
879 /* Reduce to a signed 32-bit constant using SLLI and ADDI. */
880 while (((upper.X_add_number >> shift) & 1) == 0)
883 upper.X_add_number = (int64_t) upper.X_add_number >> shift;
884 load_const(reg, &upper);
886 macro_build (NULL, "slli", "d,s,>", reg, reg, shift);
887 if (lower.X_add_number != 0)
888 macro_build (&lower, "addi", "d,s,j", reg, reg, BFD_RELOC_RISCV_LO12_I);
892 /* Simply emit LUI and/or ADDI to build a 32-bit signed constant. */
895 if (upper.X_add_number != 0)
897 macro_build (ep, "lui", "d,u", reg, BFD_RELOC_RISCV_HI20);
901 if (lower.X_add_number != 0 || hi_reg == 0)
902 macro_build (ep, ADD32_INSN, "d,s,j", reg, hi_reg,
903 BFD_RELOC_RISCV_LO12_I);
907 /* Expand RISC-V assembly macros into one or more instructions. */
909 macro (struct riscv_cl_insn *ip, expressionS *imm_expr,
910 bfd_reloc_code_real_type *imm_reloc)
912 int rd = (ip->insn_opcode >> OP_SH_RD) & OP_MASK_RD;
913 int rs1 = (ip->insn_opcode >> OP_SH_RS1) & OP_MASK_RS1;
914 int rs2 = (ip->insn_opcode >> OP_SH_RS2) & OP_MASK_RS2;
915 int mask = ip->insn_mo->mask;
920 load_const (rd, imm_expr);
925 /* Load the address of a symbol into a register. */
926 if (!IS_SEXT_32BIT_NUM (imm_expr->X_add_number))
927 as_bad (_("offset too large"));
929 if (imm_expr->X_op == O_constant)
930 load_const (rd, imm_expr);
931 else if (riscv_opts.pic && mask == M_LA) /* Global PIC symbol */
932 pcrel_load (rd, rd, imm_expr, LOAD_ADDRESS_INSN,
933 BFD_RELOC_RISCV_GOT_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
934 else /* Local PIC symbol, or any non-PIC symbol */
935 pcrel_load (rd, rd, imm_expr, "addi",
936 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
940 pcrel_load (rd, rd, imm_expr, "addi",
941 BFD_RELOC_RISCV_TLS_GD_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
945 pcrel_load (rd, rd, imm_expr, LOAD_ADDRESS_INSN,
946 BFD_RELOC_RISCV_TLS_GOT_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
950 pcrel_load (rd, rd, imm_expr, "lb",
951 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
955 pcrel_load (rd, rd, imm_expr, "lbu",
956 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
960 pcrel_load (rd, rd, imm_expr, "lh",
961 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
965 pcrel_load (rd, rd, imm_expr, "lhu",
966 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
970 pcrel_load (rd, rd, imm_expr, "lw",
971 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
975 pcrel_load (rd, rd, imm_expr, "lwu",
976 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
980 pcrel_load (rd, rd, imm_expr, "ld",
981 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
985 pcrel_load (rd, rs1, imm_expr, "flw",
986 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
990 pcrel_load (rd, rs1, imm_expr, "fld",
991 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
995 pcrel_store (rs2, rs1, imm_expr, "sb",
996 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1000 pcrel_store (rs2, rs1, imm_expr, "sh",
1001 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1005 pcrel_store (rs2, rs1, imm_expr, "sw",
1006 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1010 pcrel_store (rs2, rs1, imm_expr, "sd",
1011 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1015 pcrel_store (rs2, rs1, imm_expr, "fsw",
1016 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1020 pcrel_store (rs2, rs1, imm_expr, "fsd",
1021 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1025 riscv_call (rd, rs1, imm_expr, *imm_reloc);
1029 as_bad (_("Macro %s not implemented"), ip->insn_mo->name);
1034 static const struct percent_op_match percent_op_utype[] =
1036 {"%tprel_hi", BFD_RELOC_RISCV_TPREL_HI20},
1037 {"%pcrel_hi", BFD_RELOC_RISCV_PCREL_HI20},
1038 {"%tls_ie_pcrel_hi", BFD_RELOC_RISCV_TLS_GOT_HI20},
1039 {"%tls_gd_pcrel_hi", BFD_RELOC_RISCV_TLS_GD_HI20},
1040 {"%hi", BFD_RELOC_RISCV_HI20},
1044 static const struct percent_op_match percent_op_itype[] =
1046 {"%lo", BFD_RELOC_RISCV_LO12_I},
1047 {"%tprel_lo", BFD_RELOC_RISCV_TPREL_LO12_I},
1048 {"%pcrel_lo", BFD_RELOC_RISCV_PCREL_LO12_I},
1052 static const struct percent_op_match percent_op_stype[] =
1054 {"%lo", BFD_RELOC_RISCV_LO12_S},
1055 {"%tprel_lo", BFD_RELOC_RISCV_TPREL_LO12_S},
1056 {"%pcrel_lo", BFD_RELOC_RISCV_PCREL_LO12_S},
1060 static const struct percent_op_match percent_op_rtype[] =
1062 {"%tprel_add", BFD_RELOC_RISCV_TPREL_ADD},
1066 /* Return true if *STR points to a relocation operator. When returning true,
1067 move *STR over the operator and store its relocation code in *RELOC.
1068 Leave both *STR and *RELOC alone when returning false. */
1071 parse_relocation (char **str, bfd_reloc_code_real_type *reloc,
1072 const struct percent_op_match *percent_op)
1074 for ( ; percent_op->str; percent_op++)
1075 if (strncasecmp (*str, percent_op->str, strlen (percent_op->str)) == 0)
1077 int len = strlen (percent_op->str);
1079 if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
1082 *str += strlen (percent_op->str);
1083 *reloc = percent_op->reloc;
1085 /* Check whether the output BFD supports this relocation.
1086 If not, issue an error and fall back on something safe. */
1087 if (!bfd_reloc_type_lookup (stdoutput, percent_op->reloc))
1089 as_bad ("relocation %s isn't supported by the current ABI",
1091 *reloc = BFD_RELOC_UNUSED;
1099 my_getExpression (expressionS *ep, char *str)
1103 save_in = input_line_pointer;
1104 input_line_pointer = str;
1106 expr_end = input_line_pointer;
1107 input_line_pointer = save_in;
1110 /* Parse string STR as a 16-bit relocatable operand. Store the
1111 expression in *EP and the relocation, if any, in RELOC.
1112 Return the number of relocation operators used (0 or 1).
1114 On exit, EXPR_END points to the first character after the expression. */
1117 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
1118 char *str, const struct percent_op_match *percent_op)
1121 unsigned crux_depth, str_depth, regno;
1124 /* First, check for integer registers. */
1125 if (reg_lookup (&str, RCLASS_GPR, ®no))
1127 ep->X_op = O_register;
1128 ep->X_add_number = regno;
1132 /* Search for the start of the main expression.
1133 End the loop with CRUX pointing to the start
1134 of the main expression and with CRUX_DEPTH containing the number
1135 of open brackets at that point. */
1142 crux_depth = str_depth;
1144 /* Skip over whitespace and brackets, keeping count of the number
1146 while (*str == ' ' || *str == '\t' || *str == '(')
1152 && parse_relocation (&str, reloc, percent_op));
1154 my_getExpression (ep, crux);
1157 /* Match every open bracket. */
1158 while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
1163 as_bad ("unclosed '('");
1170 /* This routine assembles an instruction into its binary format. As a
1171 side effect, it sets the global variable imm_reloc to the type of
1172 relocation to do if one of the operands is an address expression. */
1175 riscv_ip (char *str, struct riscv_cl_insn *ip, expressionS *imm_expr,
1176 bfd_reloc_code_real_type *imm_reloc)
1181 struct riscv_opcode *insn;
1186 const struct percent_op_match *p;
1187 const char *error = "unrecognized opcode";
1189 /* Parse the name of the instruction. Terminate the string if whitespace
1190 is found so that hash_find only sees the name part of the string. */
1191 for (s = str; *s != '\0'; ++s)
1199 insn = (struct riscv_opcode *) hash_find (op_hash, str);
1202 for ( ; insn && insn->name && strcmp (insn->name, str) == 0; insn++)
1204 if (!riscv_subset_supports (insn->subset))
1207 create_insn (ip, insn);
1210 imm_expr->X_op = O_absent;
1211 *imm_reloc = BFD_RELOC_UNUSED;
1212 p = percent_op_itype;
1214 for (args = insn->args;; ++args)
1216 s += strspn (s, " \t");
1219 case '\0': /* End of args. */
1220 if (insn->pinfo != INSN_MACRO)
1222 if (!insn->match_func (insn, ip->insn_opcode))
1224 if (riscv_insn_length (insn->match) == 2 && !riscv_opts.rvc)
1229 /* Successful assembly. */
1236 case 's': /* RS1 x8-x15 */
1237 if (!reg_lookup (&s, RCLASS_GPR, ®no)
1238 || !(regno >= 8 && regno <= 15))
1240 INSERT_OPERAND (CRS1S, *ip, regno % 8);
1242 case 'w': /* RS1 x8-x15, constrained to equal RD x8-x15. */
1243 if (!reg_lookup (&s, RCLASS_GPR, ®no)
1244 || EXTRACT_OPERAND (CRS1S, ip->insn_opcode) + 8 != regno)
1247 case 't': /* RS2 x8-x15 */
1248 if (!reg_lookup (&s, RCLASS_GPR, ®no)
1249 || !(regno >= 8 && regno <= 15))
1251 INSERT_OPERAND (CRS2S, *ip, regno % 8);
1253 case 'x': /* RS2 x8-x15, constrained to equal RD x8-x15. */
1254 if (!reg_lookup (&s, RCLASS_GPR, ®no)
1255 || EXTRACT_OPERAND (CRS2S, ip->insn_opcode) + 8 != regno)
1258 case 'U': /* RS1, constrained to equal RD. */
1259 if (!reg_lookup (&s, RCLASS_GPR, ®no)
1260 || EXTRACT_OPERAND (RD, ip->insn_opcode) != regno)
1264 if (!reg_lookup (&s, RCLASS_GPR, ®no))
1266 INSERT_OPERAND (CRS2, *ip, regno);
1268 case 'c': /* RS1, constrained to equal sp. */
1269 if (!reg_lookup (&s, RCLASS_GPR, ®no)
1274 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1275 || imm_expr->X_op != O_constant
1276 || imm_expr->X_add_number <= 0
1277 || imm_expr->X_add_number >= 64)
1279 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1282 imm_expr->X_op = O_absent;
1285 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1286 || imm_expr->X_op != O_constant
1287 || !VALID_RVC_IMM (imm_expr->X_add_number)
1288 || imm_expr->X_add_number <= 0
1289 || imm_expr->X_add_number >= 32)
1291 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1294 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1295 || imm_expr->X_op != O_constant
1296 || imm_expr->X_add_number == 0
1297 || !VALID_RVC_SIMM3 (imm_expr->X_add_number))
1299 ip->insn_opcode |= ENCODE_RVC_SIMM3 (imm_expr->X_add_number);
1302 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1303 || imm_expr->X_op != O_constant
1304 || imm_expr->X_add_number == 0
1305 || !VALID_RVC_IMM (imm_expr->X_add_number))
1307 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1310 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1311 || imm_expr->X_op != O_constant
1312 || !VALID_RVC_LW_IMM (imm_expr->X_add_number))
1314 ip->insn_opcode |= ENCODE_RVC_LW_IMM (imm_expr->X_add_number);
1317 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1318 || imm_expr->X_op != O_constant
1319 || !VALID_RVC_LD_IMM (imm_expr->X_add_number))
1321 ip->insn_opcode |= ENCODE_RVC_LD_IMM (imm_expr->X_add_number);
1324 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1325 || imm_expr->X_op != O_constant
1326 || !VALID_RVC_LWSP_IMM (imm_expr->X_add_number))
1329 ENCODE_RVC_LWSP_IMM (imm_expr->X_add_number);
1332 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1333 || imm_expr->X_op != O_constant
1334 || !VALID_RVC_LDSP_IMM (imm_expr->X_add_number))
1337 ENCODE_RVC_LDSP_IMM (imm_expr->X_add_number);
1340 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1341 || imm_expr->X_op != O_constant
1342 || !VALID_RVC_ADDI4SPN_IMM (imm_expr->X_add_number)
1343 || imm_expr->X_add_number == 0)
1346 ENCODE_RVC_ADDI4SPN_IMM (imm_expr->X_add_number);
1349 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1350 || imm_expr->X_op != O_constant
1351 || !VALID_RVC_ADDI16SP_IMM (imm_expr->X_add_number)
1352 || imm_expr->X_add_number == 0)
1355 ENCODE_RVC_ADDI16SP_IMM (imm_expr->X_add_number);
1358 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1359 || imm_expr->X_op != O_constant
1360 || !VALID_RVC_SWSP_IMM (imm_expr->X_add_number))
1363 ENCODE_RVC_SWSP_IMM (imm_expr->X_add_number);
1366 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1367 || imm_expr->X_op != O_constant
1368 || !VALID_RVC_SDSP_IMM (imm_expr->X_add_number))
1371 ENCODE_RVC_SDSP_IMM (imm_expr->X_add_number);
1374 p = percent_op_utype;
1375 if (my_getSmallExpression (imm_expr, imm_reloc, s, p))
1378 if (imm_expr->X_op != O_constant
1379 || imm_expr->X_add_number <= 0
1380 || imm_expr->X_add_number >= RISCV_BIGIMM_REACH
1381 || (imm_expr->X_add_number >= RISCV_RVC_IMM_REACH / 2
1382 && (imm_expr->X_add_number <
1383 RISCV_BIGIMM_REACH - RISCV_RVC_IMM_REACH / 2)))
1385 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1388 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1389 || (imm_expr->X_add_number & (RISCV_IMM_REACH - 1))
1390 || ((int32_t)imm_expr->X_add_number
1391 != imm_expr->X_add_number))
1393 imm_expr->X_add_number =
1394 ((uint32_t) imm_expr->X_add_number) >> RISCV_IMM_BITS;
1400 case 'D': /* Floating-point RS2 x8-x15. */
1401 if (!reg_lookup (&s, RCLASS_FPR, ®no)
1402 || !(regno >= 8 && regno <= 15))
1404 INSERT_OPERAND (CRS2S, *ip, regno % 8);
1406 case 'T': /* Floating-point RS2. */
1407 if (!reg_lookup (&s, RCLASS_FPR, ®no))
1409 INSERT_OPERAND (CRS2, *ip, regno);
1412 as_bad (_("bad RVC field specifier 'C%c'\n"), *args);
1431 case '<': /* Shift amount, 0 - 31. */
1432 my_getExpression (imm_expr, s);
1433 check_absolute_expr (ip, imm_expr);
1434 if ((unsigned long) imm_expr->X_add_number > 31)
1435 as_warn (_("Improper shift amount (%lu)"),
1436 (unsigned long) imm_expr->X_add_number);
1437 INSERT_OPERAND (SHAMTW, *ip, imm_expr->X_add_number);
1438 imm_expr->X_op = O_absent;
1442 case '>': /* Shift amount, 0 - (XLEN-1). */
1443 my_getExpression (imm_expr, s);
1444 check_absolute_expr (ip, imm_expr);
1445 if ((unsigned long) imm_expr->X_add_number >= xlen)
1446 as_warn (_("Improper shift amount (%lu)"),
1447 (unsigned long) imm_expr->X_add_number);
1448 INSERT_OPERAND (SHAMT, *ip, imm_expr->X_add_number);
1449 imm_expr->X_op = O_absent;
1453 case 'Z': /* CSRRxI immediate. */
1454 my_getExpression (imm_expr, s);
1455 check_absolute_expr (ip, imm_expr);
1456 if ((unsigned long) imm_expr->X_add_number > 31)
1457 as_warn (_("Improper CSRxI immediate (%lu)"),
1458 (unsigned long) imm_expr->X_add_number);
1459 INSERT_OPERAND (RS1, *ip, imm_expr->X_add_number);
1460 imm_expr->X_op = O_absent;
1464 case 'E': /* Control register. */
1465 if (reg_lookup (&s, RCLASS_CSR, ®no))
1466 INSERT_OPERAND (CSR, *ip, regno);
1469 my_getExpression (imm_expr, s);
1470 check_absolute_expr (ip, imm_expr);
1471 if ((unsigned long) imm_expr->X_add_number > 0xfff)
1472 as_warn(_("Improper CSR address (%lu)"),
1473 (unsigned long) imm_expr->X_add_number);
1474 INSERT_OPERAND (CSR, *ip, imm_expr->X_add_number);
1475 imm_expr->X_op = O_absent;
1480 case 'm': /* Rounding mode. */
1481 if (arg_lookup (&s, riscv_rm, ARRAY_SIZE (riscv_rm), ®no))
1483 INSERT_OPERAND (RM, *ip, regno);
1489 case 'Q': /* Fence predecessor/successor. */
1490 if (arg_lookup (&s, riscv_pred_succ, ARRAY_SIZE (riscv_pred_succ),
1494 INSERT_OPERAND (PRED, *ip, regno);
1496 INSERT_OPERAND (SUCC, *ip, regno);
1501 case 'd': /* Destination register. */
1502 case 's': /* Source register. */
1503 case 't': /* Target register. */
1504 if (reg_lookup (&s, RCLASS_GPR, ®no))
1510 /* Now that we have assembled one operand, we use the args
1511 string to figure out where it goes in the instruction. */
1515 INSERT_OPERAND (RS1, *ip, regno);
1518 INSERT_OPERAND (RD, *ip, regno);
1521 INSERT_OPERAND (RS2, *ip, regno);
1528 case 'D': /* Floating point rd. */
1529 case 'S': /* Floating point rs1. */
1530 case 'T': /* Floating point rs2. */
1531 case 'U': /* Floating point rs1 and rs2. */
1532 case 'R': /* Floating point rs3. */
1533 if (reg_lookup (&s, RCLASS_FPR, ®no))
1541 INSERT_OPERAND (RD, *ip, regno);
1544 INSERT_OPERAND (RS1, *ip, regno);
1547 INSERT_OPERAND (RS1, *ip, regno);
1550 INSERT_OPERAND (RS2, *ip, regno);
1553 INSERT_OPERAND (RS3, *ip, regno);
1562 my_getExpression (imm_expr, s);
1563 if (imm_expr->X_op != O_big
1564 && imm_expr->X_op != O_constant)
1566 normalize_constant_expr (imm_expr);
1571 my_getExpression (imm_expr, s);
1572 normalize_constant_expr (imm_expr);
1573 /* The 'A' format specifier must be a symbol. */
1574 if (imm_expr->X_op != O_symbol)
1576 *imm_reloc = BFD_RELOC_32;
1580 case 'j': /* Sign-extended immediate. */
1581 *imm_reloc = BFD_RELOC_RISCV_LO12_I;
1582 p = percent_op_itype;
1584 case 'q': /* Store displacement. */
1585 p = percent_op_stype;
1586 *imm_reloc = BFD_RELOC_RISCV_LO12_S;
1588 case 'o': /* Load displacement. */
1589 p = percent_op_itype;
1590 *imm_reloc = BFD_RELOC_RISCV_LO12_I;
1592 case '0': /* AMO "displacement," which must be zero. */
1593 p = percent_op_rtype;
1594 *imm_reloc = BFD_RELOC_UNUSED;
1596 /* Check whether there is only a single bracketed expression
1597 left. If so, it must be the base register and the
1598 constant must be zero. */
1599 imm_expr->X_op = O_constant;
1600 imm_expr->X_add_number = 0;
1601 if (*s == '(' && strchr (s + 1, '(') == 0)
1604 /* If this value won't fit into a 16 bit offset, then go
1605 find a macro that will generate the 32 bit offset
1607 if (!my_getSmallExpression (imm_expr, imm_reloc, s, p))
1609 normalize_constant_expr (imm_expr);
1610 if (imm_expr->X_op != O_constant
1611 || (*args == '0' && imm_expr->X_add_number != 0)
1612 || imm_expr->X_add_number >= (signed)RISCV_IMM_REACH/2
1613 || imm_expr->X_add_number < -(signed)RISCV_IMM_REACH/2)
1620 case 'p': /* PC-relative offset. */
1622 *imm_reloc = BFD_RELOC_12_PCREL;
1623 my_getExpression (imm_expr, s);
1627 case 'u': /* Upper 20 bits. */
1628 p = percent_op_utype;
1629 if (!my_getSmallExpression (imm_expr, imm_reloc, s, p)
1630 && imm_expr->X_op == O_constant)
1632 if (imm_expr->X_add_number < 0
1633 || imm_expr->X_add_number >= (signed)RISCV_BIGIMM_REACH)
1634 as_bad (_("lui expression not in range 0..1048575"));
1636 *imm_reloc = BFD_RELOC_RISCV_HI20;
1637 imm_expr->X_add_number <<= RISCV_IMM_BITS;
1642 case 'a': /* 20-bit PC-relative offset. */
1644 my_getExpression (imm_expr, s);
1646 *imm_reloc = BFD_RELOC_RISCV_JMP;
1650 my_getExpression (imm_expr, s);
1652 if (strcmp (s, "@plt") == 0)
1654 *imm_reloc = BFD_RELOC_RISCV_CALL_PLT;
1658 *imm_reloc = BFD_RELOC_RISCV_CALL;
1662 as_fatal (_("internal error: bad argument type %c"), *args);
1667 error = _("illegal operands");
1671 /* Restore the character we might have clobbered above. */
1673 *(argsStart - 1) = save_c;
1679 md_assemble (char *str)
1681 struct riscv_cl_insn insn;
1682 expressionS imm_expr;
1683 bfd_reloc_code_real_type imm_reloc = BFD_RELOC_UNUSED;
1685 const char *error = riscv_ip (str, &insn, &imm_expr, &imm_reloc);
1689 as_bad ("%s `%s'", error, str);
1693 if (insn.insn_mo->pinfo == INSN_MACRO)
1694 macro (&insn, &imm_expr, &imm_reloc);
1696 append_insn (&insn, &imm_expr, imm_reloc);
1700 md_atof (int type, char *litP, int *sizeP)
1702 return ieee_md_atof (type, litP, sizeP, TARGET_BYTES_BIG_ENDIAN);
1706 md_number_to_chars (char *buf, valueT val, int n)
1708 number_to_chars_littleendian (buf, val, n);
1711 const char *md_shortopts = "O::g::G:";
1715 OPTION_M32 = OPTION_MD_BASE,
1727 struct option md_longopts[] =
1729 {"m32", no_argument, NULL, OPTION_M32},
1730 {"m64", no_argument, NULL, OPTION_M64},
1731 {"march", required_argument, NULL, OPTION_MARCH},
1732 {"fPIC", no_argument, NULL, OPTION_PIC},
1733 {"fpic", no_argument, NULL, OPTION_PIC},
1734 {"fno-pic", no_argument, NULL, OPTION_NO_PIC},
1735 {"mrvc", no_argument, NULL, OPTION_MRVC},
1736 {"mno-rvc", no_argument, NULL, OPTION_MNO_RVC},
1737 {"msoft-float", no_argument, NULL, OPTION_MSOFT_FLOAT},
1738 {"mhard-float", no_argument, NULL, OPTION_MHARD_FLOAT},
1740 {NULL, no_argument, NULL, 0}
1742 size_t md_longopts_size = sizeof (md_longopts);
1750 static enum float_mode float_mode = FLOAT_MODE_DEFAULT;
1753 md_parse_option (int c, const char *arg)
1758 riscv_set_rvc (TRUE);
1761 case OPTION_MNO_RVC:
1762 riscv_set_rvc (FALSE);
1765 case OPTION_MSOFT_FLOAT:
1766 float_mode = FLOAT_MODE_SOFT;
1769 case OPTION_MHARD_FLOAT:
1770 float_mode = FLOAT_MODE_HARD;
1782 riscv_set_arch (arg);
1786 riscv_opts.pic = FALSE;
1790 riscv_opts.pic = TRUE;
1801 riscv_after_parse_args (void)
1803 if (riscv_subsets == NULL)
1804 riscv_set_arch ("RVIMAFD");
1808 if (strcmp (default_arch, "riscv32") == 0)
1810 else if (strcmp (default_arch, "riscv64") == 0)
1813 as_bad ("unknown default architecture `%s'", default_arch);
1818 md_pcrel_from (fixS *fixP)
1820 return fixP->fx_where + fixP->fx_frag->fr_address;
1823 /* Apply a fixup to the object file. */
1826 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
1828 bfd_byte *buf = (bfd_byte *) (fixP->fx_frag->fr_literal + fixP->fx_where);
1830 /* Remember value for tc_gen_reloc. */
1831 fixP->fx_addnumber = *valP;
1833 switch (fixP->fx_r_type)
1835 case BFD_RELOC_RISCV_TLS_GOT_HI20:
1836 case BFD_RELOC_RISCV_TLS_GD_HI20:
1837 case BFD_RELOC_RISCV_TLS_DTPREL32:
1838 case BFD_RELOC_RISCV_TLS_DTPREL64:
1839 case BFD_RELOC_RISCV_TPREL_HI20:
1840 case BFD_RELOC_RISCV_TPREL_LO12_I:
1841 case BFD_RELOC_RISCV_TPREL_LO12_S:
1842 case BFD_RELOC_RISCV_TPREL_ADD:
1843 S_SET_THREAD_LOCAL (fixP->fx_addsy);
1846 case BFD_RELOC_RISCV_GOT_HI20:
1847 case BFD_RELOC_RISCV_PCREL_HI20:
1848 case BFD_RELOC_RISCV_HI20:
1849 case BFD_RELOC_RISCV_LO12_I:
1850 case BFD_RELOC_RISCV_LO12_S:
1851 case BFD_RELOC_RISCV_ADD8:
1852 case BFD_RELOC_RISCV_ADD16:
1853 case BFD_RELOC_RISCV_ADD32:
1854 case BFD_RELOC_RISCV_ADD64:
1855 case BFD_RELOC_RISCV_SUB8:
1856 case BFD_RELOC_RISCV_SUB16:
1857 case BFD_RELOC_RISCV_SUB32:
1858 case BFD_RELOC_RISCV_SUB64:
1859 gas_assert (fixP->fx_addsy != NULL);
1860 /* Nothing needed to do. The value comes from the reloc entry. */
1867 if (fixP->fx_addsy && fixP->fx_subsy)
1869 fixP->fx_next = xmemdup (fixP, sizeof (*fixP), sizeof (*fixP));
1870 fixP->fx_next->fx_addsy = fixP->fx_subsy;
1871 fixP->fx_next->fx_subsy = NULL;
1872 fixP->fx_next->fx_offset = 0;
1873 fixP->fx_subsy = NULL;
1875 switch (fixP->fx_r_type)
1878 fixP->fx_r_type = BFD_RELOC_RISCV_ADD64;
1879 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB64;
1883 fixP->fx_r_type = BFD_RELOC_RISCV_ADD32;
1884 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB32;
1888 fixP->fx_r_type = BFD_RELOC_RISCV_ADD16;
1889 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB16;
1893 fixP->fx_r_type = BFD_RELOC_RISCV_ADD8;
1894 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB8;
1897 /* This case is unreachable. */
1904 /* If we are deleting this reloc entry, we must fill in the
1905 value now. This can happen if we have a .word which is not
1906 resolved when it appears but is later defined. */
1907 if (fixP->fx_addsy == NULL)
1909 gas_assert (fixP->fx_size <= sizeof (valueT));
1910 md_number_to_chars ((char *) buf, *valP, fixP->fx_size);
1915 case BFD_RELOC_RISCV_JMP:
1918 /* Fill in a tentative value to improve objdump readability. */
1919 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
1920 bfd_vma delta = target - md_pcrel_from (fixP);
1921 bfd_putl32 (bfd_getl32 (buf) | ENCODE_UJTYPE_IMM (delta), buf);
1925 case BFD_RELOC_12_PCREL:
1928 /* Fill in a tentative value to improve objdump readability. */
1929 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
1930 bfd_vma delta = target - md_pcrel_from (fixP);
1931 bfd_putl32 (bfd_getl32 (buf) | ENCODE_SBTYPE_IMM (delta), buf);
1935 case BFD_RELOC_RISCV_RVC_BRANCH:
1938 /* Fill in a tentative value to improve objdump readability. */
1939 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
1940 bfd_vma delta = target - md_pcrel_from (fixP);
1941 bfd_putl16 (bfd_getl16 (buf) | ENCODE_RVC_B_IMM (delta), buf);
1945 case BFD_RELOC_RISCV_RVC_JUMP:
1948 /* Fill in a tentative value to improve objdump readability. */
1949 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
1950 bfd_vma delta = target - md_pcrel_from (fixP);
1951 bfd_putl16 (bfd_getl16 (buf) | ENCODE_RVC_J_IMM (delta), buf);
1955 case BFD_RELOC_RISCV_PCREL_LO12_S:
1956 case BFD_RELOC_RISCV_PCREL_LO12_I:
1957 case BFD_RELOC_RISCV_CALL:
1958 case BFD_RELOC_RISCV_CALL_PLT:
1959 case BFD_RELOC_RISCV_ALIGN:
1963 /* We ignore generic BFD relocations we don't know about. */
1964 if (bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type) != NULL)
1965 as_fatal (_("internal error: bad relocation #%d"), fixP->fx_r_type);
1969 /* This structure is used to hold a stack of .option values. */
1971 struct riscv_option_stack
1973 struct riscv_option_stack *next;
1974 struct riscv_set_options options;
1977 static struct riscv_option_stack *riscv_opts_stack;
1979 /* Handle the .option pseudo-op. */
1982 s_riscv_option (int x ATTRIBUTE_UNUSED)
1984 char *name = input_line_pointer, ch;
1986 while (!is_end_of_line[(unsigned char) *input_line_pointer])
1987 ++input_line_pointer;
1988 ch = *input_line_pointer;
1989 *input_line_pointer = '\0';
1991 if (strcmp (name, "rvc") == 0)
1992 riscv_set_rvc (TRUE);
1993 else if (strcmp (name, "norvc") == 0)
1994 riscv_set_rvc (FALSE);
1995 else if (strcmp (name, "pic") == 0)
1996 riscv_opts.pic = TRUE;
1997 else if (strcmp (name, "nopic") == 0)
1998 riscv_opts.pic = FALSE;
1999 else if (strcmp (name, "soft-float") == 0)
2000 float_mode = FLOAT_MODE_SOFT;
2001 else if (strcmp (name, "hard-float") == 0)
2002 float_mode = FLOAT_MODE_HARD;
2003 else if (strcmp (name, "push") == 0)
2005 struct riscv_option_stack *s;
2007 s = (struct riscv_option_stack *) xmalloc (sizeof *s);
2008 s->next = riscv_opts_stack;
2009 s->options = riscv_opts;
2010 riscv_opts_stack = s;
2012 else if (strcmp (name, "pop") == 0)
2014 struct riscv_option_stack *s;
2016 s = riscv_opts_stack;
2018 as_bad (_(".option pop with no .option push"));
2021 riscv_opts = s->options;
2022 riscv_opts_stack = s->next;
2028 as_warn (_("Unrecognized .option directive: %s\n"), name);
2030 *input_line_pointer = ch;
2031 demand_empty_rest_of_line ();
2034 /* Handle the .dtprelword and .dtpreldword pseudo-ops. They generate
2035 a 32-bit or 64-bit DTP-relative relocation (BYTES says which) for
2036 use in DWARF debug information. */
2039 s_dtprel (int bytes)
2046 if (ex.X_op != O_symbol)
2048 as_bad (_("Unsupported use of %s"), (bytes == 8
2051 ignore_rest_of_line ();
2054 p = frag_more (bytes);
2055 md_number_to_chars (p, 0, bytes);
2056 fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE,
2058 ? BFD_RELOC_RISCV_TLS_DTPREL64
2059 : BFD_RELOC_RISCV_TLS_DTPREL32));
2061 demand_empty_rest_of_line ();
2064 /* Handle the .bss pseudo-op. */
2067 s_bss (int ignore ATTRIBUTE_UNUSED)
2069 subseg_set (bss_section, 0);
2070 demand_empty_rest_of_line ();
2073 /* Align to a given power of two. */
2076 s_align (int bytes_p)
2078 int fill_value = 0, fill_value_specified = 0;
2079 int min_text_alignment = riscv_opts.rvc ? 2 : 4;
2080 int alignment = get_absolute_expression(), bytes;
2085 if (bytes < 1 || (bytes & (bytes-1)) != 0)
2086 as_bad (_("alignment not a power of 2: %d"), bytes);
2087 for (alignment = 0; bytes > 1; bytes >>= 1)
2091 bytes = 1 << alignment;
2093 if (alignment < 0 || alignment > 31)
2094 as_bad (_("unsatisfiable alignment: %d"), alignment);
2096 if (*input_line_pointer == ',')
2098 ++input_line_pointer;
2099 fill_value = get_absolute_expression ();
2100 fill_value_specified = 1;
2103 if (!fill_value_specified
2104 && subseg_text_p (now_seg)
2105 && bytes > min_text_alignment)
2107 /* Emit the worst-case NOP string. The linker will delete any
2108 unnecessary NOPs. This allows us to support code alignment
2109 in spite of linker relaxations. */
2110 bfd_vma i, worst_case_bytes = bytes - min_text_alignment;
2111 char *nops = frag_more (worst_case_bytes);
2112 for (i = 0; i < worst_case_bytes - 2; i += 4)
2113 md_number_to_chars (nops + i, RISCV_NOP, 4);
2114 if (i < worst_case_bytes)
2115 md_number_to_chars (nops + i, RVC_NOP, 2);
2118 ex.X_op = O_constant;
2119 ex.X_add_number = worst_case_bytes;
2121 fix_new_exp (frag_now, nops - frag_now->fr_literal, 0,
2122 &ex, FALSE, BFD_RELOC_RISCV_ALIGN);
2125 frag_align (alignment, fill_value, 0);
2127 record_alignment (now_seg, alignment);
2129 demand_empty_rest_of_line ();
2133 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
2135 return (fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE));
2138 /* Translate internal representation of relocation info to BFD target
2142 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
2144 arelent *reloc = (arelent *) xmalloc (sizeof (arelent));
2146 reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
2147 *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
2148 reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
2149 reloc->addend = fixp->fx_addnumber;
2151 reloc->howto = bfd_reloc_type_lookup (stdoutput, fixp->fx_r_type);
2152 if (reloc->howto == NULL)
2154 if ((fixp->fx_r_type == BFD_RELOC_16 || fixp->fx_r_type == BFD_RELOC_8)
2155 && fixp->fx_addsy != NULL && fixp->fx_subsy != NULL)
2157 /* We don't have R_RISCV_8/16, but for this special case,
2158 we can use R_RISCV_ADD8/16 with R_RISCV_SUB8/16. */
2162 as_bad_where (fixp->fx_file, fixp->fx_line,
2163 _("cannot represent %s relocation in object file"),
2164 bfd_get_reloc_code_name (fixp->fx_r_type));
2172 riscv_relax_frag (asection *sec, fragS *fragp, long stretch ATTRIBUTE_UNUSED)
2174 if (RELAX_BRANCH_P (fragp->fr_subtype))
2176 offsetT old_var = fragp->fr_var;
2177 fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
2178 return fragp->fr_var - old_var;
2184 /* Expand far branches to multi-instruction sequences. */
2187 md_convert_frag_branch (fragS *fragp)
2195 buf = (bfd_byte *)fragp->fr_literal + fragp->fr_fix;
2197 exp.X_op = O_symbol;
2198 exp.X_add_symbol = fragp->fr_symbol;
2199 exp.X_add_number = fragp->fr_offset;
2201 gas_assert (fragp->fr_var == RELAX_BRANCH_LENGTH (fragp->fr_subtype));
2203 if (RELAX_BRANCH_RVC (fragp->fr_subtype))
2205 switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
2209 /* Expand the RVC branch into a RISC-V one. */
2210 insn = bfd_getl16 (buf);
2211 rs1 = 8 + ((insn >> OP_SH_CRS1S) & OP_MASK_CRS1S);
2212 if ((insn & MASK_C_J) == MATCH_C_J)
2214 else if ((insn & MASK_C_JAL) == MATCH_C_JAL)
2215 insn = MATCH_JAL | (X_RA << OP_SH_RD);
2216 else if ((insn & MASK_C_BEQZ) == MATCH_C_BEQZ)
2217 insn = MATCH_BEQ | (rs1 << OP_SH_RS1);
2218 else if ((insn & MASK_C_BNEZ) == MATCH_C_BNEZ)
2219 insn = MATCH_BNE | (rs1 << OP_SH_RS1);
2222 bfd_putl32 (insn, buf);
2226 /* Invert the branch condition. Branch over the jump. */
2227 insn = bfd_getl16 (buf);
2228 insn ^= MATCH_C_BEQZ ^ MATCH_C_BNEZ;
2229 insn |= ENCODE_RVC_B_IMM (6);
2230 bfd_putl16 (insn, buf);
2235 /* Just keep the RVC branch. */
2236 reloc = RELAX_BRANCH_UNCOND (fragp->fr_subtype)
2237 ? BFD_RELOC_RISCV_RVC_JUMP : BFD_RELOC_RISCV_RVC_BRANCH;
2238 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
2239 2, &exp, FALSE, reloc);
2248 switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
2251 gas_assert (!RELAX_BRANCH_UNCOND (fragp->fr_subtype));
2253 /* Invert the branch condition. Branch over the jump. */
2254 insn = bfd_getl32 (buf);
2255 insn ^= MATCH_BEQ ^ MATCH_BNE;
2256 insn |= ENCODE_SBTYPE_IMM (8);
2257 md_number_to_chars ((char *) buf, insn, 4);
2261 /* Jump to the target. */
2262 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
2263 4, &exp, FALSE, BFD_RELOC_RISCV_JMP);
2264 md_number_to_chars ((char *) buf, MATCH_JAL, 4);
2269 reloc = RELAX_BRANCH_UNCOND (fragp->fr_subtype)
2270 ? BFD_RELOC_RISCV_JMP : BFD_RELOC_12_PCREL;
2271 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
2272 4, &exp, FALSE, reloc);
2281 fixp->fx_file = fragp->fr_file;
2282 fixp->fx_line = fragp->fr_line;
2284 gas_assert (buf == (bfd_byte *)fragp->fr_literal
2285 + fragp->fr_fix + fragp->fr_var);
2287 fragp->fr_fix += fragp->fr_var;
2290 /* Relax a machine dependent frag. This returns the amount by which
2291 the current size of the frag should change. */
2294 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec ATTRIBUTE_UNUSED,
2297 gas_assert (RELAX_BRANCH_P (fragp->fr_subtype));
2298 md_convert_frag_branch (fragp);
2302 md_show_usage (FILE *stream)
2304 fprintf (stream, _("\
2306 -m32 assemble RV32 code\n\
2307 -m64 assemble RV64 code (default)\n\
2308 -fpic generate position-independent code\n\
2309 -fno-pic don't generate position-independent code (default)\n\
2310 -msoft-float don't use F registers for floating-point values\n\
2311 -mhard-float use F registers for floating-point values (default)\n\
2312 -mno-rvc disable the C extension for compressed instructions (default)\n\
2313 -mrvc enable the C extension for compressed instructions\n\
2314 -march=ISA set the RISC-V architecture, RV64IMAFD by default\n\
2318 /* Standard calling conventions leave the CFA at SP on entry. */
2320 riscv_cfi_frame_initial_instructions (void)
2322 cfi_add_CFA_def_cfa_register (X_SP);
2326 tc_riscv_regname_to_dw2regnum (char *regname)
2330 if ((reg = reg_lookup_internal (regname, RCLASS_GPR)) >= 0)
2333 if ((reg = reg_lookup_internal (regname, RCLASS_FPR)) >= 0)
2336 as_bad (_("unknown register `%s'"), regname);
2341 riscv_elf_final_processing (void)
2343 enum float_mode elf_float_mode = float_mode;
2345 elf_elfheader (stdoutput)->e_flags |= elf_flags;
2347 if (elf_float_mode == FLOAT_MODE_DEFAULT)
2349 struct riscv_subset *subset;
2351 /* Assume soft-float unless D extension is present. */
2352 elf_float_mode = FLOAT_MODE_SOFT;
2354 for (subset = riscv_subsets; subset != NULL; subset = subset->next)
2355 if (strcasecmp (subset->name, "D") == 0)
2356 elf_float_mode = FLOAT_MODE_HARD;
2359 if (elf_float_mode == FLOAT_MODE_SOFT)
2360 elf_elfheader (stdoutput)->e_flags |= EF_RISCV_SOFT_FLOAT;
2363 /* Parse the .sleb128 and .uleb128 pseudos. Only allow constant expressions,
2364 since these directives break relaxation when used with symbol deltas. */
2367 s_riscv_leb128 (int sign)
2370 char *save_in = input_line_pointer;
2373 if (exp.X_op != O_constant)
2374 as_bad (_("non-constant .%cleb128 is not supported"), sign ? 's' : 'u');
2375 demand_empty_rest_of_line ();
2377 input_line_pointer = save_in;
2378 return s_leb128 (sign);
2381 /* Pseudo-op table. */
2383 static const pseudo_typeS riscv_pseudo_table[] =
2385 /* RISC-V-specific pseudo-ops. */
2386 {"option", s_riscv_option, 0},
2390 {"dtprelword", s_dtprel, 4},
2391 {"dtpreldword", s_dtprel, 8},
2393 {"align", s_align, 0},
2394 {"p2align", s_align, 0},
2395 {"balign", s_align, 1},
2396 {"uleb128", s_riscv_leb128, 0},
2397 {"sleb128", s_riscv_leb128, 1},
2403 riscv_pop_insert (void)
2405 extern void pop_insert (const pseudo_typeS *);
2407 pop_insert (riscv_pseudo_table);