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