RISCVISelLowering.cpp revision 360784
1//===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation  --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the interfaces that RISCV uses to lower LLVM code into a
10// selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
14#include "RISCVISelLowering.h"
15#include "RISCV.h"
16#include "RISCVMachineFunctionInfo.h"
17#include "RISCVRegisterInfo.h"
18#include "RISCVSubtarget.h"
19#include "RISCVTargetMachine.h"
20#include "Utils/RISCVMatInt.h"
21#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/CodeGen/CallingConvLower.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineFunction.h"
26#include "llvm/CodeGen/MachineInstrBuilder.h"
27#include "llvm/CodeGen/MachineRegisterInfo.h"
28#include "llvm/CodeGen/SelectionDAGISel.h"
29#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30#include "llvm/CodeGen/ValueTypes.h"
31#include "llvm/IR/DiagnosticInfo.h"
32#include "llvm/IR/DiagnosticPrinter.h"
33#include "llvm/IR/IntrinsicsRISCV.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Support/raw_ostream.h"
37
38using namespace llvm;
39
40#define DEBUG_TYPE "riscv-lower"
41
42STATISTIC(NumTailCalls, "Number of tail calls");
43
44RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
45                                         const RISCVSubtarget &STI)
46    : TargetLowering(TM), Subtarget(STI) {
47
48  if (Subtarget.isRV32E())
49    report_fatal_error("Codegen not yet implemented for RV32E");
50
51  RISCVABI::ABI ABI = Subtarget.getTargetABI();
52  assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
53
54  if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
55      !Subtarget.hasStdExtF()) {
56    errs() << "Hard-float 'f' ABI can't be used for a target that "
57                "doesn't support the F instruction set extension (ignoring "
58                          "target-abi)\n";
59    ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
60  } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
61             !Subtarget.hasStdExtD()) {
62    errs() << "Hard-float 'd' ABI can't be used for a target that "
63              "doesn't support the D instruction set extension (ignoring "
64              "target-abi)\n";
65    ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
66  }
67
68  switch (ABI) {
69  default:
70    report_fatal_error("Don't know how to lower this ABI");
71  case RISCVABI::ABI_ILP32:
72  case RISCVABI::ABI_ILP32F:
73  case RISCVABI::ABI_ILP32D:
74  case RISCVABI::ABI_LP64:
75  case RISCVABI::ABI_LP64F:
76  case RISCVABI::ABI_LP64D:
77    break;
78  }
79
80  MVT XLenVT = Subtarget.getXLenVT();
81
82  // Set up the register classes.
83  addRegisterClass(XLenVT, &RISCV::GPRRegClass);
84
85  if (Subtarget.hasStdExtF())
86    addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
87  if (Subtarget.hasStdExtD())
88    addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
89
90  // Compute derived properties from the register classes.
91  computeRegisterProperties(STI.getRegisterInfo());
92
93  setStackPointerRegisterToSaveRestore(RISCV::X2);
94
95  for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
96    setLoadExtAction(N, XLenVT, MVT::i1, Promote);
97
98  // TODO: add all necessary setOperationAction calls.
99  setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
100
101  setOperationAction(ISD::BR_JT, MVT::Other, Expand);
102  setOperationAction(ISD::BR_CC, XLenVT, Expand);
103  setOperationAction(ISD::SELECT, XLenVT, Custom);
104  setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
105
106  setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
107  setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
108
109  setOperationAction(ISD::VASTART, MVT::Other, Custom);
110  setOperationAction(ISD::VAARG, MVT::Other, Expand);
111  setOperationAction(ISD::VACOPY, MVT::Other, Expand);
112  setOperationAction(ISD::VAEND, MVT::Other, Expand);
113
114  for (auto VT : {MVT::i1, MVT::i8, MVT::i16})
115    setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
116
117  if (Subtarget.is64Bit()) {
118    setOperationAction(ISD::ADD, MVT::i32, Custom);
119    setOperationAction(ISD::SUB, MVT::i32, Custom);
120    setOperationAction(ISD::SHL, MVT::i32, Custom);
121    setOperationAction(ISD::SRA, MVT::i32, Custom);
122    setOperationAction(ISD::SRL, MVT::i32, Custom);
123  }
124
125  if (!Subtarget.hasStdExtM()) {
126    setOperationAction(ISD::MUL, XLenVT, Expand);
127    setOperationAction(ISD::MULHS, XLenVT, Expand);
128    setOperationAction(ISD::MULHU, XLenVT, Expand);
129    setOperationAction(ISD::SDIV, XLenVT, Expand);
130    setOperationAction(ISD::UDIV, XLenVT, Expand);
131    setOperationAction(ISD::SREM, XLenVT, Expand);
132    setOperationAction(ISD::UREM, XLenVT, Expand);
133  }
134
135  if (Subtarget.is64Bit() && Subtarget.hasStdExtM()) {
136    setOperationAction(ISD::MUL, MVT::i32, Custom);
137    setOperationAction(ISD::SDIV, MVT::i32, Custom);
138    setOperationAction(ISD::UDIV, MVT::i32, Custom);
139    setOperationAction(ISD::UREM, MVT::i32, Custom);
140  }
141
142  setOperationAction(ISD::SDIVREM, XLenVT, Expand);
143  setOperationAction(ISD::UDIVREM, XLenVT, Expand);
144  setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
145  setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
146
147  setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
148  setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
149  setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
150
151  setOperationAction(ISD::ROTL, XLenVT, Expand);
152  setOperationAction(ISD::ROTR, XLenVT, Expand);
153  setOperationAction(ISD::BSWAP, XLenVT, Expand);
154  setOperationAction(ISD::CTTZ, XLenVT, Expand);
155  setOperationAction(ISD::CTLZ, XLenVT, Expand);
156  setOperationAction(ISD::CTPOP, XLenVT, Expand);
157
158  ISD::CondCode FPCCToExtend[] = {
159      ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
160      ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
161      ISD::SETGE,  ISD::SETNE};
162
163  ISD::NodeType FPOpToExtend[] = {
164      ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FP16_TO_FP,
165      ISD::FP_TO_FP16};
166
167  if (Subtarget.hasStdExtF()) {
168    setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
169    setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
170    for (auto CC : FPCCToExtend)
171      setCondCodeAction(CC, MVT::f32, Expand);
172    setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
173    setOperationAction(ISD::SELECT, MVT::f32, Custom);
174    setOperationAction(ISD::BR_CC, MVT::f32, Expand);
175    for (auto Op : FPOpToExtend)
176      setOperationAction(Op, MVT::f32, Expand);
177    setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
178    setTruncStoreAction(MVT::f32, MVT::f16, Expand);
179  }
180
181  if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
182    setOperationAction(ISD::BITCAST, MVT::i32, Custom);
183
184  if (Subtarget.hasStdExtD()) {
185    setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
186    setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
187    for (auto CC : FPCCToExtend)
188      setCondCodeAction(CC, MVT::f64, Expand);
189    setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
190    setOperationAction(ISD::SELECT, MVT::f64, Custom);
191    setOperationAction(ISD::BR_CC, MVT::f64, Expand);
192    setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
193    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
194    for (auto Op : FPOpToExtend)
195      setOperationAction(Op, MVT::f64, Expand);
196    setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
197    setTruncStoreAction(MVT::f64, MVT::f16, Expand);
198  }
199
200  setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
201  setOperationAction(ISD::BlockAddress, XLenVT, Custom);
202  setOperationAction(ISD::ConstantPool, XLenVT, Custom);
203
204  setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
205
206  // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
207  // Unfortunately this can't be determined just from the ISA naming string.
208  setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
209                     Subtarget.is64Bit() ? Legal : Custom);
210
211  setOperationAction(ISD::TRAP, MVT::Other, Legal);
212  setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
213
214  if (Subtarget.hasStdExtA()) {
215    setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
216    setMinCmpXchgSizeInBits(32);
217  } else {
218    setMaxAtomicSizeInBitsSupported(0);
219  }
220
221  setBooleanContents(ZeroOrOneBooleanContent);
222
223  // Function alignments.
224  const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
225  setMinFunctionAlignment(FunctionAlignment);
226  setPrefFunctionAlignment(FunctionAlignment);
227
228  // Effectively disable jump table generation.
229  setMinimumJumpTableEntries(INT_MAX);
230}
231
232EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
233                                            EVT VT) const {
234  if (!VT.isVector())
235    return getPointerTy(DL);
236  return VT.changeVectorElementTypeToInteger();
237}
238
239bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
240                                             const CallInst &I,
241                                             MachineFunction &MF,
242                                             unsigned Intrinsic) const {
243  switch (Intrinsic) {
244  default:
245    return false;
246  case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
247  case Intrinsic::riscv_masked_atomicrmw_add_i32:
248  case Intrinsic::riscv_masked_atomicrmw_sub_i32:
249  case Intrinsic::riscv_masked_atomicrmw_nand_i32:
250  case Intrinsic::riscv_masked_atomicrmw_max_i32:
251  case Intrinsic::riscv_masked_atomicrmw_min_i32:
252  case Intrinsic::riscv_masked_atomicrmw_umax_i32:
253  case Intrinsic::riscv_masked_atomicrmw_umin_i32:
254  case Intrinsic::riscv_masked_cmpxchg_i32:
255    PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
256    Info.opc = ISD::INTRINSIC_W_CHAIN;
257    Info.memVT = MVT::getVT(PtrTy->getElementType());
258    Info.ptrVal = I.getArgOperand(0);
259    Info.offset = 0;
260    Info.align = Align(4);
261    Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
262                 MachineMemOperand::MOVolatile;
263    return true;
264  }
265}
266
267bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
268                                                const AddrMode &AM, Type *Ty,
269                                                unsigned AS,
270                                                Instruction *I) const {
271  // No global is ever allowed as a base.
272  if (AM.BaseGV)
273    return false;
274
275  // Require a 12-bit signed offset.
276  if (!isInt<12>(AM.BaseOffs))
277    return false;
278
279  switch (AM.Scale) {
280  case 0: // "r+i" or just "i", depending on HasBaseReg.
281    break;
282  case 1:
283    if (!AM.HasBaseReg) // allow "r+i".
284      break;
285    return false; // disallow "r+r" or "r+r+i".
286  default:
287    return false;
288  }
289
290  return true;
291}
292
293bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
294  return isInt<12>(Imm);
295}
296
297bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
298  return isInt<12>(Imm);
299}
300
301// On RV32, 64-bit integers are split into their high and low parts and held
302// in two different registers, so the trunc is free since the low register can
303// just be used.
304bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
305  if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
306    return false;
307  unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
308  unsigned DestBits = DstTy->getPrimitiveSizeInBits();
309  return (SrcBits == 64 && DestBits == 32);
310}
311
312bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
313  if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
314      !SrcVT.isInteger() || !DstVT.isInteger())
315    return false;
316  unsigned SrcBits = SrcVT.getSizeInBits();
317  unsigned DestBits = DstVT.getSizeInBits();
318  return (SrcBits == 64 && DestBits == 32);
319}
320
321bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
322  // Zexts are free if they can be combined with a load.
323  if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
324    EVT MemVT = LD->getMemoryVT();
325    if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
326         (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
327        (LD->getExtensionType() == ISD::NON_EXTLOAD ||
328         LD->getExtensionType() == ISD::ZEXTLOAD))
329      return true;
330  }
331
332  return TargetLowering::isZExtFree(Val, VT2);
333}
334
335bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
336  return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
337}
338
339bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
340  return (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
341         (VT == MVT::f64 && Subtarget.hasStdExtD());
342}
343
344// Changes the condition code and swaps operands if necessary, so the SetCC
345// operation matches one of the comparisons supported directly in the RISC-V
346// ISA.
347static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) {
348  switch (CC) {
349  default:
350    break;
351  case ISD::SETGT:
352  case ISD::SETLE:
353  case ISD::SETUGT:
354  case ISD::SETULE:
355    CC = ISD::getSetCCSwappedOperands(CC);
356    std::swap(LHS, RHS);
357    break;
358  }
359}
360
361// Return the RISC-V branch opcode that matches the given DAG integer
362// condition code. The CondCode must be one of those supported by the RISC-V
363// ISA (see normaliseSetCC).
364static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) {
365  switch (CC) {
366  default:
367    llvm_unreachable("Unsupported CondCode");
368  case ISD::SETEQ:
369    return RISCV::BEQ;
370  case ISD::SETNE:
371    return RISCV::BNE;
372  case ISD::SETLT:
373    return RISCV::BLT;
374  case ISD::SETGE:
375    return RISCV::BGE;
376  case ISD::SETULT:
377    return RISCV::BLTU;
378  case ISD::SETUGE:
379    return RISCV::BGEU;
380  }
381}
382
383SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
384                                            SelectionDAG &DAG) const {
385  switch (Op.getOpcode()) {
386  default:
387    report_fatal_error("unimplemented operand");
388  case ISD::GlobalAddress:
389    return lowerGlobalAddress(Op, DAG);
390  case ISD::BlockAddress:
391    return lowerBlockAddress(Op, DAG);
392  case ISD::ConstantPool:
393    return lowerConstantPool(Op, DAG);
394  case ISD::GlobalTLSAddress:
395    return lowerGlobalTLSAddress(Op, DAG);
396  case ISD::SELECT:
397    return lowerSELECT(Op, DAG);
398  case ISD::VASTART:
399    return lowerVASTART(Op, DAG);
400  case ISD::FRAMEADDR:
401    return lowerFRAMEADDR(Op, DAG);
402  case ISD::RETURNADDR:
403    return lowerRETURNADDR(Op, DAG);
404  case ISD::SHL_PARTS:
405    return lowerShiftLeftParts(Op, DAG);
406  case ISD::SRA_PARTS:
407    return lowerShiftRightParts(Op, DAG, true);
408  case ISD::SRL_PARTS:
409    return lowerShiftRightParts(Op, DAG, false);
410  case ISD::BITCAST: {
411    assert(Subtarget.is64Bit() && Subtarget.hasStdExtF() &&
412           "Unexpected custom legalisation");
413    SDLoc DL(Op);
414    SDValue Op0 = Op.getOperand(0);
415    if (Op.getValueType() != MVT::f32 || Op0.getValueType() != MVT::i32)
416      return SDValue();
417    SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
418    SDValue FPConv = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
419    return FPConv;
420  }
421  }
422}
423
424static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
425                             SelectionDAG &DAG, unsigned Flags) {
426  return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
427}
428
429static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
430                             SelectionDAG &DAG, unsigned Flags) {
431  return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
432                                   Flags);
433}
434
435static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
436                             SelectionDAG &DAG, unsigned Flags) {
437  return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
438                                   N->getOffset(), Flags);
439}
440
441template <class NodeTy>
442SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
443                                     bool IsLocal) const {
444  SDLoc DL(N);
445  EVT Ty = getPointerTy(DAG.getDataLayout());
446
447  if (isPositionIndependent()) {
448    SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
449    if (IsLocal)
450      // Use PC-relative addressing to access the symbol. This generates the
451      // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
452      // %pcrel_lo(auipc)).
453      return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
454
455    // Use PC-relative addressing to access the GOT for this symbol, then load
456    // the address from the GOT. This generates the pattern (PseudoLA sym),
457    // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
458    return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
459  }
460
461  switch (getTargetMachine().getCodeModel()) {
462  default:
463    report_fatal_error("Unsupported code model for lowering");
464  case CodeModel::Small: {
465    // Generate a sequence for accessing addresses within the first 2 GiB of
466    // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
467    SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
468    SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
469    SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
470    return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
471  }
472  case CodeModel::Medium: {
473    // Generate a sequence for accessing addresses within any 2GiB range within
474    // the address space. This generates the pattern (PseudoLLA sym), which
475    // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
476    SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
477    return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
478  }
479  }
480}
481
482SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
483                                                SelectionDAG &DAG) const {
484  SDLoc DL(Op);
485  EVT Ty = Op.getValueType();
486  GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
487  int64_t Offset = N->getOffset();
488  MVT XLenVT = Subtarget.getXLenVT();
489
490  const GlobalValue *GV = N->getGlobal();
491  bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
492  SDValue Addr = getAddr(N, DAG, IsLocal);
493
494  // In order to maximise the opportunity for common subexpression elimination,
495  // emit a separate ADD node for the global address offset instead of folding
496  // it in the global address node. Later peephole optimisations may choose to
497  // fold it back in when profitable.
498  if (Offset != 0)
499    return DAG.getNode(ISD::ADD, DL, Ty, Addr,
500                       DAG.getConstant(Offset, DL, XLenVT));
501  return Addr;
502}
503
504SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
505                                               SelectionDAG &DAG) const {
506  BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
507
508  return getAddr(N, DAG);
509}
510
511SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
512                                               SelectionDAG &DAG) const {
513  ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
514
515  return getAddr(N, DAG);
516}
517
518SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
519                                              SelectionDAG &DAG,
520                                              bool UseGOT) const {
521  SDLoc DL(N);
522  EVT Ty = getPointerTy(DAG.getDataLayout());
523  const GlobalValue *GV = N->getGlobal();
524  MVT XLenVT = Subtarget.getXLenVT();
525
526  if (UseGOT) {
527    // Use PC-relative addressing to access the GOT for this TLS symbol, then
528    // load the address from the GOT and add the thread pointer. This generates
529    // the pattern (PseudoLA_TLS_IE sym), which expands to
530    // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
531    SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
532    SDValue Load =
533        SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
534
535    // Add the thread pointer.
536    SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
537    return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
538  }
539
540  // Generate a sequence for accessing the address relative to the thread
541  // pointer, with the appropriate adjustment for the thread pointer offset.
542  // This generates the pattern
543  // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
544  SDValue AddrHi =
545      DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
546  SDValue AddrAdd =
547      DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
548  SDValue AddrLo =
549      DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
550
551  SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
552  SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
553  SDValue MNAdd = SDValue(
554      DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
555      0);
556  return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
557}
558
559SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
560                                               SelectionDAG &DAG) const {
561  SDLoc DL(N);
562  EVT Ty = getPointerTy(DAG.getDataLayout());
563  IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
564  const GlobalValue *GV = N->getGlobal();
565
566  // Use a PC-relative addressing mode to access the global dynamic GOT address.
567  // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
568  // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
569  SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
570  SDValue Load =
571      SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
572
573  // Prepare argument list to generate call.
574  ArgListTy Args;
575  ArgListEntry Entry;
576  Entry.Node = Load;
577  Entry.Ty = CallTy;
578  Args.push_back(Entry);
579
580  // Setup call to __tls_get_addr.
581  TargetLowering::CallLoweringInfo CLI(DAG);
582  CLI.setDebugLoc(DL)
583      .setChain(DAG.getEntryNode())
584      .setLibCallee(CallingConv::C, CallTy,
585                    DAG.getExternalSymbol("__tls_get_addr", Ty),
586                    std::move(Args));
587
588  return LowerCallTo(CLI).first;
589}
590
591SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
592                                                   SelectionDAG &DAG) const {
593  SDLoc DL(Op);
594  EVT Ty = Op.getValueType();
595  GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
596  int64_t Offset = N->getOffset();
597  MVT XLenVT = Subtarget.getXLenVT();
598
599  TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
600
601  SDValue Addr;
602  switch (Model) {
603  case TLSModel::LocalExec:
604    Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
605    break;
606  case TLSModel::InitialExec:
607    Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
608    break;
609  case TLSModel::LocalDynamic:
610  case TLSModel::GeneralDynamic:
611    Addr = getDynamicTLSAddr(N, DAG);
612    break;
613  }
614
615  // In order to maximise the opportunity for common subexpression elimination,
616  // emit a separate ADD node for the global address offset instead of folding
617  // it in the global address node. Later peephole optimisations may choose to
618  // fold it back in when profitable.
619  if (Offset != 0)
620    return DAG.getNode(ISD::ADD, DL, Ty, Addr,
621                       DAG.getConstant(Offset, DL, XLenVT));
622  return Addr;
623}
624
625SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
626  SDValue CondV = Op.getOperand(0);
627  SDValue TrueV = Op.getOperand(1);
628  SDValue FalseV = Op.getOperand(2);
629  SDLoc DL(Op);
630  MVT XLenVT = Subtarget.getXLenVT();
631
632  // If the result type is XLenVT and CondV is the output of a SETCC node
633  // which also operated on XLenVT inputs, then merge the SETCC node into the
634  // lowered RISCVISD::SELECT_CC to take advantage of the integer
635  // compare+branch instructions. i.e.:
636  // (select (setcc lhs, rhs, cc), truev, falsev)
637  // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
638  if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC &&
639      CondV.getOperand(0).getSimpleValueType() == XLenVT) {
640    SDValue LHS = CondV.getOperand(0);
641    SDValue RHS = CondV.getOperand(1);
642    auto CC = cast<CondCodeSDNode>(CondV.getOperand(2));
643    ISD::CondCode CCVal = CC->get();
644
645    normaliseSetCC(LHS, RHS, CCVal);
646
647    SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT);
648    SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
649    SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
650    return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
651  }
652
653  // Otherwise:
654  // (select condv, truev, falsev)
655  // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
656  SDValue Zero = DAG.getConstant(0, DL, XLenVT);
657  SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT);
658
659  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
660  SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
661
662  return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
663}
664
665SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
666  MachineFunction &MF = DAG.getMachineFunction();
667  RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
668
669  SDLoc DL(Op);
670  SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
671                                 getPointerTy(MF.getDataLayout()));
672
673  // vastart just stores the address of the VarArgsFrameIndex slot into the
674  // memory location argument.
675  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
676  return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
677                      MachinePointerInfo(SV));
678}
679
680SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
681                                            SelectionDAG &DAG) const {
682  const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
683  MachineFunction &MF = DAG.getMachineFunction();
684  MachineFrameInfo &MFI = MF.getFrameInfo();
685  MFI.setFrameAddressIsTaken(true);
686  Register FrameReg = RI.getFrameRegister(MF);
687  int XLenInBytes = Subtarget.getXLen() / 8;
688
689  EVT VT = Op.getValueType();
690  SDLoc DL(Op);
691  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
692  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
693  while (Depth--) {
694    int Offset = -(XLenInBytes * 2);
695    SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
696                              DAG.getIntPtrConstant(Offset, DL));
697    FrameAddr =
698        DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
699  }
700  return FrameAddr;
701}
702
703SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
704                                             SelectionDAG &DAG) const {
705  const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
706  MachineFunction &MF = DAG.getMachineFunction();
707  MachineFrameInfo &MFI = MF.getFrameInfo();
708  MFI.setReturnAddressIsTaken(true);
709  MVT XLenVT = Subtarget.getXLenVT();
710  int XLenInBytes = Subtarget.getXLen() / 8;
711
712  if (verifyReturnAddressArgumentIsConstant(Op, DAG))
713    return SDValue();
714
715  EVT VT = Op.getValueType();
716  SDLoc DL(Op);
717  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
718  if (Depth) {
719    int Off = -XLenInBytes;
720    SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
721    SDValue Offset = DAG.getConstant(Off, DL, VT);
722    return DAG.getLoad(VT, DL, DAG.getEntryNode(),
723                       DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
724                       MachinePointerInfo());
725  }
726
727  // Return the value of the return address register, marking it an implicit
728  // live-in.
729  Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
730  return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
731}
732
733SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
734                                                 SelectionDAG &DAG) const {
735  SDLoc DL(Op);
736  SDValue Lo = Op.getOperand(0);
737  SDValue Hi = Op.getOperand(1);
738  SDValue Shamt = Op.getOperand(2);
739  EVT VT = Lo.getValueType();
740
741  // if Shamt-XLEN < 0: // Shamt < XLEN
742  //   Lo = Lo << Shamt
743  //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
744  // else:
745  //   Lo = 0
746  //   Hi = Lo << (Shamt-XLEN)
747
748  SDValue Zero = DAG.getConstant(0, DL, VT);
749  SDValue One = DAG.getConstant(1, DL, VT);
750  SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
751  SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
752  SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
753  SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
754
755  SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
756  SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
757  SDValue ShiftRightLo =
758      DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
759  SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
760  SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
761  SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
762
763  SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
764
765  Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
766  Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
767
768  SDValue Parts[2] = {Lo, Hi};
769  return DAG.getMergeValues(Parts, DL);
770}
771
772SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
773                                                  bool IsSRA) const {
774  SDLoc DL(Op);
775  SDValue Lo = Op.getOperand(0);
776  SDValue Hi = Op.getOperand(1);
777  SDValue Shamt = Op.getOperand(2);
778  EVT VT = Lo.getValueType();
779
780  // SRA expansion:
781  //   if Shamt-XLEN < 0: // Shamt < XLEN
782  //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
783  //     Hi = Hi >>s Shamt
784  //   else:
785  //     Lo = Hi >>s (Shamt-XLEN);
786  //     Hi = Hi >>s (XLEN-1)
787  //
788  // SRL expansion:
789  //   if Shamt-XLEN < 0: // Shamt < XLEN
790  //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
791  //     Hi = Hi >>u Shamt
792  //   else:
793  //     Lo = Hi >>u (Shamt-XLEN);
794  //     Hi = 0;
795
796  unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
797
798  SDValue Zero = DAG.getConstant(0, DL, VT);
799  SDValue One = DAG.getConstant(1, DL, VT);
800  SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
801  SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
802  SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
803  SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
804
805  SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
806  SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
807  SDValue ShiftLeftHi =
808      DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
809  SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
810  SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
811  SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
812  SDValue HiFalse =
813      IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
814
815  SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
816
817  Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
818  Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
819
820  SDValue Parts[2] = {Lo, Hi};
821  return DAG.getMergeValues(Parts, DL);
822}
823
824// Returns the opcode of the target-specific SDNode that implements the 32-bit
825// form of the given Opcode.
826static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
827  switch (Opcode) {
828  default:
829    llvm_unreachable("Unexpected opcode");
830  case ISD::SHL:
831    return RISCVISD::SLLW;
832  case ISD::SRA:
833    return RISCVISD::SRAW;
834  case ISD::SRL:
835    return RISCVISD::SRLW;
836  case ISD::SDIV:
837    return RISCVISD::DIVW;
838  case ISD::UDIV:
839    return RISCVISD::DIVUW;
840  case ISD::UREM:
841    return RISCVISD::REMUW;
842  }
843}
844
845// Converts the given 32-bit operation to a target-specific SelectionDAG node.
846// Because i32 isn't a legal type for RV64, these operations would otherwise
847// be promoted to i64, making it difficult to select the SLLW/DIVUW/.../*W
848// later one because the fact the operation was originally of type i32 is
849// lost.
850static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG) {
851  SDLoc DL(N);
852  RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
853  SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
854  SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
855  SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
856  // ReplaceNodeResults requires we maintain the same type for the return value.
857  return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
858}
859
860// Converts the given 32-bit operation to a i64 operation with signed extension
861// semantic to reduce the signed extension instructions.
862static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
863  SDLoc DL(N);
864  SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
865  SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
866  SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
867  SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
868                               DAG.getValueType(MVT::i32));
869  return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
870}
871
872void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
873                                             SmallVectorImpl<SDValue> &Results,
874                                             SelectionDAG &DAG) const {
875  SDLoc DL(N);
876  switch (N->getOpcode()) {
877  default:
878    llvm_unreachable("Don't know how to custom type legalize this operation!");
879  case ISD::READCYCLECOUNTER: {
880    assert(!Subtarget.is64Bit() &&
881           "READCYCLECOUNTER only has custom type legalization on riscv32");
882
883    SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
884    SDValue RCW =
885        DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
886
887    Results.push_back(RCW);
888    Results.push_back(RCW.getValue(1));
889    Results.push_back(RCW.getValue(2));
890    break;
891  }
892  case ISD::ADD:
893  case ISD::SUB:
894  case ISD::MUL:
895    assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
896           "Unexpected custom legalisation");
897    if (N->getOperand(1).getOpcode() == ISD::Constant)
898      return;
899    Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
900    break;
901  case ISD::SHL:
902  case ISD::SRA:
903  case ISD::SRL:
904    assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
905           "Unexpected custom legalisation");
906    if (N->getOperand(1).getOpcode() == ISD::Constant)
907      return;
908    Results.push_back(customLegalizeToWOp(N, DAG));
909    break;
910  case ISD::SDIV:
911  case ISD::UDIV:
912  case ISD::UREM:
913    assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
914           Subtarget.hasStdExtM() && "Unexpected custom legalisation");
915    if (N->getOperand(0).getOpcode() == ISD::Constant ||
916        N->getOperand(1).getOpcode() == ISD::Constant)
917      return;
918    Results.push_back(customLegalizeToWOp(N, DAG));
919    break;
920  case ISD::BITCAST: {
921    assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
922           Subtarget.hasStdExtF() && "Unexpected custom legalisation");
923    SDLoc DL(N);
924    SDValue Op0 = N->getOperand(0);
925    if (Op0.getValueType() != MVT::f32)
926      return;
927    SDValue FPConv =
928        DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
929    Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
930    break;
931  }
932  }
933}
934
935SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
936                                               DAGCombinerInfo &DCI) const {
937  SelectionDAG &DAG = DCI.DAG;
938
939  switch (N->getOpcode()) {
940  default:
941    break;
942  case RISCVISD::SplitF64: {
943    SDValue Op0 = N->getOperand(0);
944    // If the input to SplitF64 is just BuildPairF64 then the operation is
945    // redundant. Instead, use BuildPairF64's operands directly.
946    if (Op0->getOpcode() == RISCVISD::BuildPairF64)
947      return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
948
949    SDLoc DL(N);
950
951    // It's cheaper to materialise two 32-bit integers than to load a double
952    // from the constant pool and transfer it to integer registers through the
953    // stack.
954    if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
955      APInt V = C->getValueAPF().bitcastToAPInt();
956      SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
957      SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
958      return DCI.CombineTo(N, Lo, Hi);
959    }
960
961    // This is a target-specific version of a DAGCombine performed in
962    // DAGCombiner::visitBITCAST. It performs the equivalent of:
963    // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
964    // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
965    if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
966        !Op0.getNode()->hasOneUse())
967      break;
968    SDValue NewSplitF64 =
969        DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
970                    Op0.getOperand(0));
971    SDValue Lo = NewSplitF64.getValue(0);
972    SDValue Hi = NewSplitF64.getValue(1);
973    APInt SignBit = APInt::getSignMask(32);
974    if (Op0.getOpcode() == ISD::FNEG) {
975      SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
976                                  DAG.getConstant(SignBit, DL, MVT::i32));
977      return DCI.CombineTo(N, Lo, NewHi);
978    }
979    assert(Op0.getOpcode() == ISD::FABS);
980    SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
981                                DAG.getConstant(~SignBit, DL, MVT::i32));
982    return DCI.CombineTo(N, Lo, NewHi);
983  }
984  case RISCVISD::SLLW:
985  case RISCVISD::SRAW:
986  case RISCVISD::SRLW: {
987    // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
988    SDValue LHS = N->getOperand(0);
989    SDValue RHS = N->getOperand(1);
990    APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
991    APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 5);
992    if ((SimplifyDemandedBits(N->getOperand(0), LHSMask, DCI)) ||
993        (SimplifyDemandedBits(N->getOperand(1), RHSMask, DCI)))
994      return SDValue();
995    break;
996  }
997  case RISCVISD::FMV_X_ANYEXTW_RV64: {
998    SDLoc DL(N);
999    SDValue Op0 = N->getOperand(0);
1000    // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
1001    // conversion is unnecessary and can be replaced with an ANY_EXTEND
1002    // of the FMV_W_X_RV64 operand.
1003    if (Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) {
1004      SDValue AExtOp =
1005          DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0.getOperand(0));
1006      return DCI.CombineTo(N, AExtOp);
1007    }
1008
1009    // This is a target-specific version of a DAGCombine performed in
1010    // DAGCombiner::visitBITCAST. It performs the equivalent of:
1011    // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
1012    // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
1013    if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
1014        !Op0.getNode()->hasOneUse())
1015      break;
1016    SDValue NewFMV = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64,
1017                                 Op0.getOperand(0));
1018    APInt SignBit = APInt::getSignMask(32).sext(64);
1019    if (Op0.getOpcode() == ISD::FNEG) {
1020      return DCI.CombineTo(N,
1021                           DAG.getNode(ISD::XOR, DL, MVT::i64, NewFMV,
1022                                       DAG.getConstant(SignBit, DL, MVT::i64)));
1023    }
1024    assert(Op0.getOpcode() == ISD::FABS);
1025    return DCI.CombineTo(N,
1026                         DAG.getNode(ISD::AND, DL, MVT::i64, NewFMV,
1027                                     DAG.getConstant(~SignBit, DL, MVT::i64)));
1028  }
1029  }
1030
1031  return SDValue();
1032}
1033
1034bool RISCVTargetLowering::isDesirableToCommuteWithShift(
1035    const SDNode *N, CombineLevel Level) const {
1036  // The following folds are only desirable if `(OP _, c1 << c2)` can be
1037  // materialised in fewer instructions than `(OP _, c1)`:
1038  //
1039  //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
1040  //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
1041  SDValue N0 = N->getOperand(0);
1042  EVT Ty = N0.getValueType();
1043  if (Ty.isScalarInteger() &&
1044      (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
1045    auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
1046    auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
1047    if (C1 && C2) {
1048      APInt C1Int = C1->getAPIntValue();
1049      APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
1050
1051      // We can materialise `c1 << c2` into an add immediate, so it's "free",
1052      // and the combine should happen, to potentially allow further combines
1053      // later.
1054      if (ShiftedC1Int.getMinSignedBits() <= 64 &&
1055          isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
1056        return true;
1057
1058      // We can materialise `c1` in an add immediate, so it's "free", and the
1059      // combine should be prevented.
1060      if (C1Int.getMinSignedBits() <= 64 &&
1061          isLegalAddImmediate(C1Int.getSExtValue()))
1062        return false;
1063
1064      // Neither constant will fit into an immediate, so find materialisation
1065      // costs.
1066      int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
1067                                              Subtarget.is64Bit());
1068      int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
1069          ShiftedC1Int, Ty.getSizeInBits(), Subtarget.is64Bit());
1070
1071      // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
1072      // combine should be prevented.
1073      if (C1Cost < ShiftedC1Cost)
1074        return false;
1075    }
1076  }
1077  return true;
1078}
1079
1080unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
1081    SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
1082    unsigned Depth) const {
1083  switch (Op.getOpcode()) {
1084  default:
1085    break;
1086  case RISCVISD::SLLW:
1087  case RISCVISD::SRAW:
1088  case RISCVISD::SRLW:
1089  case RISCVISD::DIVW:
1090  case RISCVISD::DIVUW:
1091  case RISCVISD::REMUW:
1092    // TODO: As the result is sign-extended, this is conservatively correct. A
1093    // more precise answer could be calculated for SRAW depending on known
1094    // bits in the shift amount.
1095    return 33;
1096  }
1097
1098  return 1;
1099}
1100
1101static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
1102                                                  MachineBasicBlock *BB) {
1103  assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
1104
1105  // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
1106  // Should the count have wrapped while it was being read, we need to try
1107  // again.
1108  // ...
1109  // read:
1110  // rdcycleh x3 # load high word of cycle
1111  // rdcycle  x2 # load low word of cycle
1112  // rdcycleh x4 # load high word of cycle
1113  // bne x3, x4, read # check if high word reads match, otherwise try again
1114  // ...
1115
1116  MachineFunction &MF = *BB->getParent();
1117  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1118  MachineFunction::iterator It = ++BB->getIterator();
1119
1120  MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
1121  MF.insert(It, LoopMBB);
1122
1123  MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
1124  MF.insert(It, DoneMBB);
1125
1126  // Transfer the remainder of BB and its successor edges to DoneMBB.
1127  DoneMBB->splice(DoneMBB->begin(), BB,
1128                  std::next(MachineBasicBlock::iterator(MI)), BB->end());
1129  DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
1130
1131  BB->addSuccessor(LoopMBB);
1132
1133  MachineRegisterInfo &RegInfo = MF.getRegInfo();
1134  Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
1135  Register LoReg = MI.getOperand(0).getReg();
1136  Register HiReg = MI.getOperand(1).getReg();
1137  DebugLoc DL = MI.getDebugLoc();
1138
1139  const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
1140  BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
1141      .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
1142      .addReg(RISCV::X0);
1143  BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
1144      .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
1145      .addReg(RISCV::X0);
1146  BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
1147      .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
1148      .addReg(RISCV::X0);
1149
1150  BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
1151      .addReg(HiReg)
1152      .addReg(ReadAgainReg)
1153      .addMBB(LoopMBB);
1154
1155  LoopMBB->addSuccessor(LoopMBB);
1156  LoopMBB->addSuccessor(DoneMBB);
1157
1158  MI.eraseFromParent();
1159
1160  return DoneMBB;
1161}
1162
1163static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
1164                                             MachineBasicBlock *BB) {
1165  assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
1166
1167  MachineFunction &MF = *BB->getParent();
1168  DebugLoc DL = MI.getDebugLoc();
1169  const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1170  const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
1171  Register LoReg = MI.getOperand(0).getReg();
1172  Register HiReg = MI.getOperand(1).getReg();
1173  Register SrcReg = MI.getOperand(2).getReg();
1174  const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
1175  int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
1176
1177  TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
1178                          RI);
1179  MachineMemOperand *MMO =
1180      MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
1181                              MachineMemOperand::MOLoad, 8, 8);
1182  BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
1183      .addFrameIndex(FI)
1184      .addImm(0)
1185      .addMemOperand(MMO);
1186  BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
1187      .addFrameIndex(FI)
1188      .addImm(4)
1189      .addMemOperand(MMO);
1190  MI.eraseFromParent(); // The pseudo instruction is gone now.
1191  return BB;
1192}
1193
1194static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
1195                                                 MachineBasicBlock *BB) {
1196  assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
1197         "Unexpected instruction");
1198
1199  MachineFunction &MF = *BB->getParent();
1200  DebugLoc DL = MI.getDebugLoc();
1201  const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1202  const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
1203  Register DstReg = MI.getOperand(0).getReg();
1204  Register LoReg = MI.getOperand(1).getReg();
1205  Register HiReg = MI.getOperand(2).getReg();
1206  const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
1207  int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
1208
1209  MachineMemOperand *MMO =
1210      MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
1211                              MachineMemOperand::MOStore, 8, 8);
1212  BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
1213      .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
1214      .addFrameIndex(FI)
1215      .addImm(0)
1216      .addMemOperand(MMO);
1217  BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
1218      .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
1219      .addFrameIndex(FI)
1220      .addImm(4)
1221      .addMemOperand(MMO);
1222  TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
1223  MI.eraseFromParent(); // The pseudo instruction is gone now.
1224  return BB;
1225}
1226
1227static bool isSelectPseudo(MachineInstr &MI) {
1228  switch (MI.getOpcode()) {
1229  default:
1230    return false;
1231  case RISCV::Select_GPR_Using_CC_GPR:
1232  case RISCV::Select_FPR32_Using_CC_GPR:
1233  case RISCV::Select_FPR64_Using_CC_GPR:
1234    return true;
1235  }
1236}
1237
1238static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
1239                                           MachineBasicBlock *BB) {
1240  // To "insert" Select_* instructions, we actually have to insert the triangle
1241  // control-flow pattern.  The incoming instructions know the destination vreg
1242  // to set, the condition code register to branch on, the true/false values to
1243  // select between, and the condcode to use to select the appropriate branch.
1244  //
1245  // We produce the following control flow:
1246  //     HeadMBB
1247  //     |  \
1248  //     |  IfFalseMBB
1249  //     | /
1250  //    TailMBB
1251  //
1252  // When we find a sequence of selects we attempt to optimize their emission
1253  // by sharing the control flow. Currently we only handle cases where we have
1254  // multiple selects with the exact same condition (same LHS, RHS and CC).
1255  // The selects may be interleaved with other instructions if the other
1256  // instructions meet some requirements we deem safe:
1257  // - They are debug instructions. Otherwise,
1258  // - They do not have side-effects, do not access memory and their inputs do
1259  //   not depend on the results of the select pseudo-instructions.
1260  // The TrueV/FalseV operands of the selects cannot depend on the result of
1261  // previous selects in the sequence.
1262  // These conditions could be further relaxed. See the X86 target for a
1263  // related approach and more information.
1264  Register LHS = MI.getOperand(1).getReg();
1265  Register RHS = MI.getOperand(2).getReg();
1266  auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm());
1267
1268  SmallVector<MachineInstr *, 4> SelectDebugValues;
1269  SmallSet<Register, 4> SelectDests;
1270  SelectDests.insert(MI.getOperand(0).getReg());
1271
1272  MachineInstr *LastSelectPseudo = &MI;
1273
1274  for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
1275       SequenceMBBI != E; ++SequenceMBBI) {
1276    if (SequenceMBBI->isDebugInstr())
1277      continue;
1278    else if (isSelectPseudo(*SequenceMBBI)) {
1279      if (SequenceMBBI->getOperand(1).getReg() != LHS ||
1280          SequenceMBBI->getOperand(2).getReg() != RHS ||
1281          SequenceMBBI->getOperand(3).getImm() != CC ||
1282          SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
1283          SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
1284        break;
1285      LastSelectPseudo = &*SequenceMBBI;
1286      SequenceMBBI->collectDebugValues(SelectDebugValues);
1287      SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
1288    } else {
1289      if (SequenceMBBI->hasUnmodeledSideEffects() ||
1290          SequenceMBBI->mayLoadOrStore())
1291        break;
1292      if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
1293            return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
1294          }))
1295        break;
1296    }
1297  }
1298
1299  const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
1300  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1301  DebugLoc DL = MI.getDebugLoc();
1302  MachineFunction::iterator I = ++BB->getIterator();
1303
1304  MachineBasicBlock *HeadMBB = BB;
1305  MachineFunction *F = BB->getParent();
1306  MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
1307  MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
1308
1309  F->insert(I, IfFalseMBB);
1310  F->insert(I, TailMBB);
1311
1312  // Transfer debug instructions associated with the selects to TailMBB.
1313  for (MachineInstr *DebugInstr : SelectDebugValues) {
1314    TailMBB->push_back(DebugInstr->removeFromParent());
1315  }
1316
1317  // Move all instructions after the sequence to TailMBB.
1318  TailMBB->splice(TailMBB->end(), HeadMBB,
1319                  std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
1320  // Update machine-CFG edges by transferring all successors of the current
1321  // block to the new block which will contain the Phi nodes for the selects.
1322  TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
1323  // Set the successors for HeadMBB.
1324  HeadMBB->addSuccessor(IfFalseMBB);
1325  HeadMBB->addSuccessor(TailMBB);
1326
1327  // Insert appropriate branch.
1328  unsigned Opcode = getBranchOpcodeForIntCondCode(CC);
1329
1330  BuildMI(HeadMBB, DL, TII.get(Opcode))
1331    .addReg(LHS)
1332    .addReg(RHS)
1333    .addMBB(TailMBB);
1334
1335  // IfFalseMBB just falls through to TailMBB.
1336  IfFalseMBB->addSuccessor(TailMBB);
1337
1338  // Create PHIs for all of the select pseudo-instructions.
1339  auto SelectMBBI = MI.getIterator();
1340  auto SelectEnd = std::next(LastSelectPseudo->getIterator());
1341  auto InsertionPoint = TailMBB->begin();
1342  while (SelectMBBI != SelectEnd) {
1343    auto Next = std::next(SelectMBBI);
1344    if (isSelectPseudo(*SelectMBBI)) {
1345      // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
1346      BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
1347              TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
1348          .addReg(SelectMBBI->getOperand(4).getReg())
1349          .addMBB(HeadMBB)
1350          .addReg(SelectMBBI->getOperand(5).getReg())
1351          .addMBB(IfFalseMBB);
1352      SelectMBBI->eraseFromParent();
1353    }
1354    SelectMBBI = Next;
1355  }
1356
1357  F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
1358  return TailMBB;
1359}
1360
1361MachineBasicBlock *
1362RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1363                                                 MachineBasicBlock *BB) const {
1364  switch (MI.getOpcode()) {
1365  default:
1366    llvm_unreachable("Unexpected instr type to insert");
1367  case RISCV::ReadCycleWide:
1368    assert(!Subtarget.is64Bit() &&
1369           "ReadCycleWrite is only to be used on riscv32");
1370    return emitReadCycleWidePseudo(MI, BB);
1371  case RISCV::Select_GPR_Using_CC_GPR:
1372  case RISCV::Select_FPR32_Using_CC_GPR:
1373  case RISCV::Select_FPR64_Using_CC_GPR:
1374    return emitSelectPseudo(MI, BB);
1375  case RISCV::BuildPairF64Pseudo:
1376    return emitBuildPairF64Pseudo(MI, BB);
1377  case RISCV::SplitF64Pseudo:
1378    return emitSplitF64Pseudo(MI, BB);
1379  }
1380}
1381
1382// Calling Convention Implementation.
1383// The expectations for frontend ABI lowering vary from target to target.
1384// Ideally, an LLVM frontend would be able to avoid worrying about many ABI
1385// details, but this is a longer term goal. For now, we simply try to keep the
1386// role of the frontend as simple and well-defined as possible. The rules can
1387// be summarised as:
1388// * Never split up large scalar arguments. We handle them here.
1389// * If a hardfloat calling convention is being used, and the struct may be
1390// passed in a pair of registers (fp+fp, int+fp), and both registers are
1391// available, then pass as two separate arguments. If either the GPRs or FPRs
1392// are exhausted, then pass according to the rule below.
1393// * If a struct could never be passed in registers or directly in a stack
1394// slot (as it is larger than 2*XLEN and the floating point rules don't
1395// apply), then pass it using a pointer with the byval attribute.
1396// * If a struct is less than 2*XLEN, then coerce to either a two-element
1397// word-sized array or a 2*XLEN scalar (depending on alignment).
1398// * The frontend can determine whether a struct is returned by reference or
1399// not based on its size and fields. If it will be returned by reference, the
1400// frontend must modify the prototype so a pointer with the sret annotation is
1401// passed as the first argument. This is not necessary for large scalar
1402// returns.
1403// * Struct return values and varargs should be coerced to structs containing
1404// register-size fields in the same situations they would be for fixed
1405// arguments.
1406
1407static const MCPhysReg ArgGPRs[] = {
1408  RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
1409  RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
1410};
1411static const MCPhysReg ArgFPR32s[] = {
1412  RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
1413  RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
1414};
1415static const MCPhysReg ArgFPR64s[] = {
1416  RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
1417  RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
1418};
1419
1420// Pass a 2*XLEN argument that has been split into two XLEN values through
1421// registers or the stack as necessary.
1422static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
1423                                ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
1424                                MVT ValVT2, MVT LocVT2,
1425                                ISD::ArgFlagsTy ArgFlags2) {
1426  unsigned XLenInBytes = XLen / 8;
1427  if (Register Reg = State.AllocateReg(ArgGPRs)) {
1428    // At least one half can be passed via register.
1429    State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
1430                                     VA1.getLocVT(), CCValAssign::Full));
1431  } else {
1432    // Both halves must be passed on the stack, with proper alignment.
1433    unsigned StackAlign = std::max(XLenInBytes, ArgFlags1.getOrigAlign());
1434    State.addLoc(
1435        CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
1436                            State.AllocateStack(XLenInBytes, StackAlign),
1437                            VA1.getLocVT(), CCValAssign::Full));
1438    State.addLoc(CCValAssign::getMem(
1439        ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
1440        CCValAssign::Full));
1441    return false;
1442  }
1443
1444  if (Register Reg = State.AllocateReg(ArgGPRs)) {
1445    // The second half can also be passed via register.
1446    State.addLoc(
1447        CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
1448  } else {
1449    // The second half is passed via the stack, without additional alignment.
1450    State.addLoc(CCValAssign::getMem(
1451        ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
1452        CCValAssign::Full));
1453  }
1454
1455  return false;
1456}
1457
1458// Implements the RISC-V calling convention. Returns true upon failure.
1459static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
1460                     MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
1461                     ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
1462                     bool IsRet, Type *OrigTy) {
1463  unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
1464  assert(XLen == 32 || XLen == 64);
1465  MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
1466
1467  // Any return value split in to more than two values can't be returned
1468  // directly.
1469  if (IsRet && ValNo > 1)
1470    return true;
1471
1472  // UseGPRForF32 if targeting one of the soft-float ABIs, if passing a
1473  // variadic argument, or if no F32 argument registers are available.
1474  bool UseGPRForF32 = true;
1475  // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
1476  // variadic argument, or if no F64 argument registers are available.
1477  bool UseGPRForF64 = true;
1478
1479  switch (ABI) {
1480  default:
1481    llvm_unreachable("Unexpected ABI");
1482  case RISCVABI::ABI_ILP32:
1483  case RISCVABI::ABI_LP64:
1484    break;
1485  case RISCVABI::ABI_ILP32F:
1486  case RISCVABI::ABI_LP64F:
1487    UseGPRForF32 = !IsFixed;
1488    break;
1489  case RISCVABI::ABI_ILP32D:
1490  case RISCVABI::ABI_LP64D:
1491    UseGPRForF32 = !IsFixed;
1492    UseGPRForF64 = !IsFixed;
1493    break;
1494  }
1495
1496  if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s))
1497    UseGPRForF32 = true;
1498  if (State.getFirstUnallocated(ArgFPR64s) == array_lengthof(ArgFPR64s))
1499    UseGPRForF64 = true;
1500
1501  // From this point on, rely on UseGPRForF32, UseGPRForF64 and similar local
1502  // variables rather than directly checking against the target ABI.
1503
1504  if (UseGPRForF32 && ValVT == MVT::f32) {
1505    LocVT = XLenVT;
1506    LocInfo = CCValAssign::BCvt;
1507  } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
1508    LocVT = MVT::i64;
1509    LocInfo = CCValAssign::BCvt;
1510  }
1511
1512  // If this is a variadic argument, the RISC-V calling convention requires
1513  // that it is assigned an 'even' or 'aligned' register if it has 8-byte
1514  // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
1515  // be used regardless of whether the original argument was split during
1516  // legalisation or not. The argument will not be passed by registers if the
1517  // original type is larger than 2*XLEN, so the register alignment rule does
1518  // not apply.
1519  unsigned TwoXLenInBytes = (2 * XLen) / 8;
1520  if (!IsFixed && ArgFlags.getOrigAlign() == TwoXLenInBytes &&
1521      DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
1522    unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
1523    // Skip 'odd' register if necessary.
1524    if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
1525      State.AllocateReg(ArgGPRs);
1526  }
1527
1528  SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
1529  SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
1530      State.getPendingArgFlags();
1531
1532  assert(PendingLocs.size() == PendingArgFlags.size() &&
1533         "PendingLocs and PendingArgFlags out of sync");
1534
1535  // Handle passing f64 on RV32D with a soft float ABI or when floating point
1536  // registers are exhausted.
1537  if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
1538    assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
1539           "Can't lower f64 if it is split");
1540    // Depending on available argument GPRS, f64 may be passed in a pair of
1541    // GPRs, split between a GPR and the stack, or passed completely on the
1542    // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
1543    // cases.
1544    Register Reg = State.AllocateReg(ArgGPRs);
1545    LocVT = MVT::i32;
1546    if (!Reg) {
1547      unsigned StackOffset = State.AllocateStack(8, 8);
1548      State.addLoc(
1549          CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
1550      return false;
1551    }
1552    if (!State.AllocateReg(ArgGPRs))
1553      State.AllocateStack(4, 4);
1554    State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1555    return false;
1556  }
1557
1558  // Split arguments might be passed indirectly, so keep track of the pending
1559  // values.
1560  if (ArgFlags.isSplit() || !PendingLocs.empty()) {
1561    LocVT = XLenVT;
1562    LocInfo = CCValAssign::Indirect;
1563    PendingLocs.push_back(
1564        CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
1565    PendingArgFlags.push_back(ArgFlags);
1566    if (!ArgFlags.isSplitEnd()) {
1567      return false;
1568    }
1569  }
1570
1571  // If the split argument only had two elements, it should be passed directly
1572  // in registers or on the stack.
1573  if (ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) {
1574    assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
1575    // Apply the normal calling convention rules to the first half of the
1576    // split argument.
1577    CCValAssign VA = PendingLocs[0];
1578    ISD::ArgFlagsTy AF = PendingArgFlags[0];
1579    PendingLocs.clear();
1580    PendingArgFlags.clear();
1581    return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
1582                               ArgFlags);
1583  }
1584
1585  // Allocate to a register if possible, or else a stack slot.
1586  Register Reg;
1587  if (ValVT == MVT::f32 && !UseGPRForF32)
1588    Reg = State.AllocateReg(ArgFPR32s, ArgFPR64s);
1589  else if (ValVT == MVT::f64 && !UseGPRForF64)
1590    Reg = State.AllocateReg(ArgFPR64s, ArgFPR32s);
1591  else
1592    Reg = State.AllocateReg(ArgGPRs);
1593  unsigned StackOffset = Reg ? 0 : State.AllocateStack(XLen / 8, XLen / 8);
1594
1595  // If we reach this point and PendingLocs is non-empty, we must be at the
1596  // end of a split argument that must be passed indirectly.
1597  if (!PendingLocs.empty()) {
1598    assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
1599    assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
1600
1601    for (auto &It : PendingLocs) {
1602      if (Reg)
1603        It.convertToReg(Reg);
1604      else
1605        It.convertToMem(StackOffset);
1606      State.addLoc(It);
1607    }
1608    PendingLocs.clear();
1609    PendingArgFlags.clear();
1610    return false;
1611  }
1612
1613  assert((!UseGPRForF32 || !UseGPRForF64 || LocVT == XLenVT) &&
1614         "Expected an XLenVT at this stage");
1615
1616  if (Reg) {
1617    State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1618    return false;
1619  }
1620
1621  // When an f32 or f64 is passed on the stack, no bit-conversion is needed.
1622  if (ValVT == MVT::f32 || ValVT == MVT::f64) {
1623    LocVT = ValVT;
1624    LocInfo = CCValAssign::Full;
1625  }
1626  State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
1627  return false;
1628}
1629
1630void RISCVTargetLowering::analyzeInputArgs(
1631    MachineFunction &MF, CCState &CCInfo,
1632    const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const {
1633  unsigned NumArgs = Ins.size();
1634  FunctionType *FType = MF.getFunction().getFunctionType();
1635
1636  for (unsigned i = 0; i != NumArgs; ++i) {
1637    MVT ArgVT = Ins[i].VT;
1638    ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
1639
1640    Type *ArgTy = nullptr;
1641    if (IsRet)
1642      ArgTy = FType->getReturnType();
1643    else if (Ins[i].isOrigArg())
1644      ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
1645
1646    RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
1647    if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
1648                 ArgFlags, CCInfo, /*IsRet=*/true, IsRet, ArgTy)) {
1649      LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
1650                        << EVT(ArgVT).getEVTString() << '\n');
1651      llvm_unreachable(nullptr);
1652    }
1653  }
1654}
1655
1656void RISCVTargetLowering::analyzeOutputArgs(
1657    MachineFunction &MF, CCState &CCInfo,
1658    const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
1659    CallLoweringInfo *CLI) const {
1660  unsigned NumArgs = Outs.size();
1661
1662  for (unsigned i = 0; i != NumArgs; i++) {
1663    MVT ArgVT = Outs[i].VT;
1664    ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1665    Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
1666
1667    RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
1668    if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
1669                 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy)) {
1670      LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
1671                        << EVT(ArgVT).getEVTString() << "\n");
1672      llvm_unreachable(nullptr);
1673    }
1674  }
1675}
1676
1677// Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
1678// values.
1679static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
1680                                   const CCValAssign &VA, const SDLoc &DL) {
1681  switch (VA.getLocInfo()) {
1682  default:
1683    llvm_unreachable("Unexpected CCValAssign::LocInfo");
1684  case CCValAssign::Full:
1685    break;
1686  case CCValAssign::BCvt:
1687    if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) {
1688      Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
1689      break;
1690    }
1691    Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
1692    break;
1693  }
1694  return Val;
1695}
1696
1697// The caller is responsible for loading the full value if the argument is
1698// passed with CCValAssign::Indirect.
1699static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
1700                                const CCValAssign &VA, const SDLoc &DL) {
1701  MachineFunction &MF = DAG.getMachineFunction();
1702  MachineRegisterInfo &RegInfo = MF.getRegInfo();
1703  EVT LocVT = VA.getLocVT();
1704  SDValue Val;
1705  const TargetRegisterClass *RC;
1706
1707  switch (LocVT.getSimpleVT().SimpleTy) {
1708  default:
1709    llvm_unreachable("Unexpected register type");
1710  case MVT::i32:
1711  case MVT::i64:
1712    RC = &RISCV::GPRRegClass;
1713    break;
1714  case MVT::f32:
1715    RC = &RISCV::FPR32RegClass;
1716    break;
1717  case MVT::f64:
1718    RC = &RISCV::FPR64RegClass;
1719    break;
1720  }
1721
1722  Register VReg = RegInfo.createVirtualRegister(RC);
1723  RegInfo.addLiveIn(VA.getLocReg(), VReg);
1724  Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
1725
1726  if (VA.getLocInfo() == CCValAssign::Indirect)
1727    return Val;
1728
1729  return convertLocVTToValVT(DAG, Val, VA, DL);
1730}
1731
1732static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
1733                                   const CCValAssign &VA, const SDLoc &DL) {
1734  EVT LocVT = VA.getLocVT();
1735
1736  switch (VA.getLocInfo()) {
1737  default:
1738    llvm_unreachable("Unexpected CCValAssign::LocInfo");
1739  case CCValAssign::Full:
1740    break;
1741  case CCValAssign::BCvt:
1742    if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) {
1743      Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
1744      break;
1745    }
1746    Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
1747    break;
1748  }
1749  return Val;
1750}
1751
1752// The caller is responsible for loading the full value if the argument is
1753// passed with CCValAssign::Indirect.
1754static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
1755                                const CCValAssign &VA, const SDLoc &DL) {
1756  MachineFunction &MF = DAG.getMachineFunction();
1757  MachineFrameInfo &MFI = MF.getFrameInfo();
1758  EVT LocVT = VA.getLocVT();
1759  EVT ValVT = VA.getValVT();
1760  EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
1761  int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
1762                                 VA.getLocMemOffset(), /*Immutable=*/true);
1763  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1764  SDValue Val;
1765
1766  ISD::LoadExtType ExtType;
1767  switch (VA.getLocInfo()) {
1768  default:
1769    llvm_unreachable("Unexpected CCValAssign::LocInfo");
1770  case CCValAssign::Full:
1771  case CCValAssign::Indirect:
1772  case CCValAssign::BCvt:
1773    ExtType = ISD::NON_EXTLOAD;
1774    break;
1775  }
1776  Val = DAG.getExtLoad(
1777      ExtType, DL, LocVT, Chain, FIN,
1778      MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
1779  return Val;
1780}
1781
1782static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
1783                                       const CCValAssign &VA, const SDLoc &DL) {
1784  assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
1785         "Unexpected VA");
1786  MachineFunction &MF = DAG.getMachineFunction();
1787  MachineFrameInfo &MFI = MF.getFrameInfo();
1788  MachineRegisterInfo &RegInfo = MF.getRegInfo();
1789
1790  if (VA.isMemLoc()) {
1791    // f64 is passed on the stack.
1792    int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
1793    SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1794    return DAG.getLoad(MVT::f64, DL, Chain, FIN,
1795                       MachinePointerInfo::getFixedStack(MF, FI));
1796  }
1797
1798  assert(VA.isRegLoc() && "Expected register VA assignment");
1799
1800  Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
1801  RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
1802  SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
1803  SDValue Hi;
1804  if (VA.getLocReg() == RISCV::X17) {
1805    // Second half of f64 is passed on the stack.
1806    int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
1807    SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1808    Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
1809                     MachinePointerInfo::getFixedStack(MF, FI));
1810  } else {
1811    // Second half of f64 is passed in another GPR.
1812    Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
1813    RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
1814    Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
1815  }
1816  return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
1817}
1818
1819// FastCC has less than 1% performance improvement for some particular
1820// benchmark. But theoretically, it may has benenfit for some cases.
1821static bool CC_RISCV_FastCC(unsigned ValNo, MVT ValVT, MVT LocVT,
1822                            CCValAssign::LocInfo LocInfo,
1823                            ISD::ArgFlagsTy ArgFlags, CCState &State) {
1824
1825  if (LocVT == MVT::i32 || LocVT == MVT::i64) {
1826    // X5 and X6 might be used for save-restore libcall.
1827    static const MCPhysReg GPRList[] = {
1828        RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
1829        RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
1830        RISCV::X29, RISCV::X30, RISCV::X31};
1831    if (unsigned Reg = State.AllocateReg(GPRList)) {
1832      State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1833      return false;
1834    }
1835  }
1836
1837  if (LocVT == MVT::f32) {
1838    static const MCPhysReg FPR32List[] = {
1839        RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
1840        RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
1841        RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
1842        RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
1843    if (unsigned Reg = State.AllocateReg(FPR32List)) {
1844      State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1845      return false;
1846    }
1847  }
1848
1849  if (LocVT == MVT::f64) {
1850    static const MCPhysReg FPR64List[] = {
1851        RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
1852        RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
1853        RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
1854        RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
1855    if (unsigned Reg = State.AllocateReg(FPR64List)) {
1856      State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1857      return false;
1858    }
1859  }
1860
1861  if (LocVT == MVT::i32 || LocVT == MVT::f32) {
1862    unsigned Offset4 = State.AllocateStack(4, 4);
1863    State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
1864    return false;
1865  }
1866
1867  if (LocVT == MVT::i64 || LocVT == MVT::f64) {
1868    unsigned Offset5 = State.AllocateStack(8, 8);
1869    State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
1870    return false;
1871  }
1872
1873  return true; // CC didn't match.
1874}
1875
1876// Transform physical registers into virtual registers.
1877SDValue RISCVTargetLowering::LowerFormalArguments(
1878    SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
1879    const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1880    SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1881
1882  switch (CallConv) {
1883  default:
1884    report_fatal_error("Unsupported calling convention");
1885  case CallingConv::C:
1886  case CallingConv::Fast:
1887    break;
1888  }
1889
1890  MachineFunction &MF = DAG.getMachineFunction();
1891
1892  const Function &Func = MF.getFunction();
1893  if (Func.hasFnAttribute("interrupt")) {
1894    if (!Func.arg_empty())
1895      report_fatal_error(
1896        "Functions with the interrupt attribute cannot have arguments!");
1897
1898    StringRef Kind =
1899      MF.getFunction().getFnAttribute("interrupt").getValueAsString();
1900
1901    if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
1902      report_fatal_error(
1903        "Function interrupt attribute argument not supported!");
1904  }
1905
1906  EVT PtrVT = getPointerTy(DAG.getDataLayout());
1907  MVT XLenVT = Subtarget.getXLenVT();
1908  unsigned XLenInBytes = Subtarget.getXLen() / 8;
1909  // Used with vargs to acumulate store chains.
1910  std::vector<SDValue> OutChains;
1911
1912  // Assign locations to all of the incoming arguments.
1913  SmallVector<CCValAssign, 16> ArgLocs;
1914  CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1915
1916  if (CallConv == CallingConv::Fast)
1917    CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_FastCC);
1918  else
1919    analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false);
1920
1921  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1922    CCValAssign &VA = ArgLocs[i];
1923    SDValue ArgValue;
1924    // Passing f64 on RV32D with a soft float ABI must be handled as a special
1925    // case.
1926    if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
1927      ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
1928    else if (VA.isRegLoc())
1929      ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL);
1930    else
1931      ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
1932
1933    if (VA.getLocInfo() == CCValAssign::Indirect) {
1934      // If the original argument was split and passed by reference (e.g. i128
1935      // on RV32), we need to load all parts of it here (using the same
1936      // address).
1937      InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
1938                                   MachinePointerInfo()));
1939      unsigned ArgIndex = Ins[i].OrigArgIndex;
1940      assert(Ins[i].PartOffset == 0);
1941      while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
1942        CCValAssign &PartVA = ArgLocs[i + 1];
1943        unsigned PartOffset = Ins[i + 1].PartOffset;
1944        SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
1945                                      DAG.getIntPtrConstant(PartOffset, DL));
1946        InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
1947                                     MachinePointerInfo()));
1948        ++i;
1949      }
1950      continue;
1951    }
1952    InVals.push_back(ArgValue);
1953  }
1954
1955  if (IsVarArg) {
1956    ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
1957    unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
1958    const TargetRegisterClass *RC = &RISCV::GPRRegClass;
1959    MachineFrameInfo &MFI = MF.getFrameInfo();
1960    MachineRegisterInfo &RegInfo = MF.getRegInfo();
1961    RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1962
1963    // Offset of the first variable argument from stack pointer, and size of
1964    // the vararg save area. For now, the varargs save area is either zero or
1965    // large enough to hold a0-a7.
1966    int VaArgOffset, VarArgsSaveSize;
1967
1968    // If all registers are allocated, then all varargs must be passed on the
1969    // stack and we don't need to save any argregs.
1970    if (ArgRegs.size() == Idx) {
1971      VaArgOffset = CCInfo.getNextStackOffset();
1972      VarArgsSaveSize = 0;
1973    } else {
1974      VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
1975      VaArgOffset = -VarArgsSaveSize;
1976    }
1977
1978    // Record the frame index of the first variable argument
1979    // which is a value necessary to VASTART.
1980    int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1981    RVFI->setVarArgsFrameIndex(FI);
1982
1983    // If saving an odd number of registers then create an extra stack slot to
1984    // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
1985    // offsets to even-numbered registered remain 2*XLEN-aligned.
1986    if (Idx % 2) {
1987      MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
1988      VarArgsSaveSize += XLenInBytes;
1989    }
1990
1991    // Copy the integer registers that may have been used for passing varargs
1992    // to the vararg save area.
1993    for (unsigned I = Idx; I < ArgRegs.size();
1994         ++I, VaArgOffset += XLenInBytes) {
1995      const Register Reg = RegInfo.createVirtualRegister(RC);
1996      RegInfo.addLiveIn(ArgRegs[I], Reg);
1997      SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
1998      FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1999      SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2000      SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
2001                                   MachinePointerInfo::getFixedStack(MF, FI));
2002      cast<StoreSDNode>(Store.getNode())
2003          ->getMemOperand()
2004          ->setValue((Value *)nullptr);
2005      OutChains.push_back(Store);
2006    }
2007    RVFI->setVarArgsSaveSize(VarArgsSaveSize);
2008  }
2009
2010  // All stores are grouped in one node to allow the matching between
2011  // the size of Ins and InVals. This only happens for vararg functions.
2012  if (!OutChains.empty()) {
2013    OutChains.push_back(Chain);
2014    Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
2015  }
2016
2017  return Chain;
2018}
2019
2020/// isEligibleForTailCallOptimization - Check whether the call is eligible
2021/// for tail call optimization.
2022/// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
2023bool RISCVTargetLowering::isEligibleForTailCallOptimization(
2024    CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
2025    const SmallVector<CCValAssign, 16> &ArgLocs) const {
2026
2027  auto &Callee = CLI.Callee;
2028  auto CalleeCC = CLI.CallConv;
2029  auto &Outs = CLI.Outs;
2030  auto &Caller = MF.getFunction();
2031  auto CallerCC = Caller.getCallingConv();
2032
2033  // Exception-handling functions need a special set of instructions to
2034  // indicate a return to the hardware. Tail-calling another function would
2035  // probably break this.
2036  // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
2037  // should be expanded as new function attributes are introduced.
2038  if (Caller.hasFnAttribute("interrupt"))
2039    return false;
2040
2041  // Do not tail call opt if the stack is used to pass parameters.
2042  if (CCInfo.getNextStackOffset() != 0)
2043    return false;
2044
2045  // Do not tail call opt if any parameters need to be passed indirectly.
2046  // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
2047  // passed indirectly. So the address of the value will be passed in a
2048  // register, or if not available, then the address is put on the stack. In
2049  // order to pass indirectly, space on the stack often needs to be allocated
2050  // in order to store the value. In this case the CCInfo.getNextStackOffset()
2051  // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
2052  // are passed CCValAssign::Indirect.
2053  for (auto &VA : ArgLocs)
2054    if (VA.getLocInfo() == CCValAssign::Indirect)
2055      return false;
2056
2057  // Do not tail call opt if either caller or callee uses struct return
2058  // semantics.
2059  auto IsCallerStructRet = Caller.hasStructRetAttr();
2060  auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
2061  if (IsCallerStructRet || IsCalleeStructRet)
2062    return false;
2063
2064  // Externally-defined functions with weak linkage should not be
2065  // tail-called. The behaviour of branch instructions in this situation (as
2066  // used for tail calls) is implementation-defined, so we cannot rely on the
2067  // linker replacing the tail call with a return.
2068  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2069    const GlobalValue *GV = G->getGlobal();
2070    if (GV->hasExternalWeakLinkage())
2071      return false;
2072  }
2073
2074  // The callee has to preserve all registers the caller needs to preserve.
2075  const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
2076  const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2077  if (CalleeCC != CallerCC) {
2078    const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2079    if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2080      return false;
2081  }
2082
2083  // Byval parameters hand the function a pointer directly into the stack area
2084  // we want to reuse during a tail call. Working around this *is* possible
2085  // but less efficient and uglier in LowerCall.
2086  for (auto &Arg : Outs)
2087    if (Arg.Flags.isByVal())
2088      return false;
2089
2090  return true;
2091}
2092
2093// Lower a call to a callseq_start + CALL + callseq_end chain, and add input
2094// and output parameter nodes.
2095SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
2096                                       SmallVectorImpl<SDValue> &InVals) const {
2097  SelectionDAG &DAG = CLI.DAG;
2098  SDLoc &DL = CLI.DL;
2099  SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2100  SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2101  SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2102  SDValue Chain = CLI.Chain;
2103  SDValue Callee = CLI.Callee;
2104  bool &IsTailCall = CLI.IsTailCall;
2105  CallingConv::ID CallConv = CLI.CallConv;
2106  bool IsVarArg = CLI.IsVarArg;
2107  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2108  MVT XLenVT = Subtarget.getXLenVT();
2109
2110  MachineFunction &MF = DAG.getMachineFunction();
2111
2112  // Analyze the operands of the call, assigning locations to each operand.
2113  SmallVector<CCValAssign, 16> ArgLocs;
2114  CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2115
2116  if (CallConv == CallingConv::Fast)
2117    ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_FastCC);
2118  else
2119    analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI);
2120
2121  // Check if it's really possible to do a tail call.
2122  if (IsTailCall)
2123    IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
2124
2125  if (IsTailCall)
2126    ++NumTailCalls;
2127  else if (CLI.CS && CLI.CS.isMustTailCall())
2128    report_fatal_error("failed to perform tail call elimination on a call "
2129                       "site marked musttail");
2130
2131  // Get a count of how many bytes are to be pushed on the stack.
2132  unsigned NumBytes = ArgCCInfo.getNextStackOffset();
2133
2134  // Create local copies for byval args
2135  SmallVector<SDValue, 8> ByValArgs;
2136  for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
2137    ISD::ArgFlagsTy Flags = Outs[i].Flags;
2138    if (!Flags.isByVal())
2139      continue;
2140
2141    SDValue Arg = OutVals[i];
2142    unsigned Size = Flags.getByValSize();
2143    unsigned Align = Flags.getByValAlign();
2144
2145    int FI = MF.getFrameInfo().CreateStackObject(Size, Align, /*isSS=*/false);
2146    SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2147    SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
2148
2149    Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Align,
2150                          /*IsVolatile=*/false,
2151                          /*AlwaysInline=*/false,
2152                          IsTailCall, MachinePointerInfo(),
2153                          MachinePointerInfo());
2154    ByValArgs.push_back(FIPtr);
2155  }
2156
2157  if (!IsTailCall)
2158    Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
2159
2160  // Copy argument values to their designated locations.
2161  SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
2162  SmallVector<SDValue, 8> MemOpChains;
2163  SDValue StackPtr;
2164  for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
2165    CCValAssign &VA = ArgLocs[i];
2166    SDValue ArgValue = OutVals[i];
2167    ISD::ArgFlagsTy Flags = Outs[i].Flags;
2168
2169    // Handle passing f64 on RV32D with a soft float ABI as a special case.
2170    bool IsF64OnRV32DSoftABI =
2171        VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
2172    if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
2173      SDValue SplitF64 = DAG.getNode(
2174          RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
2175      SDValue Lo = SplitF64.getValue(0);
2176      SDValue Hi = SplitF64.getValue(1);
2177
2178      Register RegLo = VA.getLocReg();
2179      RegsToPass.push_back(std::make_pair(RegLo, Lo));
2180
2181      if (RegLo == RISCV::X17) {
2182        // Second half of f64 is passed on the stack.
2183        // Work out the address of the stack slot.
2184        if (!StackPtr.getNode())
2185          StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
2186        // Emit the store.
2187        MemOpChains.push_back(
2188            DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
2189      } else {
2190        // Second half of f64 is passed in another GPR.
2191        assert(RegLo < RISCV::X31 && "Invalid register pair");
2192        Register RegHigh = RegLo + 1;
2193        RegsToPass.push_back(std::make_pair(RegHigh, Hi));
2194      }
2195      continue;
2196    }
2197
2198    // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
2199    // as any other MemLoc.
2200
2201    // Promote the value if needed.
2202    // For now, only handle fully promoted and indirect arguments.
2203    if (VA.getLocInfo() == CCValAssign::Indirect) {
2204      // Store the argument in a stack slot and pass its address.
2205      SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT);
2206      int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2207      MemOpChains.push_back(
2208          DAG.getStore(Chain, DL, ArgValue, SpillSlot,
2209                       MachinePointerInfo::getFixedStack(MF, FI)));
2210      // If the original argument was split (e.g. i128), we need
2211      // to store all parts of it here (and pass just one address).
2212      unsigned ArgIndex = Outs[i].OrigArgIndex;
2213      assert(Outs[i].PartOffset == 0);
2214      while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
2215        SDValue PartValue = OutVals[i + 1];
2216        unsigned PartOffset = Outs[i + 1].PartOffset;
2217        SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
2218                                      DAG.getIntPtrConstant(PartOffset, DL));
2219        MemOpChains.push_back(
2220            DAG.getStore(Chain, DL, PartValue, Address,
2221                         MachinePointerInfo::getFixedStack(MF, FI)));
2222        ++i;
2223      }
2224      ArgValue = SpillSlot;
2225    } else {
2226      ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL);
2227    }
2228
2229    // Use local copy if it is a byval arg.
2230    if (Flags.isByVal())
2231      ArgValue = ByValArgs[j++];
2232
2233    if (VA.isRegLoc()) {
2234      // Queue up the argument copies and emit them at the end.
2235      RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
2236    } else {
2237      assert(VA.isMemLoc() && "Argument not register or memory");
2238      assert(!IsTailCall && "Tail call not allowed if stack is used "
2239                            "for passing parameters");
2240
2241      // Work out the address of the stack slot.
2242      if (!StackPtr.getNode())
2243        StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
2244      SDValue Address =
2245          DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
2246                      DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
2247
2248      // Emit the store.
2249      MemOpChains.push_back(
2250          DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
2251    }
2252  }
2253
2254  // Join the stores, which are independent of one another.
2255  if (!MemOpChains.empty())
2256    Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2257
2258  SDValue Glue;
2259
2260  // Build a sequence of copy-to-reg nodes, chained and glued together.
2261  for (auto &Reg : RegsToPass) {
2262    Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
2263    Glue = Chain.getValue(1);
2264  }
2265
2266  // Validate that none of the argument registers have been marked as
2267  // reserved, if so report an error. Do the same for the return address if this
2268  // is not a tailcall.
2269  validateCCReservedRegs(RegsToPass, MF);
2270  if (!IsTailCall &&
2271      MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
2272    MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
2273        MF.getFunction(),
2274        "Return address register required, but has been reserved."});
2275
2276  // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
2277  // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
2278  // split it and then direct call can be matched by PseudoCALL.
2279  if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
2280    const GlobalValue *GV = S->getGlobal();
2281
2282    unsigned OpFlags = RISCVII::MO_CALL;
2283    if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
2284      OpFlags = RISCVII::MO_PLT;
2285
2286    Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2287  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2288    unsigned OpFlags = RISCVII::MO_CALL;
2289
2290    if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
2291                                                 nullptr))
2292      OpFlags = RISCVII::MO_PLT;
2293
2294    Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
2295  }
2296
2297  // The first call operand is the chain and the second is the target address.
2298  SmallVector<SDValue, 8> Ops;
2299  Ops.push_back(Chain);
2300  Ops.push_back(Callee);
2301
2302  // Add argument registers to the end of the list so that they are
2303  // known live into the call.
2304  for (auto &Reg : RegsToPass)
2305    Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
2306
2307  if (!IsTailCall) {
2308    // Add a register mask operand representing the call-preserved registers.
2309    const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2310    const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2311    assert(Mask && "Missing call preserved mask for calling convention");
2312    Ops.push_back(DAG.getRegisterMask(Mask));
2313  }
2314
2315  // Glue the call to the argument copies, if any.
2316  if (Glue.getNode())
2317    Ops.push_back(Glue);
2318
2319  // Emit the call.
2320  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2321
2322  if (IsTailCall) {
2323    MF.getFrameInfo().setHasTailCall();
2324    return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
2325  }
2326
2327  Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
2328  Glue = Chain.getValue(1);
2329
2330  // Mark the end of the call, which is glued to the call itself.
2331  Chain = DAG.getCALLSEQ_END(Chain,
2332                             DAG.getConstant(NumBytes, DL, PtrVT, true),
2333                             DAG.getConstant(0, DL, PtrVT, true),
2334                             Glue, DL);
2335  Glue = Chain.getValue(1);
2336
2337  // Assign locations to each value returned by this call.
2338  SmallVector<CCValAssign, 16> RVLocs;
2339  CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
2340  analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true);
2341
2342  // Copy all of the result registers out of their specified physreg.
2343  for (auto &VA : RVLocs) {
2344    // Copy the value out
2345    SDValue RetValue =
2346        DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
2347    // Glue the RetValue to the end of the call sequence
2348    Chain = RetValue.getValue(1);
2349    Glue = RetValue.getValue(2);
2350
2351    if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
2352      assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
2353      SDValue RetValue2 =
2354          DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
2355      Chain = RetValue2.getValue(1);
2356      Glue = RetValue2.getValue(2);
2357      RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
2358                             RetValue2);
2359    }
2360
2361    RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL);
2362
2363    InVals.push_back(RetValue);
2364  }
2365
2366  return Chain;
2367}
2368
2369bool RISCVTargetLowering::CanLowerReturn(
2370    CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
2371    const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2372  SmallVector<CCValAssign, 16> RVLocs;
2373  CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2374  for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
2375    MVT VT = Outs[i].VT;
2376    ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2377    RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
2378    if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
2379                 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr))
2380      return false;
2381  }
2382  return true;
2383}
2384
2385SDValue
2386RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2387                                 bool IsVarArg,
2388                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
2389                                 const SmallVectorImpl<SDValue> &OutVals,
2390                                 const SDLoc &DL, SelectionDAG &DAG) const {
2391  const MachineFunction &MF = DAG.getMachineFunction();
2392  const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
2393
2394  // Stores the assignment of the return value to a location.
2395  SmallVector<CCValAssign, 16> RVLocs;
2396
2397  // Info about the registers and stack slot.
2398  CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2399                 *DAG.getContext());
2400
2401  analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
2402                    nullptr);
2403
2404  SDValue Glue;
2405  SmallVector<SDValue, 4> RetOps(1, Chain);
2406
2407  // Copy the result values into the output registers.
2408  for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
2409    SDValue Val = OutVals[i];
2410    CCValAssign &VA = RVLocs[i];
2411    assert(VA.isRegLoc() && "Can only return in registers!");
2412
2413    if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
2414      // Handle returning f64 on RV32D with a soft float ABI.
2415      assert(VA.isRegLoc() && "Expected return via registers");
2416      SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
2417                                     DAG.getVTList(MVT::i32, MVT::i32), Val);
2418      SDValue Lo = SplitF64.getValue(0);
2419      SDValue Hi = SplitF64.getValue(1);
2420      Register RegLo = VA.getLocReg();
2421      assert(RegLo < RISCV::X31 && "Invalid register pair");
2422      Register RegHi = RegLo + 1;
2423
2424      if (STI.isRegisterReservedByUser(RegLo) ||
2425          STI.isRegisterReservedByUser(RegHi))
2426        MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
2427            MF.getFunction(),
2428            "Return value register required, but has been reserved."});
2429
2430      Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
2431      Glue = Chain.getValue(1);
2432      RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
2433      Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
2434      Glue = Chain.getValue(1);
2435      RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
2436    } else {
2437      // Handle a 'normal' return.
2438      Val = convertValVTToLocVT(DAG, Val, VA, DL);
2439      Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
2440
2441      if (STI.isRegisterReservedByUser(VA.getLocReg()))
2442        MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
2443            MF.getFunction(),
2444            "Return value register required, but has been reserved."});
2445
2446      // Guarantee that all emitted copies are stuck together.
2447      Glue = Chain.getValue(1);
2448      RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2449    }
2450  }
2451
2452  RetOps[0] = Chain; // Update chain.
2453
2454  // Add the glue node if we have it.
2455  if (Glue.getNode()) {
2456    RetOps.push_back(Glue);
2457  }
2458
2459  // Interrupt service routines use different return instructions.
2460  const Function &Func = DAG.getMachineFunction().getFunction();
2461  if (Func.hasFnAttribute("interrupt")) {
2462    if (!Func.getReturnType()->isVoidTy())
2463      report_fatal_error(
2464          "Functions with the interrupt attribute must have void return type!");
2465
2466    MachineFunction &MF = DAG.getMachineFunction();
2467    StringRef Kind =
2468      MF.getFunction().getFnAttribute("interrupt").getValueAsString();
2469
2470    unsigned RetOpc;
2471    if (Kind == "user")
2472      RetOpc = RISCVISD::URET_FLAG;
2473    else if (Kind == "supervisor")
2474      RetOpc = RISCVISD::SRET_FLAG;
2475    else
2476      RetOpc = RISCVISD::MRET_FLAG;
2477
2478    return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
2479  }
2480
2481  return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps);
2482}
2483
2484void RISCVTargetLowering::validateCCReservedRegs(
2485    const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
2486    MachineFunction &MF) const {
2487  const Function &F = MF.getFunction();
2488  const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
2489
2490  if (std::any_of(std::begin(Regs), std::end(Regs), [&STI](auto Reg) {
2491        return STI.isRegisterReservedByUser(Reg.first);
2492      }))
2493    F.getContext().diagnose(DiagnosticInfoUnsupported{
2494        F, "Argument register required, but has been reserved."});
2495}
2496
2497const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
2498  switch ((RISCVISD::NodeType)Opcode) {
2499  case RISCVISD::FIRST_NUMBER:
2500    break;
2501  case RISCVISD::RET_FLAG:
2502    return "RISCVISD::RET_FLAG";
2503  case RISCVISD::URET_FLAG:
2504    return "RISCVISD::URET_FLAG";
2505  case RISCVISD::SRET_FLAG:
2506    return "RISCVISD::SRET_FLAG";
2507  case RISCVISD::MRET_FLAG:
2508    return "RISCVISD::MRET_FLAG";
2509  case RISCVISD::CALL:
2510    return "RISCVISD::CALL";
2511  case RISCVISD::SELECT_CC:
2512    return "RISCVISD::SELECT_CC";
2513  case RISCVISD::BuildPairF64:
2514    return "RISCVISD::BuildPairF64";
2515  case RISCVISD::SplitF64:
2516    return "RISCVISD::SplitF64";
2517  case RISCVISD::TAIL:
2518    return "RISCVISD::TAIL";
2519  case RISCVISD::SLLW:
2520    return "RISCVISD::SLLW";
2521  case RISCVISD::SRAW:
2522    return "RISCVISD::SRAW";
2523  case RISCVISD::SRLW:
2524    return "RISCVISD::SRLW";
2525  case RISCVISD::DIVW:
2526    return "RISCVISD::DIVW";
2527  case RISCVISD::DIVUW:
2528    return "RISCVISD::DIVUW";
2529  case RISCVISD::REMUW:
2530    return "RISCVISD::REMUW";
2531  case RISCVISD::FMV_W_X_RV64:
2532    return "RISCVISD::FMV_W_X_RV64";
2533  case RISCVISD::FMV_X_ANYEXTW_RV64:
2534    return "RISCVISD::FMV_X_ANYEXTW_RV64";
2535  case RISCVISD::READ_CYCLE_WIDE:
2536    return "RISCVISD::READ_CYCLE_WIDE";
2537  }
2538  return nullptr;
2539}
2540
2541/// getConstraintType - Given a constraint letter, return the type of
2542/// constraint it is for this target.
2543RISCVTargetLowering::ConstraintType
2544RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
2545  if (Constraint.size() == 1) {
2546    switch (Constraint[0]) {
2547    default:
2548      break;
2549    case 'f':
2550      return C_RegisterClass;
2551    case 'I':
2552    case 'J':
2553    case 'K':
2554      return C_Immediate;
2555    case 'A':
2556      return C_Memory;
2557    }
2558  }
2559  return TargetLowering::getConstraintType(Constraint);
2560}
2561
2562std::pair<unsigned, const TargetRegisterClass *>
2563RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
2564                                                  StringRef Constraint,
2565                                                  MVT VT) const {
2566  // First, see if this is a constraint that directly corresponds to a
2567  // RISCV register class.
2568  if (Constraint.size() == 1) {
2569    switch (Constraint[0]) {
2570    case 'r':
2571      return std::make_pair(0U, &RISCV::GPRRegClass);
2572    case 'f':
2573      if (Subtarget.hasStdExtF() && VT == MVT::f32)
2574        return std::make_pair(0U, &RISCV::FPR32RegClass);
2575      if (Subtarget.hasStdExtD() && VT == MVT::f64)
2576        return std::make_pair(0U, &RISCV::FPR64RegClass);
2577      break;
2578    default:
2579      break;
2580    }
2581  }
2582
2583  // Clang will correctly decode the usage of register name aliases into their
2584  // official names. However, other frontends like `rustc` do not. This allows
2585  // users of these frontends to use the ABI names for registers in LLVM-style
2586  // register constraints.
2587  Register XRegFromAlias = StringSwitch<Register>(Constraint.lower())
2588                               .Case("{zero}", RISCV::X0)
2589                               .Case("{ra}", RISCV::X1)
2590                               .Case("{sp}", RISCV::X2)
2591                               .Case("{gp}", RISCV::X3)
2592                               .Case("{tp}", RISCV::X4)
2593                               .Case("{t0}", RISCV::X5)
2594                               .Case("{t1}", RISCV::X6)
2595                               .Case("{t2}", RISCV::X7)
2596                               .Cases("{s0}", "{fp}", RISCV::X8)
2597                               .Case("{s1}", RISCV::X9)
2598                               .Case("{a0}", RISCV::X10)
2599                               .Case("{a1}", RISCV::X11)
2600                               .Case("{a2}", RISCV::X12)
2601                               .Case("{a3}", RISCV::X13)
2602                               .Case("{a4}", RISCV::X14)
2603                               .Case("{a5}", RISCV::X15)
2604                               .Case("{a6}", RISCV::X16)
2605                               .Case("{a7}", RISCV::X17)
2606                               .Case("{s2}", RISCV::X18)
2607                               .Case("{s3}", RISCV::X19)
2608                               .Case("{s4}", RISCV::X20)
2609                               .Case("{s5}", RISCV::X21)
2610                               .Case("{s6}", RISCV::X22)
2611                               .Case("{s7}", RISCV::X23)
2612                               .Case("{s8}", RISCV::X24)
2613                               .Case("{s9}", RISCV::X25)
2614                               .Case("{s10}", RISCV::X26)
2615                               .Case("{s11}", RISCV::X27)
2616                               .Case("{t3}", RISCV::X28)
2617                               .Case("{t4}", RISCV::X29)
2618                               .Case("{t5}", RISCV::X30)
2619                               .Case("{t6}", RISCV::X31)
2620                               .Default(RISCV::NoRegister);
2621  if (XRegFromAlias != RISCV::NoRegister)
2622    return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
2623
2624  // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
2625  // TableGen record rather than the AsmName to choose registers for InlineAsm
2626  // constraints, plus we want to match those names to the widest floating point
2627  // register type available, manually select floating point registers here.
2628  //
2629  // The second case is the ABI name of the register, so that frontends can also
2630  // use the ABI names in register constraint lists.
2631  if (Subtarget.hasStdExtF() || Subtarget.hasStdExtD()) {
2632    std::pair<Register, Register> FReg =
2633        StringSwitch<std::pair<Register, Register>>(Constraint.lower())
2634            .Cases("{f0}", "{ft0}", {RISCV::F0_F, RISCV::F0_D})
2635            .Cases("{f1}", "{ft1}", {RISCV::F1_F, RISCV::F1_D})
2636            .Cases("{f2}", "{ft2}", {RISCV::F2_F, RISCV::F2_D})
2637            .Cases("{f3}", "{ft3}", {RISCV::F3_F, RISCV::F3_D})
2638            .Cases("{f4}", "{ft4}", {RISCV::F4_F, RISCV::F4_D})
2639            .Cases("{f5}", "{ft5}", {RISCV::F5_F, RISCV::F5_D})
2640            .Cases("{f6}", "{ft6}", {RISCV::F6_F, RISCV::F6_D})
2641            .Cases("{f7}", "{ft7}", {RISCV::F7_F, RISCV::F7_D})
2642            .Cases("{f8}", "{fs0}", {RISCV::F8_F, RISCV::F8_D})
2643            .Cases("{f9}", "{fs1}", {RISCV::F9_F, RISCV::F9_D})
2644            .Cases("{f10}", "{fa0}", {RISCV::F10_F, RISCV::F10_D})
2645            .Cases("{f11}", "{fa1}", {RISCV::F11_F, RISCV::F11_D})
2646            .Cases("{f12}", "{fa2}", {RISCV::F12_F, RISCV::F12_D})
2647            .Cases("{f13}", "{fa3}", {RISCV::F13_F, RISCV::F13_D})
2648            .Cases("{f14}", "{fa4}", {RISCV::F14_F, RISCV::F14_D})
2649            .Cases("{f15}", "{fa5}", {RISCV::F15_F, RISCV::F15_D})
2650            .Cases("{f16}", "{fa6}", {RISCV::F16_F, RISCV::F16_D})
2651            .Cases("{f17}", "{fa7}", {RISCV::F17_F, RISCV::F17_D})
2652            .Cases("{f18}", "{fs2}", {RISCV::F18_F, RISCV::F18_D})
2653            .Cases("{f19}", "{fs3}", {RISCV::F19_F, RISCV::F19_D})
2654            .Cases("{f20}", "{fs4}", {RISCV::F20_F, RISCV::F20_D})
2655            .Cases("{f21}", "{fs5}", {RISCV::F21_F, RISCV::F21_D})
2656            .Cases("{f22}", "{fs6}", {RISCV::F22_F, RISCV::F22_D})
2657            .Cases("{f23}", "{fs7}", {RISCV::F23_F, RISCV::F23_D})
2658            .Cases("{f24}", "{fs8}", {RISCV::F24_F, RISCV::F24_D})
2659            .Cases("{f25}", "{fs9}", {RISCV::F25_F, RISCV::F25_D})
2660            .Cases("{f26}", "{fs10}", {RISCV::F26_F, RISCV::F26_D})
2661            .Cases("{f27}", "{fs11}", {RISCV::F27_F, RISCV::F27_D})
2662            .Cases("{f28}", "{ft8}", {RISCV::F28_F, RISCV::F28_D})
2663            .Cases("{f29}", "{ft9}", {RISCV::F29_F, RISCV::F29_D})
2664            .Cases("{f30}", "{ft10}", {RISCV::F30_F, RISCV::F30_D})
2665            .Cases("{f31}", "{ft11}", {RISCV::F31_F, RISCV::F31_D})
2666            .Default({RISCV::NoRegister, RISCV::NoRegister});
2667    if (FReg.first != RISCV::NoRegister)
2668      return Subtarget.hasStdExtD()
2669                 ? std::make_pair(FReg.second, &RISCV::FPR64RegClass)
2670                 : std::make_pair(FReg.first, &RISCV::FPR32RegClass);
2671  }
2672
2673  return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
2674}
2675
2676unsigned
2677RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
2678  // Currently only support length 1 constraints.
2679  if (ConstraintCode.size() == 1) {
2680    switch (ConstraintCode[0]) {
2681    case 'A':
2682      return InlineAsm::Constraint_A;
2683    default:
2684      break;
2685    }
2686  }
2687
2688  return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
2689}
2690
2691void RISCVTargetLowering::LowerAsmOperandForConstraint(
2692    SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
2693    SelectionDAG &DAG) const {
2694  // Currently only support length 1 constraints.
2695  if (Constraint.length() == 1) {
2696    switch (Constraint[0]) {
2697    case 'I':
2698      // Validate & create a 12-bit signed immediate operand.
2699      if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2700        uint64_t CVal = C->getSExtValue();
2701        if (isInt<12>(CVal))
2702          Ops.push_back(
2703              DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
2704      }
2705      return;
2706    case 'J':
2707      // Validate & create an integer zero operand.
2708      if (auto *C = dyn_cast<ConstantSDNode>(Op))
2709        if (C->getZExtValue() == 0)
2710          Ops.push_back(
2711              DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
2712      return;
2713    case 'K':
2714      // Validate & create a 5-bit unsigned immediate operand.
2715      if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2716        uint64_t CVal = C->getZExtValue();
2717        if (isUInt<5>(CVal))
2718          Ops.push_back(
2719              DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
2720      }
2721      return;
2722    default:
2723      break;
2724    }
2725  }
2726  TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
2727}
2728
2729Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
2730                                                   Instruction *Inst,
2731                                                   AtomicOrdering Ord) const {
2732  if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
2733    return Builder.CreateFence(Ord);
2734  if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
2735    return Builder.CreateFence(AtomicOrdering::Release);
2736  return nullptr;
2737}
2738
2739Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
2740                                                    Instruction *Inst,
2741                                                    AtomicOrdering Ord) const {
2742  if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
2743    return Builder.CreateFence(AtomicOrdering::Acquire);
2744  return nullptr;
2745}
2746
2747TargetLowering::AtomicExpansionKind
2748RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
2749  // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
2750  // point operations can't be used in an lr/sc sequence without breaking the
2751  // forward-progress guarantee.
2752  if (AI->isFloatingPointOperation())
2753    return AtomicExpansionKind::CmpXChg;
2754
2755  unsigned Size = AI->getType()->getPrimitiveSizeInBits();
2756  if (Size == 8 || Size == 16)
2757    return AtomicExpansionKind::MaskedIntrinsic;
2758  return AtomicExpansionKind::None;
2759}
2760
2761static Intrinsic::ID
2762getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
2763  if (XLen == 32) {
2764    switch (BinOp) {
2765    default:
2766      llvm_unreachable("Unexpected AtomicRMW BinOp");
2767    case AtomicRMWInst::Xchg:
2768      return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
2769    case AtomicRMWInst::Add:
2770      return Intrinsic::riscv_masked_atomicrmw_add_i32;
2771    case AtomicRMWInst::Sub:
2772      return Intrinsic::riscv_masked_atomicrmw_sub_i32;
2773    case AtomicRMWInst::Nand:
2774      return Intrinsic::riscv_masked_atomicrmw_nand_i32;
2775    case AtomicRMWInst::Max:
2776      return Intrinsic::riscv_masked_atomicrmw_max_i32;
2777    case AtomicRMWInst::Min:
2778      return Intrinsic::riscv_masked_atomicrmw_min_i32;
2779    case AtomicRMWInst::UMax:
2780      return Intrinsic::riscv_masked_atomicrmw_umax_i32;
2781    case AtomicRMWInst::UMin:
2782      return Intrinsic::riscv_masked_atomicrmw_umin_i32;
2783    }
2784  }
2785
2786  if (XLen == 64) {
2787    switch (BinOp) {
2788    default:
2789      llvm_unreachable("Unexpected AtomicRMW BinOp");
2790    case AtomicRMWInst::Xchg:
2791      return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
2792    case AtomicRMWInst::Add:
2793      return Intrinsic::riscv_masked_atomicrmw_add_i64;
2794    case AtomicRMWInst::Sub:
2795      return Intrinsic::riscv_masked_atomicrmw_sub_i64;
2796    case AtomicRMWInst::Nand:
2797      return Intrinsic::riscv_masked_atomicrmw_nand_i64;
2798    case AtomicRMWInst::Max:
2799      return Intrinsic::riscv_masked_atomicrmw_max_i64;
2800    case AtomicRMWInst::Min:
2801      return Intrinsic::riscv_masked_atomicrmw_min_i64;
2802    case AtomicRMWInst::UMax:
2803      return Intrinsic::riscv_masked_atomicrmw_umax_i64;
2804    case AtomicRMWInst::UMin:
2805      return Intrinsic::riscv_masked_atomicrmw_umin_i64;
2806    }
2807  }
2808
2809  llvm_unreachable("Unexpected XLen\n");
2810}
2811
2812Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
2813    IRBuilder<> &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
2814    Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
2815  unsigned XLen = Subtarget.getXLen();
2816  Value *Ordering =
2817      Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
2818  Type *Tys[] = {AlignedAddr->getType()};
2819  Function *LrwOpScwLoop = Intrinsic::getDeclaration(
2820      AI->getModule(),
2821      getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
2822
2823  if (XLen == 64) {
2824    Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
2825    Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
2826    ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
2827  }
2828
2829  Value *Result;
2830
2831  // Must pass the shift amount needed to sign extend the loaded value prior
2832  // to performing a signed comparison for min/max. ShiftAmt is the number of
2833  // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
2834  // is the number of bits to left+right shift the value in order to
2835  // sign-extend.
2836  if (AI->getOperation() == AtomicRMWInst::Min ||
2837      AI->getOperation() == AtomicRMWInst::Max) {
2838    const DataLayout &DL = AI->getModule()->getDataLayout();
2839    unsigned ValWidth =
2840        DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
2841    Value *SextShamt =
2842        Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
2843    Result = Builder.CreateCall(LrwOpScwLoop,
2844                                {AlignedAddr, Incr, Mask, SextShamt, Ordering});
2845  } else {
2846    Result =
2847        Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
2848  }
2849
2850  if (XLen == 64)
2851    Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
2852  return Result;
2853}
2854
2855TargetLowering::AtomicExpansionKind
2856RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
2857    AtomicCmpXchgInst *CI) const {
2858  unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
2859  if (Size == 8 || Size == 16)
2860    return AtomicExpansionKind::MaskedIntrinsic;
2861  return AtomicExpansionKind::None;
2862}
2863
2864Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
2865    IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
2866    Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
2867  unsigned XLen = Subtarget.getXLen();
2868  Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
2869  Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
2870  if (XLen == 64) {
2871    CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
2872    NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
2873    Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
2874    CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
2875  }
2876  Type *Tys[] = {AlignedAddr->getType()};
2877  Function *MaskedCmpXchg =
2878      Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
2879  Value *Result = Builder.CreateCall(
2880      MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
2881  if (XLen == 64)
2882    Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
2883  return Result;
2884}
2885
2886unsigned RISCVTargetLowering::getExceptionPointerRegister(
2887    const Constant *PersonalityFn) const {
2888  return RISCV::X10;
2889}
2890
2891unsigned RISCVTargetLowering::getExceptionSelectorRegister(
2892    const Constant *PersonalityFn) const {
2893  return RISCV::X11;
2894}
2895
2896bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
2897  // Return false to suppress the unnecessary extensions if the LibCall
2898  // arguments or return value is f32 type for LP64 ABI.
2899  RISCVABI::ABI ABI = Subtarget.getTargetABI();
2900  if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
2901    return false;
2902
2903  return true;
2904}
2905
2906#define GET_REGISTER_MATCHER
2907#include "RISCVGenAsmMatcher.inc"
2908
2909Register
2910RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
2911                                       const MachineFunction &MF) const {
2912  Register Reg = MatchRegisterAltName(RegName);
2913  if (Reg == RISCV::NoRegister)
2914    Reg = MatchRegisterName(RegName);
2915  if (Reg == RISCV::NoRegister)
2916    report_fatal_error(
2917        Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
2918  BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
2919  if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
2920    report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
2921                             StringRef(RegName) + "\"."));
2922  return Reg;
2923}
2924