1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation  --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that RISCV uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "RISCVISelLowering.h"
16 #include "RISCV.h"
17 #include "RISCVMachineFunctionInfo.h"
18 #include "RISCVRegisterInfo.h"
19 #include "RISCVSubtarget.h"
20 #include "RISCVTargetMachine.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
28 #include "llvm/CodeGen/ValueTypes.h"
29 #include "llvm/IR/DiagnosticInfo.h"
30 #include "llvm/IR/DiagnosticPrinter.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 
35 using namespace llvm;
36 
37 #define DEBUG_TYPE "riscv-lower"
38 
39 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
40                                          const RISCVSubtarget &STI)
41     : TargetLowering(TM), Subtarget(STI) {
42 
43   MVT XLenVT = Subtarget.getXLenVT();
44 
45   // Set up the register classes.
46   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
47 
48   if (Subtarget.hasStdExtF())
49     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
50   if (Subtarget.hasStdExtD())
51     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
52 
53   // Compute derived properties from the register classes.
54   computeRegisterProperties(STI.getRegisterInfo());
55 
56   setStackPointerRegisterToSaveRestore(RISCV::X2);
57 
58   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
59     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
60 
61   // TODO: add all necessary setOperationAction calls.
62   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
63 
64   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
65   setOperationAction(ISD::BR_CC, XLenVT, Expand);
66   setOperationAction(ISD::SELECT, XLenVT, Custom);
67   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
68 
69   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
70   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
71 
72   setOperationAction(ISD::VASTART, MVT::Other, Custom);
73   setOperationAction(ISD::VAARG, MVT::Other, Expand);
74   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
75   setOperationAction(ISD::VAEND, MVT::Other, Expand);
76 
77   for (auto VT : {MVT::i1, MVT::i8, MVT::i16})
78     setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
79 
80   setOperationAction(ISD::ADDC, XLenVT, Expand);
81   setOperationAction(ISD::ADDE, XLenVT, Expand);
82   setOperationAction(ISD::SUBC, XLenVT, Expand);
83   setOperationAction(ISD::SUBE, XLenVT, Expand);
84 
85   if (!Subtarget.hasStdExtM()) {
86     setOperationAction(ISD::MUL, XLenVT, Expand);
87     setOperationAction(ISD::MULHS, XLenVT, Expand);
88     setOperationAction(ISD::MULHU, XLenVT, Expand);
89     setOperationAction(ISD::SDIV, XLenVT, Expand);
90     setOperationAction(ISD::UDIV, XLenVT, Expand);
91     setOperationAction(ISD::SREM, XLenVT, Expand);
92     setOperationAction(ISD::UREM, XLenVT, Expand);
93   }
94 
95   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
96   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
97   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
98   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
99 
100   setOperationAction(ISD::SHL_PARTS, XLenVT, Expand);
101   setOperationAction(ISD::SRL_PARTS, XLenVT, Expand);
102   setOperationAction(ISD::SRA_PARTS, XLenVT, Expand);
103 
104   setOperationAction(ISD::ROTL, XLenVT, Expand);
105   setOperationAction(ISD::ROTR, XLenVT, Expand);
106   setOperationAction(ISD::BSWAP, XLenVT, Expand);
107   setOperationAction(ISD::CTTZ, XLenVT, Expand);
108   setOperationAction(ISD::CTLZ, XLenVT, Expand);
109   setOperationAction(ISD::CTPOP, XLenVT, Expand);
110 
111   ISD::CondCode FPCCToExtend[] = {
112       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETO,   ISD::SETUEQ,
113       ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE,
114       ISD::SETGT,  ISD::SETGE,  ISD::SETNE};
115 
116   if (Subtarget.hasStdExtF()) {
117     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
118     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
119     for (auto CC : FPCCToExtend)
120       setCondCodeAction(CC, MVT::f32, Expand);
121     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
122     setOperationAction(ISD::SELECT, MVT::f32, Custom);
123     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
124   }
125 
126   if (Subtarget.hasStdExtD()) {
127     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
128     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
129     for (auto CC : FPCCToExtend)
130       setCondCodeAction(CC, MVT::f64, Expand);
131     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
132     setOperationAction(ISD::SELECT, MVT::f64, Custom);
133     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
134     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
135     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
136   }
137 
138   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
139   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
140   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
141 
142   setBooleanContents(ZeroOrOneBooleanContent);
143 
144   // Function alignments (log2).
145   unsigned FunctionAlignment = Subtarget.hasStdExtC() ? 1 : 2;
146   setMinFunctionAlignment(FunctionAlignment);
147   setPrefFunctionAlignment(FunctionAlignment);
148 
149   // Effectively disable jump table generation.
150   setMinimumJumpTableEntries(INT_MAX);
151 }
152 
153 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
154                                             EVT VT) const {
155   if (!VT.isVector())
156     return getPointerTy(DL);
157   return VT.changeVectorElementTypeToInteger();
158 }
159 
160 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
161                                                 const AddrMode &AM, Type *Ty,
162                                                 unsigned AS,
163                                                 Instruction *I) const {
164   // No global is ever allowed as a base.
165   if (AM.BaseGV)
166     return false;
167 
168   // Require a 12-bit signed offset.
169   if (!isInt<12>(AM.BaseOffs))
170     return false;
171 
172   switch (AM.Scale) {
173   case 0: // "r+i" or just "i", depending on HasBaseReg.
174     break;
175   case 1:
176     if (!AM.HasBaseReg) // allow "r+i".
177       break;
178     return false; // disallow "r+r" or "r+r+i".
179   default:
180     return false;
181   }
182 
183   return true;
184 }
185 
186 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
187   return isInt<12>(Imm);
188 }
189 
190 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
191   return isInt<12>(Imm);
192 }
193 
194 // On RV32, 64-bit integers are split into their high and low parts and held
195 // in two different registers, so the trunc is free since the low register can
196 // just be used.
197 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
198   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
199     return false;
200   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
201   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
202   return (SrcBits == 64 && DestBits == 32);
203 }
204 
205 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
206   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
207       !SrcVT.isInteger() || !DstVT.isInteger())
208     return false;
209   unsigned SrcBits = SrcVT.getSizeInBits();
210   unsigned DestBits = DstVT.getSizeInBits();
211   return (SrcBits == 64 && DestBits == 32);
212 }
213 
214 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
215   // Zexts are free if they can be combined with a load.
216   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
217     EVT MemVT = LD->getMemoryVT();
218     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
219          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
220         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
221          LD->getExtensionType() == ISD::ZEXTLOAD))
222       return true;
223   }
224 
225   return TargetLowering::isZExtFree(Val, VT2);
226 }
227 
228 // Changes the condition code and swaps operands if necessary, so the SetCC
229 // operation matches one of the comparisons supported directly in the RISC-V
230 // ISA.
231 static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) {
232   switch (CC) {
233   default:
234     break;
235   case ISD::SETGT:
236   case ISD::SETLE:
237   case ISD::SETUGT:
238   case ISD::SETULE:
239     CC = ISD::getSetCCSwappedOperands(CC);
240     std::swap(LHS, RHS);
241     break;
242   }
243 }
244 
245 // Return the RISC-V branch opcode that matches the given DAG integer
246 // condition code. The CondCode must be one of those supported by the RISC-V
247 // ISA (see normaliseSetCC).
248 static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) {
249   switch (CC) {
250   default:
251     llvm_unreachable("Unsupported CondCode");
252   case ISD::SETEQ:
253     return RISCV::BEQ;
254   case ISD::SETNE:
255     return RISCV::BNE;
256   case ISD::SETLT:
257     return RISCV::BLT;
258   case ISD::SETGE:
259     return RISCV::BGE;
260   case ISD::SETULT:
261     return RISCV::BLTU;
262   case ISD::SETUGE:
263     return RISCV::BGEU;
264   }
265 }
266 
267 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
268                                             SelectionDAG &DAG) const {
269   switch (Op.getOpcode()) {
270   default:
271     report_fatal_error("unimplemented operand");
272   case ISD::GlobalAddress:
273     return lowerGlobalAddress(Op, DAG);
274   case ISD::BlockAddress:
275     return lowerBlockAddress(Op, DAG);
276   case ISD::ConstantPool:
277     return lowerConstantPool(Op, DAG);
278   case ISD::SELECT:
279     return lowerSELECT(Op, DAG);
280   case ISD::VASTART:
281     return lowerVASTART(Op, DAG);
282   case ISD::FRAMEADDR:
283     return LowerFRAMEADDR(Op, DAG);
284   case ISD::RETURNADDR:
285     return LowerRETURNADDR(Op, DAG);
286   }
287 }
288 
289 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
290                                                 SelectionDAG &DAG) const {
291   SDLoc DL(Op);
292   EVT Ty = Op.getValueType();
293   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
294   const GlobalValue *GV = N->getGlobal();
295   int64_t Offset = N->getOffset();
296   MVT XLenVT = Subtarget.getXLenVT();
297 
298   if (isPositionIndependent() || Subtarget.is64Bit())
299     report_fatal_error("Unable to lowerGlobalAddress");
300   // In order to maximise the opportunity for common subexpression elimination,
301   // emit a separate ADD node for the global address offset instead of folding
302   // it in the global address node. Later peephole optimisations may choose to
303   // fold it back in when profitable.
304   SDValue GAHi = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_HI);
305   SDValue GALo = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_LO);
306   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, GAHi), 0);
307   SDValue MNLo =
308     SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, GALo), 0);
309   if (Offset != 0)
310     return DAG.getNode(ISD::ADD, DL, Ty, MNLo,
311                        DAG.getConstant(Offset, DL, XLenVT));
312   return MNLo;
313 }
314 
315 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
316                                                SelectionDAG &DAG) const {
317   SDLoc DL(Op);
318   EVT Ty = Op.getValueType();
319   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
320   const BlockAddress *BA = N->getBlockAddress();
321   int64_t Offset = N->getOffset();
322 
323   if (isPositionIndependent() || Subtarget.is64Bit())
324     report_fatal_error("Unable to lowerBlockAddress");
325 
326   SDValue BAHi = DAG.getTargetBlockAddress(BA, Ty, Offset, RISCVII::MO_HI);
327   SDValue BALo = DAG.getTargetBlockAddress(BA, Ty, Offset, RISCVII::MO_LO);
328   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, BAHi), 0);
329   SDValue MNLo =
330     SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, BALo), 0);
331   return MNLo;
332 }
333 
334 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
335                                                SelectionDAG &DAG) const {
336   SDLoc DL(Op);
337   EVT Ty = Op.getValueType();
338   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
339   const Constant *CPA = N->getConstVal();
340   int64_t Offset = N->getOffset();
341   unsigned Alignment = N->getAlignment();
342 
343   if (!isPositionIndependent()) {
344     SDValue CPAHi =
345         DAG.getTargetConstantPool(CPA, Ty, Alignment, Offset, RISCVII::MO_HI);
346     SDValue CPALo =
347         DAG.getTargetConstantPool(CPA, Ty, Alignment, Offset, RISCVII::MO_LO);
348     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, CPAHi), 0);
349     SDValue MNLo =
350         SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, CPALo), 0);
351     return MNLo;
352   } else {
353     report_fatal_error("Unable to lowerConstantPool");
354   }
355 }
356 
357 SDValue RISCVTargetLowering::lowerExternalSymbol(SDValue Op,
358                                                  SelectionDAG &DAG) const {
359   SDLoc DL(Op);
360   EVT Ty = Op.getValueType();
361   ExternalSymbolSDNode *N = cast<ExternalSymbolSDNode>(Op);
362   const char *Sym = N->getSymbol();
363 
364   // TODO: should also handle gp-relative loads.
365 
366   if (isPositionIndependent() || Subtarget.is64Bit())
367     report_fatal_error("Unable to lowerExternalSymbol");
368 
369   SDValue GAHi = DAG.getTargetExternalSymbol(Sym, Ty, RISCVII::MO_HI);
370   SDValue GALo = DAG.getTargetExternalSymbol(Sym, Ty, RISCVII::MO_LO);
371   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, GAHi), 0);
372   SDValue MNLo =
373     SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, GALo), 0);
374   return MNLo;
375 }
376 
377 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
378   SDValue CondV = Op.getOperand(0);
379   SDValue TrueV = Op.getOperand(1);
380   SDValue FalseV = Op.getOperand(2);
381   SDLoc DL(Op);
382   MVT XLenVT = Subtarget.getXLenVT();
383 
384   // If the result type is XLenVT and CondV is the output of a SETCC node
385   // which also operated on XLenVT inputs, then merge the SETCC node into the
386   // lowered RISCVISD::SELECT_CC to take advantage of the integer
387   // compare+branch instructions. i.e.:
388   // (select (setcc lhs, rhs, cc), truev, falsev)
389   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
390   if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC &&
391       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
392     SDValue LHS = CondV.getOperand(0);
393     SDValue RHS = CondV.getOperand(1);
394     auto CC = cast<CondCodeSDNode>(CondV.getOperand(2));
395     ISD::CondCode CCVal = CC->get();
396 
397     normaliseSetCC(LHS, RHS, CCVal);
398 
399     SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT);
400     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
401     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
402     return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
403   }
404 
405   // Otherwise:
406   // (select condv, truev, falsev)
407   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
408   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
409   SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT);
410 
411   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
412   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
413 
414   return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
415 }
416 
417 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
418   MachineFunction &MF = DAG.getMachineFunction();
419   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
420 
421   SDLoc DL(Op);
422   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
423                                  getPointerTy(MF.getDataLayout()));
424 
425   // vastart just stores the address of the VarArgsFrameIndex slot into the
426   // memory location argument.
427   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
428   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
429                       MachinePointerInfo(SV));
430 }
431 
432 SDValue RISCVTargetLowering::LowerFRAMEADDR(SDValue Op,
433                                             SelectionDAG &DAG) const {
434   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
435   MachineFunction &MF = DAG.getMachineFunction();
436   MachineFrameInfo &MFI = MF.getFrameInfo();
437   MFI.setFrameAddressIsTaken(true);
438   unsigned FrameReg = RI.getFrameRegister(MF);
439   int XLenInBytes = Subtarget.getXLen() / 8;
440 
441   EVT VT = Op.getValueType();
442   SDLoc DL(Op);
443   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
444   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
445   while (Depth--) {
446     int Offset = -(XLenInBytes * 2);
447     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
448                               DAG.getIntPtrConstant(Offset, DL));
449     FrameAddr =
450         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
451   }
452   return FrameAddr;
453 }
454 
455 SDValue RISCVTargetLowering::LowerRETURNADDR(SDValue Op,
456                                              SelectionDAG &DAG) const {
457   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
458   MachineFunction &MF = DAG.getMachineFunction();
459   MachineFrameInfo &MFI = MF.getFrameInfo();
460   MFI.setReturnAddressIsTaken(true);
461   MVT XLenVT = Subtarget.getXLenVT();
462   int XLenInBytes = Subtarget.getXLen() / 8;
463 
464   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
465     return SDValue();
466 
467   EVT VT = Op.getValueType();
468   SDLoc DL(Op);
469   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
470   if (Depth) {
471     int Off = -XLenInBytes;
472     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
473     SDValue Offset = DAG.getConstant(Off, DL, VT);
474     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
475                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
476                        MachinePointerInfo());
477   }
478 
479   // Return the value of the return address register, marking it an implicit
480   // live-in.
481   unsigned Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
482   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
483 }
484 
485 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
486                                              MachineBasicBlock *BB) {
487   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
488 
489   MachineFunction &MF = *BB->getParent();
490   DebugLoc DL = MI.getDebugLoc();
491   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
492   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
493   unsigned LoReg = MI.getOperand(0).getReg();
494   unsigned HiReg = MI.getOperand(1).getReg();
495   unsigned SrcReg = MI.getOperand(2).getReg();
496   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
497   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
498 
499   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
500                           RI);
501   MachineMemOperand *MMO =
502       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
503                               MachineMemOperand::MOLoad, 8, 8);
504   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
505       .addFrameIndex(FI)
506       .addImm(0)
507       .addMemOperand(MMO);
508   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
509       .addFrameIndex(FI)
510       .addImm(4)
511       .addMemOperand(MMO);
512   MI.eraseFromParent(); // The pseudo instruction is gone now.
513   return BB;
514 }
515 
516 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
517                                                  MachineBasicBlock *BB) {
518   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
519          "Unexpected instruction");
520 
521   MachineFunction &MF = *BB->getParent();
522   DebugLoc DL = MI.getDebugLoc();
523   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
524   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
525   unsigned DstReg = MI.getOperand(0).getReg();
526   unsigned LoReg = MI.getOperand(1).getReg();
527   unsigned HiReg = MI.getOperand(2).getReg();
528   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
529   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
530 
531   MachineMemOperand *MMO =
532       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
533                               MachineMemOperand::MOStore, 8, 8);
534   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
535       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
536       .addFrameIndex(FI)
537       .addImm(0)
538       .addMemOperand(MMO);
539   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
540       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
541       .addFrameIndex(FI)
542       .addImm(4)
543       .addMemOperand(MMO);
544   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
545   MI.eraseFromParent(); // The pseudo instruction is gone now.
546   return BB;
547 }
548 
549 MachineBasicBlock *
550 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
551                                                  MachineBasicBlock *BB) const {
552   switch (MI.getOpcode()) {
553   default:
554     llvm_unreachable("Unexpected instr type to insert");
555   case RISCV::Select_GPR_Using_CC_GPR:
556   case RISCV::Select_FPR32_Using_CC_GPR:
557   case RISCV::Select_FPR64_Using_CC_GPR:
558     break;
559   case RISCV::BuildPairF64Pseudo:
560     return emitBuildPairF64Pseudo(MI, BB);
561   case RISCV::SplitF64Pseudo:
562     return emitSplitF64Pseudo(MI, BB);
563   }
564 
565   // To "insert" a SELECT instruction, we actually have to insert the triangle
566   // control-flow pattern.  The incoming instruction knows the destination vreg
567   // to set, the condition code register to branch on, the true/false values to
568   // select between, and the condcode to use to select the appropriate branch.
569   //
570   // We produce the following control flow:
571   //     HeadMBB
572   //     |  \
573   //     |  IfFalseMBB
574   //     | /
575   //    TailMBB
576   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
577   const BasicBlock *LLVM_BB = BB->getBasicBlock();
578   DebugLoc DL = MI.getDebugLoc();
579   MachineFunction::iterator I = ++BB->getIterator();
580 
581   MachineBasicBlock *HeadMBB = BB;
582   MachineFunction *F = BB->getParent();
583   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
584   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
585 
586   F->insert(I, IfFalseMBB);
587   F->insert(I, TailMBB);
588   // Move all remaining instructions to TailMBB.
589   TailMBB->splice(TailMBB->begin(), HeadMBB,
590                   std::next(MachineBasicBlock::iterator(MI)), HeadMBB->end());
591   // Update machine-CFG edges by transferring all successors of the current
592   // block to the new block which will contain the Phi node for the select.
593   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
594   // Set the successors for HeadMBB.
595   HeadMBB->addSuccessor(IfFalseMBB);
596   HeadMBB->addSuccessor(TailMBB);
597 
598   // Insert appropriate branch.
599   unsigned LHS = MI.getOperand(1).getReg();
600   unsigned RHS = MI.getOperand(2).getReg();
601   auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm());
602   unsigned Opcode = getBranchOpcodeForIntCondCode(CC);
603 
604   BuildMI(HeadMBB, DL, TII.get(Opcode))
605     .addReg(LHS)
606     .addReg(RHS)
607     .addMBB(TailMBB);
608 
609   // IfFalseMBB just falls through to TailMBB.
610   IfFalseMBB->addSuccessor(TailMBB);
611 
612   // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
613   BuildMI(*TailMBB, TailMBB->begin(), DL, TII.get(RISCV::PHI),
614           MI.getOperand(0).getReg())
615       .addReg(MI.getOperand(4).getReg())
616       .addMBB(HeadMBB)
617       .addReg(MI.getOperand(5).getReg())
618       .addMBB(IfFalseMBB);
619 
620   MI.eraseFromParent(); // The pseudo instruction is gone now.
621   return TailMBB;
622 }
623 
624 // Calling Convention Implementation.
625 // The expectations for frontend ABI lowering vary from target to target.
626 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
627 // details, but this is a longer term goal. For now, we simply try to keep the
628 // role of the frontend as simple and well-defined as possible. The rules can
629 // be summarised as:
630 // * Never split up large scalar arguments. We handle them here.
631 // * If a hardfloat calling convention is being used, and the struct may be
632 // passed in a pair of registers (fp+fp, int+fp), and both registers are
633 // available, then pass as two separate arguments. If either the GPRs or FPRs
634 // are exhausted, then pass according to the rule below.
635 // * If a struct could never be passed in registers or directly in a stack
636 // slot (as it is larger than 2*XLEN and the floating point rules don't
637 // apply), then pass it using a pointer with the byval attribute.
638 // * If a struct is less than 2*XLEN, then coerce to either a two-element
639 // word-sized array or a 2*XLEN scalar (depending on alignment).
640 // * The frontend can determine whether a struct is returned by reference or
641 // not based on its size and fields. If it will be returned by reference, the
642 // frontend must modify the prototype so a pointer with the sret annotation is
643 // passed as the first argument. This is not necessary for large scalar
644 // returns.
645 // * Struct return values and varargs should be coerced to structs containing
646 // register-size fields in the same situations they would be for fixed
647 // arguments.
648 
649 static const MCPhysReg ArgGPRs[] = {
650   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
651   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
652 };
653 
654 // Pass a 2*XLEN argument that has been split into two XLEN values through
655 // registers or the stack as necessary.
656 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
657                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
658                                 MVT ValVT2, MVT LocVT2,
659                                 ISD::ArgFlagsTy ArgFlags2) {
660   unsigned XLenInBytes = XLen / 8;
661   if (unsigned Reg = State.AllocateReg(ArgGPRs)) {
662     // At least one half can be passed via register.
663     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
664                                      VA1.getLocVT(), CCValAssign::Full));
665   } else {
666     // Both halves must be passed on the stack, with proper alignment.
667     unsigned StackAlign = std::max(XLenInBytes, ArgFlags1.getOrigAlign());
668     State.addLoc(
669         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
670                             State.AllocateStack(XLenInBytes, StackAlign),
671                             VA1.getLocVT(), CCValAssign::Full));
672     State.addLoc(CCValAssign::getMem(
673         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
674         CCValAssign::Full));
675     return false;
676   }
677 
678   if (unsigned Reg = State.AllocateReg(ArgGPRs)) {
679     // The second half can also be passed via register.
680     State.addLoc(
681         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
682   } else {
683     // The second half is passed via the stack, without additional alignment.
684     State.addLoc(CCValAssign::getMem(
685         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
686         CCValAssign::Full));
687   }
688 
689   return false;
690 }
691 
692 // Implements the RISC-V calling convention. Returns true upon failure.
693 static bool CC_RISCV(const DataLayout &DL, unsigned ValNo, MVT ValVT, MVT LocVT,
694                      CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
695                      CCState &State, bool IsFixed, bool IsRet, Type *OrigTy) {
696   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
697   assert(XLen == 32 || XLen == 64);
698   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
699   if (ValVT == MVT::f32) {
700     LocVT = MVT::i32;
701     LocInfo = CCValAssign::BCvt;
702   }
703 
704   // Any return value split in to more than two values can't be returned
705   // directly.
706   if (IsRet && ValNo > 1)
707     return true;
708 
709   // If this is a variadic argument, the RISC-V calling convention requires
710   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
711   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
712   // be used regardless of whether the original argument was split during
713   // legalisation or not. The argument will not be passed by registers if the
714   // original type is larger than 2*XLEN, so the register alignment rule does
715   // not apply.
716   unsigned TwoXLenInBytes = (2 * XLen) / 8;
717   if (!IsFixed && ArgFlags.getOrigAlign() == TwoXLenInBytes &&
718       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
719     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
720     // Skip 'odd' register if necessary.
721     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
722       State.AllocateReg(ArgGPRs);
723   }
724 
725   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
726   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
727       State.getPendingArgFlags();
728 
729   assert(PendingLocs.size() == PendingArgFlags.size() &&
730          "PendingLocs and PendingArgFlags out of sync");
731 
732   // Handle passing f64 on RV32D with a soft float ABI.
733   if (XLen == 32 && ValVT == MVT::f64) {
734     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
735            "Can't lower f64 if it is split");
736     // Depending on available argument GPRS, f64 may be passed in a pair of
737     // GPRs, split between a GPR and the stack, or passed completely on the
738     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
739     // cases.
740     unsigned Reg = State.AllocateReg(ArgGPRs);
741     LocVT = MVT::i32;
742     if (!Reg) {
743       unsigned StackOffset = State.AllocateStack(8, 8);
744       State.addLoc(
745           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
746       return false;
747     }
748     if (!State.AllocateReg(ArgGPRs))
749       State.AllocateStack(4, 4);
750     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
751     return false;
752   }
753 
754   // Split arguments might be passed indirectly, so keep track of the pending
755   // values.
756   if (ArgFlags.isSplit() || !PendingLocs.empty()) {
757     LocVT = XLenVT;
758     LocInfo = CCValAssign::Indirect;
759     PendingLocs.push_back(
760         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
761     PendingArgFlags.push_back(ArgFlags);
762     if (!ArgFlags.isSplitEnd()) {
763       return false;
764     }
765   }
766 
767   // If the split argument only had two elements, it should be passed directly
768   // in registers or on the stack.
769   if (ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) {
770     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
771     // Apply the normal calling convention rules to the first half of the
772     // split argument.
773     CCValAssign VA = PendingLocs[0];
774     ISD::ArgFlagsTy AF = PendingArgFlags[0];
775     PendingLocs.clear();
776     PendingArgFlags.clear();
777     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
778                                ArgFlags);
779   }
780 
781   // Allocate to a register if possible, or else a stack slot.
782   unsigned Reg = State.AllocateReg(ArgGPRs);
783   unsigned StackOffset = Reg ? 0 : State.AllocateStack(XLen / 8, XLen / 8);
784 
785   // If we reach this point and PendingLocs is non-empty, we must be at the
786   // end of a split argument that must be passed indirectly.
787   if (!PendingLocs.empty()) {
788     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
789     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
790 
791     for (auto &It : PendingLocs) {
792       if (Reg)
793         It.convertToReg(Reg);
794       else
795         It.convertToMem(StackOffset);
796       State.addLoc(It);
797     }
798     PendingLocs.clear();
799     PendingArgFlags.clear();
800     return false;
801   }
802 
803   assert(LocVT == XLenVT && "Expected an XLenVT at this stage");
804 
805   if (Reg) {
806     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
807   } else {
808     State.addLoc(
809         CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
810   }
811   return false;
812 }
813 
814 void RISCVTargetLowering::analyzeInputArgs(
815     MachineFunction &MF, CCState &CCInfo,
816     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const {
817   unsigned NumArgs = Ins.size();
818   FunctionType *FType = MF.getFunction().getFunctionType();
819 
820   for (unsigned i = 0; i != NumArgs; ++i) {
821     MVT ArgVT = Ins[i].VT;
822     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
823 
824     Type *ArgTy = nullptr;
825     if (IsRet)
826       ArgTy = FType->getReturnType();
827     else if (Ins[i].isOrigArg())
828       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
829 
830     if (CC_RISCV(MF.getDataLayout(), i, ArgVT, ArgVT, CCValAssign::Full,
831                  ArgFlags, CCInfo, /*IsRet=*/true, IsRet, ArgTy)) {
832       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
833                         << EVT(ArgVT).getEVTString() << '\n');
834       llvm_unreachable(nullptr);
835     }
836   }
837 }
838 
839 void RISCVTargetLowering::analyzeOutputArgs(
840     MachineFunction &MF, CCState &CCInfo,
841     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
842     CallLoweringInfo *CLI) const {
843   unsigned NumArgs = Outs.size();
844 
845   for (unsigned i = 0; i != NumArgs; i++) {
846     MVT ArgVT = Outs[i].VT;
847     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
848     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
849 
850     if (CC_RISCV(MF.getDataLayout(), i, ArgVT, ArgVT, CCValAssign::Full,
851                  ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy)) {
852       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
853                         << EVT(ArgVT).getEVTString() << "\n");
854       llvm_unreachable(nullptr);
855     }
856   }
857 }
858 
859 // The caller is responsible for loading the full value if the argument is
860 // passed with CCValAssign::Indirect.
861 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
862                                 const CCValAssign &VA, const SDLoc &DL) {
863   MachineFunction &MF = DAG.getMachineFunction();
864   MachineRegisterInfo &RegInfo = MF.getRegInfo();
865   EVT LocVT = VA.getLocVT();
866   EVT ValVT = VA.getValVT();
867   SDValue Val;
868 
869   unsigned VReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
870   RegInfo.addLiveIn(VA.getLocReg(), VReg);
871   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
872 
873   switch (VA.getLocInfo()) {
874   default:
875     llvm_unreachable("Unexpected CCValAssign::LocInfo");
876   case CCValAssign::Full:
877   case CCValAssign::Indirect:
878     break;
879   case CCValAssign::BCvt:
880     Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
881     break;
882   }
883   return Val;
884 }
885 
886 // The caller is responsible for loading the full value if the argument is
887 // passed with CCValAssign::Indirect.
888 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
889                                 const CCValAssign &VA, const SDLoc &DL) {
890   MachineFunction &MF = DAG.getMachineFunction();
891   MachineFrameInfo &MFI = MF.getFrameInfo();
892   EVT LocVT = VA.getLocVT();
893   EVT ValVT = VA.getValVT();
894   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
895   int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
896                                  VA.getLocMemOffset(), /*Immutable=*/true);
897   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
898   SDValue Val;
899 
900   ISD::LoadExtType ExtType;
901   switch (VA.getLocInfo()) {
902   default:
903     llvm_unreachable("Unexpected CCValAssign::LocInfo");
904   case CCValAssign::Full:
905   case CCValAssign::Indirect:
906     ExtType = ISD::NON_EXTLOAD;
907     break;
908   }
909   Val = DAG.getExtLoad(
910       ExtType, DL, LocVT, Chain, FIN,
911       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
912   return Val;
913 }
914 
915 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
916                                        const CCValAssign &VA, const SDLoc &DL) {
917   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
918          "Unexpected VA");
919   MachineFunction &MF = DAG.getMachineFunction();
920   MachineFrameInfo &MFI = MF.getFrameInfo();
921   MachineRegisterInfo &RegInfo = MF.getRegInfo();
922 
923   if (VA.isMemLoc()) {
924     // f64 is passed on the stack.
925     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
926     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
927     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
928                        MachinePointerInfo::getFixedStack(MF, FI));
929   }
930 
931   assert(VA.isRegLoc() && "Expected register VA assignment");
932 
933   unsigned LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
934   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
935   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
936   SDValue Hi;
937   if (VA.getLocReg() == RISCV::X17) {
938     // Second half of f64 is passed on the stack.
939     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
940     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
941     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
942                      MachinePointerInfo::getFixedStack(MF, FI));
943   } else {
944     // Second half of f64 is passed in another GPR.
945     unsigned HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
946     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
947     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
948   }
949   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
950 }
951 
952 // Transform physical registers into virtual registers.
953 SDValue RISCVTargetLowering::LowerFormalArguments(
954     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
955     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
956     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
957 
958   switch (CallConv) {
959   default:
960     report_fatal_error("Unsupported calling convention");
961   case CallingConv::C:
962   case CallingConv::Fast:
963     break;
964   }
965 
966   MachineFunction &MF = DAG.getMachineFunction();
967   EVT PtrVT = getPointerTy(DAG.getDataLayout());
968   MVT XLenVT = Subtarget.getXLenVT();
969   unsigned XLenInBytes = Subtarget.getXLen() / 8;
970   // Used with vargs to acumulate store chains.
971   std::vector<SDValue> OutChains;
972 
973   // Assign locations to all of the incoming arguments.
974   SmallVector<CCValAssign, 16> ArgLocs;
975   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
976   analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false);
977 
978   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
979     CCValAssign &VA = ArgLocs[i];
980     assert(VA.getLocVT() == XLenVT && "Unhandled argument type");
981     SDValue ArgValue;
982     // Passing f64 on RV32D with a soft float ABI must be handled as a special
983     // case.
984     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
985       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
986     else if (VA.isRegLoc())
987       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL);
988     else
989       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
990 
991     if (VA.getLocInfo() == CCValAssign::Indirect) {
992       // If the original argument was split and passed by reference (e.g. i128
993       // on RV32), we need to load all parts of it here (using the same
994       // address).
995       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
996                                    MachinePointerInfo()));
997       unsigned ArgIndex = Ins[i].OrigArgIndex;
998       assert(Ins[i].PartOffset == 0);
999       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
1000         CCValAssign &PartVA = ArgLocs[i + 1];
1001         unsigned PartOffset = Ins[i + 1].PartOffset;
1002         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
1003                                       DAG.getIntPtrConstant(PartOffset, DL));
1004         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
1005                                      MachinePointerInfo()));
1006         ++i;
1007       }
1008       continue;
1009     }
1010     InVals.push_back(ArgValue);
1011   }
1012 
1013   if (IsVarArg) {
1014     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
1015     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
1016     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
1017     MachineFrameInfo &MFI = MF.getFrameInfo();
1018     MachineRegisterInfo &RegInfo = MF.getRegInfo();
1019     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1020 
1021     // Offset of the first variable argument from stack pointer, and size of
1022     // the vararg save area. For now, the varargs save area is either zero or
1023     // large enough to hold a0-a7.
1024     int VaArgOffset, VarArgsSaveSize;
1025 
1026     // If all registers are allocated, then all varargs must be passed on the
1027     // stack and we don't need to save any argregs.
1028     if (ArgRegs.size() == Idx) {
1029       VaArgOffset = CCInfo.getNextStackOffset();
1030       VarArgsSaveSize = 0;
1031     } else {
1032       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
1033       VaArgOffset = -VarArgsSaveSize;
1034     }
1035 
1036     // Record the frame index of the first variable argument
1037     // which is a value necessary to VASTART.
1038     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1039     RVFI->setVarArgsFrameIndex(FI);
1040 
1041     // If saving an odd number of registers then create an extra stack slot to
1042     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
1043     // offsets to even-numbered registered remain 2*XLEN-aligned.
1044     if (Idx % 2) {
1045       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes,
1046                                  true);
1047       VarArgsSaveSize += XLenInBytes;
1048     }
1049 
1050     // Copy the integer registers that may have been used for passing varargs
1051     // to the vararg save area.
1052     for (unsigned I = Idx; I < ArgRegs.size();
1053          ++I, VaArgOffset += XLenInBytes) {
1054       const unsigned Reg = RegInfo.createVirtualRegister(RC);
1055       RegInfo.addLiveIn(ArgRegs[I], Reg);
1056       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
1057       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1058       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1059       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
1060                                    MachinePointerInfo::getFixedStack(MF, FI));
1061       cast<StoreSDNode>(Store.getNode())
1062           ->getMemOperand()
1063           ->setValue((Value *)nullptr);
1064       OutChains.push_back(Store);
1065     }
1066     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
1067   }
1068 
1069   // All stores are grouped in one node to allow the matching between
1070   // the size of Ins and InVals. This only happens for vararg functions.
1071   if (!OutChains.empty()) {
1072     OutChains.push_back(Chain);
1073     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
1074   }
1075 
1076   return Chain;
1077 }
1078 
1079 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
1080 // and output parameter nodes.
1081 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
1082                                        SmallVectorImpl<SDValue> &InVals) const {
1083   SelectionDAG &DAG = CLI.DAG;
1084   SDLoc &DL = CLI.DL;
1085   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1086   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1087   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1088   SDValue Chain = CLI.Chain;
1089   SDValue Callee = CLI.Callee;
1090   CLI.IsTailCall = false;
1091   CallingConv::ID CallConv = CLI.CallConv;
1092   bool IsVarArg = CLI.IsVarArg;
1093   EVT PtrVT = getPointerTy(DAG.getDataLayout());
1094   MVT XLenVT = Subtarget.getXLenVT();
1095 
1096   MachineFunction &MF = DAG.getMachineFunction();
1097 
1098   // Analyze the operands of the call, assigning locations to each operand.
1099   SmallVector<CCValAssign, 16> ArgLocs;
1100   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1101   analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI);
1102 
1103   // Get a count of how many bytes are to be pushed on the stack.
1104   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1105 
1106   // Create local copies for byval args
1107   SmallVector<SDValue, 8> ByValArgs;
1108   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1109     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1110     if (!Flags.isByVal())
1111       continue;
1112 
1113     SDValue Arg = OutVals[i];
1114     unsigned Size = Flags.getByValSize();
1115     unsigned Align = Flags.getByValAlign();
1116 
1117     int FI = MF.getFrameInfo().CreateStackObject(Size, Align, /*isSS=*/false);
1118     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1119     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
1120 
1121     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Align,
1122                           /*IsVolatile=*/false,
1123                           /*AlwaysInline=*/false,
1124                           /*isTailCall=*/false, MachinePointerInfo(),
1125                           MachinePointerInfo());
1126     ByValArgs.push_back(FIPtr);
1127   }
1128 
1129   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
1130 
1131   // Copy argument values to their designated locations.
1132   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1133   SmallVector<SDValue, 8> MemOpChains;
1134   SDValue StackPtr;
1135   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
1136     CCValAssign &VA = ArgLocs[i];
1137     SDValue ArgValue = OutVals[i];
1138     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1139 
1140     // Handle passing f64 on RV32D with a soft float ABI as a special case.
1141     bool IsF64OnRV32DSoftABI =
1142         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
1143     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
1144       SDValue SplitF64 = DAG.getNode(
1145           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
1146       SDValue Lo = SplitF64.getValue(0);
1147       SDValue Hi = SplitF64.getValue(1);
1148 
1149       unsigned RegLo = VA.getLocReg();
1150       RegsToPass.push_back(std::make_pair(RegLo, Lo));
1151 
1152       if (RegLo == RISCV::X17) {
1153         // Second half of f64 is passed on the stack.
1154         // Work out the address of the stack slot.
1155         if (!StackPtr.getNode())
1156           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
1157         // Emit the store.
1158         MemOpChains.push_back(
1159             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
1160       } else {
1161         // Second half of f64 is passed in another GPR.
1162         unsigned RegHigh = RegLo + 1;
1163         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
1164       }
1165       continue;
1166     }
1167 
1168     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
1169     // as any other MemLoc.
1170 
1171     // Promote the value if needed.
1172     // For now, only handle fully promoted and indirect arguments.
1173     switch (VA.getLocInfo()) {
1174     case CCValAssign::Full:
1175       break;
1176     case CCValAssign::BCvt:
1177       ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), ArgValue);
1178       break;
1179     case CCValAssign::Indirect: {
1180       // Store the argument in a stack slot and pass its address.
1181       SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT);
1182       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1183       MemOpChains.push_back(
1184           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1185                        MachinePointerInfo::getFixedStack(MF, FI)));
1186       // If the original argument was split (e.g. i128), we need
1187       // to store all parts of it here (and pass just one address).
1188       unsigned ArgIndex = Outs[i].OrigArgIndex;
1189       assert(Outs[i].PartOffset == 0);
1190       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
1191         SDValue PartValue = OutVals[i + 1];
1192         unsigned PartOffset = Outs[i + 1].PartOffset;
1193         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
1194                                       DAG.getIntPtrConstant(PartOffset, DL));
1195         MemOpChains.push_back(
1196             DAG.getStore(Chain, DL, PartValue, Address,
1197                          MachinePointerInfo::getFixedStack(MF, FI)));
1198         ++i;
1199       }
1200       ArgValue = SpillSlot;
1201       break;
1202     }
1203     default:
1204       llvm_unreachable("Unknown loc info!");
1205     }
1206 
1207     // Use local copy if it is a byval arg.
1208     if (Flags.isByVal())
1209       ArgValue = ByValArgs[j++];
1210 
1211     if (VA.isRegLoc()) {
1212       // Queue up the argument copies and emit them at the end.
1213       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1214     } else {
1215       assert(VA.isMemLoc() && "Argument not register or memory");
1216 
1217       // Work out the address of the stack slot.
1218       if (!StackPtr.getNode())
1219         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
1220       SDValue Address =
1221           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1222                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
1223 
1224       // Emit the store.
1225       MemOpChains.push_back(
1226           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
1227     }
1228   }
1229 
1230   // Join the stores, which are independent of one another.
1231   if (!MemOpChains.empty())
1232     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1233 
1234   SDValue Glue;
1235 
1236   // Build a sequence of copy-to-reg nodes, chained and glued together.
1237   for (auto &Reg : RegsToPass) {
1238     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
1239     Glue = Chain.getValue(1);
1240   }
1241 
1242   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
1243   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
1244   // split it and then direct call can be matched by PseudoCALL.
1245   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
1246     Callee = DAG.getTargetGlobalAddress(S->getGlobal(), DL, PtrVT, 0, 0);
1247   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1248     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, 0);
1249   }
1250 
1251   // The first call operand is the chain and the second is the target address.
1252   SmallVector<SDValue, 8> Ops;
1253   Ops.push_back(Chain);
1254   Ops.push_back(Callee);
1255 
1256   // Add argument registers to the end of the list so that they are
1257   // known live into the call.
1258   for (auto &Reg : RegsToPass)
1259     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
1260 
1261   // Add a register mask operand representing the call-preserved registers.
1262   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1263   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1264   assert(Mask && "Missing call preserved mask for calling convention");
1265   Ops.push_back(DAG.getRegisterMask(Mask));
1266 
1267   // Glue the call to the argument copies, if any.
1268   if (Glue.getNode())
1269     Ops.push_back(Glue);
1270 
1271   // Emit the call.
1272   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1273   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
1274   Glue = Chain.getValue(1);
1275 
1276   // Mark the end of the call, which is glued to the call itself.
1277   Chain = DAG.getCALLSEQ_END(Chain,
1278                              DAG.getConstant(NumBytes, DL, PtrVT, true),
1279                              DAG.getConstant(0, DL, PtrVT, true),
1280                              Glue, DL);
1281   Glue = Chain.getValue(1);
1282 
1283   // Assign locations to each value returned by this call.
1284   SmallVector<CCValAssign, 16> RVLocs;
1285   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
1286   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true);
1287 
1288   // Copy all of the result registers out of their specified physreg.
1289   for (auto &VA : RVLocs) {
1290     // Copy the value out
1291     SDValue RetValue =
1292         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
1293     // Glue the RetValue to the end of the call sequence
1294     Chain = RetValue.getValue(1);
1295     Glue = RetValue.getValue(2);
1296     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
1297       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
1298       SDValue RetValue2 =
1299           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
1300       Chain = RetValue2.getValue(1);
1301       Glue = RetValue2.getValue(2);
1302       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
1303                              RetValue2);
1304     }
1305 
1306     switch (VA.getLocInfo()) {
1307     default:
1308       llvm_unreachable("Unknown loc info!");
1309     case CCValAssign::Full:
1310       break;
1311     case CCValAssign::BCvt:
1312       RetValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), RetValue);
1313       break;
1314     }
1315 
1316     InVals.push_back(RetValue);
1317   }
1318 
1319   return Chain;
1320 }
1321 
1322 bool RISCVTargetLowering::CanLowerReturn(
1323     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
1324     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
1325   SmallVector<CCValAssign, 16> RVLocs;
1326   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
1327   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1328     MVT VT = Outs[i].VT;
1329     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1330     if (CC_RISCV(MF.getDataLayout(), i, VT, VT, CCValAssign::Full, ArgFlags,
1331                  CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr))
1332       return false;
1333   }
1334   return true;
1335 }
1336 
1337 static SDValue packIntoRegLoc(SelectionDAG &DAG, SDValue Val,
1338                               const CCValAssign &VA, const SDLoc &DL) {
1339   EVT LocVT = VA.getLocVT();
1340 
1341   switch (VA.getLocInfo()) {
1342   default:
1343     llvm_unreachable("Unexpected CCValAssign::LocInfo");
1344   case CCValAssign::Full:
1345     break;
1346   case CCValAssign::BCvt:
1347     Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
1348     break;
1349   }
1350   return Val;
1351 }
1352 
1353 SDValue
1354 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1355                                  bool IsVarArg,
1356                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
1357                                  const SmallVectorImpl<SDValue> &OutVals,
1358                                  const SDLoc &DL, SelectionDAG &DAG) const {
1359   // Stores the assignment of the return value to a location.
1360   SmallVector<CCValAssign, 16> RVLocs;
1361 
1362   // Info about the registers and stack slot.
1363   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
1364                  *DAG.getContext());
1365 
1366   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
1367                     nullptr);
1368 
1369   SDValue Glue;
1370   SmallVector<SDValue, 4> RetOps(1, Chain);
1371 
1372   // Copy the result values into the output registers.
1373   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
1374     SDValue Val = OutVals[i];
1375     CCValAssign &VA = RVLocs[i];
1376     assert(VA.isRegLoc() && "Can only return in registers!");
1377 
1378     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
1379       // Handle returning f64 on RV32D with a soft float ABI.
1380       assert(VA.isRegLoc() && "Expected return via registers");
1381       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
1382                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
1383       SDValue Lo = SplitF64.getValue(0);
1384       SDValue Hi = SplitF64.getValue(1);
1385       unsigned RegLo = VA.getLocReg();
1386       unsigned RegHi = RegLo + 1;
1387       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
1388       Glue = Chain.getValue(1);
1389       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
1390       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
1391       Glue = Chain.getValue(1);
1392       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
1393     } else {
1394       // Handle a 'normal' return.
1395       Val = packIntoRegLoc(DAG, Val, VA, DL);
1396       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
1397 
1398       // Guarantee that all emitted copies are stuck together.
1399       Glue = Chain.getValue(1);
1400       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1401     }
1402   }
1403 
1404   RetOps[0] = Chain; // Update chain.
1405 
1406   // Add the glue node if we have it.
1407   if (Glue.getNode()) {
1408     RetOps.push_back(Glue);
1409   }
1410 
1411   return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps);
1412 }
1413 
1414 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
1415   switch ((RISCVISD::NodeType)Opcode) {
1416   case RISCVISD::FIRST_NUMBER:
1417     break;
1418   case RISCVISD::RET_FLAG:
1419     return "RISCVISD::RET_FLAG";
1420   case RISCVISD::CALL:
1421     return "RISCVISD::CALL";
1422   case RISCVISD::SELECT_CC:
1423     return "RISCVISD::SELECT_CC";
1424   case RISCVISD::BuildPairF64:
1425     return "RISCVISD::BuildPairF64";
1426   case RISCVISD::SplitF64:
1427     return "RISCVISD::SplitF64";
1428   }
1429   return nullptr;
1430 }
1431 
1432 std::pair<unsigned, const TargetRegisterClass *>
1433 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
1434                                                   StringRef Constraint,
1435                                                   MVT VT) const {
1436   // First, see if this is a constraint that directly corresponds to a
1437   // RISCV register class.
1438   if (Constraint.size() == 1) {
1439     switch (Constraint[0]) {
1440     case 'r':
1441       return std::make_pair(0U, &RISCV::GPRRegClass);
1442     default:
1443       break;
1444     }
1445   }
1446 
1447   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1448 }
1449