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