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