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