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