3f09101108e21fba07c44586214e22994a5c26b2
[deliverable/binutils-gdb.git] / gas / config / tc-riscv.c
1 /* tc-riscv.c -- RISC-V assembler
2 Copyright (C) 2011-2017 Free Software Foundation, Inc.
3
4 Contributed by Andrew Waterman (andrew@sifive.com).
5 Based on MIPS target.
6
7 This file is part of GAS.
8
9 GAS is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
13
14 GAS is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program; see the file COPYING3. If not,
21 see <http://www.gnu.org/licenses/>. */
22
23 #include "as.h"
24 #include "config.h"
25 #include "subsegs.h"
26 #include "safe-ctype.h"
27
28 #include "itbl-ops.h"
29 #include "dwarf2dbg.h"
30 #include "dw2gencfi.h"
31 #include "struc-symbol.h"
32
33 #include "elf/riscv.h"
34 #include "opcode/riscv.h"
35
36 #include <stdint.h>
37
38 /* Information about an instruction, including its format, operands
39 and fixups. */
40 struct riscv_cl_insn
41 {
42 /* The opcode's entry in riscv_opcodes. */
43 const struct riscv_opcode *insn_mo;
44
45 /* The encoded instruction bits. */
46 insn_t insn_opcode;
47
48 /* The frag that contains the instruction. */
49 struct frag *frag;
50
51 /* The offset into FRAG of the first instruction byte. */
52 long where;
53
54 /* The relocs associated with the instruction, if any. */
55 fixS *fixp;
56 };
57
58 #ifndef DEFAULT_ARCH
59 #define DEFAULT_ARCH "riscv64"
60 #endif
61
62 static const char default_arch[] = DEFAULT_ARCH;
63
64 static unsigned xlen = 0; /* width of an x-register */
65 static unsigned abi_xlen = 0; /* width of a pointer in the ABI */
66
67 #define LOAD_ADDRESS_INSN (abi_xlen == 64 ? "ld" : "lw")
68 #define ADD32_INSN (xlen == 64 ? "addiw" : "addi")
69
70 static unsigned elf_flags = 0;
71
72 /* This is the set of options which the .option pseudo-op may modify. */
73
74 struct riscv_set_options
75 {
76 int pic; /* Generate position-independent code. */
77 int rvc; /* Generate RVC code. */
78 int relax; /* Emit relocs the linker is allowed to relax. */
79 };
80
81 static struct riscv_set_options riscv_opts =
82 {
83 0, /* pic */
84 0, /* rvc */
85 1, /* relax */
86 };
87
88 static void
89 riscv_set_rvc (bfd_boolean rvc_value)
90 {
91 if (rvc_value)
92 elf_flags |= EF_RISCV_RVC;
93
94 riscv_opts.rvc = rvc_value;
95 }
96
97 struct riscv_subset
98 {
99 const char *name;
100
101 struct riscv_subset *next;
102 };
103
104 static struct riscv_subset *riscv_subsets;
105
106 static bfd_boolean
107 riscv_subset_supports (const char *feature)
108 {
109 struct riscv_subset *s;
110 char *p;
111 unsigned xlen_required = strtoul (feature, &p, 10);
112
113 if (xlen_required && xlen != xlen_required)
114 return FALSE;
115
116 for (s = riscv_subsets; s != NULL; s = s->next)
117 if (strcasecmp (s->name, p) == 0)
118 return TRUE;
119
120 return FALSE;
121 }
122
123 static void
124 riscv_add_subset (const char *subset)
125 {
126 struct riscv_subset *s = xmalloc (sizeof *s);
127
128 s->name = xstrdup (subset);
129 s->next = riscv_subsets;
130 riscv_subsets = s;
131 }
132
133 /* Set which ISA and extensions are available. */
134
135 static void
136 riscv_set_arch (const char *s)
137 {
138 const char *all_subsets = "imafdc";
139 const char *extension = NULL;
140 const char *p = s;
141
142 if (strncmp (p, "rv32", 4) == 0)
143 {
144 xlen = 32;
145 p += 4;
146 }
147 else if (strncmp (p, "rv64", 4) == 0)
148 {
149 xlen = 64;
150 p += 4;
151 }
152 else
153 as_fatal ("-march=%s: ISA string must begin with rv32 or rv64", s);
154
155 switch (*p)
156 {
157 case 'i':
158 break;
159
160 case 'g':
161 p++;
162 for ( ; *all_subsets != 'c'; all_subsets++)
163 {
164 const char subset[] = {*all_subsets, '\0'};
165 riscv_add_subset (subset);
166 }
167 break;
168
169 default:
170 as_fatal ("-march=%s: first ISA subset must be `i' or `g'", s);
171 }
172
173 while (*p)
174 {
175 if (*p == 'x')
176 {
177 char *subset = xstrdup (p), *q = subset;
178
179 while (*++q != '\0' && *q != '_')
180 ;
181 *q = '\0';
182
183 if (extension)
184 as_fatal ("-march=%s: only one non-standard extension is supported"
185 " (found `%s' and `%s')", s, extension, subset);
186 extension = subset;
187 riscv_add_subset (subset);
188 p += strlen (subset);
189 free (subset);
190 }
191 else if (*p == '_')
192 p++;
193 else if ((all_subsets = strchr (all_subsets, *p)) != NULL)
194 {
195 const char subset[] = {*p, 0};
196 riscv_add_subset (subset);
197 all_subsets++;
198 p++;
199 }
200 else if (*p == 'q')
201 {
202 const char subset[] = {*p, 0};
203 riscv_add_subset (subset);
204 p++;
205 }
206 else
207 as_fatal ("-march=%s: unsupported ISA subset `%c'", s, *p);
208 }
209 }
210
211 /* Handle of the OPCODE hash table. */
212 static struct hash_control *op_hash = NULL;
213
214 /* This array holds the chars that always start a comment. If the
215 pre-processor is disabled, these aren't very useful */
216 const char comment_chars[] = "#";
217
218 /* This array holds the chars that only start a comment at the beginning of
219 a line. If the line seems to have the form '# 123 filename'
220 .line and .file directives will appear in the pre-processed output */
221 /* Note that input_file.c hand checks for '#' at the beginning of the
222 first line of the input file. This is because the compiler outputs
223 #NO_APP at the beginning of its output. */
224 /* Also note that C style comments are always supported. */
225 const char line_comment_chars[] = "#";
226
227 /* This array holds machine specific line separator characters. */
228 const char line_separator_chars[] = ";";
229
230 /* Chars that can be used to separate mant from exp in floating point nums */
231 const char EXP_CHARS[] = "eE";
232
233 /* Chars that mean this number is a floating point constant */
234 /* As in 0f12.456 */
235 /* or 0d1.2345e12 */
236 const char FLT_CHARS[] = "rRsSfFdDxXpP";
237
238 /* Macros for encoding relaxation state for RVC branches and far jumps. */
239 #define RELAX_BRANCH_ENCODE(uncond, rvc, length) \
240 ((relax_substateT) \
241 (0xc0000000 \
242 | ((uncond) ? 1 : 0) \
243 | ((rvc) ? 2 : 0) \
244 | ((length) << 2)))
245 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
246 #define RELAX_BRANCH_LENGTH(i) (((i) >> 2) & 0xF)
247 #define RELAX_BRANCH_RVC(i) (((i) & 2) != 0)
248 #define RELAX_BRANCH_UNCOND(i) (((i) & 1) != 0)
249
250 /* Is the given value a sign-extended 32-bit value? */
251 #define IS_SEXT_32BIT_NUM(x) \
252 (((x) &~ (offsetT) 0x7fffffff) == 0 \
253 || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
254
255 /* Is the given value a zero-extended 32-bit value? Or a negated one? */
256 #define IS_ZEXT_32BIT_NUM(x) \
257 (((x) &~ (offsetT) 0xffffffff) == 0 \
258 || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
259
260 /* Change INSN's opcode so that the operand given by FIELD has value VALUE.
261 INSN is a riscv_cl_insn structure and VALUE is evaluated exactly once. */
262 #define INSERT_OPERAND(FIELD, INSN, VALUE) \
263 INSERT_BITS ((INSN).insn_opcode, VALUE, OP_MASK_##FIELD, OP_SH_##FIELD)
264
265 /* Determine if an instruction matches an opcode. */
266 #define OPCODE_MATCHES(OPCODE, OP) \
267 (((OPCODE) & MASK_##OP) == MATCH_##OP)
268
269 static char *expr_end;
270
271 /* The default target format to use. */
272
273 const char *
274 riscv_target_format (void)
275 {
276 return xlen == 64 ? "elf64-littleriscv" : "elf32-littleriscv";
277 }
278
279 /* Return the length of instruction INSN. */
280
281 static inline unsigned int
282 insn_length (const struct riscv_cl_insn *insn)
283 {
284 return riscv_insn_length (insn->insn_opcode);
285 }
286
287 /* Initialise INSN from opcode entry MO. Leave its position unspecified. */
288
289 static void
290 create_insn (struct riscv_cl_insn *insn, const struct riscv_opcode *mo)
291 {
292 insn->insn_mo = mo;
293 insn->insn_opcode = mo->match;
294 insn->frag = NULL;
295 insn->where = 0;
296 insn->fixp = NULL;
297 }
298
299 /* Install INSN at the location specified by its "frag" and "where" fields. */
300
301 static void
302 install_insn (const struct riscv_cl_insn *insn)
303 {
304 char *f = insn->frag->fr_literal + insn->where;
305 md_number_to_chars (f, insn->insn_opcode, insn_length (insn));
306 }
307
308 /* Move INSN to offset WHERE in FRAG. Adjust the fixups accordingly
309 and install the opcode in the new location. */
310
311 static void
312 move_insn (struct riscv_cl_insn *insn, fragS *frag, long where)
313 {
314 insn->frag = frag;
315 insn->where = where;
316 if (insn->fixp != NULL)
317 {
318 insn->fixp->fx_frag = frag;
319 insn->fixp->fx_where = where;
320 }
321 install_insn (insn);
322 }
323
324 /* Add INSN to the end of the output. */
325
326 static void
327 add_fixed_insn (struct riscv_cl_insn *insn)
328 {
329 char *f = frag_more (insn_length (insn));
330 move_insn (insn, frag_now, f - frag_now->fr_literal);
331 }
332
333 static void
334 add_relaxed_insn (struct riscv_cl_insn *insn, int max_chars, int var,
335 relax_substateT subtype, symbolS *symbol, offsetT offset)
336 {
337 frag_grow (max_chars);
338 move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
339 frag_var (rs_machine_dependent, max_chars, var,
340 subtype, symbol, offset, NULL);
341 }
342
343 /* Compute the length of a branch sequence, and adjust the stored length
344 accordingly. If FRAGP is NULL, the worst-case length is returned. */
345
346 static unsigned
347 relaxed_branch_length (fragS *fragp, asection *sec, int update)
348 {
349 int jump, rvc, length = 8;
350
351 if (!fragp)
352 return length;
353
354 jump = RELAX_BRANCH_UNCOND (fragp->fr_subtype);
355 rvc = RELAX_BRANCH_RVC (fragp->fr_subtype);
356 length = RELAX_BRANCH_LENGTH (fragp->fr_subtype);
357
358 /* Assume jumps are in range; the linker will catch any that aren't. */
359 length = jump ? 4 : 8;
360
361 if (fragp->fr_symbol != NULL
362 && S_IS_DEFINED (fragp->fr_symbol)
363 && !S_IS_WEAK (fragp->fr_symbol)
364 && sec == S_GET_SEGMENT (fragp->fr_symbol))
365 {
366 offsetT val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
367 bfd_vma rvc_range = jump ? RVC_JUMP_REACH : RVC_BRANCH_REACH;
368 val -= fragp->fr_address + fragp->fr_fix;
369
370 if (rvc && (bfd_vma)(val + rvc_range/2) < rvc_range)
371 length = 2;
372 else if ((bfd_vma)(val + RISCV_BRANCH_REACH/2) < RISCV_BRANCH_REACH)
373 length = 4;
374 else if (!jump && rvc)
375 length = 6;
376 }
377
378 if (update)
379 fragp->fr_subtype = RELAX_BRANCH_ENCODE (jump, rvc, length);
380
381 return length;
382 }
383
384 struct regname
385 {
386 const char *name;
387 unsigned int num;
388 };
389
390 enum reg_class
391 {
392 RCLASS_GPR,
393 RCLASS_FPR,
394 RCLASS_CSR,
395 RCLASS_MAX
396 };
397
398 static struct hash_control *reg_names_hash = NULL;
399
400 #define ENCODE_REG_HASH(cls, n) \
401 ((void *)(uintptr_t)((n) * RCLASS_MAX + (cls) + 1))
402 #define DECODE_REG_CLASS(hash) (((uintptr_t)(hash) - 1) % RCLASS_MAX)
403 #define DECODE_REG_NUM(hash) (((uintptr_t)(hash) - 1) / RCLASS_MAX)
404
405 static void
406 hash_reg_name (enum reg_class class, const char *name, unsigned n)
407 {
408 void *hash = ENCODE_REG_HASH (class, n);
409 const char *retval = hash_insert (reg_names_hash, name, hash);
410
411 if (retval != NULL)
412 as_fatal (_("internal error: can't hash `%s': %s"), name, retval);
413 }
414
415 static void
416 hash_reg_names (enum reg_class class, const char * const names[], unsigned n)
417 {
418 unsigned i;
419
420 for (i = 0; i < n; i++)
421 hash_reg_name (class, names[i], i);
422 }
423
424 static unsigned int
425 reg_lookup_internal (const char *s, enum reg_class class)
426 {
427 struct regname *r = (struct regname *) hash_find (reg_names_hash, s);
428
429 if (r == NULL || DECODE_REG_CLASS (r) != class)
430 return -1;
431 return DECODE_REG_NUM (r);
432 }
433
434 static bfd_boolean
435 reg_lookup (char **s, enum reg_class class, unsigned int *regnop)
436 {
437 char *e;
438 char save_c;
439 int reg = -1;
440
441 /* Find end of name. */
442 e = *s;
443 if (is_name_beginner (*e))
444 ++e;
445 while (is_part_of_name (*e))
446 ++e;
447
448 /* Terminate name. */
449 save_c = *e;
450 *e = '\0';
451
452 /* Look for the register. Advance to next token if one was recognized. */
453 if ((reg = reg_lookup_internal (*s, class)) >= 0)
454 *s = e;
455
456 *e = save_c;
457 if (regnop)
458 *regnop = reg;
459 return reg >= 0;
460 }
461
462 static bfd_boolean
463 arg_lookup (char **s, const char *const *array, size_t size, unsigned *regnop)
464 {
465 const char *p = strchr (*s, ',');
466 size_t i, len = p ? (size_t)(p - *s) : strlen (*s);
467
468 for (i = 0; i < size; i++)
469 if (array[i] != NULL && strncmp (array[i], *s, len) == 0)
470 {
471 *regnop = i;
472 *s += len;
473 return TRUE;
474 }
475
476 return FALSE;
477 }
478
479 /* For consistency checking, verify that all bits are specified either
480 by the match/mask part of the instruction definition, or by the
481 operand list. */
482 static bfd_boolean
483 validate_riscv_insn (const struct riscv_opcode *opc)
484 {
485 const char *p = opc->args;
486 char c;
487 insn_t used_bits = opc->mask;
488 int insn_width = 8 * riscv_insn_length (opc->match);
489 insn_t required_bits = ~0ULL >> (64 - insn_width);
490
491 if ((used_bits & opc->match) != (opc->match & required_bits))
492 {
493 as_bad (_("internal: bad RISC-V opcode (mask error): %s %s"),
494 opc->name, opc->args);
495 return FALSE;
496 }
497
498 #define USE_BITS(mask,shift) (used_bits |= ((insn_t)(mask) << (shift)))
499 while (*p)
500 switch (c = *p++)
501 {
502 case 'C': /* RVC */
503 switch (c = *p++)
504 {
505 case 'a': used_bits |= ENCODE_RVC_J_IMM (-1U); break;
506 case 'c': break; /* RS1, constrained to equal sp */
507 case 'i': used_bits |= ENCODE_RVC_SIMM3(-1U); break;
508 case 'j': used_bits |= ENCODE_RVC_IMM (-1U); break;
509 case 'k': used_bits |= ENCODE_RVC_LW_IMM (-1U); break;
510 case 'l': used_bits |= ENCODE_RVC_LD_IMM (-1U); break;
511 case 'm': used_bits |= ENCODE_RVC_LWSP_IMM (-1U); break;
512 case 'n': used_bits |= ENCODE_RVC_LDSP_IMM (-1U); break;
513 case 'p': used_bits |= ENCODE_RVC_B_IMM (-1U); break;
514 case 's': USE_BITS (OP_MASK_CRS1S, OP_SH_CRS1S); break;
515 case 't': USE_BITS (OP_MASK_CRS2S, OP_SH_CRS2S); break;
516 case 'u': used_bits |= ENCODE_RVC_IMM (-1U); break;
517 case 'v': used_bits |= ENCODE_RVC_IMM (-1U); break;
518 case 'w': break; /* RS1S, constrained to equal RD */
519 case 'x': break; /* RS2S, constrained to equal RD */
520 case 'K': used_bits |= ENCODE_RVC_ADDI4SPN_IMM (-1U); break;
521 case 'L': used_bits |= ENCODE_RVC_ADDI16SP_IMM (-1U); break;
522 case 'M': used_bits |= ENCODE_RVC_SWSP_IMM (-1U); break;
523 case 'N': used_bits |= ENCODE_RVC_SDSP_IMM (-1U); break;
524 case 'U': break; /* RS1, constrained to equal RD */
525 case 'V': USE_BITS (OP_MASK_CRS2, OP_SH_CRS2); break;
526 case '<': used_bits |= ENCODE_RVC_IMM (-1U); break;
527 case '>': used_bits |= ENCODE_RVC_IMM (-1U); break;
528 case 'T': USE_BITS (OP_MASK_CRS2, OP_SH_CRS2); break;
529 case 'D': USE_BITS (OP_MASK_CRS2S, OP_SH_CRS2S); break;
530 default:
531 as_bad (_("internal: bad RISC-V opcode (unknown operand type `C%c'): %s %s"),
532 c, opc->name, opc->args);
533 return FALSE;
534 }
535 break;
536 case ',': break;
537 case '(': break;
538 case ')': break;
539 case '<': USE_BITS (OP_MASK_SHAMTW, OP_SH_SHAMTW); break;
540 case '>': USE_BITS (OP_MASK_SHAMT, OP_SH_SHAMT); break;
541 case 'A': break;
542 case 'D': USE_BITS (OP_MASK_RD, OP_SH_RD); break;
543 case 'Z': USE_BITS (OP_MASK_RS1, OP_SH_RS1); break;
544 case 'E': USE_BITS (OP_MASK_CSR, OP_SH_CSR); break;
545 case 'I': break;
546 case 'R': USE_BITS (OP_MASK_RS3, OP_SH_RS3); break;
547 case 'S': USE_BITS (OP_MASK_RS1, OP_SH_RS1); break;
548 case 'U': USE_BITS (OP_MASK_RS1, OP_SH_RS1); /* fallthru */
549 case 'T': USE_BITS (OP_MASK_RS2, OP_SH_RS2); break;
550 case 'd': USE_BITS (OP_MASK_RD, OP_SH_RD); break;
551 case 'm': USE_BITS (OP_MASK_RM, OP_SH_RM); break;
552 case 's': USE_BITS (OP_MASK_RS1, OP_SH_RS1); break;
553 case 't': USE_BITS (OP_MASK_RS2, OP_SH_RS2); break;
554 case 'P': USE_BITS (OP_MASK_PRED, OP_SH_PRED); break;
555 case 'Q': USE_BITS (OP_MASK_SUCC, OP_SH_SUCC); break;
556 case 'o':
557 case 'j': used_bits |= ENCODE_ITYPE_IMM (-1U); break;
558 case 'a': used_bits |= ENCODE_UJTYPE_IMM (-1U); break;
559 case 'p': used_bits |= ENCODE_SBTYPE_IMM (-1U); break;
560 case 'q': used_bits |= ENCODE_STYPE_IMM (-1U); break;
561 case 'u': used_bits |= ENCODE_UTYPE_IMM (-1U); break;
562 case '[': break;
563 case ']': break;
564 case '0': break;
565 default:
566 as_bad (_("internal: bad RISC-V opcode "
567 "(unknown operand type `%c'): %s %s"),
568 c, opc->name, opc->args);
569 return FALSE;
570 }
571 #undef USE_BITS
572 if (used_bits != required_bits)
573 {
574 as_bad (_("internal: bad RISC-V opcode (bits 0x%lx undefined): %s %s"),
575 ~(unsigned long)(used_bits & required_bits),
576 opc->name, opc->args);
577 return FALSE;
578 }
579 return TRUE;
580 }
581
582 struct percent_op_match
583 {
584 const char *str;
585 bfd_reloc_code_real_type reloc;
586 };
587
588 /* This function is called once, at assembler startup time. It should set up
589 all the tables, etc. that the MD part of the assembler will need. */
590
591 void
592 md_begin (void)
593 {
594 int i = 0;
595 unsigned long mach = xlen == 64 ? bfd_mach_riscv64 : bfd_mach_riscv32;
596
597 if (! bfd_set_arch_mach (stdoutput, bfd_arch_riscv, mach))
598 as_warn (_("Could not set architecture and machine"));
599
600 op_hash = hash_new ();
601
602 while (riscv_opcodes[i].name)
603 {
604 const char *name = riscv_opcodes[i].name;
605 const char *hash_error =
606 hash_insert (op_hash, name, (void *) &riscv_opcodes[i]);
607
608 if (hash_error)
609 {
610 fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
611 riscv_opcodes[i].name, hash_error);
612 /* Probably a memory allocation problem? Give up now. */
613 as_fatal (_("Broken assembler. No assembly attempted."));
614 }
615
616 do
617 {
618 if (riscv_opcodes[i].pinfo != INSN_MACRO)
619 {
620 if (!validate_riscv_insn (&riscv_opcodes[i]))
621 as_fatal (_("Broken assembler. No assembly attempted."));
622 }
623 ++i;
624 }
625 while (riscv_opcodes[i].name && !strcmp (riscv_opcodes[i].name, name));
626 }
627
628 reg_names_hash = hash_new ();
629 hash_reg_names (RCLASS_GPR, riscv_gpr_names_numeric, NGPR);
630 hash_reg_names (RCLASS_GPR, riscv_gpr_names_abi, NGPR);
631 hash_reg_names (RCLASS_FPR, riscv_fpr_names_numeric, NFPR);
632 hash_reg_names (RCLASS_FPR, riscv_fpr_names_abi, NFPR);
633
634 #define DECLARE_CSR(name, num) hash_reg_name (RCLASS_CSR, #name, num);
635 #include "opcode/riscv-opc.h"
636 #undef DECLARE_CSR
637
638 /* Set the default alignment for the text section. */
639 record_alignment (text_section, riscv_opts.rvc ? 1 : 2);
640 }
641
642 static insn_t
643 riscv_apply_const_reloc (bfd_reloc_code_real_type reloc_type, bfd_vma value)
644 {
645 switch (reloc_type)
646 {
647 case BFD_RELOC_32:
648 return value;
649
650 case BFD_RELOC_RISCV_HI20:
651 return ENCODE_UTYPE_IMM (RISCV_CONST_HIGH_PART (value));
652
653 case BFD_RELOC_RISCV_LO12_S:
654 return ENCODE_STYPE_IMM (value);
655
656 case BFD_RELOC_RISCV_LO12_I:
657 return ENCODE_ITYPE_IMM (value);
658
659 default:
660 abort ();
661 }
662 }
663
664 /* Output an instruction. IP is the instruction information.
665 ADDRESS_EXPR is an operand of the instruction to be used with
666 RELOC_TYPE. */
667
668 static void
669 append_insn (struct riscv_cl_insn *ip, expressionS *address_expr,
670 bfd_reloc_code_real_type reloc_type)
671 {
672 dwarf2_emit_insn (0);
673
674 if (reloc_type != BFD_RELOC_UNUSED)
675 {
676 reloc_howto_type *howto;
677
678 gas_assert (address_expr);
679 if (reloc_type == BFD_RELOC_12_PCREL
680 || reloc_type == BFD_RELOC_RISCV_JMP)
681 {
682 int j = reloc_type == BFD_RELOC_RISCV_JMP;
683 int best_case = riscv_insn_length (ip->insn_opcode);
684 unsigned worst_case = relaxed_branch_length (NULL, NULL, 0);
685 add_relaxed_insn (ip, worst_case, best_case,
686 RELAX_BRANCH_ENCODE (j, best_case == 2, worst_case),
687 address_expr->X_add_symbol,
688 address_expr->X_add_number);
689 return;
690 }
691 else if (address_expr->X_op == O_constant)
692 ip->insn_opcode |= riscv_apply_const_reloc (reloc_type,
693 address_expr->X_add_number);
694 else
695 {
696 howto = bfd_reloc_type_lookup (stdoutput, reloc_type);
697 if (howto == NULL)
698 as_bad (_("Unsupported RISC-V relocation number %d"), reloc_type);
699
700 ip->fixp = fix_new_exp (ip->frag, ip->where,
701 bfd_get_reloc_size (howto),
702 address_expr, FALSE, reloc_type);
703
704 ip->fixp->fx_tcbit = riscv_opts.relax;
705 }
706 }
707
708 add_fixed_insn (ip);
709 install_insn (ip);
710 }
711
712 /* Build an instruction created by a macro expansion. This is passed
713 a pointer to the count of instructions created so far, an
714 expression, the name of the instruction to build, an operand format
715 string, and corresponding arguments. */
716
717 static void
718 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
719 {
720 const struct riscv_opcode *mo;
721 struct riscv_cl_insn insn;
722 bfd_reloc_code_real_type r;
723 va_list args;
724
725 va_start (args, fmt);
726
727 r = BFD_RELOC_UNUSED;
728 mo = (struct riscv_opcode *) hash_find (op_hash, name);
729 gas_assert (mo);
730
731 /* Find a non-RVC variant of the instruction. append_insn will compress
732 it if possible. */
733 while (riscv_insn_length (mo->match) < 4)
734 mo++;
735 gas_assert (strcmp (name, mo->name) == 0);
736
737 create_insn (&insn, mo);
738 for (;;)
739 {
740 switch (*fmt++)
741 {
742 case 'd':
743 INSERT_OPERAND (RD, insn, va_arg (args, int));
744 continue;
745
746 case 's':
747 INSERT_OPERAND (RS1, insn, va_arg (args, int));
748 continue;
749
750 case 't':
751 INSERT_OPERAND (RS2, insn, va_arg (args, int));
752 continue;
753
754 case '>':
755 INSERT_OPERAND (SHAMT, insn, va_arg (args, int));
756 continue;
757
758 case 'j':
759 case 'u':
760 case 'q':
761 gas_assert (ep != NULL);
762 r = va_arg (args, int);
763 continue;
764
765 case '\0':
766 break;
767 case ',':
768 continue;
769 default:
770 as_fatal (_("internal error: invalid macro"));
771 }
772 break;
773 }
774 va_end (args);
775 gas_assert (r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
776
777 append_insn (&insn, ep, r);
778 }
779
780 /* Sign-extend 32-bit mode constants that have bit 31 set and all higher bits
781 unset. */
782 static void
783 normalize_constant_expr (expressionS *ex)
784 {
785 if (xlen > 32)
786 return;
787 if ((ex->X_op == O_constant || ex->X_op == O_symbol)
788 && IS_ZEXT_32BIT_NUM (ex->X_add_number))
789 ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
790 - 0x80000000);
791 }
792
793 /* Fail if an expression is not a constant. */
794
795 static void
796 check_absolute_expr (struct riscv_cl_insn *ip, expressionS *ex)
797 {
798 if (ex->X_op == O_big)
799 as_bad (_("unsupported large constant"));
800 else if (ex->X_op != O_constant)
801 as_bad (_("Instruction %s requires absolute expression"),
802 ip->insn_mo->name);
803 normalize_constant_expr (ex);
804 }
805
806 static symbolS *
807 make_internal_label (void)
808 {
809 return (symbolS *) local_symbol_make (FAKE_LABEL_NAME, now_seg,
810 (valueT) frag_now_fix (), frag_now);
811 }
812
813 /* Load an entry from the GOT. */
814 static void
815 pcrel_access (int destreg, int tempreg, expressionS *ep,
816 const char *lo_insn, const char *lo_pattern,
817 bfd_reloc_code_real_type hi_reloc,
818 bfd_reloc_code_real_type lo_reloc)
819 {
820 expressionS ep2;
821 ep2.X_op = O_symbol;
822 ep2.X_add_symbol = make_internal_label ();
823 ep2.X_add_number = 0;
824
825 macro_build (ep, "auipc", "d,u", tempreg, hi_reloc);
826 macro_build (&ep2, lo_insn, lo_pattern, destreg, tempreg, lo_reloc);
827 }
828
829 static void
830 pcrel_load (int destreg, int tempreg, expressionS *ep, const char *lo_insn,
831 bfd_reloc_code_real_type hi_reloc,
832 bfd_reloc_code_real_type lo_reloc)
833 {
834 pcrel_access (destreg, tempreg, ep, lo_insn, "d,s,j", hi_reloc, lo_reloc);
835 }
836
837 static void
838 pcrel_store (int srcreg, int tempreg, expressionS *ep, const char *lo_insn,
839 bfd_reloc_code_real_type hi_reloc,
840 bfd_reloc_code_real_type lo_reloc)
841 {
842 pcrel_access (srcreg, tempreg, ep, lo_insn, "t,s,q", hi_reloc, lo_reloc);
843 }
844
845 /* PC-relative function call using AUIPC/JALR, relaxed to JAL. */
846 static void
847 riscv_call (int destreg, int tempreg, expressionS *ep,
848 bfd_reloc_code_real_type reloc)
849 {
850 macro_build (ep, "auipc", "d,u", tempreg, reloc);
851 macro_build (NULL, "jalr", "d,s", destreg, tempreg);
852 }
853
854 /* Load an integer constant into a register. */
855
856 static void
857 load_const (int reg, expressionS *ep)
858 {
859 int shift = RISCV_IMM_BITS;
860 expressionS upper = *ep, lower = *ep;
861 lower.X_add_number = (int32_t) ep->X_add_number << (32-shift) >> (32-shift);
862 upper.X_add_number -= lower.X_add_number;
863
864 if (ep->X_op != O_constant)
865 {
866 as_bad (_("unsupported large constant"));
867 return;
868 }
869
870 if (xlen > 32 && !IS_SEXT_32BIT_NUM (ep->X_add_number))
871 {
872 /* Reduce to a signed 32-bit constant using SLLI and ADDI. */
873 while (((upper.X_add_number >> shift) & 1) == 0)
874 shift++;
875
876 upper.X_add_number = (int64_t) upper.X_add_number >> shift;
877 load_const (reg, &upper);
878
879 macro_build (NULL, "slli", "d,s,>", reg, reg, shift);
880 if (lower.X_add_number != 0)
881 macro_build (&lower, "addi", "d,s,j", reg, reg, BFD_RELOC_RISCV_LO12_I);
882 }
883 else
884 {
885 /* Simply emit LUI and/or ADDI to build a 32-bit signed constant. */
886 int hi_reg = 0;
887
888 if (upper.X_add_number != 0)
889 {
890 macro_build (ep, "lui", "d,u", reg, BFD_RELOC_RISCV_HI20);
891 hi_reg = reg;
892 }
893
894 if (lower.X_add_number != 0 || hi_reg == 0)
895 macro_build (ep, ADD32_INSN, "d,s,j", reg, hi_reg,
896 BFD_RELOC_RISCV_LO12_I);
897 }
898 }
899
900 /* Expand RISC-V assembly macros into one or more instructions. */
901 static void
902 macro (struct riscv_cl_insn *ip, expressionS *imm_expr,
903 bfd_reloc_code_real_type *imm_reloc)
904 {
905 int rd = (ip->insn_opcode >> OP_SH_RD) & OP_MASK_RD;
906 int rs1 = (ip->insn_opcode >> OP_SH_RS1) & OP_MASK_RS1;
907 int rs2 = (ip->insn_opcode >> OP_SH_RS2) & OP_MASK_RS2;
908 int mask = ip->insn_mo->mask;
909
910 switch (mask)
911 {
912 case M_LI:
913 load_const (rd, imm_expr);
914 break;
915
916 case M_LA:
917 case M_LLA:
918 /* Load the address of a symbol into a register. */
919 if (!IS_SEXT_32BIT_NUM (imm_expr->X_add_number))
920 as_bad (_("offset too large"));
921
922 if (imm_expr->X_op == O_constant)
923 load_const (rd, imm_expr);
924 else if (riscv_opts.pic && mask == M_LA) /* Global PIC symbol */
925 pcrel_load (rd, rd, imm_expr, LOAD_ADDRESS_INSN,
926 BFD_RELOC_RISCV_GOT_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
927 else /* Local PIC symbol, or any non-PIC symbol */
928 pcrel_load (rd, rd, imm_expr, "addi",
929 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
930 break;
931
932 case M_LA_TLS_GD:
933 pcrel_load (rd, rd, imm_expr, "addi",
934 BFD_RELOC_RISCV_TLS_GD_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
935 break;
936
937 case M_LA_TLS_IE:
938 pcrel_load (rd, rd, imm_expr, LOAD_ADDRESS_INSN,
939 BFD_RELOC_RISCV_TLS_GOT_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
940 break;
941
942 case M_LB:
943 pcrel_load (rd, rd, imm_expr, "lb",
944 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
945 break;
946
947 case M_LBU:
948 pcrel_load (rd, rd, imm_expr, "lbu",
949 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
950 break;
951
952 case M_LH:
953 pcrel_load (rd, rd, imm_expr, "lh",
954 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
955 break;
956
957 case M_LHU:
958 pcrel_load (rd, rd, imm_expr, "lhu",
959 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
960 break;
961
962 case M_LW:
963 pcrel_load (rd, rd, imm_expr, "lw",
964 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
965 break;
966
967 case M_LWU:
968 pcrel_load (rd, rd, imm_expr, "lwu",
969 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
970 break;
971
972 case M_LD:
973 pcrel_load (rd, rd, imm_expr, "ld",
974 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
975 break;
976
977 case M_FLW:
978 pcrel_load (rd, rs1, imm_expr, "flw",
979 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
980 break;
981
982 case M_FLD:
983 pcrel_load (rd, rs1, imm_expr, "fld",
984 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_I);
985 break;
986
987 case M_SB:
988 pcrel_store (rs2, rs1, imm_expr, "sb",
989 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
990 break;
991
992 case M_SH:
993 pcrel_store (rs2, rs1, imm_expr, "sh",
994 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
995 break;
996
997 case M_SW:
998 pcrel_store (rs2, rs1, imm_expr, "sw",
999 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1000 break;
1001
1002 case M_SD:
1003 pcrel_store (rs2, rs1, imm_expr, "sd",
1004 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1005 break;
1006
1007 case M_FSW:
1008 pcrel_store (rs2, rs1, imm_expr, "fsw",
1009 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1010 break;
1011
1012 case M_FSD:
1013 pcrel_store (rs2, rs1, imm_expr, "fsd",
1014 BFD_RELOC_RISCV_PCREL_HI20, BFD_RELOC_RISCV_PCREL_LO12_S);
1015 break;
1016
1017 case M_CALL:
1018 riscv_call (rd, rs1, imm_expr, *imm_reloc);
1019 break;
1020
1021 default:
1022 as_bad (_("Macro %s not implemented"), ip->insn_mo->name);
1023 break;
1024 }
1025 }
1026
1027 static const struct percent_op_match percent_op_utype[] =
1028 {
1029 {"%tprel_hi", BFD_RELOC_RISCV_TPREL_HI20},
1030 {"%pcrel_hi", BFD_RELOC_RISCV_PCREL_HI20},
1031 {"%tls_ie_pcrel_hi", BFD_RELOC_RISCV_TLS_GOT_HI20},
1032 {"%tls_gd_pcrel_hi", BFD_RELOC_RISCV_TLS_GD_HI20},
1033 {"%hi", BFD_RELOC_RISCV_HI20},
1034 {0, 0}
1035 };
1036
1037 static const struct percent_op_match percent_op_itype[] =
1038 {
1039 {"%lo", BFD_RELOC_RISCV_LO12_I},
1040 {"%tprel_lo", BFD_RELOC_RISCV_TPREL_LO12_I},
1041 {"%pcrel_lo", BFD_RELOC_RISCV_PCREL_LO12_I},
1042 {0, 0}
1043 };
1044
1045 static const struct percent_op_match percent_op_stype[] =
1046 {
1047 {"%lo", BFD_RELOC_RISCV_LO12_S},
1048 {"%tprel_lo", BFD_RELOC_RISCV_TPREL_LO12_S},
1049 {"%pcrel_lo", BFD_RELOC_RISCV_PCREL_LO12_S},
1050 {0, 0}
1051 };
1052
1053 static const struct percent_op_match percent_op_rtype[] =
1054 {
1055 {"%tprel_add", BFD_RELOC_RISCV_TPREL_ADD},
1056 {0, 0}
1057 };
1058
1059 /* Return true if *STR points to a relocation operator. When returning true,
1060 move *STR over the operator and store its relocation code in *RELOC.
1061 Leave both *STR and *RELOC alone when returning false. */
1062
1063 static bfd_boolean
1064 parse_relocation (char **str, bfd_reloc_code_real_type *reloc,
1065 const struct percent_op_match *percent_op)
1066 {
1067 for ( ; percent_op->str; percent_op++)
1068 if (strncasecmp (*str, percent_op->str, strlen (percent_op->str)) == 0)
1069 {
1070 int len = strlen (percent_op->str);
1071
1072 if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
1073 continue;
1074
1075 *str += strlen (percent_op->str);
1076 *reloc = percent_op->reloc;
1077
1078 /* Check whether the output BFD supports this relocation.
1079 If not, issue an error and fall back on something safe. */
1080 if (*reloc != BFD_RELOC_UNUSED
1081 && !bfd_reloc_type_lookup (stdoutput, *reloc))
1082 {
1083 as_bad ("relocation %s isn't supported by the current ABI",
1084 percent_op->str);
1085 *reloc = BFD_RELOC_UNUSED;
1086 }
1087 return TRUE;
1088 }
1089 return FALSE;
1090 }
1091
1092 static void
1093 my_getExpression (expressionS *ep, char *str)
1094 {
1095 char *save_in;
1096
1097 save_in = input_line_pointer;
1098 input_line_pointer = str;
1099 expression (ep);
1100 expr_end = input_line_pointer;
1101 input_line_pointer = save_in;
1102 }
1103
1104 /* Parse string STR as a 16-bit relocatable operand. Store the
1105 expression in *EP and the relocation, if any, in RELOC.
1106 Return the number of relocation operators used (0 or 1).
1107
1108 On exit, EXPR_END points to the first character after the expression. */
1109
1110 static size_t
1111 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
1112 char *str, const struct percent_op_match *percent_op)
1113 {
1114 size_t reloc_index;
1115 unsigned crux_depth, str_depth, regno;
1116 char *crux;
1117
1118 /* First, check for integer registers. */
1119 if (reg_lookup (&str, RCLASS_GPR, &regno))
1120 {
1121 ep->X_op = O_register;
1122 ep->X_add_number = regno;
1123 return 0;
1124 }
1125
1126 /* Search for the start of the main expression.
1127 End the loop with CRUX pointing to the start
1128 of the main expression and with CRUX_DEPTH containing the number
1129 of open brackets at that point. */
1130 reloc_index = -1;
1131 str_depth = 0;
1132 do
1133 {
1134 reloc_index++;
1135 crux = str;
1136 crux_depth = str_depth;
1137
1138 /* Skip over whitespace and brackets, keeping count of the number
1139 of brackets. */
1140 while (*str == ' ' || *str == '\t' || *str == '(')
1141 if (*str++ == '(')
1142 str_depth++;
1143 }
1144 while (*str == '%'
1145 && reloc_index < 1
1146 && parse_relocation (&str, reloc, percent_op));
1147
1148 my_getExpression (ep, crux);
1149 str = expr_end;
1150
1151 /* Match every open bracket. */
1152 while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
1153 if (*str++ == ')')
1154 crux_depth--;
1155
1156 if (crux_depth > 0)
1157 as_bad ("unclosed '('");
1158
1159 expr_end = str;
1160
1161 return reloc_index;
1162 }
1163
1164 /* This routine assembles an instruction into its binary format. As a
1165 side effect, it sets the global variable imm_reloc to the type of
1166 relocation to do if one of the operands is an address expression. */
1167
1168 static const char *
1169 riscv_ip (char *str, struct riscv_cl_insn *ip, expressionS *imm_expr,
1170 bfd_reloc_code_real_type *imm_reloc)
1171 {
1172 char *s;
1173 const char *args;
1174 char c = 0;
1175 struct riscv_opcode *insn;
1176 char *argsStart;
1177 unsigned int regno;
1178 char save_c = 0;
1179 int argnum;
1180 const struct percent_op_match *p;
1181 const char *error = "unrecognized opcode";
1182
1183 /* Parse the name of the instruction. Terminate the string if whitespace
1184 is found so that hash_find only sees the name part of the string. */
1185 for (s = str; *s != '\0'; ++s)
1186 if (ISSPACE (*s))
1187 {
1188 save_c = *s;
1189 *s++ = '\0';
1190 break;
1191 }
1192
1193 insn = (struct riscv_opcode *) hash_find (op_hash, str);
1194
1195 argsStart = s;
1196 for ( ; insn && insn->name && strcmp (insn->name, str) == 0; insn++)
1197 {
1198 if (!riscv_subset_supports (insn->subset))
1199 continue;
1200
1201 create_insn (ip, insn);
1202 argnum = 1;
1203
1204 imm_expr->X_op = O_absent;
1205 *imm_reloc = BFD_RELOC_UNUSED;
1206 p = percent_op_itype;
1207
1208 for (args = insn->args;; ++args)
1209 {
1210 s += strspn (s, " \t");
1211 switch (*args)
1212 {
1213 case '\0': /* End of args. */
1214 if (insn->pinfo != INSN_MACRO)
1215 {
1216 if (!insn->match_func (insn, ip->insn_opcode))
1217 break;
1218 if (riscv_insn_length (insn->match) == 2 && !riscv_opts.rvc)
1219 break;
1220 }
1221 if (*s != '\0')
1222 break;
1223 /* Successful assembly. */
1224 error = NULL;
1225 goto out;
1226
1227 case 'C': /* RVC */
1228 switch (*++args)
1229 {
1230 case 's': /* RS1 x8-x15 */
1231 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1232 || !(regno >= 8 && regno <= 15))
1233 break;
1234 INSERT_OPERAND (CRS1S, *ip, regno % 8);
1235 continue;
1236 case 'w': /* RS1 x8-x15, constrained to equal RD x8-x15. */
1237 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1238 || EXTRACT_OPERAND (CRS1S, ip->insn_opcode) + 8 != regno)
1239 break;
1240 continue;
1241 case 't': /* RS2 x8-x15 */
1242 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1243 || !(regno >= 8 && regno <= 15))
1244 break;
1245 INSERT_OPERAND (CRS2S, *ip, regno % 8);
1246 continue;
1247 case 'x': /* RS2 x8-x15, constrained to equal RD x8-x15. */
1248 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1249 || EXTRACT_OPERAND (CRS2S, ip->insn_opcode) + 8 != regno)
1250 break;
1251 continue;
1252 case 'U': /* RS1, constrained to equal RD. */
1253 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1254 || EXTRACT_OPERAND (RD, ip->insn_opcode) != regno)
1255 break;
1256 continue;
1257 case 'V': /* RS2 */
1258 if (!reg_lookup (&s, RCLASS_GPR, &regno))
1259 break;
1260 INSERT_OPERAND (CRS2, *ip, regno);
1261 continue;
1262 case 'c': /* RS1, constrained to equal sp. */
1263 if (!reg_lookup (&s, RCLASS_GPR, &regno)
1264 || regno != X_SP)
1265 break;
1266 continue;
1267 case '>':
1268 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1269 || imm_expr->X_op != O_constant
1270 || imm_expr->X_add_number <= 0
1271 || imm_expr->X_add_number >= 64)
1272 break;
1273 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1274 rvc_imm_done:
1275 s = expr_end;
1276 imm_expr->X_op = O_absent;
1277 continue;
1278 case '<':
1279 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1280 || imm_expr->X_op != O_constant
1281 || !VALID_RVC_IMM (imm_expr->X_add_number)
1282 || imm_expr->X_add_number <= 0
1283 || imm_expr->X_add_number >= 32)
1284 break;
1285 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1286 goto rvc_imm_done;
1287 case 'i':
1288 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1289 || imm_expr->X_op != O_constant
1290 || imm_expr->X_add_number == 0
1291 || !VALID_RVC_SIMM3 (imm_expr->X_add_number))
1292 break;
1293 ip->insn_opcode |= ENCODE_RVC_SIMM3 (imm_expr->X_add_number);
1294 goto rvc_imm_done;
1295 case 'j':
1296 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1297 || imm_expr->X_op != O_constant
1298 || imm_expr->X_add_number == 0
1299 || !VALID_RVC_IMM (imm_expr->X_add_number))
1300 break;
1301 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1302 goto rvc_imm_done;
1303 case 'k':
1304 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1305 || imm_expr->X_op != O_constant
1306 || !VALID_RVC_LW_IMM (imm_expr->X_add_number))
1307 break;
1308 ip->insn_opcode |= ENCODE_RVC_LW_IMM (imm_expr->X_add_number);
1309 goto rvc_imm_done;
1310 case 'l':
1311 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1312 || imm_expr->X_op != O_constant
1313 || !VALID_RVC_LD_IMM (imm_expr->X_add_number))
1314 break;
1315 ip->insn_opcode |= ENCODE_RVC_LD_IMM (imm_expr->X_add_number);
1316 goto rvc_imm_done;
1317 case 'm':
1318 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1319 || imm_expr->X_op != O_constant
1320 || !VALID_RVC_LWSP_IMM (imm_expr->X_add_number))
1321 break;
1322 ip->insn_opcode |=
1323 ENCODE_RVC_LWSP_IMM (imm_expr->X_add_number);
1324 goto rvc_imm_done;
1325 case 'n':
1326 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1327 || imm_expr->X_op != O_constant
1328 || !VALID_RVC_LDSP_IMM (imm_expr->X_add_number))
1329 break;
1330 ip->insn_opcode |=
1331 ENCODE_RVC_LDSP_IMM (imm_expr->X_add_number);
1332 goto rvc_imm_done;
1333 case 'K':
1334 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1335 || imm_expr->X_op != O_constant
1336 || !VALID_RVC_ADDI4SPN_IMM (imm_expr->X_add_number)
1337 || imm_expr->X_add_number == 0)
1338 break;
1339 ip->insn_opcode |=
1340 ENCODE_RVC_ADDI4SPN_IMM (imm_expr->X_add_number);
1341 goto rvc_imm_done;
1342 case 'L':
1343 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1344 || imm_expr->X_op != O_constant
1345 || !VALID_RVC_ADDI16SP_IMM (imm_expr->X_add_number)
1346 || imm_expr->X_add_number == 0)
1347 break;
1348 ip->insn_opcode |=
1349 ENCODE_RVC_ADDI16SP_IMM (imm_expr->X_add_number);
1350 goto rvc_imm_done;
1351 case 'M':
1352 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1353 || imm_expr->X_op != O_constant
1354 || !VALID_RVC_SWSP_IMM (imm_expr->X_add_number))
1355 break;
1356 ip->insn_opcode |=
1357 ENCODE_RVC_SWSP_IMM (imm_expr->X_add_number);
1358 goto rvc_imm_done;
1359 case 'N':
1360 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1361 || imm_expr->X_op != O_constant
1362 || !VALID_RVC_SDSP_IMM (imm_expr->X_add_number))
1363 break;
1364 ip->insn_opcode |=
1365 ENCODE_RVC_SDSP_IMM (imm_expr->X_add_number);
1366 goto rvc_imm_done;
1367 case 'u':
1368 p = percent_op_utype;
1369 if (my_getSmallExpression (imm_expr, imm_reloc, s, p))
1370 break;
1371 rvc_lui:
1372 if (imm_expr->X_op != O_constant
1373 || imm_expr->X_add_number <= 0
1374 || imm_expr->X_add_number >= RISCV_BIGIMM_REACH
1375 || (imm_expr->X_add_number >= RISCV_RVC_IMM_REACH / 2
1376 && (imm_expr->X_add_number <
1377 RISCV_BIGIMM_REACH - RISCV_RVC_IMM_REACH / 2)))
1378 break;
1379 ip->insn_opcode |= ENCODE_RVC_IMM (imm_expr->X_add_number);
1380 goto rvc_imm_done;
1381 case 'v':
1382 if (my_getSmallExpression (imm_expr, imm_reloc, s, p)
1383 || (imm_expr->X_add_number & (RISCV_IMM_REACH - 1))
1384 || ((int32_t)imm_expr->X_add_number
1385 != imm_expr->X_add_number))
1386 break;
1387 imm_expr->X_add_number =
1388 ((uint32_t) imm_expr->X_add_number) >> RISCV_IMM_BITS;
1389 goto rvc_lui;
1390 case 'p':
1391 goto branch;
1392 case 'a':
1393 goto jump;
1394 case 'D': /* Floating-point RS2 x8-x15. */
1395 if (!reg_lookup (&s, RCLASS_FPR, &regno)
1396 || !(regno >= 8 && regno <= 15))
1397 break;
1398 INSERT_OPERAND (CRS2S, *ip, regno % 8);
1399 continue;
1400 case 'T': /* Floating-point RS2. */
1401 if (!reg_lookup (&s, RCLASS_FPR, &regno))
1402 break;
1403 INSERT_OPERAND (CRS2, *ip, regno);
1404 continue;
1405 default:
1406 as_bad (_("bad RVC field specifier 'C%c'\n"), *args);
1407 }
1408 break;
1409
1410 case ',':
1411 ++argnum;
1412 if (*s++ == *args)
1413 continue;
1414 s--;
1415 break;
1416
1417 case '(':
1418 case ')':
1419 case '[':
1420 case ']':
1421 if (*s++ == *args)
1422 continue;
1423 break;
1424
1425 case '<': /* Shift amount, 0 - 31. */
1426 my_getExpression (imm_expr, s);
1427 check_absolute_expr (ip, imm_expr);
1428 if ((unsigned long) imm_expr->X_add_number > 31)
1429 as_warn (_("Improper shift amount (%lu)"),
1430 (unsigned long) imm_expr->X_add_number);
1431 INSERT_OPERAND (SHAMTW, *ip, imm_expr->X_add_number);
1432 imm_expr->X_op = O_absent;
1433 s = expr_end;
1434 continue;
1435
1436 case '>': /* Shift amount, 0 - (XLEN-1). */
1437 my_getExpression (imm_expr, s);
1438 check_absolute_expr (ip, imm_expr);
1439 if ((unsigned long) imm_expr->X_add_number >= xlen)
1440 as_warn (_("Improper shift amount (%lu)"),
1441 (unsigned long) imm_expr->X_add_number);
1442 INSERT_OPERAND (SHAMT, *ip, imm_expr->X_add_number);
1443 imm_expr->X_op = O_absent;
1444 s = expr_end;
1445 continue;
1446
1447 case 'Z': /* CSRRxI immediate. */
1448 my_getExpression (imm_expr, s);
1449 check_absolute_expr (ip, imm_expr);
1450 if ((unsigned long) imm_expr->X_add_number > 31)
1451 as_warn (_("Improper CSRxI immediate (%lu)"),
1452 (unsigned long) imm_expr->X_add_number);
1453 INSERT_OPERAND (RS1, *ip, imm_expr->X_add_number);
1454 imm_expr->X_op = O_absent;
1455 s = expr_end;
1456 continue;
1457
1458 case 'E': /* Control register. */
1459 if (reg_lookup (&s, RCLASS_CSR, &regno))
1460 INSERT_OPERAND (CSR, *ip, regno);
1461 else
1462 {
1463 my_getExpression (imm_expr, s);
1464 check_absolute_expr (ip, imm_expr);
1465 if ((unsigned long) imm_expr->X_add_number > 0xfff)
1466 as_warn (_("Improper CSR address (%lu)"),
1467 (unsigned long) imm_expr->X_add_number);
1468 INSERT_OPERAND (CSR, *ip, imm_expr->X_add_number);
1469 imm_expr->X_op = O_absent;
1470 s = expr_end;
1471 }
1472 continue;
1473
1474 case 'm': /* Rounding mode. */
1475 if (arg_lookup (&s, riscv_rm, ARRAY_SIZE (riscv_rm), &regno))
1476 {
1477 INSERT_OPERAND (RM, *ip, regno);
1478 continue;
1479 }
1480 break;
1481
1482 case 'P':
1483 case 'Q': /* Fence predecessor/successor. */
1484 if (arg_lookup (&s, riscv_pred_succ, ARRAY_SIZE (riscv_pred_succ),
1485 &regno))
1486 {
1487 if (*args == 'P')
1488 INSERT_OPERAND (PRED, *ip, regno);
1489 else
1490 INSERT_OPERAND (SUCC, *ip, regno);
1491 continue;
1492 }
1493 break;
1494
1495 case 'd': /* Destination register. */
1496 case 's': /* Source register. */
1497 case 't': /* Target register. */
1498 if (reg_lookup (&s, RCLASS_GPR, &regno))
1499 {
1500 c = *args;
1501 if (*s == ' ')
1502 ++s;
1503
1504 /* Now that we have assembled one operand, we use the args
1505 string to figure out where it goes in the instruction. */
1506 switch (c)
1507 {
1508 case 's':
1509 INSERT_OPERAND (RS1, *ip, regno);
1510 break;
1511 case 'd':
1512 INSERT_OPERAND (RD, *ip, regno);
1513 break;
1514 case 't':
1515 INSERT_OPERAND (RS2, *ip, regno);
1516 break;
1517 }
1518 continue;
1519 }
1520 break;
1521
1522 case 'D': /* Floating point rd. */
1523 case 'S': /* Floating point rs1. */
1524 case 'T': /* Floating point rs2. */
1525 case 'U': /* Floating point rs1 and rs2. */
1526 case 'R': /* Floating point rs3. */
1527 if (reg_lookup (&s, RCLASS_FPR, &regno))
1528 {
1529 c = *args;
1530 if (*s == ' ')
1531 ++s;
1532 switch (c)
1533 {
1534 case 'D':
1535 INSERT_OPERAND (RD, *ip, regno);
1536 break;
1537 case 'S':
1538 INSERT_OPERAND (RS1, *ip, regno);
1539 break;
1540 case 'U':
1541 INSERT_OPERAND (RS1, *ip, regno);
1542 /* fallthru */
1543 case 'T':
1544 INSERT_OPERAND (RS2, *ip, regno);
1545 break;
1546 case 'R':
1547 INSERT_OPERAND (RS3, *ip, regno);
1548 break;
1549 }
1550 continue;
1551 }
1552
1553 break;
1554
1555 case 'I':
1556 my_getExpression (imm_expr, s);
1557 if (imm_expr->X_op != O_big
1558 && imm_expr->X_op != O_constant)
1559 break;
1560 normalize_constant_expr (imm_expr);
1561 s = expr_end;
1562 continue;
1563
1564 case 'A':
1565 my_getExpression (imm_expr, s);
1566 normalize_constant_expr (imm_expr);
1567 /* The 'A' format specifier must be a symbol. */
1568 if (imm_expr->X_op != O_symbol)
1569 break;
1570 *imm_reloc = BFD_RELOC_32;
1571 s = expr_end;
1572 continue;
1573
1574 case 'j': /* Sign-extended immediate. */
1575 *imm_reloc = BFD_RELOC_RISCV_LO12_I;
1576 p = percent_op_itype;
1577 goto alu_op;
1578 case 'q': /* Store displacement. */
1579 p = percent_op_stype;
1580 *imm_reloc = BFD_RELOC_RISCV_LO12_S;
1581 goto load_store;
1582 case 'o': /* Load displacement. */
1583 p = percent_op_itype;
1584 *imm_reloc = BFD_RELOC_RISCV_LO12_I;
1585 goto load_store;
1586 case '0': /* AMO "displacement," which must be zero. */
1587 p = percent_op_rtype;
1588 *imm_reloc = BFD_RELOC_UNUSED;
1589 load_store:
1590 /* Check whether there is only a single bracketed expression
1591 left. If so, it must be the base register and the
1592 constant must be zero. */
1593 imm_expr->X_op = O_constant;
1594 imm_expr->X_add_number = 0;
1595 if (*s == '(' && strchr (s + 1, '(') == 0)
1596 continue;
1597 alu_op:
1598 /* If this value won't fit into a 16 bit offset, then go
1599 find a macro that will generate the 32 bit offset
1600 code pattern. */
1601 if (!my_getSmallExpression (imm_expr, imm_reloc, s, p))
1602 {
1603 normalize_constant_expr (imm_expr);
1604 if (imm_expr->X_op != O_constant
1605 || (*args == '0' && imm_expr->X_add_number != 0)
1606 || imm_expr->X_add_number >= (signed)RISCV_IMM_REACH/2
1607 || imm_expr->X_add_number < -(signed)RISCV_IMM_REACH/2)
1608 break;
1609 }
1610
1611 s = expr_end;
1612 continue;
1613
1614 case 'p': /* PC-relative offset. */
1615 branch:
1616 *imm_reloc = BFD_RELOC_12_PCREL;
1617 my_getExpression (imm_expr, s);
1618 s = expr_end;
1619 continue;
1620
1621 case 'u': /* Upper 20 bits. */
1622 p = percent_op_utype;
1623 if (!my_getSmallExpression (imm_expr, imm_reloc, s, p)
1624 && imm_expr->X_op == O_constant)
1625 {
1626 if (imm_expr->X_add_number < 0
1627 || imm_expr->X_add_number >= (signed)RISCV_BIGIMM_REACH)
1628 as_bad (_("lui expression not in range 0..1048575"));
1629
1630 *imm_reloc = BFD_RELOC_RISCV_HI20;
1631 imm_expr->X_add_number <<= RISCV_IMM_BITS;
1632 }
1633 s = expr_end;
1634 continue;
1635
1636 case 'a': /* 20-bit PC-relative offset. */
1637 jump:
1638 my_getExpression (imm_expr, s);
1639 s = expr_end;
1640 *imm_reloc = BFD_RELOC_RISCV_JMP;
1641 continue;
1642
1643 case 'c':
1644 my_getExpression (imm_expr, s);
1645 s = expr_end;
1646 if (strcmp (s, "@plt") == 0)
1647 {
1648 *imm_reloc = BFD_RELOC_RISCV_CALL_PLT;
1649 s += 4;
1650 }
1651 else
1652 *imm_reloc = BFD_RELOC_RISCV_CALL;
1653 continue;
1654
1655 default:
1656 as_fatal (_("internal error: bad argument type %c"), *args);
1657 }
1658 break;
1659 }
1660 s = argsStart;
1661 error = _("illegal operands");
1662 }
1663
1664 out:
1665 /* Restore the character we might have clobbered above. */
1666 if (save_c)
1667 *(argsStart - 1) = save_c;
1668
1669 return error;
1670 }
1671
1672 void
1673 md_assemble (char *str)
1674 {
1675 struct riscv_cl_insn insn;
1676 expressionS imm_expr;
1677 bfd_reloc_code_real_type imm_reloc = BFD_RELOC_UNUSED;
1678
1679 const char *error = riscv_ip (str, &insn, &imm_expr, &imm_reloc);
1680
1681 if (error)
1682 {
1683 as_bad ("%s `%s'", error, str);
1684 return;
1685 }
1686
1687 if (insn.insn_mo->pinfo == INSN_MACRO)
1688 macro (&insn, &imm_expr, &imm_reloc);
1689 else
1690 append_insn (&insn, &imm_expr, imm_reloc);
1691 }
1692
1693 const char *
1694 md_atof (int type, char *litP, int *sizeP)
1695 {
1696 return ieee_md_atof (type, litP, sizeP, TARGET_BYTES_BIG_ENDIAN);
1697 }
1698
1699 void
1700 md_number_to_chars (char *buf, valueT val, int n)
1701 {
1702 number_to_chars_littleendian (buf, val, n);
1703 }
1704
1705 const char *md_shortopts = "O::g::G:";
1706
1707 enum options
1708 {
1709 OPTION_MARCH = OPTION_MD_BASE,
1710 OPTION_PIC,
1711 OPTION_NO_PIC,
1712 OPTION_MABI,
1713 OPTION_END_OF_ENUM
1714 };
1715
1716 struct option md_longopts[] =
1717 {
1718 {"march", required_argument, NULL, OPTION_MARCH},
1719 {"fPIC", no_argument, NULL, OPTION_PIC},
1720 {"fpic", no_argument, NULL, OPTION_PIC},
1721 {"fno-pic", no_argument, NULL, OPTION_NO_PIC},
1722 {"mabi", required_argument, NULL, OPTION_MABI},
1723
1724 {NULL, no_argument, NULL, 0}
1725 };
1726 size_t md_longopts_size = sizeof (md_longopts);
1727
1728 enum float_abi {
1729 FLOAT_ABI_DEFAULT = -1,
1730 FLOAT_ABI_SOFT,
1731 FLOAT_ABI_SINGLE,
1732 FLOAT_ABI_DOUBLE,
1733 FLOAT_ABI_QUAD
1734 };
1735 static enum float_abi float_abi = FLOAT_ABI_DEFAULT;
1736
1737 static void
1738 riscv_set_abi (unsigned new_xlen, enum float_abi new_float_abi)
1739 {
1740 abi_xlen = new_xlen;
1741 float_abi = new_float_abi;
1742 }
1743
1744 int
1745 md_parse_option (int c, const char *arg)
1746 {
1747 switch (c)
1748 {
1749 case OPTION_MARCH:
1750 riscv_set_arch (arg);
1751 break;
1752
1753 case OPTION_NO_PIC:
1754 riscv_opts.pic = FALSE;
1755 break;
1756
1757 case OPTION_PIC:
1758 riscv_opts.pic = TRUE;
1759 break;
1760
1761 case OPTION_MABI:
1762 if (strcmp (arg, "ilp32") == 0)
1763 riscv_set_abi (32, FLOAT_ABI_SOFT);
1764 else if (strcmp (arg, "ilp32f") == 0)
1765 riscv_set_abi (32, FLOAT_ABI_SINGLE);
1766 else if (strcmp (arg, "ilp32d") == 0)
1767 riscv_set_abi (32, FLOAT_ABI_DOUBLE);
1768 else if (strcmp (arg, "ilp32q") == 0)
1769 riscv_set_abi (32, FLOAT_ABI_QUAD);
1770 else if (strcmp (arg, "lp64") == 0)
1771 riscv_set_abi (64, FLOAT_ABI_SOFT);
1772 else if (strcmp (arg, "lp64f") == 0)
1773 riscv_set_abi (64, FLOAT_ABI_SINGLE);
1774 else if (strcmp (arg, "lp64d") == 0)
1775 riscv_set_abi (64, FLOAT_ABI_DOUBLE);
1776 else if (strcmp (arg, "lp64q") == 0)
1777 riscv_set_abi (64, FLOAT_ABI_QUAD);
1778 else
1779 return 0;
1780 break;
1781
1782 default:
1783 return 0;
1784 }
1785
1786 return 1;
1787 }
1788
1789 void
1790 riscv_after_parse_args (void)
1791 {
1792 if (xlen == 0)
1793 {
1794 if (strcmp (default_arch, "riscv32") == 0)
1795 xlen = 32;
1796 else if (strcmp (default_arch, "riscv64") == 0)
1797 xlen = 64;
1798 else
1799 as_bad ("unknown default architecture `%s'", default_arch);
1800 }
1801
1802 if (riscv_subsets == NULL)
1803 riscv_set_arch (xlen == 64 ? "rv64g" : "rv32g");
1804
1805 /* Add the RVC extension, regardless of -march, to support .option rvc. */
1806 if (riscv_subset_supports ("c"))
1807 riscv_set_rvc (TRUE);
1808 else
1809 riscv_add_subset ("c");
1810
1811 /* Infer ABI from ISA if not specified on command line. */
1812 if (abi_xlen == 0)
1813 abi_xlen = xlen;
1814 else if (abi_xlen > xlen)
1815 as_bad ("can't have %d-bit ABI on %d-bit ISA", abi_xlen, xlen);
1816 else if (abi_xlen < xlen)
1817 as_bad ("%d-bit ABI not yet supported on %d-bit ISA", abi_xlen, xlen);
1818
1819 if (float_abi == FLOAT_ABI_DEFAULT)
1820 {
1821 struct riscv_subset *subset;
1822
1823 /* Assume soft-float unless D extension is present. */
1824 float_abi = FLOAT_ABI_SOFT;
1825
1826 for (subset = riscv_subsets; subset != NULL; subset = subset->next)
1827 {
1828 if (strcasecmp (subset->name, "D") == 0)
1829 float_abi = FLOAT_ABI_DOUBLE;
1830 if (strcasecmp (subset->name, "Q") == 0)
1831 float_abi = FLOAT_ABI_QUAD;
1832 }
1833 }
1834
1835 /* Insert float_abi into the EF_RISCV_FLOAT_ABI field of elf_flags. */
1836 elf_flags |= float_abi * (EF_RISCV_FLOAT_ABI & ~(EF_RISCV_FLOAT_ABI << 1));
1837 }
1838
1839 long
1840 md_pcrel_from (fixS *fixP)
1841 {
1842 return fixP->fx_where + fixP->fx_frag->fr_address;
1843 }
1844
1845 /* Apply a fixup to the object file. */
1846
1847 void
1848 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
1849 {
1850 unsigned int subtype;
1851 bfd_byte *buf = (bfd_byte *) (fixP->fx_frag->fr_literal + fixP->fx_where);
1852 bfd_boolean relaxable = FALSE;
1853
1854 /* Remember value for tc_gen_reloc. */
1855 fixP->fx_addnumber = *valP;
1856
1857 switch (fixP->fx_r_type)
1858 {
1859 case BFD_RELOC_RISCV_HI20:
1860 case BFD_RELOC_RISCV_LO12_I:
1861 case BFD_RELOC_RISCV_LO12_S:
1862 bfd_putl32 (riscv_apply_const_reloc (fixP->fx_r_type, *valP)
1863 | bfd_getl32 (buf), buf);
1864 relaxable = TRUE;
1865 break;
1866
1867 case BFD_RELOC_RISCV_GOT_HI20:
1868 case BFD_RELOC_RISCV_PCREL_HI20:
1869 case BFD_RELOC_RISCV_ADD8:
1870 case BFD_RELOC_RISCV_ADD16:
1871 case BFD_RELOC_RISCV_ADD32:
1872 case BFD_RELOC_RISCV_ADD64:
1873 case BFD_RELOC_RISCV_SUB6:
1874 case BFD_RELOC_RISCV_SUB8:
1875 case BFD_RELOC_RISCV_SUB16:
1876 case BFD_RELOC_RISCV_SUB32:
1877 case BFD_RELOC_RISCV_SUB64:
1878 case BFD_RELOC_RISCV_RELAX:
1879 break;
1880
1881 case BFD_RELOC_RISCV_TPREL_HI20:
1882 case BFD_RELOC_RISCV_TPREL_LO12_I:
1883 case BFD_RELOC_RISCV_TPREL_LO12_S:
1884 case BFD_RELOC_RISCV_TPREL_ADD:
1885 relaxable = TRUE;
1886 /* Fall through. */
1887
1888 case BFD_RELOC_RISCV_TLS_GOT_HI20:
1889 case BFD_RELOC_RISCV_TLS_GD_HI20:
1890 case BFD_RELOC_RISCV_TLS_DTPREL32:
1891 case BFD_RELOC_RISCV_TLS_DTPREL64:
1892 if (fixP->fx_addsy != NULL)
1893 S_SET_THREAD_LOCAL (fixP->fx_addsy);
1894 else
1895 as_bad_where (fixP->fx_file, fixP->fx_line,
1896 _("TLS relocation against a constant"));
1897 break;
1898
1899 case BFD_RELOC_64:
1900 case BFD_RELOC_32:
1901 case BFD_RELOC_16:
1902 case BFD_RELOC_8:
1903 case BFD_RELOC_RISCV_CFA:
1904 if (fixP->fx_addsy && fixP->fx_subsy)
1905 {
1906 fixP->fx_next = xmemdup (fixP, sizeof (*fixP), sizeof (*fixP));
1907 fixP->fx_next->fx_addsy = fixP->fx_subsy;
1908 fixP->fx_next->fx_subsy = NULL;
1909 fixP->fx_next->fx_offset = 0;
1910 fixP->fx_subsy = NULL;
1911
1912 switch (fixP->fx_r_type)
1913 {
1914 case BFD_RELOC_64:
1915 fixP->fx_r_type = BFD_RELOC_RISCV_ADD64;
1916 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB64;
1917 break;
1918
1919 case BFD_RELOC_32:
1920 fixP->fx_r_type = BFD_RELOC_RISCV_ADD32;
1921 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB32;
1922 break;
1923
1924 case BFD_RELOC_16:
1925 fixP->fx_r_type = BFD_RELOC_RISCV_ADD16;
1926 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB16;
1927 break;
1928
1929 case BFD_RELOC_8:
1930 fixP->fx_r_type = BFD_RELOC_RISCV_ADD8;
1931 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB8;
1932 break;
1933
1934 case BFD_RELOC_RISCV_CFA:
1935 /* Load the byte to get the subtype. */
1936 subtype = bfd_get_8 (NULL, &fixP->fx_frag->fr_literal[fixP->fx_where]);
1937 switch (subtype)
1938 {
1939 case DW_CFA_advance_loc1:
1940 fixP->fx_where++;
1941 fixP->fx_next->fx_where++;
1942 fixP->fx_r_type = BFD_RELOC_RISCV_SET8;
1943 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB8;
1944 break;
1945
1946 case DW_CFA_advance_loc2:
1947 fixP->fx_size = 2;
1948 fixP->fx_where++;
1949 fixP->fx_next->fx_size = 2;
1950 fixP->fx_next->fx_where++;
1951 fixP->fx_r_type = BFD_RELOC_RISCV_SET16;
1952 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB16;
1953 break;
1954
1955 case DW_CFA_advance_loc4:
1956 fixP->fx_size = 4;
1957 fixP->fx_where++;
1958 fixP->fx_next->fx_size = 4;
1959 fixP->fx_next->fx_where++;
1960 fixP->fx_r_type = BFD_RELOC_RISCV_SET32;
1961 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB32;
1962 break;
1963
1964 default:
1965 if (subtype < 0x80 && (subtype & 0x40))
1966 {
1967 /* DW_CFA_advance_loc */
1968 fixP->fx_r_type = BFD_RELOC_RISCV_SET6;
1969 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_SUB6;
1970 }
1971 else
1972 as_fatal (_("internal error: bad CFA value #%d"), subtype);
1973 break;
1974 }
1975 break;
1976
1977 default:
1978 /* This case is unreachable. */
1979 abort ();
1980 }
1981 }
1982 /* Fall through. */
1983
1984 case BFD_RELOC_RVA:
1985 /* If we are deleting this reloc entry, we must fill in the
1986 value now. This can happen if we have a .word which is not
1987 resolved when it appears but is later defined. */
1988 if (fixP->fx_addsy == NULL)
1989 {
1990 gas_assert (fixP->fx_size <= sizeof (valueT));
1991 md_number_to_chars ((char *) buf, *valP, fixP->fx_size);
1992 fixP->fx_done = 1;
1993 }
1994 break;
1995
1996 case BFD_RELOC_RISCV_JMP:
1997 if (fixP->fx_addsy)
1998 {
1999 /* Fill in a tentative value to improve objdump readability. */
2000 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
2001 bfd_vma delta = target - md_pcrel_from (fixP);
2002 bfd_putl32 (bfd_getl32 (buf) | ENCODE_UJTYPE_IMM (delta), buf);
2003 }
2004 break;
2005
2006 case BFD_RELOC_12_PCREL:
2007 if (fixP->fx_addsy)
2008 {
2009 /* Fill in a tentative value to improve objdump readability. */
2010 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
2011 bfd_vma delta = target - md_pcrel_from (fixP);
2012 bfd_putl32 (bfd_getl32 (buf) | ENCODE_SBTYPE_IMM (delta), buf);
2013 }
2014 break;
2015
2016 case BFD_RELOC_RISCV_RVC_BRANCH:
2017 if (fixP->fx_addsy)
2018 {
2019 /* Fill in a tentative value to improve objdump readability. */
2020 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
2021 bfd_vma delta = target - md_pcrel_from (fixP);
2022 bfd_putl16 (bfd_getl16 (buf) | ENCODE_RVC_B_IMM (delta), buf);
2023 }
2024 break;
2025
2026 case BFD_RELOC_RISCV_RVC_JUMP:
2027 if (fixP->fx_addsy)
2028 {
2029 /* Fill in a tentative value to improve objdump readability. */
2030 bfd_vma target = S_GET_VALUE (fixP->fx_addsy) + *valP;
2031 bfd_vma delta = target - md_pcrel_from (fixP);
2032 bfd_putl16 (bfd_getl16 (buf) | ENCODE_RVC_J_IMM (delta), buf);
2033 }
2034 break;
2035
2036 case BFD_RELOC_RISCV_CALL:
2037 case BFD_RELOC_RISCV_CALL_PLT:
2038 relaxable = TRUE;
2039 break;
2040
2041 case BFD_RELOC_RISCV_PCREL_LO12_S:
2042 case BFD_RELOC_RISCV_PCREL_LO12_I:
2043 case BFD_RELOC_RISCV_ALIGN:
2044 break;
2045
2046 default:
2047 /* We ignore generic BFD relocations we don't know about. */
2048 if (bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type) != NULL)
2049 as_fatal (_("internal error: bad relocation #%d"), fixP->fx_r_type);
2050 }
2051
2052 if (fixP->fx_subsy != NULL)
2053 as_bad_where (fixP->fx_file, fixP->fx_line,
2054 _("unsupported symbol subtraction"));
2055
2056 /* Add an R_RISCV_RELAX reloc if the reloc is relaxable. */
2057 if (relaxable && fixP->fx_tcbit && fixP->fx_addsy != NULL)
2058 {
2059 fixP->fx_next = xmemdup (fixP, sizeof (*fixP), sizeof (*fixP));
2060 fixP->fx_next->fx_addsy = fixP->fx_next->fx_subsy = NULL;
2061 fixP->fx_next->fx_r_type = BFD_RELOC_RISCV_RELAX;
2062 }
2063 }
2064
2065 /* Because the value of .cfi_remember_state may changed after relaxation,
2066 we insert a fix to relocate it again in link-time. */
2067
2068 void
2069 riscv_pre_output_hook (void)
2070 {
2071 const frchainS *frch;
2072 const asection *s;
2073
2074 for (s = stdoutput->sections; s; s = s->next)
2075 for (frch = seg_info (s)->frchainP; frch; frch = frch->frch_next)
2076 {
2077 const fragS *frag;
2078
2079 for (frag = frch->frch_root; frag; frag = frag->fr_next)
2080 {
2081 if (frag->fr_type == rs_cfa)
2082 {
2083 fragS *loc4_frag;
2084 expressionS exp;
2085
2086 symbolS *add_symbol = frag->fr_symbol->sy_value.X_add_symbol;
2087 symbolS *op_symbol = frag->fr_symbol->sy_value.X_op_symbol;
2088
2089 exp.X_op = O_subtract;
2090 exp.X_add_symbol = add_symbol;
2091 exp.X_add_number = 0;
2092 exp.X_op_symbol = op_symbol;
2093
2094 loc4_frag = (fragS *) frag->fr_opcode;
2095 fix_new_exp (loc4_frag, (int) frag->fr_offset, 1, &exp, 0,
2096 BFD_RELOC_RISCV_CFA);
2097 }
2098 }
2099 }
2100 }
2101
2102
2103 /* This structure is used to hold a stack of .option values. */
2104
2105 struct riscv_option_stack
2106 {
2107 struct riscv_option_stack *next;
2108 struct riscv_set_options options;
2109 };
2110
2111 static struct riscv_option_stack *riscv_opts_stack;
2112
2113 /* Handle the .option pseudo-op. */
2114
2115 static void
2116 s_riscv_option (int x ATTRIBUTE_UNUSED)
2117 {
2118 char *name = input_line_pointer, ch;
2119
2120 while (!is_end_of_line[(unsigned char) *input_line_pointer])
2121 ++input_line_pointer;
2122 ch = *input_line_pointer;
2123 *input_line_pointer = '\0';
2124
2125 if (strcmp (name, "rvc") == 0)
2126 riscv_set_rvc (TRUE);
2127 else if (strcmp (name, "norvc") == 0)
2128 riscv_set_rvc (FALSE);
2129 else if (strcmp (name, "pic") == 0)
2130 riscv_opts.pic = TRUE;
2131 else if (strcmp (name, "nopic") == 0)
2132 riscv_opts.pic = FALSE;
2133 else if (strcmp (name, "relax") == 0)
2134 riscv_opts.relax = TRUE;
2135 else if (strcmp (name, "norelax") == 0)
2136 riscv_opts.relax = FALSE;
2137 else if (strcmp (name, "push") == 0)
2138 {
2139 struct riscv_option_stack *s;
2140
2141 s = (struct riscv_option_stack *) xmalloc (sizeof *s);
2142 s->next = riscv_opts_stack;
2143 s->options = riscv_opts;
2144 riscv_opts_stack = s;
2145 }
2146 else if (strcmp (name, "pop") == 0)
2147 {
2148 struct riscv_option_stack *s;
2149
2150 s = riscv_opts_stack;
2151 if (s == NULL)
2152 as_bad (_(".option pop with no .option push"));
2153 else
2154 {
2155 riscv_opts = s->options;
2156 riscv_opts_stack = s->next;
2157 free (s);
2158 }
2159 }
2160 else
2161 {
2162 as_warn (_("Unrecognized .option directive: %s\n"), name);
2163 }
2164 *input_line_pointer = ch;
2165 demand_empty_rest_of_line ();
2166 }
2167
2168 /* Handle the .dtprelword and .dtpreldword pseudo-ops. They generate
2169 a 32-bit or 64-bit DTP-relative relocation (BYTES says which) for
2170 use in DWARF debug information. */
2171
2172 static void
2173 s_dtprel (int bytes)
2174 {
2175 expressionS ex;
2176 char *p;
2177
2178 expression (&ex);
2179
2180 if (ex.X_op != O_symbol)
2181 {
2182 as_bad (_("Unsupported use of %s"), (bytes == 8
2183 ? ".dtpreldword"
2184 : ".dtprelword"));
2185 ignore_rest_of_line ();
2186 }
2187
2188 p = frag_more (bytes);
2189 md_number_to_chars (p, 0, bytes);
2190 fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE,
2191 (bytes == 8
2192 ? BFD_RELOC_RISCV_TLS_DTPREL64
2193 : BFD_RELOC_RISCV_TLS_DTPREL32));
2194
2195 demand_empty_rest_of_line ();
2196 }
2197
2198 /* Handle the .bss pseudo-op. */
2199
2200 static void
2201 s_bss (int ignore ATTRIBUTE_UNUSED)
2202 {
2203 subseg_set (bss_section, 0);
2204 demand_empty_rest_of_line ();
2205 }
2206
2207 static void
2208 riscv_make_nops (char *buf, bfd_vma bytes)
2209 {
2210 bfd_vma i = 0;
2211
2212 /* RISC-V instructions cannot begin or end on odd addresses, so this case
2213 means we are not within a valid instruction sequence. It is thus safe
2214 to use a zero byte, even though that is not a valid instruction. */
2215 if (bytes % 2 == 1)
2216 buf[i++] = 0;
2217
2218 /* Use at most one 2-byte NOP. */
2219 if ((bytes - i) % 4 == 2)
2220 {
2221 md_number_to_chars (buf + i, RVC_NOP, 2);
2222 i += 2;
2223 }
2224
2225 /* Fill the remainder with 4-byte NOPs. */
2226 for ( ; i < bytes; i += 4)
2227 md_number_to_chars (buf + i, RISCV_NOP, 4);
2228 }
2229
2230 /* Called from md_do_align. Used to create an alignment frag in a
2231 code section by emitting a worst-case NOP sequence that the linker
2232 will later relax to the correct number of NOPs. We can't compute
2233 the correct alignment now because of other linker relaxations. */
2234
2235 bfd_boolean
2236 riscv_frag_align_code (int n)
2237 {
2238 bfd_vma bytes = (bfd_vma) 1 << n;
2239 bfd_vma min_text_alignment_order = riscv_opts.rvc ? 1 : 2;
2240 bfd_vma min_text_alignment = (bfd_vma) 1 << min_text_alignment_order;
2241
2242 /* First, get back to minimal alignment. */
2243 frag_align_code (min_text_alignment_order, 0);
2244
2245 /* When not relaxing, riscv_handle_align handles code alignment. */
2246 if (!riscv_opts.relax)
2247 return FALSE;
2248
2249 if (bytes > min_text_alignment)
2250 {
2251 bfd_vma worst_case_bytes = bytes - min_text_alignment;
2252 char *nops = frag_more (worst_case_bytes);
2253 expressionS ex;
2254
2255 ex.X_op = O_constant;
2256 ex.X_add_number = worst_case_bytes;
2257
2258 riscv_make_nops (nops, worst_case_bytes);
2259
2260 fix_new_exp (frag_now, nops - frag_now->fr_literal, 0,
2261 &ex, FALSE, BFD_RELOC_RISCV_ALIGN);
2262 }
2263
2264 return TRUE;
2265 }
2266
2267 /* Implement HANDLE_ALIGN. */
2268
2269 void
2270 riscv_handle_align (fragS *fragP)
2271 {
2272 switch (fragP->fr_type)
2273 {
2274 case rs_align_code:
2275 /* When relaxing, riscv_frag_align_code handles code alignment. */
2276 if (!riscv_opts.relax)
2277 {
2278 bfd_signed_vma count = fragP->fr_next->fr_address
2279 - fragP->fr_address - fragP->fr_fix;
2280
2281 if (count <= 0)
2282 break;
2283
2284 count &= MAX_MEM_FOR_RS_ALIGN_CODE;
2285 riscv_make_nops (fragP->fr_literal + fragP->fr_fix, count);
2286 fragP->fr_var = count;
2287 }
2288 break;
2289
2290 default:
2291 break;
2292 }
2293 }
2294
2295 int
2296 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
2297 {
2298 return (fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE));
2299 }
2300
2301 /* Translate internal representation of relocation info to BFD target
2302 format. */
2303
2304 arelent *
2305 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
2306 {
2307 arelent *reloc = (arelent *) xmalloc (sizeof (arelent));
2308
2309 reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
2310 *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
2311 reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
2312 reloc->addend = fixp->fx_addnumber;
2313
2314 reloc->howto = bfd_reloc_type_lookup (stdoutput, fixp->fx_r_type);
2315 if (reloc->howto == NULL)
2316 {
2317 if ((fixp->fx_r_type == BFD_RELOC_16 || fixp->fx_r_type == BFD_RELOC_8)
2318 && fixp->fx_addsy != NULL && fixp->fx_subsy != NULL)
2319 {
2320 /* We don't have R_RISCV_8/16, but for this special case,
2321 we can use R_RISCV_ADD8/16 with R_RISCV_SUB8/16. */
2322 return reloc;
2323 }
2324
2325 as_bad_where (fixp->fx_file, fixp->fx_line,
2326 _("cannot represent %s relocation in object file"),
2327 bfd_get_reloc_code_name (fixp->fx_r_type));
2328 return NULL;
2329 }
2330
2331 return reloc;
2332 }
2333
2334 int
2335 riscv_relax_frag (asection *sec, fragS *fragp, long stretch ATTRIBUTE_UNUSED)
2336 {
2337 if (RELAX_BRANCH_P (fragp->fr_subtype))
2338 {
2339 offsetT old_var = fragp->fr_var;
2340 fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
2341 return fragp->fr_var - old_var;
2342 }
2343
2344 return 0;
2345 }
2346
2347 /* Expand far branches to multi-instruction sequences. */
2348
2349 static void
2350 md_convert_frag_branch (fragS *fragp)
2351 {
2352 bfd_byte *buf;
2353 expressionS exp;
2354 fixS *fixp;
2355 insn_t insn;
2356 int rs1, reloc;
2357
2358 buf = (bfd_byte *)fragp->fr_literal + fragp->fr_fix;
2359
2360 exp.X_op = O_symbol;
2361 exp.X_add_symbol = fragp->fr_symbol;
2362 exp.X_add_number = fragp->fr_offset;
2363
2364 gas_assert (fragp->fr_var == RELAX_BRANCH_LENGTH (fragp->fr_subtype));
2365
2366 if (RELAX_BRANCH_RVC (fragp->fr_subtype))
2367 {
2368 switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
2369 {
2370 case 8:
2371 case 4:
2372 /* Expand the RVC branch into a RISC-V one. */
2373 insn = bfd_getl16 (buf);
2374 rs1 = 8 + ((insn >> OP_SH_CRS1S) & OP_MASK_CRS1S);
2375 if ((insn & MASK_C_J) == MATCH_C_J)
2376 insn = MATCH_JAL;
2377 else if ((insn & MASK_C_JAL) == MATCH_C_JAL)
2378 insn = MATCH_JAL | (X_RA << OP_SH_RD);
2379 else if ((insn & MASK_C_BEQZ) == MATCH_C_BEQZ)
2380 insn = MATCH_BEQ | (rs1 << OP_SH_RS1);
2381 else if ((insn & MASK_C_BNEZ) == MATCH_C_BNEZ)
2382 insn = MATCH_BNE | (rs1 << OP_SH_RS1);
2383 else
2384 abort ();
2385 bfd_putl32 (insn, buf);
2386 break;
2387
2388 case 6:
2389 /* Invert the branch condition. Branch over the jump. */
2390 insn = bfd_getl16 (buf);
2391 insn ^= MATCH_C_BEQZ ^ MATCH_C_BNEZ;
2392 insn |= ENCODE_RVC_B_IMM (6);
2393 bfd_putl16 (insn, buf);
2394 buf += 2;
2395 goto jump;
2396
2397 case 2:
2398 /* Just keep the RVC branch. */
2399 reloc = RELAX_BRANCH_UNCOND (fragp->fr_subtype)
2400 ? BFD_RELOC_RISCV_RVC_JUMP : BFD_RELOC_RISCV_RVC_BRANCH;
2401 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
2402 2, &exp, FALSE, reloc);
2403 buf += 2;
2404 goto done;
2405
2406 default:
2407 abort ();
2408 }
2409 }
2410
2411 switch (RELAX_BRANCH_LENGTH (fragp->fr_subtype))
2412 {
2413 case 8:
2414 gas_assert (!RELAX_BRANCH_UNCOND (fragp->fr_subtype));
2415
2416 /* Invert the branch condition. Branch over the jump. */
2417 insn = bfd_getl32 (buf);
2418 insn ^= MATCH_BEQ ^ MATCH_BNE;
2419 insn |= ENCODE_SBTYPE_IMM (8);
2420 md_number_to_chars ((char *) buf, insn, 4);
2421 buf += 4;
2422
2423 jump:
2424 /* Jump to the target. */
2425 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
2426 4, &exp, FALSE, BFD_RELOC_RISCV_JMP);
2427 md_number_to_chars ((char *) buf, MATCH_JAL, 4);
2428 buf += 4;
2429 break;
2430
2431 case 4:
2432 reloc = RELAX_BRANCH_UNCOND (fragp->fr_subtype)
2433 ? BFD_RELOC_RISCV_JMP : BFD_RELOC_12_PCREL;
2434 fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
2435 4, &exp, FALSE, reloc);
2436 buf += 4;
2437 break;
2438
2439 default:
2440 abort ();
2441 }
2442
2443 done:
2444 fixp->fx_file = fragp->fr_file;
2445 fixp->fx_line = fragp->fr_line;
2446
2447 gas_assert (buf == (bfd_byte *)fragp->fr_literal
2448 + fragp->fr_fix + fragp->fr_var);
2449
2450 fragp->fr_fix += fragp->fr_var;
2451 }
2452
2453 /* Relax a machine dependent frag. This returns the amount by which
2454 the current size of the frag should change. */
2455
2456 void
2457 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec ATTRIBUTE_UNUSED,
2458 fragS *fragp)
2459 {
2460 gas_assert (RELAX_BRANCH_P (fragp->fr_subtype));
2461 md_convert_frag_branch (fragp);
2462 }
2463
2464 void
2465 md_show_usage (FILE *stream)
2466 {
2467 fprintf (stream, _("\
2468 RISC-V options:\n\
2469 -m32 assemble RV32 code\n\
2470 -m64 assemble RV64 code (default)\n\
2471 -fpic generate position-independent code\n\
2472 -fno-pic don't generate position-independent code (default)\n\
2473 -msoft-float don't use F registers for floating-point values\n\
2474 -mhard-float use F registers for floating-point values (default)\n\
2475 -mno-rvc disable the C extension for compressed instructions (default)\n\
2476 -mrvc enable the C extension for compressed instructions\n\
2477 -march=ISA set the RISC-V architecture, RV64IMAFD by default\n\
2478 "));
2479 }
2480
2481 /* Standard calling conventions leave the CFA at SP on entry. */
2482 void
2483 riscv_cfi_frame_initial_instructions (void)
2484 {
2485 cfi_add_CFA_def_cfa_register (X_SP);
2486 }
2487
2488 int
2489 tc_riscv_regname_to_dw2regnum (char *regname)
2490 {
2491 int reg;
2492
2493 if ((reg = reg_lookup_internal (regname, RCLASS_GPR)) >= 0)
2494 return reg;
2495
2496 if ((reg = reg_lookup_internal (regname, RCLASS_FPR)) >= 0)
2497 return reg + 32;
2498
2499 as_bad (_("unknown register `%s'"), regname);
2500 return -1;
2501 }
2502
2503 void
2504 riscv_elf_final_processing (void)
2505 {
2506 elf_elfheader (stdoutput)->e_flags |= elf_flags;
2507 }
2508
2509 /* Parse the .sleb128 and .uleb128 pseudos. Only allow constant expressions,
2510 since these directives break relaxation when used with symbol deltas. */
2511
2512 static void
2513 s_riscv_leb128 (int sign)
2514 {
2515 expressionS exp;
2516 char *save_in = input_line_pointer;
2517
2518 expression (&exp);
2519 if (exp.X_op != O_constant)
2520 as_bad (_("non-constant .%cleb128 is not supported"), sign ? 's' : 'u');
2521 demand_empty_rest_of_line ();
2522
2523 input_line_pointer = save_in;
2524 return s_leb128 (sign);
2525 }
2526
2527 /* Pseudo-op table. */
2528
2529 static const pseudo_typeS riscv_pseudo_table[] =
2530 {
2531 /* RISC-V-specific pseudo-ops. */
2532 {"option", s_riscv_option, 0},
2533 {"half", cons, 2},
2534 {"word", cons, 4},
2535 {"dword", cons, 8},
2536 {"dtprelword", s_dtprel, 4},
2537 {"dtpreldword", s_dtprel, 8},
2538 {"bss", s_bss, 0},
2539 {"uleb128", s_riscv_leb128, 0},
2540 {"sleb128", s_riscv_leb128, 1},
2541
2542 { NULL, NULL, 0 },
2543 };
2544
2545 void
2546 riscv_pop_insert (void)
2547 {
2548 extern void pop_insert (const pseudo_typeS *);
2549
2550 pop_insert (riscv_pseudo_table);
2551 }
This page took 0.082381 seconds and 4 git commands to generate.