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