RISC-V: Add RV32E support.
[official-gcc.git] / gcc / config / riscv / riscv.c
blob9a9d9e1befe8f927716df8202a152323779a851d
1 /* Subroutines used for code generation for RISC-V.
2 Copyright (C) 2011-2018 Free Software Foundation, Inc.
3 Contributed by Andrew Waterman (andrew@sifive.com).
4 Based on MIPS target for GNU compiler.
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
22 #define IN_TARGET_CODE 1
24 #include "config.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "tm.h"
28 #include "rtl.h"
29 #include "regs.h"
30 #include "insn-config.h"
31 #include "insn-attr.h"
32 #include "recog.h"
33 #include "output.h"
34 #include "alias.h"
35 #include "tree.h"
36 #include "stringpool.h"
37 #include "attribs.h"
38 #include "varasm.h"
39 #include "stor-layout.h"
40 #include "calls.h"
41 #include "function.h"
42 #include "explow.h"
43 #include "memmodel.h"
44 #include "emit-rtl.h"
45 #include "reload.h"
46 #include "tm_p.h"
47 #include "target.h"
48 #include "target-def.h"
49 #include "basic-block.h"
50 #include "expr.h"
51 #include "optabs.h"
52 #include "bitmap.h"
53 #include "df.h"
54 #include "diagnostic.h"
55 #include "builtins.h"
56 #include "predict.h"
58 /* True if X is an UNSPEC wrapper around a SYMBOL_REF or LABEL_REF. */
59 #define UNSPEC_ADDRESS_P(X) \
60 (GET_CODE (X) == UNSPEC \
61 && XINT (X, 1) >= UNSPEC_ADDRESS_FIRST \
62 && XINT (X, 1) < UNSPEC_ADDRESS_FIRST + NUM_SYMBOL_TYPES)
64 /* Extract the symbol or label from UNSPEC wrapper X. */
65 #define UNSPEC_ADDRESS(X) \
66 XVECEXP (X, 0, 0)
68 /* Extract the symbol type from UNSPEC wrapper X. */
69 #define UNSPEC_ADDRESS_TYPE(X) \
70 ((enum riscv_symbol_type) (XINT (X, 1) - UNSPEC_ADDRESS_FIRST))
72 /* True if bit BIT is set in VALUE. */
73 #define BITSET_P(VALUE, BIT) (((VALUE) & (1ULL << (BIT))) != 0)
75 /* Classifies an address.
77 ADDRESS_REG
78 A natural register + offset address. The register satisfies
79 riscv_valid_base_register_p and the offset is a const_arith_operand.
81 ADDRESS_LO_SUM
82 A LO_SUM rtx. The first operand is a valid base register and
83 the second operand is a symbolic address.
85 ADDRESS_CONST_INT
86 A signed 16-bit constant address.
88 ADDRESS_SYMBOLIC:
89 A constant symbolic address. */
90 enum riscv_address_type {
91 ADDRESS_REG,
92 ADDRESS_LO_SUM,
93 ADDRESS_CONST_INT,
94 ADDRESS_SYMBOLIC
97 /* Information about a function's frame layout. */
98 struct GTY(()) riscv_frame_info {
99 /* The size of the frame in bytes. */
100 HOST_WIDE_INT total_size;
102 /* Bit X is set if the function saves or restores GPR X. */
103 unsigned int mask;
105 /* Likewise FPR X. */
106 unsigned int fmask;
108 /* How much the GPR save/restore routines adjust sp (or 0 if unused). */
109 unsigned save_libcall_adjustment;
111 /* Offsets of fixed-point and floating-point save areas from frame bottom */
112 HOST_WIDE_INT gp_sp_offset;
113 HOST_WIDE_INT fp_sp_offset;
115 /* Offset of virtual frame pointer from stack pointer/frame bottom */
116 HOST_WIDE_INT frame_pointer_offset;
118 /* Offset of hard frame pointer from stack pointer/frame bottom */
119 HOST_WIDE_INT hard_frame_pointer_offset;
121 /* The offset of arg_pointer_rtx from the bottom of the frame. */
122 HOST_WIDE_INT arg_pointer_offset;
125 struct GTY(()) machine_function {
126 /* The number of extra stack bytes taken up by register varargs.
127 This area is allocated by the callee at the very top of the frame. */
128 int varargs_size;
130 /* True if current function is a naked function. */
131 bool naked_p;
133 /* The current frame information, calculated by riscv_compute_frame_info. */
134 struct riscv_frame_info frame;
137 /* Information about a single argument. */
138 struct riscv_arg_info {
139 /* True if the argument is at least partially passed on the stack. */
140 bool stack_p;
142 /* The number of integer registers allocated to this argument. */
143 unsigned int num_gprs;
145 /* The offset of the first register used, provided num_gprs is nonzero.
146 If passed entirely on the stack, the value is MAX_ARGS_IN_REGISTERS. */
147 unsigned int gpr_offset;
149 /* The number of floating-point registers allocated to this argument. */
150 unsigned int num_fprs;
152 /* The offset of the first register used, provided num_fprs is nonzero. */
153 unsigned int fpr_offset;
156 /* Information about an address described by riscv_address_type.
158 ADDRESS_CONST_INT
159 No fields are used.
161 ADDRESS_REG
162 REG is the base register and OFFSET is the constant offset.
164 ADDRESS_LO_SUM
165 REG and OFFSET are the operands to the LO_SUM and SYMBOL_TYPE
166 is the type of symbol it references.
168 ADDRESS_SYMBOLIC
169 SYMBOL_TYPE is the type of symbol that the address references. */
170 struct riscv_address_info {
171 enum riscv_address_type type;
172 rtx reg;
173 rtx offset;
174 enum riscv_symbol_type symbol_type;
177 /* One stage in a constant building sequence. These sequences have
178 the form:
180 A = VALUE[0]
181 A = A CODE[1] VALUE[1]
182 A = A CODE[2] VALUE[2]
185 where A is an accumulator, each CODE[i] is a binary rtl operation
186 and each VALUE[i] is a constant integer. CODE[0] is undefined. */
187 struct riscv_integer_op {
188 enum rtx_code code;
189 unsigned HOST_WIDE_INT value;
192 /* The largest number of operations needed to load an integer constant.
193 The worst case is LUI, ADDI, SLLI, ADDI, SLLI, ADDI, SLLI, ADDI. */
194 #define RISCV_MAX_INTEGER_OPS 8
196 /* Costs of various operations on the different architectures. */
198 struct riscv_tune_info
200 unsigned short fp_add[2];
201 unsigned short fp_mul[2];
202 unsigned short fp_div[2];
203 unsigned short int_mul[2];
204 unsigned short int_div[2];
205 unsigned short issue_rate;
206 unsigned short branch_cost;
207 unsigned short memory_cost;
208 bool slow_unaligned_access;
211 /* Information about one CPU we know about. */
212 struct riscv_cpu_info {
213 /* This CPU's canonical name. */
214 const char *name;
216 /* Tuning parameters for this CPU. */
217 const struct riscv_tune_info *tune_info;
220 /* Global variables for machine-dependent things. */
222 /* Whether unaligned accesses execute very slowly. */
223 bool riscv_slow_unaligned_access_p;
225 /* Stack alignment to assume/maintain. */
226 unsigned riscv_stack_boundary;
228 /* Which tuning parameters to use. */
229 static const struct riscv_tune_info *tune_info;
231 /* Index R is the smallest register class that contains register R. */
232 const enum reg_class riscv_regno_to_class[FIRST_PSEUDO_REGISTER] = {
233 GR_REGS, GR_REGS, GR_REGS, GR_REGS,
234 GR_REGS, GR_REGS, SIBCALL_REGS, SIBCALL_REGS,
235 JALR_REGS, JALR_REGS, JALR_REGS, JALR_REGS,
236 JALR_REGS, JALR_REGS, JALR_REGS, JALR_REGS,
237 JALR_REGS, JALR_REGS, JALR_REGS, JALR_REGS,
238 JALR_REGS, JALR_REGS, JALR_REGS, JALR_REGS,
239 JALR_REGS, JALR_REGS, JALR_REGS, JALR_REGS,
240 SIBCALL_REGS, SIBCALL_REGS, SIBCALL_REGS, SIBCALL_REGS,
241 FP_REGS, FP_REGS, FP_REGS, FP_REGS,
242 FP_REGS, FP_REGS, FP_REGS, FP_REGS,
243 FP_REGS, FP_REGS, FP_REGS, FP_REGS,
244 FP_REGS, FP_REGS, FP_REGS, FP_REGS,
245 FP_REGS, FP_REGS, FP_REGS, FP_REGS,
246 FP_REGS, FP_REGS, FP_REGS, FP_REGS,
247 FP_REGS, FP_REGS, FP_REGS, FP_REGS,
248 FP_REGS, FP_REGS, FP_REGS, FP_REGS,
249 FRAME_REGS, FRAME_REGS,
252 /* Costs to use when optimizing for rocket. */
253 static const struct riscv_tune_info rocket_tune_info = {
254 {COSTS_N_INSNS (4), COSTS_N_INSNS (5)}, /* fp_add */
255 {COSTS_N_INSNS (4), COSTS_N_INSNS (5)}, /* fp_mul */
256 {COSTS_N_INSNS (20), COSTS_N_INSNS (20)}, /* fp_div */
257 {COSTS_N_INSNS (4), COSTS_N_INSNS (4)}, /* int_mul */
258 {COSTS_N_INSNS (6), COSTS_N_INSNS (6)}, /* int_div */
259 1, /* issue_rate */
260 3, /* branch_cost */
261 5, /* memory_cost */
262 true, /* slow_unaligned_access */
265 /* Costs to use when optimizing for size. */
266 static const struct riscv_tune_info optimize_size_tune_info = {
267 {COSTS_N_INSNS (1), COSTS_N_INSNS (1)}, /* fp_add */
268 {COSTS_N_INSNS (1), COSTS_N_INSNS (1)}, /* fp_mul */
269 {COSTS_N_INSNS (1), COSTS_N_INSNS (1)}, /* fp_div */
270 {COSTS_N_INSNS (1), COSTS_N_INSNS (1)}, /* int_mul */
271 {COSTS_N_INSNS (1), COSTS_N_INSNS (1)}, /* int_div */
272 1, /* issue_rate */
273 1, /* branch_cost */
274 2, /* memory_cost */
275 false, /* slow_unaligned_access */
278 static tree riscv_handle_fndecl_attribute (tree *, tree, tree, int, bool *);
280 /* Defining target-specific uses of __attribute__. */
281 static const struct attribute_spec riscv_attribute_table[] =
283 /* Syntax: { name, min_len, max_len, decl_required, type_required,
284 function_type_required, affects_type_identity, handler,
285 exclude } */
287 /* The attribute telling no prologue/epilogue. */
288 { "naked", 0, 0, true, false, false, false,
289 riscv_handle_fndecl_attribute, NULL },
291 /* The last attribute spec is set to be NULL. */
292 { NULL, 0, 0, false, false, false, false, NULL, NULL }
295 /* A table describing all the processors GCC knows about. */
296 static const struct riscv_cpu_info riscv_cpu_info_table[] = {
297 { "rocket", &rocket_tune_info },
298 { "size", &optimize_size_tune_info },
301 /* Return the riscv_cpu_info entry for the given name string. */
303 static const struct riscv_cpu_info *
304 riscv_parse_cpu (const char *cpu_string)
306 for (unsigned i = 0; i < ARRAY_SIZE (riscv_cpu_info_table); i++)
307 if (strcmp (riscv_cpu_info_table[i].name, cpu_string) == 0)
308 return riscv_cpu_info_table + i;
310 error ("unknown cpu %qs for -mtune", cpu_string);
311 return riscv_cpu_info_table;
314 /* Helper function for riscv_build_integer; arguments are as for
315 riscv_build_integer. */
317 static int
318 riscv_build_integer_1 (struct riscv_integer_op codes[RISCV_MAX_INTEGER_OPS],
319 HOST_WIDE_INT value, machine_mode mode)
321 HOST_WIDE_INT low_part = CONST_LOW_PART (value);
322 int cost = RISCV_MAX_INTEGER_OPS + 1, alt_cost;
323 struct riscv_integer_op alt_codes[RISCV_MAX_INTEGER_OPS];
325 if (SMALL_OPERAND (value) || LUI_OPERAND (value))
327 /* Simply ADDI or LUI. */
328 codes[0].code = UNKNOWN;
329 codes[0].value = value;
330 return 1;
333 /* End with ADDI. When constructing HImode constants, do not generate any
334 intermediate value that is not itself a valid HImode constant. The
335 XORI case below will handle those remaining HImode constants. */
336 if (low_part != 0
337 && (mode != HImode
338 || value - low_part <= ((1 << (GET_MODE_BITSIZE (HImode) - 1)) - 1)))
340 alt_cost = 1 + riscv_build_integer_1 (alt_codes, value - low_part, mode);
341 if (alt_cost < cost)
343 alt_codes[alt_cost-1].code = PLUS;
344 alt_codes[alt_cost-1].value = low_part;
345 memcpy (codes, alt_codes, sizeof (alt_codes));
346 cost = alt_cost;
350 /* End with XORI. */
351 if (cost > 2 && (low_part < 0 || mode == HImode))
353 alt_cost = 1 + riscv_build_integer_1 (alt_codes, value ^ low_part, mode);
354 if (alt_cost < cost)
356 alt_codes[alt_cost-1].code = XOR;
357 alt_codes[alt_cost-1].value = low_part;
358 memcpy (codes, alt_codes, sizeof (alt_codes));
359 cost = alt_cost;
363 /* Eliminate trailing zeros and end with SLLI. */
364 if (cost > 2 && (value & 1) == 0)
366 int shift = ctz_hwi (value);
367 unsigned HOST_WIDE_INT x = value;
368 x = sext_hwi (x >> shift, HOST_BITS_PER_WIDE_INT - shift);
370 /* Don't eliminate the lower 12 bits if LUI might apply. */
371 if (shift > IMM_BITS && !SMALL_OPERAND (x) && LUI_OPERAND (x << IMM_BITS))
372 shift -= IMM_BITS, x <<= IMM_BITS;
374 alt_cost = 1 + riscv_build_integer_1 (alt_codes, x, mode);
375 if (alt_cost < cost)
377 alt_codes[alt_cost-1].code = ASHIFT;
378 alt_codes[alt_cost-1].value = shift;
379 memcpy (codes, alt_codes, sizeof (alt_codes));
380 cost = alt_cost;
384 gcc_assert (cost <= RISCV_MAX_INTEGER_OPS);
385 return cost;
388 /* Fill CODES with a sequence of rtl operations to load VALUE.
389 Return the number of operations needed. */
391 static int
392 riscv_build_integer (struct riscv_integer_op *codes, HOST_WIDE_INT value,
393 machine_mode mode)
395 int cost = riscv_build_integer_1 (codes, value, mode);
397 /* Eliminate leading zeros and end with SRLI. */
398 if (value > 0 && cost > 2)
400 struct riscv_integer_op alt_codes[RISCV_MAX_INTEGER_OPS];
401 int alt_cost, shift = clz_hwi (value);
402 HOST_WIDE_INT shifted_val;
404 /* Try filling trailing bits with 1s. */
405 shifted_val = (value << shift) | ((((HOST_WIDE_INT) 1) << shift) - 1);
406 alt_cost = 1 + riscv_build_integer_1 (alt_codes, shifted_val, mode);
407 if (alt_cost < cost)
409 alt_codes[alt_cost-1].code = LSHIFTRT;
410 alt_codes[alt_cost-1].value = shift;
411 memcpy (codes, alt_codes, sizeof (alt_codes));
412 cost = alt_cost;
415 /* Try filling trailing bits with 0s. */
416 shifted_val = value << shift;
417 alt_cost = 1 + riscv_build_integer_1 (alt_codes, shifted_val, mode);
418 if (alt_cost < cost)
420 alt_codes[alt_cost-1].code = LSHIFTRT;
421 alt_codes[alt_cost-1].value = shift;
422 memcpy (codes, alt_codes, sizeof (alt_codes));
423 cost = alt_cost;
427 return cost;
430 /* Return the cost of constructing VAL in the event that a scratch
431 register is available. */
433 static int
434 riscv_split_integer_cost (HOST_WIDE_INT val)
436 int cost;
437 unsigned HOST_WIDE_INT loval = sext_hwi (val, 32);
438 unsigned HOST_WIDE_INT hival = sext_hwi ((val - loval) >> 32, 32);
439 struct riscv_integer_op codes[RISCV_MAX_INTEGER_OPS];
441 cost = 2 + riscv_build_integer (codes, loval, VOIDmode);
442 if (loval != hival)
443 cost += riscv_build_integer (codes, hival, VOIDmode);
445 return cost;
448 /* Return the cost of constructing the integer constant VAL. */
450 static int
451 riscv_integer_cost (HOST_WIDE_INT val)
453 struct riscv_integer_op codes[RISCV_MAX_INTEGER_OPS];
454 return MIN (riscv_build_integer (codes, val, VOIDmode),
455 riscv_split_integer_cost (val));
458 /* Try to split a 64b integer into 32b parts, then reassemble. */
460 static rtx
461 riscv_split_integer (HOST_WIDE_INT val, machine_mode mode)
463 unsigned HOST_WIDE_INT loval = sext_hwi (val, 32);
464 unsigned HOST_WIDE_INT hival = sext_hwi ((val - loval) >> 32, 32);
465 rtx hi = gen_reg_rtx (mode), lo = gen_reg_rtx (mode);
467 riscv_move_integer (hi, hi, hival);
468 riscv_move_integer (lo, lo, loval);
470 hi = gen_rtx_fmt_ee (ASHIFT, mode, hi, GEN_INT (32));
471 hi = force_reg (mode, hi);
473 return gen_rtx_fmt_ee (PLUS, mode, hi, lo);
476 /* Return true if X is a thread-local symbol. */
478 static bool
479 riscv_tls_symbol_p (const_rtx x)
481 return SYMBOL_REF_P (x) && SYMBOL_REF_TLS_MODEL (x) != 0;
484 /* Return true if symbol X binds locally. */
486 static bool
487 riscv_symbol_binds_local_p (const_rtx x)
489 if (SYMBOL_REF_P (x))
490 return (SYMBOL_REF_DECL (x)
491 ? targetm.binds_local_p (SYMBOL_REF_DECL (x))
492 : SYMBOL_REF_LOCAL_P (x));
493 else
494 return false;
497 /* Return the method that should be used to access SYMBOL_REF or
498 LABEL_REF X. */
500 static enum riscv_symbol_type
501 riscv_classify_symbol (const_rtx x)
503 if (riscv_tls_symbol_p (x))
504 return SYMBOL_TLS;
506 if (GET_CODE (x) == SYMBOL_REF && flag_pic && !riscv_symbol_binds_local_p (x))
507 return SYMBOL_GOT_DISP;
509 return riscv_cmodel == CM_MEDLOW ? SYMBOL_ABSOLUTE : SYMBOL_PCREL;
512 /* Classify the base of symbolic expression X. */
514 enum riscv_symbol_type
515 riscv_classify_symbolic_expression (rtx x)
517 rtx offset;
519 split_const (x, &x, &offset);
520 if (UNSPEC_ADDRESS_P (x))
521 return UNSPEC_ADDRESS_TYPE (x);
523 return riscv_classify_symbol (x);
526 /* Return true if X is a symbolic constant. If it is, store the type of
527 the symbol in *SYMBOL_TYPE. */
529 bool
530 riscv_symbolic_constant_p (rtx x, enum riscv_symbol_type *symbol_type)
532 rtx offset;
534 split_const (x, &x, &offset);
535 if (UNSPEC_ADDRESS_P (x))
537 *symbol_type = UNSPEC_ADDRESS_TYPE (x);
538 x = UNSPEC_ADDRESS (x);
540 else if (GET_CODE (x) == SYMBOL_REF || GET_CODE (x) == LABEL_REF)
541 *symbol_type = riscv_classify_symbol (x);
542 else
543 return false;
545 if (offset == const0_rtx)
546 return true;
548 /* Nonzero offsets are only valid for references that don't use the GOT. */
549 switch (*symbol_type)
551 case SYMBOL_ABSOLUTE:
552 case SYMBOL_PCREL:
553 case SYMBOL_TLS_LE:
554 /* GAS rejects offsets outside the range [-2^31, 2^31-1]. */
555 return sext_hwi (INTVAL (offset), 32) == INTVAL (offset);
557 default:
558 return false;
562 /* Returns the number of instructions necessary to reference a symbol. */
564 static int riscv_symbol_insns (enum riscv_symbol_type type)
566 switch (type)
568 case SYMBOL_TLS: return 0; /* Depends on the TLS model. */
569 case SYMBOL_ABSOLUTE: return 2; /* LUI + the reference. */
570 case SYMBOL_PCREL: return 2; /* AUIPC + the reference. */
571 case SYMBOL_TLS_LE: return 3; /* LUI + ADD TP + the reference. */
572 case SYMBOL_GOT_DISP: return 3; /* AUIPC + LD GOT + the reference. */
573 default: gcc_unreachable ();
577 /* Implement TARGET_LEGITIMATE_CONSTANT_P. */
579 static bool
580 riscv_legitimate_constant_p (machine_mode mode ATTRIBUTE_UNUSED, rtx x)
582 return riscv_const_insns (x) > 0;
585 /* Implement TARGET_CANNOT_FORCE_CONST_MEM. */
587 static bool
588 riscv_cannot_force_const_mem (machine_mode mode ATTRIBUTE_UNUSED, rtx x)
590 enum riscv_symbol_type type;
591 rtx base, offset;
593 /* There is no assembler syntax for expressing an address-sized
594 high part. */
595 if (GET_CODE (x) == HIGH)
596 return true;
598 split_const (x, &base, &offset);
599 if (riscv_symbolic_constant_p (base, &type))
601 /* As an optimization, don't spill symbolic constants that are as
602 cheap to rematerialize as to access in the constant pool. */
603 if (SMALL_OPERAND (INTVAL (offset)) && riscv_symbol_insns (type) > 0)
604 return true;
606 /* As an optimization, avoid needlessly generate dynamic relocations. */
607 if (flag_pic)
608 return true;
611 /* TLS symbols must be computed by riscv_legitimize_move. */
612 if (tls_referenced_p (x))
613 return true;
615 return false;
618 /* Return true if register REGNO is a valid base register for mode MODE.
619 STRICT_P is true if REG_OK_STRICT is in effect. */
622 riscv_regno_mode_ok_for_base_p (int regno,
623 machine_mode mode ATTRIBUTE_UNUSED,
624 bool strict_p)
626 if (!HARD_REGISTER_NUM_P (regno))
628 if (!strict_p)
629 return true;
630 regno = reg_renumber[regno];
633 /* These fake registers will be eliminated to either the stack or
634 hard frame pointer, both of which are usually valid base registers.
635 Reload deals with the cases where the eliminated form isn't valid. */
636 if (regno == ARG_POINTER_REGNUM || regno == FRAME_POINTER_REGNUM)
637 return true;
639 return GP_REG_P (regno);
642 /* Return true if X is a valid base register for mode MODE.
643 STRICT_P is true if REG_OK_STRICT is in effect. */
645 static bool
646 riscv_valid_base_register_p (rtx x, machine_mode mode, bool strict_p)
648 if (!strict_p && GET_CODE (x) == SUBREG)
649 x = SUBREG_REG (x);
651 return (REG_P (x)
652 && riscv_regno_mode_ok_for_base_p (REGNO (x), mode, strict_p));
655 /* Return true if, for every base register BASE_REG, (plus BASE_REG X)
656 can address a value of mode MODE. */
658 static bool
659 riscv_valid_offset_p (rtx x, machine_mode mode)
661 /* Check that X is a signed 12-bit number. */
662 if (!const_arith_operand (x, Pmode))
663 return false;
665 /* We may need to split multiword moves, so make sure that every word
666 is accessible. */
667 if (GET_MODE_SIZE (mode) > UNITS_PER_WORD
668 && !SMALL_OPERAND (INTVAL (x) + GET_MODE_SIZE (mode) - UNITS_PER_WORD))
669 return false;
671 return true;
674 /* Should a symbol of type SYMBOL_TYPE should be split in two? */
676 bool
677 riscv_split_symbol_type (enum riscv_symbol_type symbol_type)
679 if (symbol_type == SYMBOL_TLS_LE)
680 return true;
682 if (!TARGET_EXPLICIT_RELOCS)
683 return false;
685 return symbol_type == SYMBOL_ABSOLUTE || symbol_type == SYMBOL_PCREL;
688 /* Return true if a LO_SUM can address a value of mode MODE when the
689 LO_SUM symbol has type SYM_TYPE. */
691 static bool
692 riscv_valid_lo_sum_p (enum riscv_symbol_type sym_type, machine_mode mode)
694 /* Check that symbols of type SYMBOL_TYPE can be used to access values
695 of mode MODE. */
696 if (riscv_symbol_insns (sym_type) == 0)
697 return false;
699 /* Check that there is a known low-part relocation. */
700 if (!riscv_split_symbol_type (sym_type))
701 return false;
703 /* We may need to split multiword moves, so make sure that each word
704 can be accessed without inducing a carry. */
705 if (GET_MODE_SIZE (mode) > UNITS_PER_WORD
706 && (!TARGET_STRICT_ALIGN
707 || GET_MODE_BITSIZE (mode) > GET_MODE_ALIGNMENT (mode)))
708 return false;
710 return true;
713 /* Return true if X is a valid address for machine mode MODE. If it is,
714 fill in INFO appropriately. STRICT_P is true if REG_OK_STRICT is in
715 effect. */
717 static bool
718 riscv_classify_address (struct riscv_address_info *info, rtx x,
719 machine_mode mode, bool strict_p)
721 switch (GET_CODE (x))
723 case REG:
724 case SUBREG:
725 info->type = ADDRESS_REG;
726 info->reg = x;
727 info->offset = const0_rtx;
728 return riscv_valid_base_register_p (info->reg, mode, strict_p);
730 case PLUS:
731 info->type = ADDRESS_REG;
732 info->reg = XEXP (x, 0);
733 info->offset = XEXP (x, 1);
734 return (riscv_valid_base_register_p (info->reg, mode, strict_p)
735 && riscv_valid_offset_p (info->offset, mode));
737 case LO_SUM:
738 info->type = ADDRESS_LO_SUM;
739 info->reg = XEXP (x, 0);
740 info->offset = XEXP (x, 1);
741 /* We have to trust the creator of the LO_SUM to do something vaguely
742 sane. Target-independent code that creates a LO_SUM should also
743 create and verify the matching HIGH. Target-independent code that
744 adds an offset to a LO_SUM must prove that the offset will not
745 induce a carry. Failure to do either of these things would be
746 a bug, and we are not required to check for it here. The RISC-V
747 backend itself should only create LO_SUMs for valid symbolic
748 constants, with the high part being either a HIGH or a copy
749 of _gp. */
750 info->symbol_type
751 = riscv_classify_symbolic_expression (info->offset);
752 return (riscv_valid_base_register_p (info->reg, mode, strict_p)
753 && riscv_valid_lo_sum_p (info->symbol_type, mode));
755 case CONST_INT:
756 /* Small-integer addresses don't occur very often, but they
757 are legitimate if x0 is a valid base register. */
758 info->type = ADDRESS_CONST_INT;
759 return SMALL_OPERAND (INTVAL (x));
761 default:
762 return false;
766 /* Implement TARGET_LEGITIMATE_ADDRESS_P. */
768 static bool
769 riscv_legitimate_address_p (machine_mode mode, rtx x, bool strict_p)
771 struct riscv_address_info addr;
773 return riscv_classify_address (&addr, x, mode, strict_p);
776 /* Return the number of instructions needed to load or store a value
777 of mode MODE at address X. Return 0 if X isn't valid for MODE.
778 Assume that multiword moves may need to be split into word moves
779 if MIGHT_SPLIT_P, otherwise assume that a single load or store is
780 enough. */
783 riscv_address_insns (rtx x, machine_mode mode, bool might_split_p)
785 struct riscv_address_info addr;
786 int n = 1;
788 if (!riscv_classify_address (&addr, x, mode, false))
789 return 0;
791 /* BLKmode is used for single unaligned loads and stores and should
792 not count as a multiword mode. */
793 if (mode != BLKmode && might_split_p)
794 n += (GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
796 if (addr.type == ADDRESS_LO_SUM)
797 n += riscv_symbol_insns (addr.symbol_type) - 1;
799 return n;
802 /* Return the number of instructions needed to load constant X.
803 Return 0 if X isn't a valid constant. */
806 riscv_const_insns (rtx x)
808 enum riscv_symbol_type symbol_type;
809 rtx offset;
811 switch (GET_CODE (x))
813 case HIGH:
814 if (!riscv_symbolic_constant_p (XEXP (x, 0), &symbol_type)
815 || !riscv_split_symbol_type (symbol_type))
816 return 0;
818 /* This is simply an LUI. */
819 return 1;
821 case CONST_INT:
823 int cost = riscv_integer_cost (INTVAL (x));
824 /* Force complicated constants to memory. */
825 return cost < 4 ? cost : 0;
828 case CONST_DOUBLE:
829 case CONST_VECTOR:
830 /* We can use x0 to load floating-point zero. */
831 return x == CONST0_RTX (GET_MODE (x)) ? 1 : 0;
833 case CONST:
834 /* See if we can refer to X directly. */
835 if (riscv_symbolic_constant_p (x, &symbol_type))
836 return riscv_symbol_insns (symbol_type);
838 /* Otherwise try splitting the constant into a base and offset. */
839 split_const (x, &x, &offset);
840 if (offset != 0)
842 int n = riscv_const_insns (x);
843 if (n != 0)
844 return n + riscv_integer_cost (INTVAL (offset));
846 return 0;
848 case SYMBOL_REF:
849 case LABEL_REF:
850 return riscv_symbol_insns (riscv_classify_symbol (x));
852 default:
853 return 0;
857 /* X is a doubleword constant that can be handled by splitting it into
858 two words and loading each word separately. Return the number of
859 instructions required to do this. */
862 riscv_split_const_insns (rtx x)
864 unsigned int low, high;
866 low = riscv_const_insns (riscv_subword (x, false));
867 high = riscv_const_insns (riscv_subword (x, true));
868 gcc_assert (low > 0 && high > 0);
869 return low + high;
872 /* Return the number of instructions needed to implement INSN,
873 given that it loads from or stores to MEM. */
876 riscv_load_store_insns (rtx mem, rtx_insn *insn)
878 machine_mode mode;
879 bool might_split_p;
880 rtx set;
882 gcc_assert (MEM_P (mem));
883 mode = GET_MODE (mem);
885 /* Try to prove that INSN does not need to be split. */
886 might_split_p = true;
887 if (GET_MODE_BITSIZE (mode) <= 32)
888 might_split_p = false;
889 else if (GET_MODE_BITSIZE (mode) == 64)
891 set = single_set (insn);
892 if (set && !riscv_split_64bit_move_p (SET_DEST (set), SET_SRC (set)))
893 might_split_p = false;
896 return riscv_address_insns (XEXP (mem, 0), mode, might_split_p);
899 /* Emit a move from SRC to DEST. Assume that the move expanders can
900 handle all moves if !can_create_pseudo_p (). The distinction is
901 important because, unlike emit_move_insn, the move expanders know
902 how to force Pmode objects into the constant pool even when the
903 constant pool address is not itself legitimate. */
906 riscv_emit_move (rtx dest, rtx src)
908 return (can_create_pseudo_p ()
909 ? emit_move_insn (dest, src)
910 : emit_move_insn_1 (dest, src));
913 /* Emit an instruction of the form (set TARGET SRC). */
915 static rtx
916 riscv_emit_set (rtx target, rtx src)
918 emit_insn (gen_rtx_SET (target, src));
919 return target;
922 /* Emit an instruction of the form (set DEST (CODE X Y)). */
924 static rtx
925 riscv_emit_binary (enum rtx_code code, rtx dest, rtx x, rtx y)
927 return riscv_emit_set (dest, gen_rtx_fmt_ee (code, GET_MODE (dest), x, y));
930 /* Compute (CODE X Y) and store the result in a new register
931 of mode MODE. Return that new register. */
933 static rtx
934 riscv_force_binary (machine_mode mode, enum rtx_code code, rtx x, rtx y)
936 return riscv_emit_binary (code, gen_reg_rtx (mode), x, y);
939 /* Copy VALUE to a register and return that register. If new pseudos
940 are allowed, copy it into a new register, otherwise use DEST. */
942 static rtx
943 riscv_force_temporary (rtx dest, rtx value)
945 if (can_create_pseudo_p ())
946 return force_reg (Pmode, value);
947 else
949 riscv_emit_move (dest, value);
950 return dest;
954 /* Wrap symbol or label BASE in an UNSPEC address of type SYMBOL_TYPE,
955 then add CONST_INT OFFSET to the result. */
957 static rtx
958 riscv_unspec_address_offset (rtx base, rtx offset,
959 enum riscv_symbol_type symbol_type)
961 base = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, base),
962 UNSPEC_ADDRESS_FIRST + symbol_type);
963 if (offset != const0_rtx)
964 base = gen_rtx_PLUS (Pmode, base, offset);
965 return gen_rtx_CONST (Pmode, base);
968 /* Return an UNSPEC address with underlying address ADDRESS and symbol
969 type SYMBOL_TYPE. */
972 riscv_unspec_address (rtx address, enum riscv_symbol_type symbol_type)
974 rtx base, offset;
976 split_const (address, &base, &offset);
977 return riscv_unspec_address_offset (base, offset, symbol_type);
980 /* If OP is an UNSPEC address, return the address to which it refers,
981 otherwise return OP itself. */
983 static rtx
984 riscv_strip_unspec_address (rtx op)
986 rtx base, offset;
988 split_const (op, &base, &offset);
989 if (UNSPEC_ADDRESS_P (base))
990 op = plus_constant (Pmode, UNSPEC_ADDRESS (base), INTVAL (offset));
991 return op;
994 /* If riscv_unspec_address (ADDR, SYMBOL_TYPE) is a 32-bit value, add the
995 high part to BASE and return the result. Just return BASE otherwise.
996 TEMP is as for riscv_force_temporary.
998 The returned expression can be used as the first operand to a LO_SUM. */
1000 static rtx
1001 riscv_unspec_offset_high (rtx temp, rtx addr, enum riscv_symbol_type symbol_type)
1003 addr = gen_rtx_HIGH (Pmode, riscv_unspec_address (addr, symbol_type));
1004 return riscv_force_temporary (temp, addr);
1007 /* Load an entry from the GOT for a TLS GD access. */
1009 static rtx riscv_got_load_tls_gd (rtx dest, rtx sym)
1011 if (Pmode == DImode)
1012 return gen_got_load_tls_gddi (dest, sym);
1013 else
1014 return gen_got_load_tls_gdsi (dest, sym);
1017 /* Load an entry from the GOT for a TLS IE access. */
1019 static rtx riscv_got_load_tls_ie (rtx dest, rtx sym)
1021 if (Pmode == DImode)
1022 return gen_got_load_tls_iedi (dest, sym);
1023 else
1024 return gen_got_load_tls_iesi (dest, sym);
1027 /* Add in the thread pointer for a TLS LE access. */
1029 static rtx riscv_tls_add_tp_le (rtx dest, rtx base, rtx sym)
1031 rtx tp = gen_rtx_REG (Pmode, THREAD_POINTER_REGNUM);
1032 if (Pmode == DImode)
1033 return gen_tls_add_tp_ledi (dest, base, tp, sym);
1034 else
1035 return gen_tls_add_tp_lesi (dest, base, tp, sym);
1038 /* If MODE is MAX_MACHINE_MODE, ADDR appears as a move operand, otherwise
1039 it appears in a MEM of that mode. Return true if ADDR is a legitimate
1040 constant in that context and can be split into high and low parts.
1041 If so, and if LOW_OUT is nonnull, emit the high part and store the
1042 low part in *LOW_OUT. Leave *LOW_OUT unchanged otherwise.
1044 TEMP is as for riscv_force_temporary and is used to load the high
1045 part into a register.
1047 When MODE is MAX_MACHINE_MODE, the low part is guaranteed to be
1048 a legitimize SET_SRC for an .md pattern, otherwise the low part
1049 is guaranteed to be a legitimate address for mode MODE. */
1051 bool
1052 riscv_split_symbol (rtx temp, rtx addr, machine_mode mode, rtx *low_out)
1054 enum riscv_symbol_type symbol_type;
1056 if ((GET_CODE (addr) == HIGH && mode == MAX_MACHINE_MODE)
1057 || !riscv_symbolic_constant_p (addr, &symbol_type)
1058 || riscv_symbol_insns (symbol_type) == 0
1059 || !riscv_split_symbol_type (symbol_type))
1060 return false;
1062 if (low_out)
1063 switch (symbol_type)
1065 case SYMBOL_ABSOLUTE:
1067 rtx high = gen_rtx_HIGH (Pmode, copy_rtx (addr));
1068 high = riscv_force_temporary (temp, high);
1069 *low_out = gen_rtx_LO_SUM (Pmode, high, addr);
1071 break;
1073 case SYMBOL_PCREL:
1075 static unsigned seqno;
1076 char buf[32];
1077 rtx label;
1079 ssize_t bytes = snprintf (buf, sizeof (buf), ".LA%u", seqno);
1080 gcc_assert ((size_t) bytes < sizeof (buf));
1082 label = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (buf));
1083 SYMBOL_REF_FLAGS (label) |= SYMBOL_FLAG_LOCAL;
1085 if (temp == NULL)
1086 temp = gen_reg_rtx (Pmode);
1088 if (Pmode == DImode)
1089 emit_insn (gen_auipcdi (temp, copy_rtx (addr), GEN_INT (seqno)));
1090 else
1091 emit_insn (gen_auipcsi (temp, copy_rtx (addr), GEN_INT (seqno)));
1093 *low_out = gen_rtx_LO_SUM (Pmode, temp, label);
1095 seqno++;
1097 break;
1099 default:
1100 gcc_unreachable ();
1103 return true;
1106 /* Return a legitimate address for REG + OFFSET. TEMP is as for
1107 riscv_force_temporary; it is only needed when OFFSET is not a
1108 SMALL_OPERAND. */
1110 static rtx
1111 riscv_add_offset (rtx temp, rtx reg, HOST_WIDE_INT offset)
1113 if (!SMALL_OPERAND (offset))
1115 rtx high;
1117 /* Leave OFFSET as a 16-bit offset and put the excess in HIGH.
1118 The addition inside the macro CONST_HIGH_PART may cause an
1119 overflow, so we need to force a sign-extension check. */
1120 high = gen_int_mode (CONST_HIGH_PART (offset), Pmode);
1121 offset = CONST_LOW_PART (offset);
1122 high = riscv_force_temporary (temp, high);
1123 reg = riscv_force_temporary (temp, gen_rtx_PLUS (Pmode, high, reg));
1125 return plus_constant (Pmode, reg, offset);
1128 /* The __tls_get_attr symbol. */
1129 static GTY(()) rtx riscv_tls_symbol;
1131 /* Return an instruction sequence that calls __tls_get_addr. SYM is
1132 the TLS symbol we are referencing and TYPE is the symbol type to use
1133 (either global dynamic or local dynamic). RESULT is an RTX for the
1134 return value location. */
1136 static rtx_insn *
1137 riscv_call_tls_get_addr (rtx sym, rtx result)
1139 rtx a0 = gen_rtx_REG (Pmode, GP_ARG_FIRST), func;
1140 rtx_insn *insn;
1142 if (!riscv_tls_symbol)
1143 riscv_tls_symbol = init_one_libfunc ("__tls_get_addr");
1144 func = gen_rtx_MEM (FUNCTION_MODE, riscv_tls_symbol);
1146 start_sequence ();
1148 emit_insn (riscv_got_load_tls_gd (a0, sym));
1149 insn = emit_call_insn (gen_call_value (result, func, const0_rtx, NULL));
1150 RTL_CONST_CALL_P (insn) = 1;
1151 use_reg (&CALL_INSN_FUNCTION_USAGE (insn), a0);
1152 insn = get_insns ();
1154 end_sequence ();
1156 return insn;
1159 /* Generate the code to access LOC, a thread-local SYMBOL_REF, and return
1160 its address. The return value will be both a valid address and a valid
1161 SET_SRC (either a REG or a LO_SUM). */
1163 static rtx
1164 riscv_legitimize_tls_address (rtx loc)
1166 rtx dest, tp, tmp;
1167 enum tls_model model = SYMBOL_REF_TLS_MODEL (loc);
1169 /* Since we support TLS copy relocs, non-PIC TLS accesses may all use LE. */
1170 if (!flag_pic)
1171 model = TLS_MODEL_LOCAL_EXEC;
1173 switch (model)
1175 case TLS_MODEL_LOCAL_DYNAMIC:
1176 /* Rely on section anchors for the optimization that LDM TLS
1177 provides. The anchor's address is loaded with GD TLS. */
1178 case TLS_MODEL_GLOBAL_DYNAMIC:
1179 tmp = gen_rtx_REG (Pmode, GP_RETURN);
1180 dest = gen_reg_rtx (Pmode);
1181 emit_libcall_block (riscv_call_tls_get_addr (loc, tmp), dest, tmp, loc);
1182 break;
1184 case TLS_MODEL_INITIAL_EXEC:
1185 /* la.tls.ie; tp-relative add */
1186 tp = gen_rtx_REG (Pmode, THREAD_POINTER_REGNUM);
1187 tmp = gen_reg_rtx (Pmode);
1188 emit_insn (riscv_got_load_tls_ie (tmp, loc));
1189 dest = gen_reg_rtx (Pmode);
1190 emit_insn (gen_add3_insn (dest, tmp, tp));
1191 break;
1193 case TLS_MODEL_LOCAL_EXEC:
1194 tmp = riscv_unspec_offset_high (NULL, loc, SYMBOL_TLS_LE);
1195 dest = gen_reg_rtx (Pmode);
1196 emit_insn (riscv_tls_add_tp_le (dest, tmp, loc));
1197 dest = gen_rtx_LO_SUM (Pmode, dest,
1198 riscv_unspec_address (loc, SYMBOL_TLS_LE));
1199 break;
1201 default:
1202 gcc_unreachable ();
1204 return dest;
1207 /* If X is not a valid address for mode MODE, force it into a register. */
1209 static rtx
1210 riscv_force_address (rtx x, machine_mode mode)
1212 if (!riscv_legitimate_address_p (mode, x, false))
1213 x = force_reg (Pmode, x);
1214 return x;
1217 /* This function is used to implement LEGITIMIZE_ADDRESS. If X can
1218 be legitimized in a way that the generic machinery might not expect,
1219 return a new address, otherwise return NULL. MODE is the mode of
1220 the memory being accessed. */
1222 static rtx
1223 riscv_legitimize_address (rtx x, rtx oldx ATTRIBUTE_UNUSED,
1224 machine_mode mode)
1226 rtx addr;
1228 if (riscv_tls_symbol_p (x))
1229 return riscv_legitimize_tls_address (x);
1231 /* See if the address can split into a high part and a LO_SUM. */
1232 if (riscv_split_symbol (NULL, x, mode, &addr))
1233 return riscv_force_address (addr, mode);
1235 /* Handle BASE + OFFSET using riscv_add_offset. */
1236 if (GET_CODE (x) == PLUS && CONST_INT_P (XEXP (x, 1))
1237 && INTVAL (XEXP (x, 1)) != 0)
1239 rtx base = XEXP (x, 0);
1240 HOST_WIDE_INT offset = INTVAL (XEXP (x, 1));
1242 if (!riscv_valid_base_register_p (base, mode, false))
1243 base = copy_to_mode_reg (Pmode, base);
1244 addr = riscv_add_offset (NULL, base, offset);
1245 return riscv_force_address (addr, mode);
1248 return x;
1251 /* Load VALUE into DEST. TEMP is as for riscv_force_temporary. */
1253 void
1254 riscv_move_integer (rtx temp, rtx dest, HOST_WIDE_INT value)
1256 struct riscv_integer_op codes[RISCV_MAX_INTEGER_OPS];
1257 machine_mode mode;
1258 int i, num_ops;
1259 rtx x;
1261 mode = GET_MODE (dest);
1262 num_ops = riscv_build_integer (codes, value, mode);
1264 if (can_create_pseudo_p () && num_ops > 2 /* not a simple constant */
1265 && num_ops >= riscv_split_integer_cost (value))
1266 x = riscv_split_integer (value, mode);
1267 else
1269 /* Apply each binary operation to X. */
1270 x = GEN_INT (codes[0].value);
1272 for (i = 1; i < num_ops; i++)
1274 if (!can_create_pseudo_p ())
1275 x = riscv_emit_set (temp, x);
1276 else
1277 x = force_reg (mode, x);
1279 x = gen_rtx_fmt_ee (codes[i].code, mode, x, GEN_INT (codes[i].value));
1283 riscv_emit_set (dest, x);
1286 /* Subroutine of riscv_legitimize_move. Move constant SRC into register
1287 DEST given that SRC satisfies immediate_operand but doesn't satisfy
1288 move_operand. */
1290 static void
1291 riscv_legitimize_const_move (machine_mode mode, rtx dest, rtx src)
1293 rtx base, offset;
1295 /* Split moves of big integers into smaller pieces. */
1296 if (splittable_const_int_operand (src, mode))
1298 riscv_move_integer (dest, dest, INTVAL (src));
1299 return;
1302 /* Split moves of symbolic constants into high/low pairs. */
1303 if (riscv_split_symbol (dest, src, MAX_MACHINE_MODE, &src))
1305 riscv_emit_set (dest, src);
1306 return;
1309 /* Generate the appropriate access sequences for TLS symbols. */
1310 if (riscv_tls_symbol_p (src))
1312 riscv_emit_move (dest, riscv_legitimize_tls_address (src));
1313 return;
1316 /* If we have (const (plus symbol offset)), and that expression cannot
1317 be forced into memory, load the symbol first and add in the offset. Also
1318 prefer to do this even if the constant _can_ be forced into memory, as it
1319 usually produces better code. */
1320 split_const (src, &base, &offset);
1321 if (offset != const0_rtx
1322 && (targetm.cannot_force_const_mem (mode, src) || can_create_pseudo_p ()))
1324 base = riscv_force_temporary (dest, base);
1325 riscv_emit_move (dest, riscv_add_offset (NULL, base, INTVAL (offset)));
1326 return;
1329 src = force_const_mem (mode, src);
1331 /* When using explicit relocs, constant pool references are sometimes
1332 not legitimate addresses. */
1333 riscv_split_symbol (dest, XEXP (src, 0), mode, &XEXP (src, 0));
1334 riscv_emit_move (dest, src);
1337 /* If (set DEST SRC) is not a valid move instruction, emit an equivalent
1338 sequence that is valid. */
1340 bool
1341 riscv_legitimize_move (machine_mode mode, rtx dest, rtx src)
1343 if (!register_operand (dest, mode) && !reg_or_0_operand (src, mode))
1345 riscv_emit_move (dest, force_reg (mode, src));
1346 return true;
1349 /* We need to deal with constants that would be legitimate
1350 immediate_operands but aren't legitimate move_operands. */
1351 if (CONSTANT_P (src) && !move_operand (src, mode))
1353 riscv_legitimize_const_move (mode, dest, src);
1354 set_unique_reg_note (get_last_insn (), REG_EQUAL, copy_rtx (src));
1355 return true;
1358 /* RISC-V GCC may generate non-legitimate address due to we provide some
1359 pattern for optimize access PIC local symbol and it's make GCC generate
1360 unrecognizable instruction during optmizing. */
1362 if (MEM_P (dest) && !riscv_legitimate_address_p (mode, XEXP (dest, 0),
1363 reload_completed))
1365 XEXP (dest, 0) = riscv_force_address (XEXP (dest, 0), mode);
1368 if (MEM_P (src) && !riscv_legitimate_address_p (mode, XEXP (src, 0),
1369 reload_completed))
1371 XEXP (src, 0) = riscv_force_address (XEXP (src, 0), mode);
1374 return false;
1377 /* Return true if there is an instruction that implements CODE and accepts
1378 X as an immediate operand. */
1380 static int
1381 riscv_immediate_operand_p (int code, HOST_WIDE_INT x)
1383 switch (code)
1385 case ASHIFT:
1386 case ASHIFTRT:
1387 case LSHIFTRT:
1388 /* All shift counts are truncated to a valid constant. */
1389 return true;
1391 case AND:
1392 case IOR:
1393 case XOR:
1394 case PLUS:
1395 case LT:
1396 case LTU:
1397 /* These instructions take 12-bit signed immediates. */
1398 return SMALL_OPERAND (x);
1400 case LE:
1401 /* We add 1 to the immediate and use SLT. */
1402 return SMALL_OPERAND (x + 1);
1404 case LEU:
1405 /* Likewise SLTU, but reject the always-true case. */
1406 return SMALL_OPERAND (x + 1) && x + 1 != 0;
1408 case GE:
1409 case GEU:
1410 /* We can emulate an immediate of 1 by using GT/GTU against x0. */
1411 return x == 1;
1413 default:
1414 /* By default assume that x0 can be used for 0. */
1415 return x == 0;
1419 /* Return the cost of binary operation X, given that the instruction
1420 sequence for a word-sized or smaller operation takes SIGNLE_INSNS
1421 instructions and that the sequence of a double-word operation takes
1422 DOUBLE_INSNS instructions. */
1424 static int
1425 riscv_binary_cost (rtx x, int single_insns, int double_insns)
1427 if (GET_MODE_SIZE (GET_MODE (x)) == UNITS_PER_WORD * 2)
1428 return COSTS_N_INSNS (double_insns);
1429 return COSTS_N_INSNS (single_insns);
1432 /* Return the cost of sign- or zero-extending OP. */
1434 static int
1435 riscv_extend_cost (rtx op, bool unsigned_p)
1437 if (MEM_P (op))
1438 return 0;
1440 if (unsigned_p && GET_MODE (op) == QImode)
1441 /* We can use ANDI. */
1442 return COSTS_N_INSNS (1);
1444 if (!unsigned_p && GET_MODE (op) == SImode)
1445 /* We can use SEXT.W. */
1446 return COSTS_N_INSNS (1);
1448 /* We need to use a shift left and a shift right. */
1449 return COSTS_N_INSNS (2);
1452 /* Implement TARGET_RTX_COSTS. */
1454 #define SINGLE_SHIFT_COST 1
1456 static bool
1457 riscv_rtx_costs (rtx x, machine_mode mode, int outer_code, int opno ATTRIBUTE_UNUSED,
1458 int *total, bool speed)
1460 bool float_mode_p = FLOAT_MODE_P (mode);
1461 int cost;
1463 switch (GET_CODE (x))
1465 case CONST_INT:
1466 if (riscv_immediate_operand_p (outer_code, INTVAL (x)))
1468 *total = 0;
1469 return true;
1471 /* Fall through. */
1473 case SYMBOL_REF:
1474 case LABEL_REF:
1475 case CONST_DOUBLE:
1476 case CONST:
1477 if ((cost = riscv_const_insns (x)) > 0)
1479 /* If the constant is likely to be stored in a GPR, SETs of
1480 single-insn constants are as cheap as register sets; we
1481 never want to CSE them. */
1482 if (cost == 1 && outer_code == SET)
1483 *total = 0;
1484 /* When we load a constant more than once, it usually is better
1485 to duplicate the last operation in the sequence than to CSE
1486 the constant itself. */
1487 else if (outer_code == SET || GET_MODE (x) == VOIDmode)
1488 *total = COSTS_N_INSNS (1);
1490 else /* The instruction will be fetched from the constant pool. */
1491 *total = COSTS_N_INSNS (riscv_symbol_insns (SYMBOL_ABSOLUTE));
1492 return true;
1494 case MEM:
1495 /* If the address is legitimate, return the number of
1496 instructions it needs. */
1497 if ((cost = riscv_address_insns (XEXP (x, 0), mode, true)) > 0)
1499 *total = COSTS_N_INSNS (cost + tune_info->memory_cost);
1500 return true;
1502 /* Otherwise use the default handling. */
1503 return false;
1505 case NOT:
1506 *total = COSTS_N_INSNS (GET_MODE_SIZE (mode) > UNITS_PER_WORD ? 2 : 1);
1507 return false;
1509 case AND:
1510 case IOR:
1511 case XOR:
1512 /* Double-word operations use two single-word operations. */
1513 *total = riscv_binary_cost (x, 1, 2);
1514 return false;
1516 case ZERO_EXTRACT:
1517 /* This is an SImode shift. */
1518 if (outer_code == SET && (INTVAL (XEXP (x, 2)) > 0)
1519 && (INTVAL (XEXP (x, 1)) + INTVAL (XEXP (x, 2)) == 32))
1521 *total = COSTS_N_INSNS (SINGLE_SHIFT_COST);
1522 return true;
1524 return false;
1526 case ASHIFT:
1527 case ASHIFTRT:
1528 case LSHIFTRT:
1529 *total = riscv_binary_cost (x, SINGLE_SHIFT_COST,
1530 CONSTANT_P (XEXP (x, 1)) ? 4 : 9);
1531 return false;
1533 case ABS:
1534 *total = COSTS_N_INSNS (float_mode_p ? 1 : 3);
1535 return false;
1537 case LO_SUM:
1538 *total = set_src_cost (XEXP (x, 0), mode, speed);
1539 return true;
1541 case LT:
1542 /* This is an SImode shift. */
1543 if (outer_code == SET && GET_MODE (x) == DImode
1544 && GET_MODE (XEXP (x, 0)) == SImode)
1546 *total = COSTS_N_INSNS (SINGLE_SHIFT_COST);
1547 return true;
1549 /* Fall through. */
1550 case LTU:
1551 case LE:
1552 case LEU:
1553 case GT:
1554 case GTU:
1555 case GE:
1556 case GEU:
1557 case EQ:
1558 case NE:
1559 /* Branch comparisons have VOIDmode, so use the first operand's
1560 mode instead. */
1561 mode = GET_MODE (XEXP (x, 0));
1562 if (float_mode_p)
1563 *total = tune_info->fp_add[mode == DFmode];
1564 else
1565 *total = riscv_binary_cost (x, 1, 3);
1566 return false;
1568 case UNORDERED:
1569 case ORDERED:
1570 /* (FEQ(A, A) & FEQ(B, B)) compared against 0. */
1571 mode = GET_MODE (XEXP (x, 0));
1572 *total = tune_info->fp_add[mode == DFmode] + COSTS_N_INSNS (2);
1573 return false;
1575 case UNEQ:
1576 case LTGT:
1577 /* (FEQ(A, A) & FEQ(B, B)) compared against FEQ(A, B). */
1578 mode = GET_MODE (XEXP (x, 0));
1579 *total = tune_info->fp_add[mode == DFmode] + COSTS_N_INSNS (3);
1580 return false;
1582 case UNGE:
1583 case UNGT:
1584 case UNLE:
1585 case UNLT:
1586 /* FLT or FLE, but guarded by an FFLAGS read and write. */
1587 mode = GET_MODE (XEXP (x, 0));
1588 *total = tune_info->fp_add[mode == DFmode] + COSTS_N_INSNS (4);
1589 return false;
1591 case MINUS:
1592 case PLUS:
1593 if (float_mode_p)
1594 *total = tune_info->fp_add[mode == DFmode];
1595 else
1596 *total = riscv_binary_cost (x, 1, 4);
1597 return false;
1599 case NEG:
1601 rtx op = XEXP (x, 0);
1602 if (GET_CODE (op) == FMA && !HONOR_SIGNED_ZEROS (mode))
1604 *total = (tune_info->fp_mul[mode == DFmode]
1605 + set_src_cost (XEXP (op, 0), mode, speed)
1606 + set_src_cost (XEXP (op, 1), mode, speed)
1607 + set_src_cost (XEXP (op, 2), mode, speed));
1608 return true;
1612 if (float_mode_p)
1613 *total = tune_info->fp_add[mode == DFmode];
1614 else
1615 *total = COSTS_N_INSNS (GET_MODE_SIZE (mode) > UNITS_PER_WORD ? 4 : 1);
1616 return false;
1618 case MULT:
1619 if (float_mode_p)
1620 *total = tune_info->fp_mul[mode == DFmode];
1621 else if (!TARGET_MUL)
1622 /* Estimate the cost of a library call. */
1623 *total = COSTS_N_INSNS (speed ? 32 : 6);
1624 else if (GET_MODE_SIZE (mode) > UNITS_PER_WORD)
1625 *total = 3 * tune_info->int_mul[0] + COSTS_N_INSNS (2);
1626 else if (!speed)
1627 *total = COSTS_N_INSNS (1);
1628 else
1629 *total = tune_info->int_mul[mode == DImode];
1630 return false;
1632 case DIV:
1633 case SQRT:
1634 case MOD:
1635 if (float_mode_p)
1637 *total = tune_info->fp_div[mode == DFmode];
1638 return false;
1640 /* Fall through. */
1642 case UDIV:
1643 case UMOD:
1644 if (!TARGET_DIV)
1645 /* Estimate the cost of a library call. */
1646 *total = COSTS_N_INSNS (speed ? 32 : 6);
1647 else if (speed)
1648 *total = tune_info->int_div[mode == DImode];
1649 else
1650 *total = COSTS_N_INSNS (1);
1651 return false;
1653 case ZERO_EXTEND:
1654 /* This is an SImode shift. */
1655 if (GET_CODE (XEXP (x, 0)) == LSHIFTRT)
1657 *total = COSTS_N_INSNS (SINGLE_SHIFT_COST);
1658 return true;
1660 /* Fall through. */
1661 case SIGN_EXTEND:
1662 *total = riscv_extend_cost (XEXP (x, 0), GET_CODE (x) == ZERO_EXTEND);
1663 return false;
1665 case FLOAT:
1666 case UNSIGNED_FLOAT:
1667 case FIX:
1668 case FLOAT_EXTEND:
1669 case FLOAT_TRUNCATE:
1670 *total = tune_info->fp_add[mode == DFmode];
1671 return false;
1673 case FMA:
1674 *total = (tune_info->fp_mul[mode == DFmode]
1675 + set_src_cost (XEXP (x, 0), mode, speed)
1676 + set_src_cost (XEXP (x, 1), mode, speed)
1677 + set_src_cost (XEXP (x, 2), mode, speed));
1678 return true;
1680 case UNSPEC:
1681 if (XINT (x, 1) == UNSPEC_AUIPC)
1683 /* Make AUIPC cheap to avoid spilling its result to the stack. */
1684 *total = 1;
1685 return true;
1687 return false;
1689 default:
1690 return false;
1694 /* Implement TARGET_ADDRESS_COST. */
1696 static int
1697 riscv_address_cost (rtx addr, machine_mode mode,
1698 addr_space_t as ATTRIBUTE_UNUSED,
1699 bool speed ATTRIBUTE_UNUSED)
1701 return riscv_address_insns (addr, mode, false);
1704 /* Return one word of double-word value OP. HIGH_P is true to select the
1705 high part or false to select the low part. */
1708 riscv_subword (rtx op, bool high_p)
1710 unsigned int byte = high_p ? UNITS_PER_WORD : 0;
1711 machine_mode mode = GET_MODE (op);
1713 if (mode == VOIDmode)
1714 mode = TARGET_64BIT ? TImode : DImode;
1716 if (MEM_P (op))
1717 return adjust_address (op, word_mode, byte);
1719 if (REG_P (op))
1720 gcc_assert (!FP_REG_RTX_P (op));
1722 return simplify_gen_subreg (word_mode, op, mode, byte);
1725 /* Return true if a 64-bit move from SRC to DEST should be split into two. */
1727 bool
1728 riscv_split_64bit_move_p (rtx dest, rtx src)
1730 if (TARGET_64BIT)
1731 return false;
1733 /* Allow FPR <-> FPR and FPR <-> MEM moves, and permit the special case
1734 of zeroing an FPR with FCVT.D.W. */
1735 if (TARGET_DOUBLE_FLOAT
1736 && ((FP_REG_RTX_P (src) && FP_REG_RTX_P (dest))
1737 || (FP_REG_RTX_P (dest) && MEM_P (src))
1738 || (FP_REG_RTX_P (src) && MEM_P (dest))
1739 || (FP_REG_RTX_P (dest) && src == CONST0_RTX (GET_MODE (src)))))
1740 return false;
1742 return true;
1745 /* Split a doubleword move from SRC to DEST. On 32-bit targets,
1746 this function handles 64-bit moves for which riscv_split_64bit_move_p
1747 holds. For 64-bit targets, this function handles 128-bit moves. */
1749 void
1750 riscv_split_doubleword_move (rtx dest, rtx src)
1752 rtx low_dest;
1754 /* The operation can be split into two normal moves. Decide in
1755 which order to do them. */
1756 low_dest = riscv_subword (dest, false);
1757 if (REG_P (low_dest) && reg_overlap_mentioned_p (low_dest, src))
1759 riscv_emit_move (riscv_subword (dest, true), riscv_subword (src, true));
1760 riscv_emit_move (low_dest, riscv_subword (src, false));
1762 else
1764 riscv_emit_move (low_dest, riscv_subword (src, false));
1765 riscv_emit_move (riscv_subword (dest, true), riscv_subword (src, true));
1769 /* Return the appropriate instructions to move SRC into DEST. Assume
1770 that SRC is operand 1 and DEST is operand 0. */
1772 const char *
1773 riscv_output_move (rtx dest, rtx src)
1775 enum rtx_code dest_code, src_code;
1776 machine_mode mode;
1777 bool dbl_p;
1779 dest_code = GET_CODE (dest);
1780 src_code = GET_CODE (src);
1781 mode = GET_MODE (dest);
1782 dbl_p = (GET_MODE_SIZE (mode) == 8);
1784 if (dbl_p && riscv_split_64bit_move_p (dest, src))
1785 return "#";
1787 if (dest_code == REG && GP_REG_P (REGNO (dest)))
1789 if (src_code == REG && FP_REG_P (REGNO (src)))
1790 return dbl_p ? "fmv.x.d\t%0,%1" : "fmv.x.s\t%0,%1";
1792 if (src_code == MEM)
1793 switch (GET_MODE_SIZE (mode))
1795 case 1: return "lbu\t%0,%1";
1796 case 2: return "lhu\t%0,%1";
1797 case 4: return "lw\t%0,%1";
1798 case 8: return "ld\t%0,%1";
1801 if (src_code == CONST_INT)
1802 return "li\t%0,%1";
1804 if (src_code == HIGH)
1805 return "lui\t%0,%h1";
1807 if (symbolic_operand (src, VOIDmode))
1808 switch (riscv_classify_symbolic_expression (src))
1810 case SYMBOL_GOT_DISP: return "la\t%0,%1";
1811 case SYMBOL_ABSOLUTE: return "lla\t%0,%1";
1812 case SYMBOL_PCREL: return "lla\t%0,%1";
1813 default: gcc_unreachable ();
1816 if ((src_code == REG && GP_REG_P (REGNO (src)))
1817 || (src == CONST0_RTX (mode)))
1819 if (dest_code == REG)
1821 if (GP_REG_P (REGNO (dest)))
1822 return "mv\t%0,%z1";
1824 if (FP_REG_P (REGNO (dest)))
1826 if (!dbl_p)
1827 return "fmv.s.x\t%0,%z1";
1828 if (TARGET_64BIT)
1829 return "fmv.d.x\t%0,%z1";
1830 /* in RV32, we can emulate fmv.d.x %0, x0 using fcvt.d.w */
1831 gcc_assert (src == CONST0_RTX (mode));
1832 return "fcvt.d.w\t%0,x0";
1835 if (dest_code == MEM)
1836 switch (GET_MODE_SIZE (mode))
1838 case 1: return "sb\t%z1,%0";
1839 case 2: return "sh\t%z1,%0";
1840 case 4: return "sw\t%z1,%0";
1841 case 8: return "sd\t%z1,%0";
1844 if (src_code == REG && FP_REG_P (REGNO (src)))
1846 if (dest_code == REG && FP_REG_P (REGNO (dest)))
1847 return dbl_p ? "fmv.d\t%0,%1" : "fmv.s\t%0,%1";
1849 if (dest_code == MEM)
1850 return dbl_p ? "fsd\t%1,%0" : "fsw\t%1,%0";
1852 if (dest_code == REG && FP_REG_P (REGNO (dest)))
1854 if (src_code == MEM)
1855 return dbl_p ? "fld\t%0,%1" : "flw\t%0,%1";
1857 gcc_unreachable ();
1860 const char *
1861 riscv_output_return ()
1863 if (cfun->machine->naked_p)
1864 return "";
1866 return "ret";
1870 /* Return true if CMP1 is a suitable second operand for integer ordering
1871 test CODE. See also the *sCC patterns in riscv.md. */
1873 static bool
1874 riscv_int_order_operand_ok_p (enum rtx_code code, rtx cmp1)
1876 switch (code)
1878 case GT:
1879 case GTU:
1880 return reg_or_0_operand (cmp1, VOIDmode);
1882 case GE:
1883 case GEU:
1884 return cmp1 == const1_rtx;
1886 case LT:
1887 case LTU:
1888 return arith_operand (cmp1, VOIDmode);
1890 case LE:
1891 return sle_operand (cmp1, VOIDmode);
1893 case LEU:
1894 return sleu_operand (cmp1, VOIDmode);
1896 default:
1897 gcc_unreachable ();
1901 /* Return true if *CMP1 (of mode MODE) is a valid second operand for
1902 integer ordering test *CODE, or if an equivalent combination can
1903 be formed by adjusting *CODE and *CMP1. When returning true, update
1904 *CODE and *CMP1 with the chosen code and operand, otherwise leave
1905 them alone. */
1907 static bool
1908 riscv_canonicalize_int_order_test (enum rtx_code *code, rtx *cmp1,
1909 machine_mode mode)
1911 HOST_WIDE_INT plus_one;
1913 if (riscv_int_order_operand_ok_p (*code, *cmp1))
1914 return true;
1916 if (CONST_INT_P (*cmp1))
1917 switch (*code)
1919 case LE:
1920 plus_one = trunc_int_for_mode (UINTVAL (*cmp1) + 1, mode);
1921 if (INTVAL (*cmp1) < plus_one)
1923 *code = LT;
1924 *cmp1 = force_reg (mode, GEN_INT (plus_one));
1925 return true;
1927 break;
1929 case LEU:
1930 plus_one = trunc_int_for_mode (UINTVAL (*cmp1) + 1, mode);
1931 if (plus_one != 0)
1933 *code = LTU;
1934 *cmp1 = force_reg (mode, GEN_INT (plus_one));
1935 return true;
1937 break;
1939 default:
1940 break;
1942 return false;
1945 /* Compare CMP0 and CMP1 using ordering test CODE and store the result
1946 in TARGET. CMP0 and TARGET are register_operands. If INVERT_PTR
1947 is nonnull, it's OK to set TARGET to the inverse of the result and
1948 flip *INVERT_PTR instead. */
1950 static void
1951 riscv_emit_int_order_test (enum rtx_code code, bool *invert_ptr,
1952 rtx target, rtx cmp0, rtx cmp1)
1954 machine_mode mode;
1956 /* First see if there is a RISCV instruction that can do this operation.
1957 If not, try doing the same for the inverse operation. If that also
1958 fails, force CMP1 into a register and try again. */
1959 mode = GET_MODE (cmp0);
1960 if (riscv_canonicalize_int_order_test (&code, &cmp1, mode))
1961 riscv_emit_binary (code, target, cmp0, cmp1);
1962 else
1964 enum rtx_code inv_code = reverse_condition (code);
1965 if (!riscv_canonicalize_int_order_test (&inv_code, &cmp1, mode))
1967 cmp1 = force_reg (mode, cmp1);
1968 riscv_emit_int_order_test (code, invert_ptr, target, cmp0, cmp1);
1970 else if (invert_ptr == 0)
1972 rtx inv_target = riscv_force_binary (GET_MODE (target),
1973 inv_code, cmp0, cmp1);
1974 riscv_emit_binary (XOR, target, inv_target, const1_rtx);
1976 else
1978 *invert_ptr = !*invert_ptr;
1979 riscv_emit_binary (inv_code, target, cmp0, cmp1);
1984 /* Return a register that is zero iff CMP0 and CMP1 are equal.
1985 The register will have the same mode as CMP0. */
1987 static rtx
1988 riscv_zero_if_equal (rtx cmp0, rtx cmp1)
1990 if (cmp1 == const0_rtx)
1991 return cmp0;
1993 return expand_binop (GET_MODE (cmp0), sub_optab,
1994 cmp0, cmp1, 0, 0, OPTAB_DIRECT);
1997 /* Sign- or zero-extend OP0 and OP1 for integer comparisons. */
1999 static void
2000 riscv_extend_comparands (rtx_code code, rtx *op0, rtx *op1)
2002 /* Comparisons consider all XLEN bits, so extend sub-XLEN values. */
2003 if (GET_MODE_SIZE (word_mode) > GET_MODE_SIZE (GET_MODE (*op0)))
2005 /* It is more profitable to zero-extend QImode values. But not if the
2006 first operand has already been sign-extended, and the second one is
2007 is a constant or has already been sign-extended also. */
2008 if (unsigned_condition (code) == code
2009 && (GET_MODE (*op0) == QImode
2010 && ! (GET_CODE (*op0) == SUBREG
2011 && SUBREG_PROMOTED_VAR_P (*op0)
2012 && SUBREG_PROMOTED_SIGNED_P (*op0)
2013 && (CONST_INT_P (*op1)
2014 || (GET_CODE (*op1) == SUBREG
2015 && SUBREG_PROMOTED_VAR_P (*op1)
2016 && SUBREG_PROMOTED_SIGNED_P (*op1))))))
2018 *op0 = gen_rtx_ZERO_EXTEND (word_mode, *op0);
2019 if (CONST_INT_P (*op1))
2020 *op1 = GEN_INT ((uint8_t) INTVAL (*op1));
2021 else
2022 *op1 = gen_rtx_ZERO_EXTEND (word_mode, *op1);
2024 else
2026 *op0 = gen_rtx_SIGN_EXTEND (word_mode, *op0);
2027 if (*op1 != const0_rtx)
2028 *op1 = gen_rtx_SIGN_EXTEND (word_mode, *op1);
2033 /* Convert a comparison into something that can be used in a branch. On
2034 entry, *OP0 and *OP1 are the values being compared and *CODE is the code
2035 used to compare them. Update them to describe the final comparison. */
2037 static void
2038 riscv_emit_int_compare (enum rtx_code *code, rtx *op0, rtx *op1)
2040 if (splittable_const_int_operand (*op1, VOIDmode))
2042 HOST_WIDE_INT rhs = INTVAL (*op1);
2044 if (*code == EQ || *code == NE)
2046 /* Convert e.g. OP0 == 2048 into OP0 - 2048 == 0. */
2047 if (SMALL_OPERAND (-rhs))
2049 *op0 = riscv_force_binary (GET_MODE (*op0), PLUS, *op0,
2050 GEN_INT (-rhs));
2051 *op1 = const0_rtx;
2054 else
2056 static const enum rtx_code mag_comparisons[][2] = {
2057 {LEU, LTU}, {GTU, GEU}, {LE, LT}, {GT, GE}
2060 /* Convert e.g. (OP0 <= 0xFFF) into (OP0 < 0x1000). */
2061 for (size_t i = 0; i < ARRAY_SIZE (mag_comparisons); i++)
2063 HOST_WIDE_INT new_rhs;
2064 bool increment = *code == mag_comparisons[i][0];
2065 bool decrement = *code == mag_comparisons[i][1];
2066 if (!increment && !decrement)
2067 continue;
2069 new_rhs = rhs + (increment ? 1 : -1);
2070 if (riscv_integer_cost (new_rhs) < riscv_integer_cost (rhs)
2071 && (rhs < 0) == (new_rhs < 0))
2073 *op1 = GEN_INT (new_rhs);
2074 *code = mag_comparisons[i][increment];
2076 break;
2081 riscv_extend_comparands (*code, op0, op1);
2083 *op0 = force_reg (word_mode, *op0);
2084 if (*op1 != const0_rtx)
2085 *op1 = force_reg (word_mode, *op1);
2088 /* Like riscv_emit_int_compare, but for floating-point comparisons. */
2090 static void
2091 riscv_emit_float_compare (enum rtx_code *code, rtx *op0, rtx *op1)
2093 rtx tmp0, tmp1, cmp_op0 = *op0, cmp_op1 = *op1;
2094 enum rtx_code fp_code = *code;
2095 *code = NE;
2097 switch (fp_code)
2099 case UNORDERED:
2100 *code = EQ;
2101 /* Fall through. */
2103 case ORDERED:
2104 /* a == a && b == b */
2105 tmp0 = riscv_force_binary (word_mode, EQ, cmp_op0, cmp_op0);
2106 tmp1 = riscv_force_binary (word_mode, EQ, cmp_op1, cmp_op1);
2107 *op0 = riscv_force_binary (word_mode, AND, tmp0, tmp1);
2108 *op1 = const0_rtx;
2109 break;
2111 case UNEQ:
2112 case LTGT:
2113 /* ordered(a, b) > (a == b) */
2114 *code = fp_code == LTGT ? GTU : EQ;
2115 tmp0 = riscv_force_binary (word_mode, EQ, cmp_op0, cmp_op0);
2116 tmp1 = riscv_force_binary (word_mode, EQ, cmp_op1, cmp_op1);
2117 *op0 = riscv_force_binary (word_mode, AND, tmp0, tmp1);
2118 *op1 = riscv_force_binary (word_mode, EQ, cmp_op0, cmp_op1);
2119 break;
2121 #define UNORDERED_COMPARISON(CODE, CMP) \
2122 case CODE: \
2123 *code = EQ; \
2124 *op0 = gen_reg_rtx (word_mode); \
2125 if (GET_MODE (cmp_op0) == SFmode && TARGET_64BIT) \
2126 emit_insn (gen_f##CMP##_quietsfdi4 (*op0, cmp_op0, cmp_op1)); \
2127 else if (GET_MODE (cmp_op0) == SFmode) \
2128 emit_insn (gen_f##CMP##_quietsfsi4 (*op0, cmp_op0, cmp_op1)); \
2129 else if (GET_MODE (cmp_op0) == DFmode && TARGET_64BIT) \
2130 emit_insn (gen_f##CMP##_quietdfdi4 (*op0, cmp_op0, cmp_op1)); \
2131 else if (GET_MODE (cmp_op0) == DFmode) \
2132 emit_insn (gen_f##CMP##_quietdfsi4 (*op0, cmp_op0, cmp_op1)); \
2133 else \
2134 gcc_unreachable (); \
2135 *op1 = const0_rtx; \
2136 break;
2138 case UNLT:
2139 std::swap (cmp_op0, cmp_op1);
2140 gcc_fallthrough ();
2142 UNORDERED_COMPARISON(UNGT, le)
2144 case UNLE:
2145 std::swap (cmp_op0, cmp_op1);
2146 gcc_fallthrough ();
2148 UNORDERED_COMPARISON(UNGE, lt)
2149 #undef UNORDERED_COMPARISON
2151 case NE:
2152 fp_code = EQ;
2153 *code = EQ;
2154 /* Fall through. */
2156 case EQ:
2157 case LE:
2158 case LT:
2159 case GE:
2160 case GT:
2161 /* We have instructions for these cases. */
2162 *op0 = riscv_force_binary (word_mode, fp_code, cmp_op0, cmp_op1);
2163 *op1 = const0_rtx;
2164 break;
2166 default:
2167 gcc_unreachable ();
2171 /* CODE-compare OP0 and OP1. Store the result in TARGET. */
2173 void
2174 riscv_expand_int_scc (rtx target, enum rtx_code code, rtx op0, rtx op1)
2176 riscv_extend_comparands (code, &op0, &op1);
2177 op0 = force_reg (word_mode, op0);
2179 if (code == EQ || code == NE)
2181 rtx zie = riscv_zero_if_equal (op0, op1);
2182 riscv_emit_binary (code, target, zie, const0_rtx);
2184 else
2185 riscv_emit_int_order_test (code, 0, target, op0, op1);
2188 /* Like riscv_expand_int_scc, but for floating-point comparisons. */
2190 void
2191 riscv_expand_float_scc (rtx target, enum rtx_code code, rtx op0, rtx op1)
2193 riscv_emit_float_compare (&code, &op0, &op1);
2195 rtx cmp = riscv_force_binary (word_mode, code, op0, op1);
2196 riscv_emit_set (target, lowpart_subreg (SImode, cmp, word_mode));
2199 /* Jump to LABEL if (CODE OP0 OP1) holds. */
2201 void
2202 riscv_expand_conditional_branch (rtx label, rtx_code code, rtx op0, rtx op1)
2204 if (FLOAT_MODE_P (GET_MODE (op1)))
2205 riscv_emit_float_compare (&code, &op0, &op1);
2206 else
2207 riscv_emit_int_compare (&code, &op0, &op1);
2209 rtx condition = gen_rtx_fmt_ee (code, VOIDmode, op0, op1);
2210 emit_jump_insn (gen_condjump (condition, label));
2213 /* Implement TARGET_FUNCTION_ARG_BOUNDARY. Every parameter gets at
2214 least PARM_BOUNDARY bits of alignment, but will be given anything up
2215 to PREFERRED_STACK_BOUNDARY bits if the type requires it. */
2217 static unsigned int
2218 riscv_function_arg_boundary (machine_mode mode, const_tree type)
2220 unsigned int alignment;
2222 /* Use natural alignment if the type is not aggregate data. */
2223 if (type && !AGGREGATE_TYPE_P (type))
2224 alignment = TYPE_ALIGN (TYPE_MAIN_VARIANT (type));
2225 else
2226 alignment = type ? TYPE_ALIGN (type) : GET_MODE_ALIGNMENT (mode);
2228 return MIN (PREFERRED_STACK_BOUNDARY, MAX (PARM_BOUNDARY, alignment));
2231 /* If MODE represents an argument that can be passed or returned in
2232 floating-point registers, return the number of registers, else 0. */
2234 static unsigned
2235 riscv_pass_mode_in_fpr_p (machine_mode mode)
2237 if (GET_MODE_UNIT_SIZE (mode) <= UNITS_PER_FP_ARG)
2239 if (GET_MODE_CLASS (mode) == MODE_FLOAT)
2240 return 1;
2242 if (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
2243 return 2;
2246 return 0;
2249 typedef struct {
2250 const_tree type;
2251 HOST_WIDE_INT offset;
2252 } riscv_aggregate_field;
2254 /* Identify subfields of aggregates that are candidates for passing in
2255 floating-point registers. */
2257 static int
2258 riscv_flatten_aggregate_field (const_tree type,
2259 riscv_aggregate_field fields[2],
2260 int n, HOST_WIDE_INT offset)
2262 switch (TREE_CODE (type))
2264 case RECORD_TYPE:
2265 /* Can't handle incomplete types nor sizes that are not fixed. */
2266 if (!COMPLETE_TYPE_P (type)
2267 || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST
2268 || !tree_fits_uhwi_p (TYPE_SIZE (type)))
2269 return -1;
2271 for (tree f = TYPE_FIELDS (type); f; f = DECL_CHAIN (f))
2272 if (TREE_CODE (f) == FIELD_DECL)
2274 if (!TYPE_P (TREE_TYPE (f)))
2275 return -1;
2277 HOST_WIDE_INT pos = offset + int_byte_position (f);
2278 n = riscv_flatten_aggregate_field (TREE_TYPE (f), fields, n, pos);
2279 if (n < 0)
2280 return -1;
2282 return n;
2284 case ARRAY_TYPE:
2286 HOST_WIDE_INT n_elts;
2287 riscv_aggregate_field subfields[2];
2288 tree index = TYPE_DOMAIN (type);
2289 tree elt_size = TYPE_SIZE_UNIT (TREE_TYPE (type));
2290 int n_subfields = riscv_flatten_aggregate_field (TREE_TYPE (type),
2291 subfields, 0, offset);
2293 /* Can't handle incomplete types nor sizes that are not fixed. */
2294 if (n_subfields <= 0
2295 || !COMPLETE_TYPE_P (type)
2296 || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST
2297 || !index
2298 || !TYPE_MAX_VALUE (index)
2299 || !tree_fits_uhwi_p (TYPE_MAX_VALUE (index))
2300 || !TYPE_MIN_VALUE (index)
2301 || !tree_fits_uhwi_p (TYPE_MIN_VALUE (index))
2302 || !tree_fits_uhwi_p (elt_size))
2303 return -1;
2305 n_elts = 1 + tree_to_uhwi (TYPE_MAX_VALUE (index))
2306 - tree_to_uhwi (TYPE_MIN_VALUE (index));
2307 gcc_assert (n_elts >= 0);
2309 for (HOST_WIDE_INT i = 0; i < n_elts; i++)
2310 for (int j = 0; j < n_subfields; j++)
2312 if (n >= 2)
2313 return -1;
2315 fields[n] = subfields[j];
2316 fields[n++].offset += i * tree_to_uhwi (elt_size);
2319 return n;
2322 case COMPLEX_TYPE:
2324 /* Complex type need consume 2 field, so n must be 0. */
2325 if (n != 0)
2326 return -1;
2328 HOST_WIDE_INT elt_size = GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (type)));
2330 if (elt_size <= UNITS_PER_FP_ARG)
2332 fields[0].type = TREE_TYPE (type);
2333 fields[0].offset = offset;
2334 fields[1].type = TREE_TYPE (type);
2335 fields[1].offset = offset + elt_size;
2337 return 2;
2340 return -1;
2343 default:
2344 if (n < 2
2345 && ((SCALAR_FLOAT_TYPE_P (type)
2346 && GET_MODE_SIZE (TYPE_MODE (type)) <= UNITS_PER_FP_ARG)
2347 || (INTEGRAL_TYPE_P (type)
2348 && GET_MODE_SIZE (TYPE_MODE (type)) <= UNITS_PER_WORD)))
2350 fields[n].type = type;
2351 fields[n].offset = offset;
2352 return n + 1;
2354 else
2355 return -1;
2359 /* Identify candidate aggregates for passing in floating-point registers.
2360 Candidates have at most two fields after flattening. */
2362 static int
2363 riscv_flatten_aggregate_argument (const_tree type,
2364 riscv_aggregate_field fields[2])
2366 if (!type || TREE_CODE (type) != RECORD_TYPE)
2367 return -1;
2369 return riscv_flatten_aggregate_field (type, fields, 0, 0);
2372 /* See whether TYPE is a record whose fields should be returned in one or
2373 two floating-point registers. If so, populate FIELDS accordingly. */
2375 static unsigned
2376 riscv_pass_aggregate_in_fpr_pair_p (const_tree type,
2377 riscv_aggregate_field fields[2])
2379 int n = riscv_flatten_aggregate_argument (type, fields);
2381 for (int i = 0; i < n; i++)
2382 if (!SCALAR_FLOAT_TYPE_P (fields[i].type))
2383 return 0;
2385 return n > 0 ? n : 0;
2388 /* See whether TYPE is a record whose fields should be returned in one or
2389 floating-point register and one integer register. If so, populate
2390 FIELDS accordingly. */
2392 static bool
2393 riscv_pass_aggregate_in_fpr_and_gpr_p (const_tree type,
2394 riscv_aggregate_field fields[2])
2396 unsigned num_int = 0, num_float = 0;
2397 int n = riscv_flatten_aggregate_argument (type, fields);
2399 for (int i = 0; i < n; i++)
2401 num_float += SCALAR_FLOAT_TYPE_P (fields[i].type);
2402 num_int += INTEGRAL_TYPE_P (fields[i].type);
2405 return num_int == 1 && num_float == 1;
2408 /* Return the representation of an argument passed or returned in an FPR
2409 when the value has mode VALUE_MODE and the type has TYPE_MODE. The
2410 two modes may be different for structures like:
2412 struct __attribute__((packed)) foo { float f; }
2414 where the SFmode value "f" is passed in REGNO but the struct itself
2415 has mode BLKmode. */
2417 static rtx
2418 riscv_pass_fpr_single (machine_mode type_mode, unsigned regno,
2419 machine_mode value_mode)
2421 rtx x = gen_rtx_REG (value_mode, regno);
2423 if (type_mode != value_mode)
2425 x = gen_rtx_EXPR_LIST (VOIDmode, x, const0_rtx);
2426 x = gen_rtx_PARALLEL (type_mode, gen_rtvec (1, x));
2428 return x;
2431 /* Pass or return a composite value in the FPR pair REGNO and REGNO + 1.
2432 MODE is the mode of the composite. MODE1 and OFFSET1 are the mode and
2433 byte offset for the first value, likewise MODE2 and OFFSET2 for the
2434 second value. */
2436 static rtx
2437 riscv_pass_fpr_pair (machine_mode mode, unsigned regno1,
2438 machine_mode mode1, HOST_WIDE_INT offset1,
2439 unsigned regno2, machine_mode mode2,
2440 HOST_WIDE_INT offset2)
2442 return gen_rtx_PARALLEL
2443 (mode,
2444 gen_rtvec (2,
2445 gen_rtx_EXPR_LIST (VOIDmode,
2446 gen_rtx_REG (mode1, regno1),
2447 GEN_INT (offset1)),
2448 gen_rtx_EXPR_LIST (VOIDmode,
2449 gen_rtx_REG (mode2, regno2),
2450 GEN_INT (offset2))));
2453 /* Fill INFO with information about a single argument, and return an
2454 RTL pattern to pass or return the argument. CUM is the cumulative
2455 state for earlier arguments. MODE is the mode of this argument and
2456 TYPE is its type (if known). NAMED is true if this is a named
2457 (fixed) argument rather than a variable one. RETURN_P is true if
2458 returning the argument, or false if passing the argument. */
2460 static rtx
2461 riscv_get_arg_info (struct riscv_arg_info *info, const CUMULATIVE_ARGS *cum,
2462 machine_mode mode, const_tree type, bool named,
2463 bool return_p)
2465 unsigned num_bytes, num_words;
2466 unsigned fpr_base = return_p ? FP_RETURN : FP_ARG_FIRST;
2467 unsigned gpr_base = return_p ? GP_RETURN : GP_ARG_FIRST;
2468 unsigned alignment = riscv_function_arg_boundary (mode, type);
2470 memset (info, 0, sizeof (*info));
2471 info->gpr_offset = cum->num_gprs;
2472 info->fpr_offset = cum->num_fprs;
2474 if (named)
2476 riscv_aggregate_field fields[2];
2477 unsigned fregno = fpr_base + info->fpr_offset;
2478 unsigned gregno = gpr_base + info->gpr_offset;
2480 /* Pass one- or two-element floating-point aggregates in FPRs. */
2481 if ((info->num_fprs = riscv_pass_aggregate_in_fpr_pair_p (type, fields))
2482 && info->fpr_offset + info->num_fprs <= MAX_ARGS_IN_REGISTERS)
2483 switch (info->num_fprs)
2485 case 1:
2486 return riscv_pass_fpr_single (mode, fregno,
2487 TYPE_MODE (fields[0].type));
2489 case 2:
2490 return riscv_pass_fpr_pair (mode, fregno,
2491 TYPE_MODE (fields[0].type),
2492 fields[0].offset,
2493 fregno + 1,
2494 TYPE_MODE (fields[1].type),
2495 fields[1].offset);
2497 default:
2498 gcc_unreachable ();
2501 /* Pass real and complex floating-point numbers in FPRs. */
2502 if ((info->num_fprs = riscv_pass_mode_in_fpr_p (mode))
2503 && info->fpr_offset + info->num_fprs <= MAX_ARGS_IN_REGISTERS)
2504 switch (GET_MODE_CLASS (mode))
2506 case MODE_FLOAT:
2507 return gen_rtx_REG (mode, fregno);
2509 case MODE_COMPLEX_FLOAT:
2510 return riscv_pass_fpr_pair (mode, fregno, GET_MODE_INNER (mode), 0,
2511 fregno + 1, GET_MODE_INNER (mode),
2512 GET_MODE_UNIT_SIZE (mode));
2514 default:
2515 gcc_unreachable ();
2518 /* Pass structs with one float and one integer in an FPR and a GPR. */
2519 if (riscv_pass_aggregate_in_fpr_and_gpr_p (type, fields)
2520 && info->gpr_offset < MAX_ARGS_IN_REGISTERS
2521 && info->fpr_offset < MAX_ARGS_IN_REGISTERS)
2523 info->num_gprs = 1;
2524 info->num_fprs = 1;
2526 if (!SCALAR_FLOAT_TYPE_P (fields[0].type))
2527 std::swap (fregno, gregno);
2529 return riscv_pass_fpr_pair (mode, fregno, TYPE_MODE (fields[0].type),
2530 fields[0].offset,
2531 gregno, TYPE_MODE (fields[1].type),
2532 fields[1].offset);
2536 /* Work out the size of the argument. */
2537 num_bytes = type ? int_size_in_bytes (type) : GET_MODE_SIZE (mode);
2538 num_words = (num_bytes + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
2540 /* Doubleword-aligned varargs start on an even register boundary. */
2541 if (!named && num_bytes != 0 && alignment > BITS_PER_WORD)
2542 info->gpr_offset += info->gpr_offset & 1;
2544 /* Partition the argument between registers and stack. */
2545 info->num_fprs = 0;
2546 info->num_gprs = MIN (num_words, MAX_ARGS_IN_REGISTERS - info->gpr_offset);
2547 info->stack_p = (num_words - info->num_gprs) != 0;
2549 if (info->num_gprs || return_p)
2550 return gen_rtx_REG (mode, gpr_base + info->gpr_offset);
2552 return NULL_RTX;
2555 /* Implement TARGET_FUNCTION_ARG. */
2557 static rtx
2558 riscv_function_arg (cumulative_args_t cum_v, machine_mode mode,
2559 const_tree type, bool named)
2561 CUMULATIVE_ARGS *cum = get_cumulative_args (cum_v);
2562 struct riscv_arg_info info;
2564 if (mode == VOIDmode)
2565 return NULL;
2567 return riscv_get_arg_info (&info, cum, mode, type, named, false);
2570 /* Implement TARGET_FUNCTION_ARG_ADVANCE. */
2572 static void
2573 riscv_function_arg_advance (cumulative_args_t cum_v, machine_mode mode,
2574 const_tree type, bool named)
2576 CUMULATIVE_ARGS *cum = get_cumulative_args (cum_v);
2577 struct riscv_arg_info info;
2579 riscv_get_arg_info (&info, cum, mode, type, named, false);
2581 /* Advance the register count. This has the effect of setting
2582 num_gprs to MAX_ARGS_IN_REGISTERS if a doubleword-aligned
2583 argument required us to skip the final GPR and pass the whole
2584 argument on the stack. */
2585 cum->num_fprs = info.fpr_offset + info.num_fprs;
2586 cum->num_gprs = info.gpr_offset + info.num_gprs;
2589 /* Implement TARGET_ARG_PARTIAL_BYTES. */
2591 static int
2592 riscv_arg_partial_bytes (cumulative_args_t cum,
2593 machine_mode mode, tree type, bool named)
2595 struct riscv_arg_info arg;
2597 riscv_get_arg_info (&arg, get_cumulative_args (cum), mode, type, named, false);
2598 return arg.stack_p ? arg.num_gprs * UNITS_PER_WORD : 0;
2601 /* Implement FUNCTION_VALUE and LIBCALL_VALUE. For normal calls,
2602 VALTYPE is the return type and MODE is VOIDmode. For libcalls,
2603 VALTYPE is null and MODE is the mode of the return value. */
2606 riscv_function_value (const_tree type, const_tree func, machine_mode mode)
2608 struct riscv_arg_info info;
2609 CUMULATIVE_ARGS args;
2611 if (type)
2613 int unsigned_p = TYPE_UNSIGNED (type);
2615 mode = TYPE_MODE (type);
2617 /* Since TARGET_PROMOTE_FUNCTION_MODE unconditionally promotes,
2618 return values, promote the mode here too. */
2619 mode = promote_function_mode (type, mode, &unsigned_p, func, 1);
2622 memset (&args, 0, sizeof args);
2623 return riscv_get_arg_info (&info, &args, mode, type, true, true);
2626 /* Implement TARGET_PASS_BY_REFERENCE. */
2628 static bool
2629 riscv_pass_by_reference (cumulative_args_t cum_v, machine_mode mode,
2630 const_tree type, bool named)
2632 HOST_WIDE_INT size = type ? int_size_in_bytes (type) : GET_MODE_SIZE (mode);
2633 struct riscv_arg_info info;
2634 CUMULATIVE_ARGS *cum = get_cumulative_args (cum_v);
2636 /* ??? std_gimplify_va_arg_expr passes NULL for cum. Fortunately, we
2637 never pass variadic arguments in floating-point registers, so we can
2638 avoid the call to riscv_get_arg_info in this case. */
2639 if (cum != NULL)
2641 /* Don't pass by reference if we can use a floating-point register. */
2642 riscv_get_arg_info (&info, cum, mode, type, named, false);
2643 if (info.num_fprs)
2644 return false;
2647 /* Pass by reference if the data do not fit in two integer registers. */
2648 return !IN_RANGE (size, 0, 2 * UNITS_PER_WORD);
2651 /* Implement TARGET_RETURN_IN_MEMORY. */
2653 static bool
2654 riscv_return_in_memory (const_tree type, const_tree fndecl ATTRIBUTE_UNUSED)
2656 CUMULATIVE_ARGS args;
2657 cumulative_args_t cum = pack_cumulative_args (&args);
2659 /* The rules for returning in memory are the same as for passing the
2660 first named argument by reference. */
2661 memset (&args, 0, sizeof args);
2662 return riscv_pass_by_reference (cum, TYPE_MODE (type), type, true);
2665 /* Implement TARGET_SETUP_INCOMING_VARARGS. */
2667 static void
2668 riscv_setup_incoming_varargs (cumulative_args_t cum, machine_mode mode,
2669 tree type, int *pretend_size ATTRIBUTE_UNUSED,
2670 int no_rtl)
2672 CUMULATIVE_ARGS local_cum;
2673 int gp_saved;
2675 /* The caller has advanced CUM up to, but not beyond, the last named
2676 argument. Advance a local copy of CUM past the last "real" named
2677 argument, to find out how many registers are left over. */
2678 local_cum = *get_cumulative_args (cum);
2679 riscv_function_arg_advance (pack_cumulative_args (&local_cum), mode, type, 1);
2681 /* Found out how many registers we need to save. */
2682 gp_saved = MAX_ARGS_IN_REGISTERS - local_cum.num_gprs;
2684 if (!no_rtl && gp_saved > 0)
2686 rtx ptr = plus_constant (Pmode, virtual_incoming_args_rtx,
2687 REG_PARM_STACK_SPACE (cfun->decl)
2688 - gp_saved * UNITS_PER_WORD);
2689 rtx mem = gen_frame_mem (BLKmode, ptr);
2690 set_mem_alias_set (mem, get_varargs_alias_set ());
2692 move_block_from_reg (local_cum.num_gprs + GP_ARG_FIRST,
2693 mem, gp_saved);
2695 if (REG_PARM_STACK_SPACE (cfun->decl) == 0)
2696 cfun->machine->varargs_size = gp_saved * UNITS_PER_WORD;
2699 /* Handle an attribute requiring a FUNCTION_DECL;
2700 arguments as in struct attribute_spec.handler. */
2701 static tree
2702 riscv_handle_fndecl_attribute (tree *node, tree name,
2703 tree args ATTRIBUTE_UNUSED,
2704 int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
2706 if (TREE_CODE (*node) != FUNCTION_DECL)
2708 warning (OPT_Wattributes, "%qE attribute only applies to functions",
2709 name);
2710 *no_add_attrs = true;
2713 return NULL_TREE;
2716 /* Return true if func is a naked function. */
2717 static bool
2718 riscv_naked_function_p (tree func)
2720 tree func_decl = func;
2721 if (func == NULL_TREE)
2722 func_decl = current_function_decl;
2723 return NULL_TREE != lookup_attribute ("naked", DECL_ATTRIBUTES (func_decl));
2726 /* Implement TARGET_ALLOCATE_STACK_SLOTS_FOR_ARGS. */
2727 static bool
2728 riscv_allocate_stack_slots_for_args ()
2730 /* Naked functions should not allocate stack slots for arguments. */
2731 return !riscv_naked_function_p (current_function_decl);
2734 /* Implement TARGET_WARN_FUNC_RETURN. */
2735 static bool
2736 riscv_warn_func_return (tree decl)
2738 /* Naked functions are implemented entirely in assembly, including the
2739 return sequence, so suppress warnings about this. */
2740 return !riscv_naked_function_p (decl);
2743 /* Implement TARGET_EXPAND_BUILTIN_VA_START. */
2745 static void
2746 riscv_va_start (tree valist, rtx nextarg)
2748 nextarg = plus_constant (Pmode, nextarg, -cfun->machine->varargs_size);
2749 std_expand_builtin_va_start (valist, nextarg);
2752 /* Make ADDR suitable for use as a call or sibcall target. */
2755 riscv_legitimize_call_address (rtx addr)
2757 if (!call_insn_operand (addr, VOIDmode))
2759 rtx reg = RISCV_PROLOGUE_TEMP (Pmode);
2760 riscv_emit_move (reg, addr);
2761 return reg;
2763 return addr;
2766 /* Emit straight-line code to move LENGTH bytes from SRC to DEST.
2767 Assume that the areas do not overlap. */
2769 static void
2770 riscv_block_move_straight (rtx dest, rtx src, HOST_WIDE_INT length)
2772 HOST_WIDE_INT offset, delta;
2773 unsigned HOST_WIDE_INT bits;
2774 int i;
2775 enum machine_mode mode;
2776 rtx *regs;
2778 bits = MAX (BITS_PER_UNIT,
2779 MIN (BITS_PER_WORD, MIN (MEM_ALIGN (src), MEM_ALIGN (dest))));
2781 mode = mode_for_size (bits, MODE_INT, 0).require ();
2782 delta = bits / BITS_PER_UNIT;
2784 /* Allocate a buffer for the temporary registers. */
2785 regs = XALLOCAVEC (rtx, length / delta);
2787 /* Load as many BITS-sized chunks as possible. Use a normal load if
2788 the source has enough alignment, otherwise use left/right pairs. */
2789 for (offset = 0, i = 0; offset + delta <= length; offset += delta, i++)
2791 regs[i] = gen_reg_rtx (mode);
2792 riscv_emit_move (regs[i], adjust_address (src, mode, offset));
2795 /* Copy the chunks to the destination. */
2796 for (offset = 0, i = 0; offset + delta <= length; offset += delta, i++)
2797 riscv_emit_move (adjust_address (dest, mode, offset), regs[i]);
2799 /* Mop up any left-over bytes. */
2800 if (offset < length)
2802 src = adjust_address (src, BLKmode, offset);
2803 dest = adjust_address (dest, BLKmode, offset);
2804 move_by_pieces (dest, src, length - offset,
2805 MIN (MEM_ALIGN (src), MEM_ALIGN (dest)), 0);
2809 /* Helper function for doing a loop-based block operation on memory
2810 reference MEM. Each iteration of the loop will operate on LENGTH
2811 bytes of MEM.
2813 Create a new base register for use within the loop and point it to
2814 the start of MEM. Create a new memory reference that uses this
2815 register. Store them in *LOOP_REG and *LOOP_MEM respectively. */
2817 static void
2818 riscv_adjust_block_mem (rtx mem, HOST_WIDE_INT length,
2819 rtx *loop_reg, rtx *loop_mem)
2821 *loop_reg = copy_addr_to_reg (XEXP (mem, 0));
2823 /* Although the new mem does not refer to a known location,
2824 it does keep up to LENGTH bytes of alignment. */
2825 *loop_mem = change_address (mem, BLKmode, *loop_reg);
2826 set_mem_align (*loop_mem, MIN (MEM_ALIGN (mem), length * BITS_PER_UNIT));
2829 /* Move LENGTH bytes from SRC to DEST using a loop that moves BYTES_PER_ITER
2830 bytes at a time. LENGTH must be at least BYTES_PER_ITER. Assume that
2831 the memory regions do not overlap. */
2833 static void
2834 riscv_block_move_loop (rtx dest, rtx src, HOST_WIDE_INT length,
2835 HOST_WIDE_INT bytes_per_iter)
2837 rtx label, src_reg, dest_reg, final_src, test;
2838 HOST_WIDE_INT leftover;
2840 leftover = length % bytes_per_iter;
2841 length -= leftover;
2843 /* Create registers and memory references for use within the loop. */
2844 riscv_adjust_block_mem (src, bytes_per_iter, &src_reg, &src);
2845 riscv_adjust_block_mem (dest, bytes_per_iter, &dest_reg, &dest);
2847 /* Calculate the value that SRC_REG should have after the last iteration
2848 of the loop. */
2849 final_src = expand_simple_binop (Pmode, PLUS, src_reg, GEN_INT (length),
2850 0, 0, OPTAB_WIDEN);
2852 /* Emit the start of the loop. */
2853 label = gen_label_rtx ();
2854 emit_label (label);
2856 /* Emit the loop body. */
2857 riscv_block_move_straight (dest, src, bytes_per_iter);
2859 /* Move on to the next block. */
2860 riscv_emit_move (src_reg, plus_constant (Pmode, src_reg, bytes_per_iter));
2861 riscv_emit_move (dest_reg, plus_constant (Pmode, dest_reg, bytes_per_iter));
2863 /* Emit the loop condition. */
2864 test = gen_rtx_NE (VOIDmode, src_reg, final_src);
2865 if (Pmode == DImode)
2866 emit_jump_insn (gen_cbranchdi4 (test, src_reg, final_src, label));
2867 else
2868 emit_jump_insn (gen_cbranchsi4 (test, src_reg, final_src, label));
2870 /* Mop up any left-over bytes. */
2871 if (leftover)
2872 riscv_block_move_straight (dest, src, leftover);
2873 else
2874 emit_insn(gen_nop ());
2877 /* Expand a movmemsi instruction, which copies LENGTH bytes from
2878 memory reference SRC to memory reference DEST. */
2880 bool
2881 riscv_expand_block_move (rtx dest, rtx src, rtx length)
2883 if (CONST_INT_P (length))
2885 HOST_WIDE_INT factor, align;
2887 align = MIN (MIN (MEM_ALIGN (src), MEM_ALIGN (dest)), BITS_PER_WORD);
2888 factor = BITS_PER_WORD / align;
2890 if (optimize_function_for_size_p (cfun)
2891 && INTVAL (length) * factor * UNITS_PER_WORD > MOVE_RATIO (false))
2892 return false;
2894 if (INTVAL (length) <= RISCV_MAX_MOVE_BYTES_STRAIGHT / factor)
2896 riscv_block_move_straight (dest, src, INTVAL (length));
2897 return true;
2899 else if (optimize && align >= BITS_PER_WORD)
2901 unsigned min_iter_words
2902 = RISCV_MAX_MOVE_BYTES_PER_LOOP_ITER / UNITS_PER_WORD;
2903 unsigned iter_words = min_iter_words;
2904 HOST_WIDE_INT bytes = INTVAL (length), words = bytes / UNITS_PER_WORD;
2906 /* Lengthen the loop body if it shortens the tail. */
2907 for (unsigned i = min_iter_words; i < min_iter_words * 2 - 1; i++)
2909 unsigned cur_cost = iter_words + words % iter_words;
2910 unsigned new_cost = i + words % i;
2911 if (new_cost <= cur_cost)
2912 iter_words = i;
2915 riscv_block_move_loop (dest, src, bytes, iter_words * UNITS_PER_WORD);
2916 return true;
2919 return false;
2922 /* Print symbolic operand OP, which is part of a HIGH or LO_SUM
2923 in context CONTEXT. HI_RELOC indicates a high-part reloc. */
2925 static void
2926 riscv_print_operand_reloc (FILE *file, rtx op, bool hi_reloc)
2928 const char *reloc;
2930 switch (riscv_classify_symbolic_expression (op))
2932 case SYMBOL_ABSOLUTE:
2933 reloc = hi_reloc ? "%hi" : "%lo";
2934 break;
2936 case SYMBOL_PCREL:
2937 reloc = hi_reloc ? "%pcrel_hi" : "%pcrel_lo";
2938 break;
2940 case SYMBOL_TLS_LE:
2941 reloc = hi_reloc ? "%tprel_hi" : "%tprel_lo";
2942 break;
2944 default:
2945 gcc_unreachable ();
2948 fprintf (file, "%s(", reloc);
2949 output_addr_const (file, riscv_strip_unspec_address (op));
2950 fputc (')', file);
2953 /* Return true if the .AQ suffix should be added to an AMO to implement the
2954 acquire portion of memory model MODEL. */
2956 static bool
2957 riscv_memmodel_needs_amo_acquire (enum memmodel model)
2959 switch (model)
2961 case MEMMODEL_ACQ_REL:
2962 case MEMMODEL_SEQ_CST:
2963 case MEMMODEL_SYNC_SEQ_CST:
2964 case MEMMODEL_ACQUIRE:
2965 case MEMMODEL_CONSUME:
2966 case MEMMODEL_SYNC_ACQUIRE:
2967 return true;
2969 case MEMMODEL_RELEASE:
2970 case MEMMODEL_SYNC_RELEASE:
2971 case MEMMODEL_RELAXED:
2972 return false;
2974 default:
2975 gcc_unreachable ();
2979 /* Return true if a FENCE should be emitted to before a memory access to
2980 implement the release portion of memory model MODEL. */
2982 static bool
2983 riscv_memmodel_needs_release_fence (enum memmodel model)
2985 switch (model)
2987 case MEMMODEL_ACQ_REL:
2988 case MEMMODEL_SEQ_CST:
2989 case MEMMODEL_SYNC_SEQ_CST:
2990 case MEMMODEL_RELEASE:
2991 case MEMMODEL_SYNC_RELEASE:
2992 return true;
2994 case MEMMODEL_ACQUIRE:
2995 case MEMMODEL_CONSUME:
2996 case MEMMODEL_SYNC_ACQUIRE:
2997 case MEMMODEL_RELAXED:
2998 return false;
3000 default:
3001 gcc_unreachable ();
3005 /* Implement TARGET_PRINT_OPERAND. The RISCV-specific operand codes are:
3007 'h' Print the high-part relocation associated with OP, after stripping
3008 any outermost HIGH.
3009 'R' Print the low-part relocation associated with OP.
3010 'C' Print the integer branch condition for comparison OP.
3011 'A' Print the atomic operation suffix for memory model OP.
3012 'F' Print a FENCE if the memory model requires a release.
3013 'z' Print x0 if OP is zero, otherwise print OP normally.
3014 'i' Print i if the operand is not a register. */
3016 static void
3017 riscv_print_operand (FILE *file, rtx op, int letter)
3019 machine_mode mode = GET_MODE (op);
3020 enum rtx_code code = GET_CODE (op);
3022 switch (letter)
3024 case 'h':
3025 if (code == HIGH)
3026 op = XEXP (op, 0);
3027 riscv_print_operand_reloc (file, op, true);
3028 break;
3030 case 'R':
3031 riscv_print_operand_reloc (file, op, false);
3032 break;
3034 case 'C':
3035 /* The RTL names match the instruction names. */
3036 fputs (GET_RTX_NAME (code), file);
3037 break;
3039 case 'A':
3040 if (riscv_memmodel_needs_amo_acquire ((enum memmodel) INTVAL (op)))
3041 fputs (".aq", file);
3042 break;
3044 case 'F':
3045 if (riscv_memmodel_needs_release_fence ((enum memmodel) INTVAL (op)))
3046 fputs ("fence iorw,ow; ", file);
3047 break;
3049 case 'i':
3050 if (code != REG)
3051 fputs ("i", file);
3052 break;
3054 default:
3055 switch (code)
3057 case REG:
3058 if (letter && letter != 'z')
3059 output_operand_lossage ("invalid use of '%%%c'", letter);
3060 fprintf (file, "%s", reg_names[REGNO (op)]);
3061 break;
3063 case MEM:
3064 if (letter && letter != 'z')
3065 output_operand_lossage ("invalid use of '%%%c'", letter);
3066 else
3067 output_address (mode, XEXP (op, 0));
3068 break;
3070 default:
3071 if (letter == 'z' && op == CONST0_RTX (GET_MODE (op)))
3072 fputs (reg_names[GP_REG_FIRST], file);
3073 else if (letter && letter != 'z')
3074 output_operand_lossage ("invalid use of '%%%c'", letter);
3075 else
3076 output_addr_const (file, riscv_strip_unspec_address (op));
3077 break;
3082 /* Implement TARGET_PRINT_OPERAND_ADDRESS. */
3084 static void
3085 riscv_print_operand_address (FILE *file, machine_mode mode ATTRIBUTE_UNUSED, rtx x)
3087 struct riscv_address_info addr;
3089 if (riscv_classify_address (&addr, x, word_mode, true))
3090 switch (addr.type)
3092 case ADDRESS_REG:
3093 riscv_print_operand (file, addr.offset, 0);
3094 fprintf (file, "(%s)", reg_names[REGNO (addr.reg)]);
3095 return;
3097 case ADDRESS_LO_SUM:
3098 riscv_print_operand_reloc (file, addr.offset, false);
3099 fprintf (file, "(%s)", reg_names[REGNO (addr.reg)]);
3100 return;
3102 case ADDRESS_CONST_INT:
3103 output_addr_const (file, x);
3104 fprintf (file, "(%s)", reg_names[GP_REG_FIRST]);
3105 return;
3107 case ADDRESS_SYMBOLIC:
3108 output_addr_const (file, riscv_strip_unspec_address (x));
3109 return;
3111 gcc_unreachable ();
3114 static bool
3115 riscv_size_ok_for_small_data_p (int size)
3117 return g_switch_value && IN_RANGE (size, 1, g_switch_value);
3120 /* Return true if EXP should be placed in the small data section. */
3122 static bool
3123 riscv_in_small_data_p (const_tree x)
3125 if (TREE_CODE (x) == STRING_CST || TREE_CODE (x) == FUNCTION_DECL)
3126 return false;
3128 if (TREE_CODE (x) == VAR_DECL && DECL_SECTION_NAME (x))
3130 const char *sec = DECL_SECTION_NAME (x);
3131 return strcmp (sec, ".sdata") == 0 || strcmp (sec, ".sbss") == 0;
3134 return riscv_size_ok_for_small_data_p (int_size_in_bytes (TREE_TYPE (x)));
3137 /* Switch to the appropriate section for output of DECL. */
3139 static section *
3140 riscv_select_section (tree decl, int reloc,
3141 unsigned HOST_WIDE_INT align)
3143 switch (categorize_decl_for_section (decl, reloc))
3145 case SECCAT_SRODATA:
3146 return get_named_section (decl, ".srodata", reloc);
3148 default:
3149 return default_elf_select_section (decl, reloc, align);
3153 /* Return a section for X, handling small data. */
3155 static section *
3156 riscv_elf_select_rtx_section (machine_mode mode, rtx x,
3157 unsigned HOST_WIDE_INT align)
3159 section *s = default_elf_select_rtx_section (mode, x, align);
3161 if (riscv_size_ok_for_small_data_p (GET_MODE_SIZE (mode)))
3163 if (strncmp (s->named.name, ".rodata.cst", strlen (".rodata.cst")) == 0)
3165 /* Rename .rodata.cst* to .srodata.cst*. */
3166 char *name = (char *) alloca (strlen (s->named.name) + 2);
3167 sprintf (name, ".s%s", s->named.name + 1);
3168 return get_section (name, s->named.common.flags, NULL);
3171 if (s == data_section)
3172 return sdata_section;
3175 return s;
3178 /* Make the last instruction frame-related and note that it performs
3179 the operation described by FRAME_PATTERN. */
3181 static void
3182 riscv_set_frame_expr (rtx frame_pattern)
3184 rtx insn;
3186 insn = get_last_insn ();
3187 RTX_FRAME_RELATED_P (insn) = 1;
3188 REG_NOTES (insn) = alloc_EXPR_LIST (REG_FRAME_RELATED_EXPR,
3189 frame_pattern,
3190 REG_NOTES (insn));
3193 /* Return a frame-related rtx that stores REG at MEM.
3194 REG must be a single register. */
3196 static rtx
3197 riscv_frame_set (rtx mem, rtx reg)
3199 rtx set = gen_rtx_SET (mem, reg);
3200 RTX_FRAME_RELATED_P (set) = 1;
3201 return set;
3204 /* Return true if the current function must save register REGNO. */
3206 static bool
3207 riscv_save_reg_p (unsigned int regno)
3209 bool call_saved = !global_regs[regno] && !call_used_regs[regno];
3210 bool might_clobber = crtl->saves_all_registers
3211 || df_regs_ever_live_p (regno);
3213 if (call_saved && might_clobber)
3214 return true;
3216 if (regno == HARD_FRAME_POINTER_REGNUM && frame_pointer_needed)
3217 return true;
3219 if (regno == RETURN_ADDR_REGNUM && crtl->calls_eh_return)
3220 return true;
3222 return false;
3225 /* Determine whether to call GPR save/restore routines. */
3226 static bool
3227 riscv_use_save_libcall (const struct riscv_frame_info *frame)
3229 if (!TARGET_SAVE_RESTORE || crtl->calls_eh_return || frame_pointer_needed)
3230 return false;
3232 return frame->save_libcall_adjustment != 0;
3235 /* Determine which GPR save/restore routine to call. */
3237 static unsigned
3238 riscv_save_libcall_count (unsigned mask)
3240 for (unsigned n = GP_REG_LAST; n > GP_REG_FIRST; n--)
3241 if (BITSET_P (mask, n))
3242 return CALLEE_SAVED_REG_NUMBER (n) + 1;
3243 abort ();
3246 /* Populate the current function's riscv_frame_info structure.
3248 RISC-V stack frames grown downward. High addresses are at the top.
3250 +-------------------------------+
3252 | incoming stack arguments |
3254 +-------------------------------+ <-- incoming stack pointer
3256 | callee-allocated save area |
3257 | for arguments that are |
3258 | split between registers and |
3259 | the stack |
3261 +-------------------------------+ <-- arg_pointer_rtx
3263 | callee-allocated save area |
3264 | for register varargs |
3266 +-------------------------------+ <-- hard_frame_pointer_rtx;
3267 | | stack_pointer_rtx + gp_sp_offset
3268 | GPR save area | + UNITS_PER_WORD
3270 +-------------------------------+ <-- stack_pointer_rtx + fp_sp_offset
3271 | | + UNITS_PER_HWVALUE
3272 | FPR save area |
3274 +-------------------------------+ <-- frame_pointer_rtx (virtual)
3276 | local variables |
3278 P +-------------------------------+
3280 | outgoing stack arguments |
3282 +-------------------------------+ <-- stack_pointer_rtx
3284 Dynamic stack allocations such as alloca insert data at point P.
3285 They decrease stack_pointer_rtx but leave frame_pointer_rtx and
3286 hard_frame_pointer_rtx unchanged. */
3288 static void
3289 riscv_compute_frame_info (void)
3291 struct riscv_frame_info *frame;
3292 HOST_WIDE_INT offset;
3293 unsigned int regno, i, num_x_saved = 0, num_f_saved = 0;
3295 frame = &cfun->machine->frame;
3296 memset (frame, 0, sizeof (*frame));
3298 if (!cfun->machine->naked_p)
3300 /* Find out which GPRs we need to save. */
3301 for (regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
3302 if (riscv_save_reg_p (regno))
3303 frame->mask |= 1 << (regno - GP_REG_FIRST), num_x_saved++;
3305 /* If this function calls eh_return, we must also save and restore the
3306 EH data registers. */
3307 if (crtl->calls_eh_return)
3308 for (i = 0; (regno = EH_RETURN_DATA_REGNO (i)) != INVALID_REGNUM; i++)
3309 frame->mask |= 1 << (regno - GP_REG_FIRST), num_x_saved++;
3311 /* Find out which FPRs we need to save. This loop must iterate over
3312 the same space as its companion in riscv_for_each_saved_reg. */
3313 if (TARGET_HARD_FLOAT)
3314 for (regno = FP_REG_FIRST; regno <= FP_REG_LAST; regno++)
3315 if (riscv_save_reg_p (regno))
3316 frame->fmask |= 1 << (regno - FP_REG_FIRST), num_f_saved++;
3319 /* At the bottom of the frame are any outgoing stack arguments. */
3320 offset = RISCV_STACK_ALIGN (crtl->outgoing_args_size);
3321 /* Next are local stack variables. */
3322 offset += RISCV_STACK_ALIGN (get_frame_size ());
3323 /* The virtual frame pointer points above the local variables. */
3324 frame->frame_pointer_offset = offset;
3325 /* Next are the callee-saved FPRs. */
3326 if (frame->fmask)
3327 offset += RISCV_STACK_ALIGN (num_f_saved * UNITS_PER_FP_REG);
3328 frame->fp_sp_offset = offset - UNITS_PER_FP_REG;
3329 /* Next are the callee-saved GPRs. */
3330 if (frame->mask)
3332 unsigned x_save_size = RISCV_STACK_ALIGN (num_x_saved * UNITS_PER_WORD);
3333 unsigned num_save_restore = 1 + riscv_save_libcall_count (frame->mask);
3335 /* Only use save/restore routines if they don't alter the stack size. */
3336 if (RISCV_STACK_ALIGN (num_save_restore * UNITS_PER_WORD) == x_save_size)
3338 /* Libcall saves/restores 3 registers at once, so we need to
3339 allocate 12 bytes for callee-saved register. */
3340 if (TARGET_RVE)
3341 x_save_size = 3 * UNITS_PER_WORD;
3343 frame->save_libcall_adjustment = x_save_size;
3346 offset += x_save_size;
3348 frame->gp_sp_offset = offset - UNITS_PER_WORD;
3349 /* The hard frame pointer points above the callee-saved GPRs. */
3350 frame->hard_frame_pointer_offset = offset;
3351 /* Above the hard frame pointer is the callee-allocated varags save area. */
3352 offset += RISCV_STACK_ALIGN (cfun->machine->varargs_size);
3353 /* Next is the callee-allocated area for pretend stack arguments. */
3354 offset += RISCV_STACK_ALIGN (crtl->args.pretend_args_size);
3355 /* Arg pointer must be below pretend args, but must be above alignment
3356 padding. */
3357 frame->arg_pointer_offset = offset - crtl->args.pretend_args_size;
3358 frame->total_size = offset;
3359 /* Next points the incoming stack pointer and any incoming arguments. */
3361 /* Only use save/restore routines when the GPRs are atop the frame. */
3362 if (frame->hard_frame_pointer_offset != frame->total_size)
3363 frame->save_libcall_adjustment = 0;
3366 /* Make sure that we're not trying to eliminate to the wrong hard frame
3367 pointer. */
3369 static bool
3370 riscv_can_eliminate (const int from ATTRIBUTE_UNUSED, const int to)
3372 return (to == HARD_FRAME_POINTER_REGNUM || to == STACK_POINTER_REGNUM);
3375 /* Implement INITIAL_ELIMINATION_OFFSET. FROM is either the frame pointer
3376 or argument pointer. TO is either the stack pointer or hard frame
3377 pointer. */
3379 HOST_WIDE_INT
3380 riscv_initial_elimination_offset (int from, int to)
3382 HOST_WIDE_INT src, dest;
3384 riscv_compute_frame_info ();
3386 if (to == HARD_FRAME_POINTER_REGNUM)
3387 dest = cfun->machine->frame.hard_frame_pointer_offset;
3388 else if (to == STACK_POINTER_REGNUM)
3389 dest = 0; /* The stack pointer is the base of all offsets, hence 0. */
3390 else
3391 gcc_unreachable ();
3393 if (from == FRAME_POINTER_REGNUM)
3394 src = cfun->machine->frame.frame_pointer_offset;
3395 else if (from == ARG_POINTER_REGNUM)
3396 src = cfun->machine->frame.arg_pointer_offset;
3397 else
3398 gcc_unreachable ();
3400 return src - dest;
3403 /* Implement RETURN_ADDR_RTX. We do not support moving back to a
3404 previous frame. */
3407 riscv_return_addr (int count, rtx frame ATTRIBUTE_UNUSED)
3409 if (count != 0)
3410 return const0_rtx;
3412 return get_hard_reg_initial_val (Pmode, RETURN_ADDR_REGNUM);
3415 /* Emit code to change the current function's return address to
3416 ADDRESS. SCRATCH is available as a scratch register, if needed.
3417 ADDRESS and SCRATCH are both word-mode GPRs. */
3419 void
3420 riscv_set_return_address (rtx address, rtx scratch)
3422 rtx slot_address;
3424 gcc_assert (BITSET_P (cfun->machine->frame.mask, RETURN_ADDR_REGNUM));
3425 slot_address = riscv_add_offset (scratch, stack_pointer_rtx,
3426 cfun->machine->frame.gp_sp_offset);
3427 riscv_emit_move (gen_frame_mem (GET_MODE (address), slot_address), address);
3430 /* A function to save or store a register. The first argument is the
3431 register and the second is the stack slot. */
3432 typedef void (*riscv_save_restore_fn) (rtx, rtx);
3434 /* Use FN to save or restore register REGNO. MODE is the register's
3435 mode and OFFSET is the offset of its save slot from the current
3436 stack pointer. */
3438 static void
3439 riscv_save_restore_reg (machine_mode mode, int regno,
3440 HOST_WIDE_INT offset, riscv_save_restore_fn fn)
3442 rtx mem;
3444 mem = gen_frame_mem (mode, plus_constant (Pmode, stack_pointer_rtx, offset));
3445 fn (gen_rtx_REG (mode, regno), mem);
3448 /* Call FN for each register that is saved by the current function.
3449 SP_OFFSET is the offset of the current stack pointer from the start
3450 of the frame. */
3452 static void
3453 riscv_for_each_saved_reg (HOST_WIDE_INT sp_offset, riscv_save_restore_fn fn)
3455 HOST_WIDE_INT offset;
3457 /* Save the link register and s-registers. */
3458 offset = cfun->machine->frame.gp_sp_offset - sp_offset;
3459 for (int regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
3460 if (BITSET_P (cfun->machine->frame.mask, regno - GP_REG_FIRST))
3462 riscv_save_restore_reg (word_mode, regno, offset, fn);
3463 offset -= UNITS_PER_WORD;
3466 /* This loop must iterate over the same space as its companion in
3467 riscv_compute_frame_info. */
3468 offset = cfun->machine->frame.fp_sp_offset - sp_offset;
3469 for (int regno = FP_REG_FIRST; regno <= FP_REG_LAST; regno++)
3470 if (BITSET_P (cfun->machine->frame.fmask, regno - FP_REG_FIRST))
3472 machine_mode mode = TARGET_DOUBLE_FLOAT ? DFmode : SFmode;
3474 riscv_save_restore_reg (mode, regno, offset, fn);
3475 offset -= GET_MODE_SIZE (mode);
3479 /* Save register REG to MEM. Make the instruction frame-related. */
3481 static void
3482 riscv_save_reg (rtx reg, rtx mem)
3484 riscv_emit_move (mem, reg);
3485 riscv_set_frame_expr (riscv_frame_set (mem, reg));
3488 /* Restore register REG from MEM. */
3490 static void
3491 riscv_restore_reg (rtx reg, rtx mem)
3493 rtx insn = riscv_emit_move (reg, mem);
3494 rtx dwarf = NULL_RTX;
3495 dwarf = alloc_reg_note (REG_CFA_RESTORE, reg, dwarf);
3496 REG_NOTES (insn) = dwarf;
3498 RTX_FRAME_RELATED_P (insn) = 1;
3501 /* Return the code to invoke the GPR save routine. */
3503 const char *
3504 riscv_output_gpr_save (unsigned mask)
3506 static char s[32];
3507 unsigned n = riscv_save_libcall_count (mask);
3509 ssize_t bytes = snprintf (s, sizeof (s), "call\tt0,__riscv_save_%u", n);
3510 gcc_assert ((size_t) bytes < sizeof (s));
3512 return s;
3515 /* For stack frames that can't be allocated with a single ADDI instruction,
3516 compute the best value to initially allocate. It must at a minimum
3517 allocate enough space to spill the callee-saved registers. If TARGET_RVC,
3518 try to pick a value that will allow compression of the register saves
3519 without adding extra instructions. */
3521 static HOST_WIDE_INT
3522 riscv_first_stack_step (struct riscv_frame_info *frame)
3524 if (SMALL_OPERAND (frame->total_size))
3525 return frame->total_size;
3527 HOST_WIDE_INT min_first_step =
3528 RISCV_STACK_ALIGN (frame->total_size - frame->fp_sp_offset);
3529 HOST_WIDE_INT max_first_step = IMM_REACH / 2 - PREFERRED_STACK_BOUNDARY / 8;
3530 HOST_WIDE_INT min_second_step = frame->total_size - max_first_step;
3531 gcc_assert (min_first_step <= max_first_step);
3533 /* As an optimization, use the least-significant bits of the total frame
3534 size, so that the second adjustment step is just LUI + ADD. */
3535 if (!SMALL_OPERAND (min_second_step)
3536 && frame->total_size % IMM_REACH < IMM_REACH / 2
3537 && frame->total_size % IMM_REACH >= min_first_step)
3538 return frame->total_size % IMM_REACH;
3540 if (TARGET_RVC)
3542 /* If we need two subtracts, and one is small enough to allow compressed
3543 loads and stores, then put that one first. */
3544 if (IN_RANGE (min_second_step, 0,
3545 (TARGET_64BIT ? SDSP_REACH : SWSP_REACH)))
3546 return MAX (min_second_step, min_first_step);
3548 /* If we need LUI + ADDI + ADD for the second adjustment step, then start
3549 with the minimum first step, so that we can get compressed loads and
3550 stores. */
3551 else if (!SMALL_OPERAND (min_second_step))
3552 return min_first_step;
3555 return max_first_step;
3558 static rtx
3559 riscv_adjust_libcall_cfi_prologue ()
3561 rtx dwarf = NULL_RTX;
3562 rtx adjust_sp_rtx, reg, mem, insn;
3563 int saved_size = cfun->machine->frame.save_libcall_adjustment;
3564 int offset;
3566 for (int regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
3567 if (BITSET_P (cfun->machine->frame.mask, regno - GP_REG_FIRST))
3569 /* The save order is ra, s0, s1, s2 to s11. */
3570 if (regno == RETURN_ADDR_REGNUM)
3571 offset = saved_size - UNITS_PER_WORD;
3572 else if (regno == S0_REGNUM)
3573 offset = saved_size - UNITS_PER_WORD * 2;
3574 else if (regno == S1_REGNUM)
3575 offset = saved_size - UNITS_PER_WORD * 3;
3576 else
3577 offset = saved_size - ((regno - S2_REGNUM + 4) * UNITS_PER_WORD);
3579 reg = gen_rtx_REG (SImode, regno);
3580 mem = gen_frame_mem (SImode, plus_constant (Pmode,
3581 stack_pointer_rtx,
3582 offset));
3584 insn = gen_rtx_SET (mem, reg);
3585 dwarf = alloc_reg_note (REG_CFA_OFFSET, insn, dwarf);
3588 /* Debug info for adjust sp. */
3589 adjust_sp_rtx = gen_add3_insn (stack_pointer_rtx,
3590 stack_pointer_rtx, GEN_INT (-saved_size));
3591 dwarf = alloc_reg_note (REG_CFA_ADJUST_CFA, adjust_sp_rtx,
3592 dwarf);
3593 return dwarf;
3596 static void
3597 riscv_emit_stack_tie (void)
3599 if (Pmode == SImode)
3600 emit_insn (gen_stack_tiesi (stack_pointer_rtx, hard_frame_pointer_rtx));
3601 else
3602 emit_insn (gen_stack_tiedi (stack_pointer_rtx, hard_frame_pointer_rtx));
3605 /* Expand the "prologue" pattern. */
3607 void
3608 riscv_expand_prologue (void)
3610 struct riscv_frame_info *frame = &cfun->machine->frame;
3611 HOST_WIDE_INT size = frame->total_size;
3612 unsigned mask = frame->mask;
3613 rtx insn;
3615 if (cfun->machine->naked_p)
3617 if (flag_stack_usage_info)
3618 current_function_static_stack_size = 0;
3620 return;
3623 if (flag_stack_usage_info)
3624 current_function_static_stack_size = size;
3626 /* When optimizing for size, call a subroutine to save the registers. */
3627 if (riscv_use_save_libcall (frame))
3629 rtx dwarf = NULL_RTX;
3630 dwarf = riscv_adjust_libcall_cfi_prologue ();
3632 frame->mask = 0; /* Temporarily fib that we need not save GPRs. */
3633 size -= frame->save_libcall_adjustment;
3634 insn = emit_insn (gen_gpr_save (GEN_INT (mask)));
3636 RTX_FRAME_RELATED_P (insn) = 1;
3637 REG_NOTES (insn) = dwarf;
3640 /* Save the registers. */
3641 if ((frame->mask | frame->fmask) != 0)
3643 HOST_WIDE_INT step1 = MIN (size, riscv_first_stack_step (frame));
3645 insn = gen_add3_insn (stack_pointer_rtx,
3646 stack_pointer_rtx,
3647 GEN_INT (-step1));
3648 RTX_FRAME_RELATED_P (emit_insn (insn)) = 1;
3649 size -= step1;
3650 riscv_for_each_saved_reg (size, riscv_save_reg);
3653 frame->mask = mask; /* Undo the above fib. */
3655 /* Set up the frame pointer, if we're using one. */
3656 if (frame_pointer_needed)
3658 insn = gen_add3_insn (hard_frame_pointer_rtx, stack_pointer_rtx,
3659 GEN_INT (frame->hard_frame_pointer_offset - size));
3660 RTX_FRAME_RELATED_P (emit_insn (insn)) = 1;
3662 riscv_emit_stack_tie ();
3665 /* Allocate the rest of the frame. */
3666 if (size > 0)
3668 if (SMALL_OPERAND (-size))
3670 insn = gen_add3_insn (stack_pointer_rtx, stack_pointer_rtx,
3671 GEN_INT (-size));
3672 RTX_FRAME_RELATED_P (emit_insn (insn)) = 1;
3674 else
3676 riscv_emit_move (RISCV_PROLOGUE_TEMP (Pmode), GEN_INT (-size));
3677 emit_insn (gen_add3_insn (stack_pointer_rtx,
3678 stack_pointer_rtx,
3679 RISCV_PROLOGUE_TEMP (Pmode)));
3681 /* Describe the effect of the previous instructions. */
3682 insn = plus_constant (Pmode, stack_pointer_rtx, -size);
3683 insn = gen_rtx_SET (stack_pointer_rtx, insn);
3684 riscv_set_frame_expr (insn);
3689 static rtx
3690 riscv_adjust_libcall_cfi_epilogue ()
3692 rtx dwarf = NULL_RTX;
3693 rtx adjust_sp_rtx, reg;
3694 int saved_size = cfun->machine->frame.save_libcall_adjustment;
3696 /* Debug info for adjust sp. */
3697 adjust_sp_rtx = gen_add3_insn (stack_pointer_rtx,
3698 stack_pointer_rtx, GEN_INT (saved_size));
3699 dwarf = alloc_reg_note (REG_CFA_ADJUST_CFA, adjust_sp_rtx,
3700 dwarf);
3702 for (int regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
3703 if (BITSET_P (cfun->machine->frame.mask, regno - GP_REG_FIRST))
3705 reg = gen_rtx_REG (SImode, regno);
3706 dwarf = alloc_reg_note (REG_CFA_RESTORE, reg, dwarf);
3709 return dwarf;
3712 /* Expand an "epilogue" or "sibcall_epilogue" pattern; SIBCALL_P
3713 says which. */
3715 void
3716 riscv_expand_epilogue (bool sibcall_p)
3718 /* Split the frame into two. STEP1 is the amount of stack we should
3719 deallocate before restoring the registers. STEP2 is the amount we
3720 should deallocate afterwards.
3722 Start off by assuming that no registers need to be restored. */
3723 struct riscv_frame_info *frame = &cfun->machine->frame;
3724 unsigned mask = frame->mask;
3725 HOST_WIDE_INT step1 = frame->total_size;
3726 HOST_WIDE_INT step2 = 0;
3727 bool use_restore_libcall = !sibcall_p && riscv_use_save_libcall (frame);
3728 rtx ra = gen_rtx_REG (Pmode, RETURN_ADDR_REGNUM);
3729 rtx insn;
3731 /* We need to add memory barrier to prevent read from deallocated stack. */
3732 bool need_barrier_p = (get_frame_size ()
3733 + cfun->machine->frame.arg_pointer_offset) != 0;
3735 if (cfun->machine->naked_p)
3737 gcc_assert (!sibcall_p);
3739 emit_jump_insn (gen_return ());
3741 return;
3744 if (!sibcall_p && riscv_can_use_return_insn ())
3746 emit_jump_insn (gen_return ());
3747 return;
3750 /* Move past any dynamic stack allocations. */
3751 if (cfun->calls_alloca)
3753 /* Emit a barrier to prevent loads from a deallocated stack. */
3754 riscv_emit_stack_tie ();
3755 need_barrier_p = false;
3757 rtx adjust = GEN_INT (-frame->hard_frame_pointer_offset);
3758 if (!SMALL_OPERAND (INTVAL (adjust)))
3760 riscv_emit_move (RISCV_PROLOGUE_TEMP (Pmode), adjust);
3761 adjust = RISCV_PROLOGUE_TEMP (Pmode);
3764 insn = emit_insn (
3765 gen_add3_insn (stack_pointer_rtx, hard_frame_pointer_rtx,
3766 adjust));
3768 rtx dwarf = NULL_RTX;
3769 rtx cfa_adjust_value = gen_rtx_PLUS (
3770 Pmode, hard_frame_pointer_rtx,
3771 GEN_INT (-frame->hard_frame_pointer_offset));
3772 rtx cfa_adjust_rtx = gen_rtx_SET (stack_pointer_rtx, cfa_adjust_value);
3773 dwarf = alloc_reg_note (REG_CFA_ADJUST_CFA, cfa_adjust_rtx, dwarf);
3774 RTX_FRAME_RELATED_P (insn) = 1;
3776 REG_NOTES (insn) = dwarf;
3779 /* If we need to restore registers, deallocate as much stack as
3780 possible in the second step without going out of range. */
3781 if ((frame->mask | frame->fmask) != 0)
3783 step2 = riscv_first_stack_step (frame);
3784 step1 -= step2;
3787 /* Set TARGET to BASE + STEP1. */
3788 if (step1 > 0)
3790 /* Emit a barrier to prevent loads from a deallocated stack. */
3791 riscv_emit_stack_tie ();
3792 need_barrier_p = false;
3794 /* Get an rtx for STEP1 that we can add to BASE. */
3795 rtx adjust = GEN_INT (step1);
3796 if (!SMALL_OPERAND (step1))
3798 riscv_emit_move (RISCV_PROLOGUE_TEMP (Pmode), adjust);
3799 adjust = RISCV_PROLOGUE_TEMP (Pmode);
3802 insn = emit_insn (
3803 gen_add3_insn (stack_pointer_rtx, stack_pointer_rtx, adjust));
3805 rtx dwarf = NULL_RTX;
3806 rtx cfa_adjust_rtx = gen_rtx_PLUS (Pmode, stack_pointer_rtx,
3807 GEN_INT (step2));
3809 dwarf = alloc_reg_note (REG_CFA_DEF_CFA, cfa_adjust_rtx, dwarf);
3810 RTX_FRAME_RELATED_P (insn) = 1;
3812 REG_NOTES (insn) = dwarf;
3815 if (use_restore_libcall)
3816 frame->mask = 0; /* Temporarily fib that we need not save GPRs. */
3818 /* Restore the registers. */
3819 riscv_for_each_saved_reg (frame->total_size - step2, riscv_restore_reg);
3821 if (use_restore_libcall)
3823 frame->mask = mask; /* Undo the above fib. */
3824 gcc_assert (step2 >= frame->save_libcall_adjustment);
3825 step2 -= frame->save_libcall_adjustment;
3828 if (need_barrier_p)
3829 riscv_emit_stack_tie ();
3831 /* Deallocate the final bit of the frame. */
3832 if (step2 > 0)
3834 insn = emit_insn (gen_add3_insn (stack_pointer_rtx, stack_pointer_rtx,
3835 GEN_INT (step2)));
3837 rtx dwarf = NULL_RTX;
3838 rtx cfa_adjust_rtx = gen_rtx_PLUS (Pmode, stack_pointer_rtx,
3839 const0_rtx);
3840 dwarf = alloc_reg_note (REG_CFA_DEF_CFA, cfa_adjust_rtx, dwarf);
3841 RTX_FRAME_RELATED_P (insn) = 1;
3843 REG_NOTES (insn) = dwarf;
3846 if (use_restore_libcall)
3848 rtx dwarf = riscv_adjust_libcall_cfi_epilogue ();
3849 insn = emit_insn (gen_gpr_restore (GEN_INT (riscv_save_libcall_count (mask))));
3850 RTX_FRAME_RELATED_P (insn) = 1;
3851 REG_NOTES (insn) = dwarf;
3853 emit_jump_insn (gen_gpr_restore_return (ra));
3854 return;
3857 /* Add in the __builtin_eh_return stack adjustment. */
3858 if (crtl->calls_eh_return)
3859 emit_insn (gen_add3_insn (stack_pointer_rtx, stack_pointer_rtx,
3860 EH_RETURN_STACKADJ_RTX));
3862 if (!sibcall_p)
3863 emit_jump_insn (gen_simple_return_internal (ra));
3866 /* Return nonzero if this function is known to have a null epilogue.
3867 This allows the optimizer to omit jumps to jumps if no stack
3868 was created. */
3870 bool
3871 riscv_can_use_return_insn (void)
3873 return reload_completed && cfun->machine->frame.total_size == 0;
3876 /* Implement TARGET_SECONDARY_MEMORY_NEEDED.
3878 When floating-point registers are wider than integer ones, moves between
3879 them must go through memory. */
3881 static bool
3882 riscv_secondary_memory_needed (machine_mode mode, reg_class_t class1,
3883 reg_class_t class2)
3885 return (GET_MODE_SIZE (mode) > UNITS_PER_WORD
3886 && (class1 == FP_REGS) != (class2 == FP_REGS));
3889 /* Implement TARGET_REGISTER_MOVE_COST. */
3891 static int
3892 riscv_register_move_cost (machine_mode mode,
3893 reg_class_t from, reg_class_t to)
3895 return riscv_secondary_memory_needed (mode, from, to) ? 8 : 2;
3898 /* Implement TARGET_HARD_REGNO_NREGS. */
3900 static unsigned int
3901 riscv_hard_regno_nregs (unsigned int regno, machine_mode mode)
3903 if (FP_REG_P (regno))
3904 return (GET_MODE_SIZE (mode) + UNITS_PER_FP_REG - 1) / UNITS_PER_FP_REG;
3906 /* All other registers are word-sized. */
3907 return (GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
3910 /* Implement TARGET_HARD_REGNO_MODE_OK. */
3912 static bool
3913 riscv_hard_regno_mode_ok (unsigned int regno, machine_mode mode)
3915 unsigned int nregs = riscv_hard_regno_nregs (regno, mode);
3917 if (GP_REG_P (regno))
3919 if (!GP_REG_P (regno + nregs - 1))
3920 return false;
3922 else if (FP_REG_P (regno))
3924 if (!FP_REG_P (regno + nregs - 1))
3925 return false;
3927 if (GET_MODE_CLASS (mode) != MODE_FLOAT
3928 && GET_MODE_CLASS (mode) != MODE_COMPLEX_FLOAT)
3929 return false;
3931 /* Only use callee-saved registers if a potential callee is guaranteed
3932 to spill the requisite width. */
3933 if (GET_MODE_UNIT_SIZE (mode) > UNITS_PER_FP_REG
3934 || (!call_used_regs[regno]
3935 && GET_MODE_UNIT_SIZE (mode) > UNITS_PER_FP_ARG))
3936 return false;
3938 else
3939 return false;
3941 /* Require same callee-savedness for all registers. */
3942 for (unsigned i = 1; i < nregs; i++)
3943 if (call_used_regs[regno] != call_used_regs[regno + i])
3944 return false;
3946 return true;
3949 /* Implement TARGET_MODES_TIEABLE_P.
3951 Don't allow floating-point modes to be tied, since type punning of
3952 single-precision and double-precision is implementation defined. */
3954 static bool
3955 riscv_modes_tieable_p (machine_mode mode1, machine_mode mode2)
3957 return (mode1 == mode2
3958 || !(GET_MODE_CLASS (mode1) == MODE_FLOAT
3959 && GET_MODE_CLASS (mode2) == MODE_FLOAT));
3962 /* Implement CLASS_MAX_NREGS. */
3964 static unsigned char
3965 riscv_class_max_nregs (reg_class_t rclass, machine_mode mode)
3967 if (reg_class_subset_p (FP_REGS, rclass))
3968 return riscv_hard_regno_nregs (FP_REG_FIRST, mode);
3970 if (reg_class_subset_p (GR_REGS, rclass))
3971 return riscv_hard_regno_nregs (GP_REG_FIRST, mode);
3973 return 0;
3976 /* Implement TARGET_MEMORY_MOVE_COST. */
3978 static int
3979 riscv_memory_move_cost (machine_mode mode, reg_class_t rclass, bool in)
3981 return (tune_info->memory_cost
3982 + memory_move_secondary_cost (mode, rclass, in));
3985 /* Return the number of instructions that can be issued per cycle. */
3987 static int
3988 riscv_issue_rate (void)
3990 return tune_info->issue_rate;
3993 /* Implement TARGET_ASM_FILE_START. */
3995 static void
3996 riscv_file_start (void)
3998 default_file_start ();
4000 /* Instruct GAS to generate position-[in]dependent code. */
4001 fprintf (asm_out_file, "\t.option %spic\n", (flag_pic ? "" : "no"));
4003 /* If the user specifies "-mno-relax" on the command line then disable linker
4004 relaxation in the assembler. */
4005 if (! riscv_mrelax)
4006 fprintf (asm_out_file, "\t.option norelax\n");
4009 /* Implement TARGET_ASM_OUTPUT_MI_THUNK. Generate rtl rather than asm text
4010 in order to avoid duplicating too much logic from elsewhere. */
4012 static void
4013 riscv_output_mi_thunk (FILE *file, tree thunk_fndecl ATTRIBUTE_UNUSED,
4014 HOST_WIDE_INT delta, HOST_WIDE_INT vcall_offset,
4015 tree function)
4017 rtx this_rtx, temp1, temp2, fnaddr;
4018 rtx_insn *insn;
4020 /* Pretend to be a post-reload pass while generating rtl. */
4021 reload_completed = 1;
4023 /* Mark the end of the (empty) prologue. */
4024 emit_note (NOTE_INSN_PROLOGUE_END);
4026 /* Determine if we can use a sibcall to call FUNCTION directly. */
4027 fnaddr = gen_rtx_MEM (FUNCTION_MODE, XEXP (DECL_RTL (function), 0));
4029 /* We need two temporary registers in some cases. */
4030 temp1 = gen_rtx_REG (Pmode, RISCV_PROLOGUE_TEMP_REGNUM);
4031 temp2 = gen_rtx_REG (Pmode, STATIC_CHAIN_REGNUM);
4033 /* Find out which register contains the "this" pointer. */
4034 if (aggregate_value_p (TREE_TYPE (TREE_TYPE (function)), function))
4035 this_rtx = gen_rtx_REG (Pmode, GP_ARG_FIRST + 1);
4036 else
4037 this_rtx = gen_rtx_REG (Pmode, GP_ARG_FIRST);
4039 /* Add DELTA to THIS_RTX. */
4040 if (delta != 0)
4042 rtx offset = GEN_INT (delta);
4043 if (!SMALL_OPERAND (delta))
4045 riscv_emit_move (temp1, offset);
4046 offset = temp1;
4048 emit_insn (gen_add3_insn (this_rtx, this_rtx, offset));
4051 /* If needed, add *(*THIS_RTX + VCALL_OFFSET) to THIS_RTX. */
4052 if (vcall_offset != 0)
4054 rtx addr;
4056 /* Set TEMP1 to *THIS_RTX. */
4057 riscv_emit_move (temp1, gen_rtx_MEM (Pmode, this_rtx));
4059 /* Set ADDR to a legitimate address for *THIS_RTX + VCALL_OFFSET. */
4060 addr = riscv_add_offset (temp2, temp1, vcall_offset);
4062 /* Load the offset and add it to THIS_RTX. */
4063 riscv_emit_move (temp1, gen_rtx_MEM (Pmode, addr));
4064 emit_insn (gen_add3_insn (this_rtx, this_rtx, temp1));
4067 /* Jump to the target function. */
4068 insn = emit_call_insn (gen_sibcall (fnaddr, const0_rtx, NULL, const0_rtx));
4069 SIBLING_CALL_P (insn) = 1;
4071 /* Run just enough of rest_of_compilation. This sequence was
4072 "borrowed" from alpha.c. */
4073 insn = get_insns ();
4074 split_all_insns_noflow ();
4075 shorten_branches (insn);
4076 final_start_function (insn, file, 1);
4077 final (insn, file, 1);
4078 final_end_function ();
4080 /* Clean up the vars set above. Note that final_end_function resets
4081 the global pointer for us. */
4082 reload_completed = 0;
4085 /* Allocate a chunk of memory for per-function machine-dependent data. */
4087 static struct machine_function *
4088 riscv_init_machine_status (void)
4090 return ggc_cleared_alloc<machine_function> ();
4093 /* Implement TARGET_OPTION_OVERRIDE. */
4095 static void
4096 riscv_option_override (void)
4098 const struct riscv_cpu_info *cpu;
4100 #ifdef SUBTARGET_OVERRIDE_OPTIONS
4101 SUBTARGET_OVERRIDE_OPTIONS;
4102 #endif
4104 flag_pcc_struct_return = 0;
4106 if (flag_pic)
4107 g_switch_value = 0;
4109 /* The presence of the M extension implies that division instructions
4110 are present, so include them unless explicitly disabled. */
4111 if (TARGET_MUL && (target_flags_explicit & MASK_DIV) == 0)
4112 target_flags |= MASK_DIV;
4113 else if (!TARGET_MUL && TARGET_DIV)
4114 error ("-mdiv requires -march to subsume the %<M%> extension");
4116 /* Likewise floating-point division and square root. */
4117 if (TARGET_HARD_FLOAT && (target_flags_explicit & MASK_FDIV) == 0)
4118 target_flags |= MASK_FDIV;
4120 /* Handle -mtune. */
4121 cpu = riscv_parse_cpu (riscv_tune_string ? riscv_tune_string :
4122 RISCV_TUNE_STRING_DEFAULT);
4123 tune_info = optimize_size ? &optimize_size_tune_info : cpu->tune_info;
4125 /* Use -mtune's setting for slow_unaligned_access, even when optimizing
4126 for size. For architectures that trap and emulate unaligned accesses,
4127 the performance cost is too great, even for -Os. Similarly, if
4128 -m[no-]strict-align is left unspecified, heed -mtune's advice. */
4129 riscv_slow_unaligned_access_p = (cpu->tune_info->slow_unaligned_access
4130 || TARGET_STRICT_ALIGN);
4131 if ((target_flags_explicit & MASK_STRICT_ALIGN) == 0
4132 && cpu->tune_info->slow_unaligned_access)
4133 target_flags |= MASK_STRICT_ALIGN;
4135 /* If the user hasn't specified a branch cost, use the processor's
4136 default. */
4137 if (riscv_branch_cost == 0)
4138 riscv_branch_cost = tune_info->branch_cost;
4140 /* Function to allocate machine-dependent function status. */
4141 init_machine_status = &riscv_init_machine_status;
4143 if (flag_pic)
4144 riscv_cmodel = CM_PIC;
4146 /* We get better code with explicit relocs for CM_MEDLOW, but
4147 worse code for the others (for now). Pick the best default. */
4148 if ((target_flags_explicit & MASK_EXPLICIT_RELOCS) == 0)
4149 if (riscv_cmodel == CM_MEDLOW)
4150 target_flags |= MASK_EXPLICIT_RELOCS;
4152 /* Require that the ISA supports the requested floating-point ABI. */
4153 if (UNITS_PER_FP_ARG > (TARGET_HARD_FLOAT ? UNITS_PER_FP_REG : 0))
4154 error ("requested ABI requires -march to subsume the %qc extension",
4155 UNITS_PER_FP_ARG > 8 ? 'Q' : (UNITS_PER_FP_ARG > 4 ? 'D' : 'F'));
4157 if (TARGET_RVE && riscv_abi != ABI_ILP32E)
4158 error ("rv32e requires ilp32e ABI");
4160 /* We do not yet support ILP32 on RV64. */
4161 if (BITS_PER_WORD != POINTER_SIZE)
4162 error ("ABI requires -march=rv%d", POINTER_SIZE);
4164 /* Validate -mpreferred-stack-boundary= value. */
4165 riscv_stack_boundary = ABI_STACK_BOUNDARY;
4166 if (riscv_preferred_stack_boundary_arg)
4168 int min = ctz_hwi (STACK_BOUNDARY / 8);
4169 int max = 8;
4171 if (!IN_RANGE (riscv_preferred_stack_boundary_arg, min, max))
4172 error ("-mpreferred-stack-boundary=%d must be between %d and %d",
4173 riscv_preferred_stack_boundary_arg, min, max);
4175 riscv_stack_boundary = 8 << riscv_preferred_stack_boundary_arg;
4179 /* Implement TARGET_CONDITIONAL_REGISTER_USAGE. */
4181 static void
4182 riscv_conditional_register_usage (void)
4184 /* We have only x0~x15 on RV32E. */
4185 if (TARGET_RVE)
4187 for (int r = 16; r <= 31; r++)
4188 fixed_regs[r] = 1;
4191 if (riscv_abi == ABI_ILP32E)
4193 for (int r = 16; r <= 31; r++)
4194 call_used_regs[r] = 1;
4197 if (!TARGET_HARD_FLOAT)
4199 for (int regno = FP_REG_FIRST; regno <= FP_REG_LAST; regno++)
4200 fixed_regs[regno] = call_used_regs[regno] = 1;
4203 /* In the soft-float ABI, there are no callee-saved FP registers. */
4204 if (UNITS_PER_FP_ARG == 0)
4206 for (int regno = FP_REG_FIRST; regno <= FP_REG_LAST; regno++)
4207 call_used_regs[regno] = 1;
4211 /* Return a register priority for hard reg REGNO. */
4213 static int
4214 riscv_register_priority (int regno)
4216 /* Favor x8-x15/f8-f15 to improve the odds of RVC instruction selection. */
4217 if (TARGET_RVC && (IN_RANGE (regno, GP_REG_FIRST + 8, GP_REG_FIRST + 15)
4218 || IN_RANGE (regno, FP_REG_FIRST + 8, FP_REG_FIRST + 15)))
4219 return 1;
4221 return 0;
4224 /* Implement TARGET_TRAMPOLINE_INIT. */
4226 static void
4227 riscv_trampoline_init (rtx m_tramp, tree fndecl, rtx chain_value)
4229 rtx addr, end_addr, mem;
4230 uint32_t trampoline[4];
4231 unsigned int i;
4232 HOST_WIDE_INT static_chain_offset, target_function_offset;
4234 /* Work out the offsets of the pointers from the start of the
4235 trampoline code. */
4236 gcc_assert (ARRAY_SIZE (trampoline) * 4 == TRAMPOLINE_CODE_SIZE);
4238 /* Get pointers to the beginning and end of the code block. */
4239 addr = force_reg (Pmode, XEXP (m_tramp, 0));
4240 end_addr = riscv_force_binary (Pmode, PLUS, addr,
4241 GEN_INT (TRAMPOLINE_CODE_SIZE));
4244 if (Pmode == SImode)
4246 chain_value = force_reg (Pmode, chain_value);
4248 rtx target_function = force_reg (Pmode, XEXP (DECL_RTL (fndecl), 0));
4249 /* lui t2, hi(chain)
4250 lui t1, hi(func)
4251 addi t2, t2, lo(chain)
4252 jr r1, lo(func)
4254 unsigned HOST_WIDE_INT lui_hi_chain_code, lui_hi_func_code;
4255 unsigned HOST_WIDE_INT lo_chain_code, lo_func_code;
4257 rtx uimm_mask = force_reg (SImode, gen_int_mode (-IMM_REACH, SImode));
4259 /* 0xfff. */
4260 rtx imm12_mask = gen_reg_rtx (SImode);
4261 emit_insn (gen_one_cmplsi2 (imm12_mask, uimm_mask));
4263 rtx fixup_value = force_reg (SImode, gen_int_mode (IMM_REACH/2, SImode));
4265 /* Gen lui t2, hi(chain). */
4266 rtx hi_chain = riscv_force_binary (SImode, PLUS, chain_value,
4267 fixup_value);
4268 hi_chain = riscv_force_binary (SImode, AND, hi_chain,
4269 uimm_mask);
4270 lui_hi_chain_code = OPCODE_LUI | (STATIC_CHAIN_REGNUM << SHIFT_RD);
4271 rtx lui_hi_chain = riscv_force_binary (SImode, IOR, hi_chain,
4272 gen_int_mode (lui_hi_chain_code, SImode));
4274 mem = adjust_address (m_tramp, SImode, 0);
4275 riscv_emit_move (mem, lui_hi_chain);
4277 /* Gen lui t1, hi(func). */
4278 rtx hi_func = riscv_force_binary (SImode, PLUS, target_function,
4279 fixup_value);
4280 hi_func = riscv_force_binary (SImode, AND, hi_func,
4281 uimm_mask);
4282 lui_hi_func_code = OPCODE_LUI | (RISCV_PROLOGUE_TEMP_REGNUM << SHIFT_RD);
4283 rtx lui_hi_func = riscv_force_binary (SImode, IOR, hi_func,
4284 gen_int_mode (lui_hi_func_code, SImode));
4286 mem = adjust_address (m_tramp, SImode, 1 * GET_MODE_SIZE (SImode));
4287 riscv_emit_move (mem, lui_hi_func);
4289 /* Gen addi t2, t2, lo(chain). */
4290 rtx lo_chain = riscv_force_binary (SImode, AND, chain_value,
4291 imm12_mask);
4292 lo_chain = riscv_force_binary (SImode, ASHIFT, lo_chain, GEN_INT (20));
4294 lo_chain_code = OPCODE_ADDI
4295 | (STATIC_CHAIN_REGNUM << SHIFT_RD)
4296 | (STATIC_CHAIN_REGNUM << SHIFT_RS1);
4298 rtx addi_lo_chain = riscv_force_binary (SImode, IOR, lo_chain,
4299 force_reg (SImode, GEN_INT (lo_chain_code)));
4301 mem = adjust_address (m_tramp, SImode, 2 * GET_MODE_SIZE (SImode));
4302 riscv_emit_move (mem, addi_lo_chain);
4304 /* Gen jr r1, lo(func). */
4305 rtx lo_func = riscv_force_binary (SImode, AND, target_function,
4306 imm12_mask);
4307 lo_func = riscv_force_binary (SImode, ASHIFT, lo_func, GEN_INT (20));
4309 lo_func_code = OPCODE_JALR | (RISCV_PROLOGUE_TEMP_REGNUM << SHIFT_RS1);
4311 rtx jr_lo_func = riscv_force_binary (SImode, IOR, lo_func,
4312 force_reg (SImode, GEN_INT (lo_func_code)));
4314 mem = adjust_address (m_tramp, SImode, 3 * GET_MODE_SIZE (SImode));
4315 riscv_emit_move (mem, jr_lo_func);
4317 else
4319 static_chain_offset = TRAMPOLINE_CODE_SIZE;
4320 target_function_offset = static_chain_offset + GET_MODE_SIZE (ptr_mode);
4322 /* auipc t2, 0
4323 l[wd] t1, target_function_offset(t2)
4324 l[wd] t2, static_chain_offset(t2)
4325 jr t1
4327 trampoline[0] = OPCODE_AUIPC | (STATIC_CHAIN_REGNUM << SHIFT_RD);
4328 trampoline[1] = (Pmode == DImode ? OPCODE_LD : OPCODE_LW)
4329 | (RISCV_PROLOGUE_TEMP_REGNUM << SHIFT_RD)
4330 | (STATIC_CHAIN_REGNUM << SHIFT_RS1)
4331 | (target_function_offset << SHIFT_IMM);
4332 trampoline[2] = (Pmode == DImode ? OPCODE_LD : OPCODE_LW)
4333 | (STATIC_CHAIN_REGNUM << SHIFT_RD)
4334 | (STATIC_CHAIN_REGNUM << SHIFT_RS1)
4335 | (static_chain_offset << SHIFT_IMM);
4336 trampoline[3] = OPCODE_JALR | (RISCV_PROLOGUE_TEMP_REGNUM << SHIFT_RS1);
4338 /* Copy the trampoline code. */
4339 for (i = 0; i < ARRAY_SIZE (trampoline); i++)
4341 mem = adjust_address (m_tramp, SImode, i * GET_MODE_SIZE (SImode));
4342 riscv_emit_move (mem, gen_int_mode (trampoline[i], SImode));
4345 /* Set up the static chain pointer field. */
4346 mem = adjust_address (m_tramp, ptr_mode, static_chain_offset);
4347 riscv_emit_move (mem, chain_value);
4349 /* Set up the target function field. */
4350 mem = adjust_address (m_tramp, ptr_mode, target_function_offset);
4351 riscv_emit_move (mem, XEXP (DECL_RTL (fndecl), 0));
4354 /* Flush the code part of the trampoline. */
4355 emit_insn (gen_add3_insn (end_addr, addr, GEN_INT (TRAMPOLINE_SIZE)));
4356 emit_insn (gen_clear_cache (addr, end_addr));
4359 /* Implement TARGET_FUNCTION_OK_FOR_SIBCALL. */
4361 static bool
4362 riscv_function_ok_for_sibcall (tree decl ATTRIBUTE_UNUSED,
4363 tree exp ATTRIBUTE_UNUSED)
4365 /* Don't use sibcalls when use save-restore routine. */
4366 if (TARGET_SAVE_RESTORE)
4367 return false;
4369 /* Don't use sibcall for naked function. */
4370 if (cfun->machine->naked_p)
4371 return false;
4373 return true;
4376 /* Implement `TARGET_SET_CURRENT_FUNCTION'. */
4377 /* Sanity cheching for above function attributes. */
4378 static void
4379 riscv_set_current_function (tree decl)
4381 if (decl == NULL_TREE
4382 || current_function_decl == NULL_TREE
4383 || current_function_decl == error_mark_node
4384 || !cfun->machine)
4385 return;
4387 cfun->machine->naked_p = riscv_naked_function_p (decl);
4390 /* Implement TARGET_CANNOT_COPY_INSN_P. */
4392 static bool
4393 riscv_cannot_copy_insn_p (rtx_insn *insn)
4395 return recog_memoized (insn) >= 0 && get_attr_cannot_copy (insn);
4398 /* Implement TARGET_SLOW_UNALIGNED_ACCESS. */
4400 static bool
4401 riscv_slow_unaligned_access (machine_mode, unsigned int)
4403 return riscv_slow_unaligned_access_p;
4406 /* Implement TARGET_CAN_CHANGE_MODE_CLASS. */
4408 static bool
4409 riscv_can_change_mode_class (machine_mode, machine_mode, reg_class_t rclass)
4411 return !reg_classes_intersect_p (FP_REGS, rclass);
4415 /* Implement TARGET_CONSTANT_ALIGNMENT. */
4417 static HOST_WIDE_INT
4418 riscv_constant_alignment (const_tree exp, HOST_WIDE_INT align)
4420 if (TREE_CODE (exp) == STRING_CST || TREE_CODE (exp) == CONSTRUCTOR)
4421 return MAX (align, BITS_PER_WORD);
4422 return align;
4425 /* Initialize the GCC target structure. */
4426 #undef TARGET_ASM_ALIGNED_HI_OP
4427 #define TARGET_ASM_ALIGNED_HI_OP "\t.half\t"
4428 #undef TARGET_ASM_ALIGNED_SI_OP
4429 #define TARGET_ASM_ALIGNED_SI_OP "\t.word\t"
4430 #undef TARGET_ASM_ALIGNED_DI_OP
4431 #define TARGET_ASM_ALIGNED_DI_OP "\t.dword\t"
4433 #undef TARGET_OPTION_OVERRIDE
4434 #define TARGET_OPTION_OVERRIDE riscv_option_override
4436 #undef TARGET_LEGITIMIZE_ADDRESS
4437 #define TARGET_LEGITIMIZE_ADDRESS riscv_legitimize_address
4439 #undef TARGET_SCHED_ISSUE_RATE
4440 #define TARGET_SCHED_ISSUE_RATE riscv_issue_rate
4442 #undef TARGET_FUNCTION_OK_FOR_SIBCALL
4443 #define TARGET_FUNCTION_OK_FOR_SIBCALL riscv_function_ok_for_sibcall
4445 #undef TARGET_SET_CURRENT_FUNCTION
4446 #define TARGET_SET_CURRENT_FUNCTION riscv_set_current_function
4448 #undef TARGET_REGISTER_MOVE_COST
4449 #define TARGET_REGISTER_MOVE_COST riscv_register_move_cost
4450 #undef TARGET_MEMORY_MOVE_COST
4451 #define TARGET_MEMORY_MOVE_COST riscv_memory_move_cost
4452 #undef TARGET_RTX_COSTS
4453 #define TARGET_RTX_COSTS riscv_rtx_costs
4454 #undef TARGET_ADDRESS_COST
4455 #define TARGET_ADDRESS_COST riscv_address_cost
4457 #undef TARGET_ASM_FILE_START
4458 #define TARGET_ASM_FILE_START riscv_file_start
4459 #undef TARGET_ASM_FILE_START_FILE_DIRECTIVE
4460 #define TARGET_ASM_FILE_START_FILE_DIRECTIVE true
4462 #undef TARGET_EXPAND_BUILTIN_VA_START
4463 #define TARGET_EXPAND_BUILTIN_VA_START riscv_va_start
4465 #undef TARGET_PROMOTE_FUNCTION_MODE
4466 #define TARGET_PROMOTE_FUNCTION_MODE default_promote_function_mode_always_promote
4468 #undef TARGET_RETURN_IN_MEMORY
4469 #define TARGET_RETURN_IN_MEMORY riscv_return_in_memory
4471 #undef TARGET_ASM_OUTPUT_MI_THUNK
4472 #define TARGET_ASM_OUTPUT_MI_THUNK riscv_output_mi_thunk
4473 #undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
4474 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK hook_bool_const_tree_hwi_hwi_const_tree_true
4476 #undef TARGET_PRINT_OPERAND
4477 #define TARGET_PRINT_OPERAND riscv_print_operand
4478 #undef TARGET_PRINT_OPERAND_ADDRESS
4479 #define TARGET_PRINT_OPERAND_ADDRESS riscv_print_operand_address
4481 #undef TARGET_SETUP_INCOMING_VARARGS
4482 #define TARGET_SETUP_INCOMING_VARARGS riscv_setup_incoming_varargs
4483 #undef TARGET_ALLOCATE_STACK_SLOTS_FOR_ARGS
4484 #define TARGET_ALLOCATE_STACK_SLOTS_FOR_ARGS riscv_allocate_stack_slots_for_args
4485 #undef TARGET_STRICT_ARGUMENT_NAMING
4486 #define TARGET_STRICT_ARGUMENT_NAMING hook_bool_CUMULATIVE_ARGS_true
4487 #undef TARGET_MUST_PASS_IN_STACK
4488 #define TARGET_MUST_PASS_IN_STACK must_pass_in_stack_var_size
4489 #undef TARGET_PASS_BY_REFERENCE
4490 #define TARGET_PASS_BY_REFERENCE riscv_pass_by_reference
4491 #undef TARGET_ARG_PARTIAL_BYTES
4492 #define TARGET_ARG_PARTIAL_BYTES riscv_arg_partial_bytes
4493 #undef TARGET_FUNCTION_ARG
4494 #define TARGET_FUNCTION_ARG riscv_function_arg
4495 #undef TARGET_FUNCTION_ARG_ADVANCE
4496 #define TARGET_FUNCTION_ARG_ADVANCE riscv_function_arg_advance
4497 #undef TARGET_FUNCTION_ARG_BOUNDARY
4498 #define TARGET_FUNCTION_ARG_BOUNDARY riscv_function_arg_boundary
4500 /* The generic ELF target does not always have TLS support. */
4501 #ifdef HAVE_AS_TLS
4502 #undef TARGET_HAVE_TLS
4503 #define TARGET_HAVE_TLS true
4504 #endif
4506 #undef TARGET_CANNOT_FORCE_CONST_MEM
4507 #define TARGET_CANNOT_FORCE_CONST_MEM riscv_cannot_force_const_mem
4509 #undef TARGET_LEGITIMATE_CONSTANT_P
4510 #define TARGET_LEGITIMATE_CONSTANT_P riscv_legitimate_constant_p
4512 #undef TARGET_USE_BLOCKS_FOR_CONSTANT_P
4513 #define TARGET_USE_BLOCKS_FOR_CONSTANT_P hook_bool_mode_const_rtx_true
4515 #undef TARGET_LEGITIMATE_ADDRESS_P
4516 #define TARGET_LEGITIMATE_ADDRESS_P riscv_legitimate_address_p
4518 #undef TARGET_CAN_ELIMINATE
4519 #define TARGET_CAN_ELIMINATE riscv_can_eliminate
4521 #undef TARGET_CONDITIONAL_REGISTER_USAGE
4522 #define TARGET_CONDITIONAL_REGISTER_USAGE riscv_conditional_register_usage
4524 #undef TARGET_CLASS_MAX_NREGS
4525 #define TARGET_CLASS_MAX_NREGS riscv_class_max_nregs
4527 #undef TARGET_TRAMPOLINE_INIT
4528 #define TARGET_TRAMPOLINE_INIT riscv_trampoline_init
4530 #undef TARGET_IN_SMALL_DATA_P
4531 #define TARGET_IN_SMALL_DATA_P riscv_in_small_data_p
4533 #undef TARGET_HAVE_SRODATA_SECTION
4534 #define TARGET_HAVE_SRODATA_SECTION true
4536 #undef TARGET_ASM_SELECT_SECTION
4537 #define TARGET_ASM_SELECT_SECTION riscv_select_section
4539 #undef TARGET_ASM_SELECT_RTX_SECTION
4540 #define TARGET_ASM_SELECT_RTX_SECTION riscv_elf_select_rtx_section
4542 #undef TARGET_MIN_ANCHOR_OFFSET
4543 #define TARGET_MIN_ANCHOR_OFFSET (-IMM_REACH/2)
4545 #undef TARGET_MAX_ANCHOR_OFFSET
4546 #define TARGET_MAX_ANCHOR_OFFSET (IMM_REACH/2-1)
4548 #undef TARGET_REGISTER_PRIORITY
4549 #define TARGET_REGISTER_PRIORITY riscv_register_priority
4551 #undef TARGET_CANNOT_COPY_INSN_P
4552 #define TARGET_CANNOT_COPY_INSN_P riscv_cannot_copy_insn_p
4554 #undef TARGET_ATOMIC_ASSIGN_EXPAND_FENV
4555 #define TARGET_ATOMIC_ASSIGN_EXPAND_FENV riscv_atomic_assign_expand_fenv
4557 #undef TARGET_INIT_BUILTINS
4558 #define TARGET_INIT_BUILTINS riscv_init_builtins
4560 #undef TARGET_BUILTIN_DECL
4561 #define TARGET_BUILTIN_DECL riscv_builtin_decl
4563 #undef TARGET_EXPAND_BUILTIN
4564 #define TARGET_EXPAND_BUILTIN riscv_expand_builtin
4566 #undef TARGET_HARD_REGNO_NREGS
4567 #define TARGET_HARD_REGNO_NREGS riscv_hard_regno_nregs
4568 #undef TARGET_HARD_REGNO_MODE_OK
4569 #define TARGET_HARD_REGNO_MODE_OK riscv_hard_regno_mode_ok
4571 #undef TARGET_MODES_TIEABLE_P
4572 #define TARGET_MODES_TIEABLE_P riscv_modes_tieable_p
4574 #undef TARGET_SLOW_UNALIGNED_ACCESS
4575 #define TARGET_SLOW_UNALIGNED_ACCESS riscv_slow_unaligned_access
4577 #undef TARGET_SECONDARY_MEMORY_NEEDED
4578 #define TARGET_SECONDARY_MEMORY_NEEDED riscv_secondary_memory_needed
4580 #undef TARGET_CAN_CHANGE_MODE_CLASS
4581 #define TARGET_CAN_CHANGE_MODE_CLASS riscv_can_change_mode_class
4583 #undef TARGET_CONSTANT_ALIGNMENT
4584 #define TARGET_CONSTANT_ALIGNMENT riscv_constant_alignment
4586 #undef TARGET_ATTRIBUTE_TABLE
4587 #define TARGET_ATTRIBUTE_TABLE riscv_attribute_table
4589 #undef TARGET_WARN_FUNC_RETURN
4590 #define TARGET_WARN_FUNC_RETURN riscv_warn_func_return
4592 struct gcc_target targetm = TARGET_INITIALIZER;
4594 #include "gt-riscv.h"