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