blob: 7c1d01845b4f59065ff4e90967cae132606c4278 [file] [log] [blame]
Alex Bradbury89718422017-10-19 21:37:38 +00001//===-- 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"
Alex Bradburyc85be0d2018-01-10 19:41:03 +000017#include "RISCVMachineFunctionInfo.h"
Alex Bradbury89718422017-10-19 21:37:38 +000018#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"
Craig Topper2fa14362018-03-29 17:21:10 +000028#include "llvm/CodeGen/ValueTypes.h"
Alex Bradbury89718422017-10-19 21:37:38 +000029#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
35using namespace llvm;
36
37#define DEBUG_TYPE "riscv-lower"
38
39RISCVTargetLowering::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
Alex Bradbury76c29ee2018-03-20 12:45:35 +000048 if (Subtarget.hasStdExtF())
49 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
Alex Bradbury0b4175f2018-04-12 05:34:25 +000050 if (Subtarget.hasStdExtD())
51 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
Alex Bradbury76c29ee2018-03-20 12:45:35 +000052
Alex Bradbury89718422017-10-19 21:37:38 +000053 // Compute derived properties from the register classes.
54 computeRegisterProperties(STI.getRegisterInfo());
55
56 setStackPointerRegisterToSaveRestore(RISCV::X2);
57
Alex Bradburycfa62912017-11-08 12:20:01 +000058 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
59 setLoadExtAction(N, XLenVT, MVT::i1, Promote);
60
Alex Bradbury89718422017-10-19 21:37:38 +000061 // TODO: add all necessary setOperationAction calls.
Alex Bradburybfb00d42017-12-11 12:38:17 +000062 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
63
Alex Bradburyffc435e2017-11-21 08:11:03 +000064 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
Alex Bradbury74913e12017-11-08 13:31:40 +000065 setOperationAction(ISD::BR_CC, XLenVT, Expand);
Alex Bradbury65385162017-11-21 07:51:32 +000066 setOperationAction(ISD::SELECT, XLenVT, Custom);
67 setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
68
Alex Bradburybfb00d42017-12-11 12:38:17 +000069 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
70 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
71
Alex Bradburyc85be0d2018-01-10 19:41:03 +000072 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
Alex Bradburyffc435e2017-11-21 08:11:03 +000077 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
Alex Bradbury92138382018-01-18 12:36:38 +000085 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 }
Alex Bradburyffc435e2017-11-21 08:11:03 +000094
Alex Bradbury92138382018-01-18 12:36:38 +000095 setOperationAction(ISD::SDIVREM, XLenVT, Expand);
96 setOperationAction(ISD::UDIVREM, XLenVT, Expand);
Alex Bradburyffc435e2017-11-21 08:11:03 +000097 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
98 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
Alex Bradburyffc435e2017-11-21 08:11:03 +000099
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
Alex Bradbury21d28fe2018-04-12 05:50:06 +0000111 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
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000116 if (Subtarget.hasStdExtF()) {
117 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
118 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
Alex Bradbury21d28fe2018-04-12 05:50:06 +0000119 for (auto CC : FPCCToExtend)
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000120 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);
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000124 }
125
Alex Bradbury5d0dfa52018-04-12 05:42:42 +0000126 if (Subtarget.hasStdExtD()) {
127 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
128 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
Alex Bradbury21d28fe2018-04-12 05:50:06 +0000129 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);
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000134 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
Alex Bradbury60baa2e2018-04-12 05:47:15 +0000135 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
Alex Bradbury5d0dfa52018-04-12 05:42:42 +0000136 }
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000137
Alex Bradburyffc435e2017-11-21 08:11:03 +0000138 setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
139 setOperationAction(ISD::BlockAddress, XLenVT, Custom);
Alex Bradbury80c8eb72018-03-20 13:26:12 +0000140 setOperationAction(ISD::ConstantPool, XLenVT, Custom);
Alex Bradburyffc435e2017-11-21 08:11:03 +0000141
Alex Bradbury89718422017-10-19 21:37:38 +0000142 setBooleanContents(ZeroOrOneBooleanContent);
143
144 // Function alignments (log2).
Shiva Chenb48b0272018-04-12 11:30:59 +0000145 unsigned FunctionAlignment = Subtarget.hasStdExtC() ? 1 : 2;
146 setMinFunctionAlignment(FunctionAlignment);
147 setPrefFunctionAlignment(FunctionAlignment);
Alex Bradburyffc435e2017-11-21 08:11:03 +0000148
149 // Effectively disable jump table generation.
150 setMinimumJumpTableEntries(INT_MAX);
Alex Bradbury89718422017-10-19 21:37:38 +0000151}
152
Shiva Chenbbf4c5c2018-02-02 02:43:18 +0000153EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
154 EVT VT) const {
155 if (!VT.isVector())
156 return getPointerTy(DL);
157 return VT.changeVectorElementTypeToInteger();
158}
159
Alex Bradbury09926292018-04-26 12:13:48 +0000160bool 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
Alex Bradbury5c41ece2018-04-26 13:00:37 +0000186bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
187 return isInt<12>(Imm);
188}
189
Alex Bradbury65385162017-11-21 07:51:32 +0000190// Changes the condition code and swaps operands if necessary, so the SetCC
191// operation matches one of the comparisons supported directly in the RISC-V
192// ISA.
193static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) {
194 switch (CC) {
195 default:
196 break;
197 case ISD::SETGT:
198 case ISD::SETLE:
199 case ISD::SETUGT:
200 case ISD::SETULE:
201 CC = ISD::getSetCCSwappedOperands(CC);
202 std::swap(LHS, RHS);
203 break;
204 }
205}
206
207// Return the RISC-V branch opcode that matches the given DAG integer
208// condition code. The CondCode must be one of those supported by the RISC-V
209// ISA (see normaliseSetCC).
210static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) {
211 switch (CC) {
212 default:
213 llvm_unreachable("Unsupported CondCode");
214 case ISD::SETEQ:
215 return RISCV::BEQ;
216 case ISD::SETNE:
217 return RISCV::BNE;
218 case ISD::SETLT:
219 return RISCV::BLT;
220 case ISD::SETGE:
221 return RISCV::BGE;
222 case ISD::SETULT:
223 return RISCV::BLTU;
224 case ISD::SETUGE:
225 return RISCV::BGEU;
226 }
227}
228
Alex Bradbury89718422017-10-19 21:37:38 +0000229SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
230 SelectionDAG &DAG) const {
231 switch (Op.getOpcode()) {
232 default:
233 report_fatal_error("unimplemented operand");
Alex Bradburyec8aa912017-11-08 13:24:21 +0000234 case ISD::GlobalAddress:
235 return lowerGlobalAddress(Op, DAG);
Alex Bradburyffc435e2017-11-21 08:11:03 +0000236 case ISD::BlockAddress:
237 return lowerBlockAddress(Op, DAG);
Alex Bradbury80c8eb72018-03-20 13:26:12 +0000238 case ISD::ConstantPool:
239 return lowerConstantPool(Op, DAG);
Alex Bradbury65385162017-11-21 07:51:32 +0000240 case ISD::SELECT:
241 return lowerSELECT(Op, DAG);
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000242 case ISD::VASTART:
243 return lowerVASTART(Op, DAG);
Alex Bradbury70f137b2018-01-10 20:12:00 +0000244 case ISD::FRAMEADDR:
245 return LowerFRAMEADDR(Op, DAG);
246 case ISD::RETURNADDR:
247 return LowerRETURNADDR(Op, DAG);
Alex Bradburyec8aa912017-11-08 13:24:21 +0000248 }
249}
250
251SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
252 SelectionDAG &DAG) const {
253 SDLoc DL(Op);
254 EVT Ty = Op.getValueType();
255 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
256 const GlobalValue *GV = N->getGlobal();
257 int64_t Offset = N->getOffset();
258
Alex Bradburyffc435e2017-11-21 08:11:03 +0000259 if (isPositionIndependent() || Subtarget.is64Bit())
Alex Bradburyec8aa912017-11-08 13:24:21 +0000260 report_fatal_error("Unable to lowerGlobalAddress");
Alex Bradburyffc435e2017-11-21 08:11:03 +0000261
262 SDValue GAHi =
263 DAG.getTargetGlobalAddress(GV, DL, Ty, Offset, RISCVII::MO_HI);
264 SDValue GALo =
265 DAG.getTargetGlobalAddress(GV, DL, Ty, Offset, RISCVII::MO_LO);
266 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, GAHi), 0);
267 SDValue MNLo =
268 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, GALo), 0);
269 return MNLo;
270}
271
272SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
273 SelectionDAG &DAG) const {
274 SDLoc DL(Op);
275 EVT Ty = Op.getValueType();
276 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
277 const BlockAddress *BA = N->getBlockAddress();
278 int64_t Offset = N->getOffset();
279
280 if (isPositionIndependent() || Subtarget.is64Bit())
281 report_fatal_error("Unable to lowerBlockAddress");
282
283 SDValue BAHi = DAG.getTargetBlockAddress(BA, Ty, Offset, RISCVII::MO_HI);
284 SDValue BALo = DAG.getTargetBlockAddress(BA, Ty, Offset, RISCVII::MO_LO);
285 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, BAHi), 0);
286 SDValue MNLo =
287 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, BALo), 0);
288 return MNLo;
289}
290
Alex Bradbury80c8eb72018-03-20 13:26:12 +0000291SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
292 SelectionDAG &DAG) const {
293 SDLoc DL(Op);
294 EVT Ty = Op.getValueType();
295 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
296 const Constant *CPA = N->getConstVal();
297 int64_t Offset = N->getOffset();
298 unsigned Alignment = N->getAlignment();
299
300 if (!isPositionIndependent()) {
301 SDValue CPAHi =
302 DAG.getTargetConstantPool(CPA, Ty, Alignment, Offset, RISCVII::MO_HI);
303 SDValue CPALo =
304 DAG.getTargetConstantPool(CPA, Ty, Alignment, Offset, RISCVII::MO_LO);
305 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, CPAHi), 0);
306 SDValue MNLo =
307 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, CPALo), 0);
308 return MNLo;
309 } else {
310 report_fatal_error("Unable to lowerConstantPool");
311 }
312}
313
Alex Bradburyffc435e2017-11-21 08:11:03 +0000314SDValue RISCVTargetLowering::lowerExternalSymbol(SDValue Op,
315 SelectionDAG &DAG) const {
316 SDLoc DL(Op);
317 EVT Ty = Op.getValueType();
318 ExternalSymbolSDNode *N = cast<ExternalSymbolSDNode>(Op);
319 const char *Sym = N->getSymbol();
320
321 // TODO: should also handle gp-relative loads.
322
323 if (isPositionIndependent() || Subtarget.is64Bit())
324 report_fatal_error("Unable to lowerExternalSymbol");
325
326 SDValue GAHi = DAG.getTargetExternalSymbol(Sym, Ty, RISCVII::MO_HI);
327 SDValue GALo = DAG.getTargetExternalSymbol(Sym, Ty, RISCVII::MO_LO);
328 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, GAHi), 0);
329 SDValue MNLo =
330 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, GALo), 0);
331 return MNLo;
Alex Bradbury89718422017-10-19 21:37:38 +0000332}
333
Alex Bradbury65385162017-11-21 07:51:32 +0000334SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
335 SDValue CondV = Op.getOperand(0);
336 SDValue TrueV = Op.getOperand(1);
337 SDValue FalseV = Op.getOperand(2);
338 SDLoc DL(Op);
339 MVT XLenVT = Subtarget.getXLenVT();
340
341 // If the result type is XLenVT and CondV is the output of a SETCC node
342 // which also operated on XLenVT inputs, then merge the SETCC node into the
343 // lowered RISCVISD::SELECT_CC to take advantage of the integer
344 // compare+branch instructions. i.e.:
345 // (select (setcc lhs, rhs, cc), truev, falsev)
346 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
347 if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC &&
348 CondV.getOperand(0).getSimpleValueType() == XLenVT) {
349 SDValue LHS = CondV.getOperand(0);
350 SDValue RHS = CondV.getOperand(1);
351 auto CC = cast<CondCodeSDNode>(CondV.getOperand(2));
352 ISD::CondCode CCVal = CC->get();
353
354 normaliseSetCC(LHS, RHS, CCVal);
355
356 SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT);
357 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
358 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
359 return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
360 }
361
362 // Otherwise:
363 // (select condv, truev, falsev)
364 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
365 SDValue Zero = DAG.getConstant(0, DL, XLenVT);
366 SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT);
367
368 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
369 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
370
371 return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
372}
373
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000374SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
375 MachineFunction &MF = DAG.getMachineFunction();
376 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
377
378 SDLoc DL(Op);
379 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
380 getPointerTy(MF.getDataLayout()));
381
382 // vastart just stores the address of the VarArgsFrameIndex slot into the
383 // memory location argument.
384 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
385 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
386 MachinePointerInfo(SV));
387}
388
Alex Bradbury70f137b2018-01-10 20:12:00 +0000389SDValue RISCVTargetLowering::LowerFRAMEADDR(SDValue Op,
390 SelectionDAG &DAG) const {
391 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
392 MachineFunction &MF = DAG.getMachineFunction();
393 MachineFrameInfo &MFI = MF.getFrameInfo();
394 MFI.setFrameAddressIsTaken(true);
395 unsigned FrameReg = RI.getFrameRegister(MF);
396 int XLenInBytes = Subtarget.getXLen() / 8;
397
398 EVT VT = Op.getValueType();
399 SDLoc DL(Op);
400 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
401 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
402 while (Depth--) {
403 int Offset = -(XLenInBytes * 2);
404 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
405 DAG.getIntPtrConstant(Offset, DL));
406 FrameAddr =
407 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
408 }
409 return FrameAddr;
410}
411
412SDValue RISCVTargetLowering::LowerRETURNADDR(SDValue Op,
413 SelectionDAG &DAG) const {
414 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
415 MachineFunction &MF = DAG.getMachineFunction();
416 MachineFrameInfo &MFI = MF.getFrameInfo();
417 MFI.setReturnAddressIsTaken(true);
418 MVT XLenVT = Subtarget.getXLenVT();
419 int XLenInBytes = Subtarget.getXLen() / 8;
420
421 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
422 return SDValue();
423
424 EVT VT = Op.getValueType();
425 SDLoc DL(Op);
426 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
427 if (Depth) {
428 int Off = -XLenInBytes;
429 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
430 SDValue Offset = DAG.getConstant(Off, DL, VT);
431 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
432 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
433 MachinePointerInfo());
434 }
435
436 // Return the value of the return address register, marking it an implicit
437 // live-in.
438 unsigned Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
439 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
440}
441
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000442static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
443 MachineBasicBlock *BB) {
444 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
445
446 MachineFunction &MF = *BB->getParent();
447 DebugLoc DL = MI.getDebugLoc();
448 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
449 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
450 unsigned LoReg = MI.getOperand(0).getReg();
451 unsigned HiReg = MI.getOperand(1).getReg();
452 unsigned SrcReg = MI.getOperand(2).getReg();
453 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
454 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
455
456 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
457 RI);
458 MachineMemOperand *MMO =
459 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
460 MachineMemOperand::MOLoad, 8, 8);
461 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
462 .addFrameIndex(FI)
463 .addImm(0)
464 .addMemOperand(MMO);
465 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
466 .addFrameIndex(FI)
467 .addImm(4)
468 .addMemOperand(MMO);
469 MI.eraseFromParent(); // The pseudo instruction is gone now.
470 return BB;
471}
472
473static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
474 MachineBasicBlock *BB) {
475 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
476 "Unexpected instruction");
477
478 MachineFunction &MF = *BB->getParent();
479 DebugLoc DL = MI.getDebugLoc();
480 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
481 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
482 unsigned DstReg = MI.getOperand(0).getReg();
483 unsigned LoReg = MI.getOperand(1).getReg();
484 unsigned HiReg = MI.getOperand(2).getReg();
485 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
486 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
487
488 MachineMemOperand *MMO =
489 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
490 MachineMemOperand::MOStore, 8, 8);
491 BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
492 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
493 .addFrameIndex(FI)
494 .addImm(0)
495 .addMemOperand(MMO);
496 BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
497 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
498 .addFrameIndex(FI)
499 .addImm(4)
500 .addMemOperand(MMO);
501 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
502 MI.eraseFromParent(); // The pseudo instruction is gone now.
503 return BB;
504}
505
Alex Bradbury65385162017-11-21 07:51:32 +0000506MachineBasicBlock *
507RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
508 MachineBasicBlock *BB) const {
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000509 switch (MI.getOpcode()) {
510 default:
511 llvm_unreachable("Unexpected instr type to insert");
512 case RISCV::Select_GPR_Using_CC_GPR:
513 case RISCV::Select_FPR32_Using_CC_GPR:
Alex Bradbury21d28fe2018-04-12 05:50:06 +0000514 case RISCV::Select_FPR64_Using_CC_GPR:
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000515 break;
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000516 case RISCV::BuildPairF64Pseudo:
517 return emitBuildPairF64Pseudo(MI, BB);
518 case RISCV::SplitF64Pseudo:
519 return emitSplitF64Pseudo(MI, BB);
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000520 }
Alex Bradbury65385162017-11-21 07:51:32 +0000521
522 // To "insert" a SELECT instruction, we actually have to insert the triangle
523 // control-flow pattern. The incoming instruction knows the destination vreg
524 // to set, the condition code register to branch on, the true/false values to
525 // select between, and the condcode to use to select the appropriate branch.
526 //
527 // We produce the following control flow:
528 // HeadMBB
529 // | \
530 // | IfFalseMBB
531 // | /
532 // TailMBB
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000533 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
Alex Bradbury65385162017-11-21 07:51:32 +0000534 const BasicBlock *LLVM_BB = BB->getBasicBlock();
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000535 DebugLoc DL = MI.getDebugLoc();
Alex Bradbury65385162017-11-21 07:51:32 +0000536 MachineFunction::iterator I = ++BB->getIterator();
537
538 MachineBasicBlock *HeadMBB = BB;
539 MachineFunction *F = BB->getParent();
540 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
541 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
542
543 F->insert(I, IfFalseMBB);
544 F->insert(I, TailMBB);
545 // Move all remaining instructions to TailMBB.
546 TailMBB->splice(TailMBB->begin(), HeadMBB,
547 std::next(MachineBasicBlock::iterator(MI)), HeadMBB->end());
548 // Update machine-CFG edges by transferring all successors of the current
549 // block to the new block which will contain the Phi node for the select.
550 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
551 // Set the successors for HeadMBB.
552 HeadMBB->addSuccessor(IfFalseMBB);
553 HeadMBB->addSuccessor(TailMBB);
554
555 // Insert appropriate branch.
556 unsigned LHS = MI.getOperand(1).getReg();
557 unsigned RHS = MI.getOperand(2).getReg();
558 auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm());
559 unsigned Opcode = getBranchOpcodeForIntCondCode(CC);
560
561 BuildMI(HeadMBB, DL, TII.get(Opcode))
562 .addReg(LHS)
563 .addReg(RHS)
564 .addMBB(TailMBB);
565
566 // IfFalseMBB just falls through to TailMBB.
567 IfFalseMBB->addSuccessor(TailMBB);
568
569 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
570 BuildMI(*TailMBB, TailMBB->begin(), DL, TII.get(RISCV::PHI),
571 MI.getOperand(0).getReg())
572 .addReg(MI.getOperand(4).getReg())
573 .addMBB(HeadMBB)
574 .addReg(MI.getOperand(5).getReg())
575 .addMBB(IfFalseMBB);
576
577 MI.eraseFromParent(); // The pseudo instruction is gone now.
578 return TailMBB;
579}
580
Alex Bradbury89718422017-10-19 21:37:38 +0000581// Calling Convention Implementation.
Alex Bradburydc31c612017-12-11 12:49:02 +0000582// The expectations for frontend ABI lowering vary from target to target.
583// Ideally, an LLVM frontend would be able to avoid worrying about many ABI
584// details, but this is a longer term goal. For now, we simply try to keep the
585// role of the frontend as simple and well-defined as possible. The rules can
586// be summarised as:
587// * Never split up large scalar arguments. We handle them here.
588// * If a hardfloat calling convention is being used, and the struct may be
589// passed in a pair of registers (fp+fp, int+fp), and both registers are
590// available, then pass as two separate arguments. If either the GPRs or FPRs
591// are exhausted, then pass according to the rule below.
592// * If a struct could never be passed in registers or directly in a stack
593// slot (as it is larger than 2*XLEN and the floating point rules don't
594// apply), then pass it using a pointer with the byval attribute.
595// * If a struct is less than 2*XLEN, then coerce to either a two-element
596// word-sized array or a 2*XLEN scalar (depending on alignment).
597// * The frontend can determine whether a struct is returned by reference or
598// not based on its size and fields. If it will be returned by reference, the
599// frontend must modify the prototype so a pointer with the sret annotation is
600// passed as the first argument. This is not necessary for large scalar
601// returns.
602// * Struct return values and varargs should be coerced to structs containing
603// register-size fields in the same situations they would be for fixed
604// arguments.
605
606static const MCPhysReg ArgGPRs[] = {
607 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
608 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
609};
610
611// Pass a 2*XLEN argument that has been split into two XLEN values through
612// registers or the stack as necessary.
613static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
614 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
615 MVT ValVT2, MVT LocVT2,
616 ISD::ArgFlagsTy ArgFlags2) {
617 unsigned XLenInBytes = XLen / 8;
618 if (unsigned Reg = State.AllocateReg(ArgGPRs)) {
619 // At least one half can be passed via register.
620 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
621 VA1.getLocVT(), CCValAssign::Full));
622 } else {
623 // Both halves must be passed on the stack, with proper alignment.
624 unsigned StackAlign = std::max(XLenInBytes, ArgFlags1.getOrigAlign());
625 State.addLoc(
626 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
627 State.AllocateStack(XLenInBytes, StackAlign),
628 VA1.getLocVT(), CCValAssign::Full));
629 State.addLoc(CCValAssign::getMem(
630 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
631 CCValAssign::Full));
632 return false;
633 }
634
635 if (unsigned Reg = State.AllocateReg(ArgGPRs)) {
636 // The second half can also be passed via register.
637 State.addLoc(
638 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
639 } else {
640 // The second half is passed via the stack, without additional alignment.
641 State.addLoc(CCValAssign::getMem(
642 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
643 CCValAssign::Full));
644 }
645
646 return false;
647}
648
649// Implements the RISC-V calling convention. Returns true upon failure.
650static bool CC_RISCV(const DataLayout &DL, unsigned ValNo, MVT ValVT, MVT LocVT,
651 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000652 CCState &State, bool IsFixed, bool IsRet, Type *OrigTy) {
Alex Bradburydc31c612017-12-11 12:49:02 +0000653 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
654 assert(XLen == 32 || XLen == 64);
655 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000656 if (ValVT == MVT::f32) {
657 LocVT = MVT::i32;
658 LocInfo = CCValAssign::BCvt;
659 }
Alex Bradburydc31c612017-12-11 12:49:02 +0000660
661 // Any return value split in to more than two values can't be returned
662 // directly.
663 if (IsRet && ValNo > 1)
664 return true;
665
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000666 // If this is a variadic argument, the RISC-V calling convention requires
667 // that it is assigned an 'even' or 'aligned' register if it has 8-byte
668 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
669 // be used regardless of whether the original argument was split during
670 // legalisation or not. The argument will not be passed by registers if the
671 // original type is larger than 2*XLEN, so the register alignment rule does
672 // not apply.
673 unsigned TwoXLenInBytes = (2 * XLen) / 8;
674 if (!IsFixed && ArgFlags.getOrigAlign() == TwoXLenInBytes &&
675 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
676 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
677 // Skip 'odd' register if necessary.
678 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
679 State.AllocateReg(ArgGPRs);
680 }
681
Alex Bradburydc31c612017-12-11 12:49:02 +0000682 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
683 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
684 State.getPendingArgFlags();
685
686 assert(PendingLocs.size() == PendingArgFlags.size() &&
687 "PendingLocs and PendingArgFlags out of sync");
688
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000689 // Handle passing f64 on RV32D with a soft float ABI.
690 if (XLen == 32 && ValVT == MVT::f64) {
Mandeep Singh Grang88a8b262018-04-16 18:56:10 +0000691 assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000692 "Can't lower f64 if it is split");
693 // Depending on available argument GPRS, f64 may be passed in a pair of
694 // GPRs, split between a GPR and the stack, or passed completely on the
695 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
696 // cases.
697 unsigned Reg = State.AllocateReg(ArgGPRs);
698 LocVT = MVT::i32;
699 if (!Reg) {
700 unsigned StackOffset = State.AllocateStack(8, 8);
701 State.addLoc(
702 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
703 return false;
704 }
705 if (!State.AllocateReg(ArgGPRs))
706 State.AllocateStack(4, 4);
707 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
708 return false;
709 }
710
Alex Bradburydc31c612017-12-11 12:49:02 +0000711 // Split arguments might be passed indirectly, so keep track of the pending
712 // values.
713 if (ArgFlags.isSplit() || !PendingLocs.empty()) {
714 LocVT = XLenVT;
715 LocInfo = CCValAssign::Indirect;
716 PendingLocs.push_back(
717 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
718 PendingArgFlags.push_back(ArgFlags);
719 if (!ArgFlags.isSplitEnd()) {
720 return false;
721 }
722 }
723
724 // If the split argument only had two elements, it should be passed directly
725 // in registers or on the stack.
726 if (ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) {
727 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
728 // Apply the normal calling convention rules to the first half of the
729 // split argument.
730 CCValAssign VA = PendingLocs[0];
731 ISD::ArgFlagsTy AF = PendingArgFlags[0];
732 PendingLocs.clear();
733 PendingArgFlags.clear();
734 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
735 ArgFlags);
736 }
737
738 // Allocate to a register if possible, or else a stack slot.
739 unsigned Reg = State.AllocateReg(ArgGPRs);
740 unsigned StackOffset = Reg ? 0 : State.AllocateStack(XLen / 8, XLen / 8);
741
742 // If we reach this point and PendingLocs is non-empty, we must be at the
743 // end of a split argument that must be passed indirectly.
744 if (!PendingLocs.empty()) {
745 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
746 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
747
748 for (auto &It : PendingLocs) {
749 if (Reg)
750 It.convertToReg(Reg);
751 else
752 It.convertToMem(StackOffset);
753 State.addLoc(It);
754 }
755 PendingLocs.clear();
756 PendingArgFlags.clear();
757 return false;
758 }
759
760 assert(LocVT == XLenVT && "Expected an XLenVT at this stage");
761
762 if (Reg) {
763 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
764 } else {
765 State.addLoc(
766 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
767 }
768 return false;
769}
770
771void RISCVTargetLowering::analyzeInputArgs(
772 MachineFunction &MF, CCState &CCInfo,
773 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const {
774 unsigned NumArgs = Ins.size();
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000775 FunctionType *FType = MF.getFunction().getFunctionType();
Alex Bradburydc31c612017-12-11 12:49:02 +0000776
777 for (unsigned i = 0; i != NumArgs; ++i) {
778 MVT ArgVT = Ins[i].VT;
779 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
780
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000781 Type *ArgTy = nullptr;
782 if (IsRet)
783 ArgTy = FType->getReturnType();
784 else if (Ins[i].isOrigArg())
785 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
786
Alex Bradburydc31c612017-12-11 12:49:02 +0000787 if (CC_RISCV(MF.getDataLayout(), i, ArgVT, ArgVT, CCValAssign::Full,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000788 ArgFlags, CCInfo, /*IsRet=*/true, IsRet, ArgTy)) {
Alex Bradburydc31c612017-12-11 12:49:02 +0000789 DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
790 << EVT(ArgVT).getEVTString() << '\n');
791 llvm_unreachable(nullptr);
792 }
793 }
794}
795
796void RISCVTargetLowering::analyzeOutputArgs(
797 MachineFunction &MF, CCState &CCInfo,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000798 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
799 CallLoweringInfo *CLI) const {
Alex Bradburydc31c612017-12-11 12:49:02 +0000800 unsigned NumArgs = Outs.size();
801
802 for (unsigned i = 0; i != NumArgs; i++) {
803 MVT ArgVT = Outs[i].VT;
804 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000805 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
Alex Bradburydc31c612017-12-11 12:49:02 +0000806
807 if (CC_RISCV(MF.getDataLayout(), i, ArgVT, ArgVT, CCValAssign::Full,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000808 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy)) {
Alex Bradburydc31c612017-12-11 12:49:02 +0000809 DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
810 << EVT(ArgVT).getEVTString() << "\n");
811 llvm_unreachable(nullptr);
812 }
813 }
814}
815
816// The caller is responsible for loading the full value if the argument is
817// passed with CCValAssign::Indirect.
818static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
819 const CCValAssign &VA, const SDLoc &DL) {
820 MachineFunction &MF = DAG.getMachineFunction();
821 MachineRegisterInfo &RegInfo = MF.getRegInfo();
822 EVT LocVT = VA.getLocVT();
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000823 EVT ValVT = VA.getValVT();
Alex Bradburydc31c612017-12-11 12:49:02 +0000824 SDValue Val;
825
826 unsigned VReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
827 RegInfo.addLiveIn(VA.getLocReg(), VReg);
828 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
829
830 switch (VA.getLocInfo()) {
831 default:
832 llvm_unreachable("Unexpected CCValAssign::LocInfo");
833 case CCValAssign::Full:
834 case CCValAssign::Indirect:
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000835 break;
836 case CCValAssign::BCvt:
837 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
838 break;
Alex Bradburydc31c612017-12-11 12:49:02 +0000839 }
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000840 return Val;
Alex Bradburydc31c612017-12-11 12:49:02 +0000841}
842
843// The caller is responsible for loading the full value if the argument is
844// passed with CCValAssign::Indirect.
845static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
846 const CCValAssign &VA, const SDLoc &DL) {
847 MachineFunction &MF = DAG.getMachineFunction();
848 MachineFrameInfo &MFI = MF.getFrameInfo();
849 EVT LocVT = VA.getLocVT();
850 EVT ValVT = VA.getValVT();
851 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
852 int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
853 VA.getLocMemOffset(), /*Immutable=*/true);
854 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
855 SDValue Val;
856
857 ISD::LoadExtType ExtType;
858 switch (VA.getLocInfo()) {
859 default:
860 llvm_unreachable("Unexpected CCValAssign::LocInfo");
861 case CCValAssign::Full:
862 case CCValAssign::Indirect:
863 ExtType = ISD::NON_EXTLOAD;
864 break;
865 }
866 Val = DAG.getExtLoad(
867 ExtType, DL, LocVT, Chain, FIN,
868 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
869 return Val;
870}
Alex Bradbury89718422017-10-19 21:37:38 +0000871
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000872static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
873 const CCValAssign &VA, const SDLoc &DL) {
874 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
875 "Unexpected VA");
876 MachineFunction &MF = DAG.getMachineFunction();
877 MachineFrameInfo &MFI = MF.getFrameInfo();
878 MachineRegisterInfo &RegInfo = MF.getRegInfo();
879
880 if (VA.isMemLoc()) {
881 // f64 is passed on the stack.
882 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
883 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
884 return DAG.getLoad(MVT::f64, DL, Chain, FIN,
885 MachinePointerInfo::getFixedStack(MF, FI));
886 }
887
888 assert(VA.isRegLoc() && "Expected register VA assignment");
889
890 unsigned LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
891 RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
892 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
893 SDValue Hi;
894 if (VA.getLocReg() == RISCV::X17) {
895 // Second half of f64 is passed on the stack.
896 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
897 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
898 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
899 MachinePointerInfo::getFixedStack(MF, FI));
900 } else {
901 // Second half of f64 is passed in another GPR.
902 unsigned HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
903 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
904 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
905 }
906 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
907}
908
Alex Bradbury89718422017-10-19 21:37:38 +0000909// Transform physical registers into virtual registers.
910SDValue RISCVTargetLowering::LowerFormalArguments(
911 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
912 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
913 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
914
915 switch (CallConv) {
916 default:
917 report_fatal_error("Unsupported calling convention");
918 case CallingConv::C:
Alex Bradburya3376752017-11-08 13:41:21 +0000919 case CallingConv::Fast:
Alex Bradbury89718422017-10-19 21:37:38 +0000920 break;
921 }
922
923 MachineFunction &MF = DAG.getMachineFunction();
Alex Bradburydc31c612017-12-11 12:49:02 +0000924 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000925 MVT XLenVT = Subtarget.getXLenVT();
926 unsigned XLenInBytes = Subtarget.getXLen() / 8;
927 // Used with vargs to acumulate store chains.
928 std::vector<SDValue> OutChains;
Alex Bradbury89718422017-10-19 21:37:38 +0000929
930 // Assign locations to all of the incoming arguments.
931 SmallVector<CCValAssign, 16> ArgLocs;
932 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
Alex Bradburydc31c612017-12-11 12:49:02 +0000933 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false);
Alex Bradbury89718422017-10-19 21:37:38 +0000934
Alex Bradburydc31c612017-12-11 12:49:02 +0000935 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
936 CCValAssign &VA = ArgLocs[i];
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000937 assert(VA.getLocVT() == XLenVT && "Unhandled argument type");
Alex Bradburydc31c612017-12-11 12:49:02 +0000938 SDValue ArgValue;
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000939 // Passing f64 on RV32D with a soft float ABI must be handled as a special
940 // case.
941 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
942 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
943 else if (VA.isRegLoc())
Alex Bradburydc31c612017-12-11 12:49:02 +0000944 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL);
945 else
946 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
Alex Bradbury89718422017-10-19 21:37:38 +0000947
Alex Bradburydc31c612017-12-11 12:49:02 +0000948 if (VA.getLocInfo() == CCValAssign::Indirect) {
949 // If the original argument was split and passed by reference (e.g. i128
950 // on RV32), we need to load all parts of it here (using the same
951 // address).
952 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
953 MachinePointerInfo()));
954 unsigned ArgIndex = Ins[i].OrigArgIndex;
955 assert(Ins[i].PartOffset == 0);
956 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
957 CCValAssign &PartVA = ArgLocs[i + 1];
958 unsigned PartOffset = Ins[i + 1].PartOffset;
959 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
960 DAG.getIntPtrConstant(PartOffset, DL));
961 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
962 MachinePointerInfo()));
963 ++i;
964 }
965 continue;
Alex Bradbury89718422017-10-19 21:37:38 +0000966 }
Alex Bradburydc31c612017-12-11 12:49:02 +0000967 InVals.push_back(ArgValue);
Alex Bradbury89718422017-10-19 21:37:38 +0000968 }
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000969
970 if (IsVarArg) {
971 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
972 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
973 const TargetRegisterClass *RC = &RISCV::GPRRegClass;
974 MachineFrameInfo &MFI = MF.getFrameInfo();
975 MachineRegisterInfo &RegInfo = MF.getRegInfo();
976 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
977
978 // Offset of the first variable argument from stack pointer, and size of
979 // the vararg save area. For now, the varargs save area is either zero or
980 // large enough to hold a0-a7.
981 int VaArgOffset, VarArgsSaveSize;
982
983 // If all registers are allocated, then all varargs must be passed on the
984 // stack and we don't need to save any argregs.
985 if (ArgRegs.size() == Idx) {
986 VaArgOffset = CCInfo.getNextStackOffset();
987 VarArgsSaveSize = 0;
988 } else {
989 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
990 VaArgOffset = -VarArgsSaveSize;
991 }
992
993 // Record the frame index of the first variable argument
994 // which is a value necessary to VASTART.
995 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
996 RVFI->setVarArgsFrameIndex(FI);
997
998 // If saving an odd number of registers then create an extra stack slot to
999 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
1000 // offsets to even-numbered registered remain 2*XLEN-aligned.
1001 if (Idx % 2) {
1002 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes,
1003 true);
1004 VarArgsSaveSize += XLenInBytes;
1005 }
1006
1007 // Copy the integer registers that may have been used for passing varargs
1008 // to the vararg save area.
1009 for (unsigned I = Idx; I < ArgRegs.size();
1010 ++I, VaArgOffset += XLenInBytes) {
1011 const unsigned Reg = RegInfo.createVirtualRegister(RC);
1012 RegInfo.addLiveIn(ArgRegs[I], Reg);
1013 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
1014 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1015 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1016 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
1017 MachinePointerInfo::getFixedStack(MF, FI));
1018 cast<StoreSDNode>(Store.getNode())
1019 ->getMemOperand()
1020 ->setValue((Value *)nullptr);
1021 OutChains.push_back(Store);
1022 }
1023 RVFI->setVarArgsSaveSize(VarArgsSaveSize);
1024 }
1025
1026 // All stores are grouped in one node to allow the matching between
1027 // the size of Ins and InVals. This only happens for vararg functions.
1028 if (!OutChains.empty()) {
1029 OutChains.push_back(Chain);
1030 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
1031 }
1032
Alex Bradbury89718422017-10-19 21:37:38 +00001033 return Chain;
1034}
1035
Alex Bradburya3376752017-11-08 13:41:21 +00001036// Lower a call to a callseq_start + CALL + callseq_end chain, and add input
1037// and output parameter nodes.
1038SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
1039 SmallVectorImpl<SDValue> &InVals) const {
1040 SelectionDAG &DAG = CLI.DAG;
1041 SDLoc &DL = CLI.DL;
1042 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1043 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1044 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1045 SDValue Chain = CLI.Chain;
1046 SDValue Callee = CLI.Callee;
1047 CLI.IsTailCall = false;
1048 CallingConv::ID CallConv = CLI.CallConv;
1049 bool IsVarArg = CLI.IsVarArg;
1050 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Alex Bradburydc31c612017-12-11 12:49:02 +00001051 MVT XLenVT = Subtarget.getXLenVT();
Alex Bradburya3376752017-11-08 13:41:21 +00001052
Alex Bradburya3376752017-11-08 13:41:21 +00001053 MachineFunction &MF = DAG.getMachineFunction();
1054
1055 // Analyze the operands of the call, assigning locations to each operand.
1056 SmallVector<CCValAssign, 16> ArgLocs;
1057 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001058 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI);
Alex Bradburya3376752017-11-08 13:41:21 +00001059
1060 // Get a count of how many bytes are to be pushed on the stack.
1061 unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1062
Alex Bradburydc31c612017-12-11 12:49:02 +00001063 // Create local copies for byval args
1064 SmallVector<SDValue, 8> ByValArgs;
1065 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1066 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1067 if (!Flags.isByVal())
Alex Bradburya3376752017-11-08 13:41:21 +00001068 continue;
Alex Bradburydc31c612017-12-11 12:49:02 +00001069
1070 SDValue Arg = OutVals[i];
1071 unsigned Size = Flags.getByValSize();
1072 unsigned Align = Flags.getByValAlign();
1073
1074 int FI = MF.getFrameInfo().CreateStackObject(Size, Align, /*isSS=*/false);
1075 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1076 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
1077
1078 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Align,
1079 /*IsVolatile=*/false,
1080 /*AlwaysInline=*/false,
1081 /*isTailCall=*/false, MachinePointerInfo(),
1082 MachinePointerInfo());
1083 ByValArgs.push_back(FIPtr);
Alex Bradburya3376752017-11-08 13:41:21 +00001084 }
1085
1086 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
1087
1088 // Copy argument values to their designated locations.
1089 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
Alex Bradburydc31c612017-12-11 12:49:02 +00001090 SmallVector<SDValue, 8> MemOpChains;
Alex Bradburya3376752017-11-08 13:41:21 +00001091 SDValue StackPtr;
Alex Bradburydc31c612017-12-11 12:49:02 +00001092 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
1093 CCValAssign &VA = ArgLocs[i];
1094 SDValue ArgValue = OutVals[i];
1095 ISD::ArgFlagsTy Flags = Outs[i].Flags;
Alex Bradburya3376752017-11-08 13:41:21 +00001096
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001097 // Handle passing f64 on RV32D with a soft float ABI as a special case.
1098 bool IsF64OnRV32DSoftABI =
1099 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
1100 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
1101 SDValue SplitF64 = DAG.getNode(
1102 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
1103 SDValue Lo = SplitF64.getValue(0);
1104 SDValue Hi = SplitF64.getValue(1);
1105
1106 unsigned RegLo = VA.getLocReg();
1107 RegsToPass.push_back(std::make_pair(RegLo, Lo));
1108
1109 if (RegLo == RISCV::X17) {
1110 // Second half of f64 is passed on the stack.
1111 // Work out the address of the stack slot.
1112 if (!StackPtr.getNode())
1113 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
1114 // Emit the store.
1115 MemOpChains.push_back(
1116 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
1117 } else {
1118 // Second half of f64 is passed in another GPR.
1119 unsigned RegHigh = RegLo + 1;
1120 RegsToPass.push_back(std::make_pair(RegHigh, Hi));
1121 }
1122 continue;
1123 }
1124
1125 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
1126 // as any other MemLoc.
1127
Alex Bradburya3376752017-11-08 13:41:21 +00001128 // Promote the value if needed.
Alex Bradburydc31c612017-12-11 12:49:02 +00001129 // For now, only handle fully promoted and indirect arguments.
Alex Bradburya3376752017-11-08 13:41:21 +00001130 switch (VA.getLocInfo()) {
1131 case CCValAssign::Full:
1132 break;
Alex Bradbury76c29ee2018-03-20 12:45:35 +00001133 case CCValAssign::BCvt:
1134 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), ArgValue);
1135 break;
Alex Bradburydc31c612017-12-11 12:49:02 +00001136 case CCValAssign::Indirect: {
1137 // Store the argument in a stack slot and pass its address.
1138 SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT);
1139 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1140 MemOpChains.push_back(
1141 DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1142 MachinePointerInfo::getFixedStack(MF, FI)));
1143 // If the original argument was split (e.g. i128), we need
1144 // to store all parts of it here (and pass just one address).
1145 unsigned ArgIndex = Outs[i].OrigArgIndex;
1146 assert(Outs[i].PartOffset == 0);
1147 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
1148 SDValue PartValue = OutVals[i + 1];
1149 unsigned PartOffset = Outs[i + 1].PartOffset;
1150 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
1151 DAG.getIntPtrConstant(PartOffset, DL));
1152 MemOpChains.push_back(
1153 DAG.getStore(Chain, DL, PartValue, Address,
1154 MachinePointerInfo::getFixedStack(MF, FI)));
1155 ++i;
1156 }
1157 ArgValue = SpillSlot;
1158 break;
1159 }
Alex Bradburya3376752017-11-08 13:41:21 +00001160 default:
1161 llvm_unreachable("Unknown loc info!");
1162 }
1163
Alex Bradburydc31c612017-12-11 12:49:02 +00001164 // Use local copy if it is a byval arg.
1165 if (Flags.isByVal())
1166 ArgValue = ByValArgs[j++];
1167
Alex Bradburya3376752017-11-08 13:41:21 +00001168 if (VA.isRegLoc()) {
1169 // Queue up the argument copies and emit them at the end.
1170 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1171 } else {
1172 assert(VA.isMemLoc() && "Argument not register or memory");
Alex Bradburydc31c612017-12-11 12:49:02 +00001173
1174 // Work out the address of the stack slot.
1175 if (!StackPtr.getNode())
1176 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
1177 SDValue Address =
1178 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1179 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
1180
1181 // Emit the store.
1182 MemOpChains.push_back(
1183 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
Alex Bradburya3376752017-11-08 13:41:21 +00001184 }
1185 }
1186
Alex Bradburydc31c612017-12-11 12:49:02 +00001187 // Join the stores, which are independent of one another.
1188 if (!MemOpChains.empty())
1189 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1190
Alex Bradburya3376752017-11-08 13:41:21 +00001191 SDValue Glue;
1192
1193 // Build a sequence of copy-to-reg nodes, chained and glued together.
1194 for (auto &Reg : RegsToPass) {
1195 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
1196 Glue = Chain.getValue(1);
1197 }
1198
Shiva Chend58bd8d2018-04-25 14:19:12 +00001199 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
1200 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
1201 // split it and then direct call can be matched by PseudoCALL.
1202 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
1203 Callee = DAG.getTargetGlobalAddress(S->getGlobal(), DL, PtrVT, 0, 0);
1204 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1205 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, 0);
Alex Bradburya3376752017-11-08 13:41:21 +00001206 }
1207
1208 // The first call operand is the chain and the second is the target address.
1209 SmallVector<SDValue, 8> Ops;
1210 Ops.push_back(Chain);
1211 Ops.push_back(Callee);
1212
1213 // Add argument registers to the end of the list so that they are
1214 // known live into the call.
1215 for (auto &Reg : RegsToPass)
1216 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
1217
1218 // Add a register mask operand representing the call-preserved registers.
1219 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1220 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1221 assert(Mask && "Missing call preserved mask for calling convention");
1222 Ops.push_back(DAG.getRegisterMask(Mask));
1223
1224 // Glue the call to the argument copies, if any.
1225 if (Glue.getNode())
1226 Ops.push_back(Glue);
1227
1228 // Emit the call.
1229 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1230 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
1231 Glue = Chain.getValue(1);
1232
1233 // Mark the end of the call, which is glued to the call itself.
1234 Chain = DAG.getCALLSEQ_END(Chain,
1235 DAG.getConstant(NumBytes, DL, PtrVT, true),
1236 DAG.getConstant(0, DL, PtrVT, true),
1237 Glue, DL);
1238 Glue = Chain.getValue(1);
1239
1240 // Assign locations to each value returned by this call.
1241 SmallVector<CCValAssign, 16> RVLocs;
1242 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
Alex Bradburydc31c612017-12-11 12:49:02 +00001243 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true);
Alex Bradburya3376752017-11-08 13:41:21 +00001244
1245 // Copy all of the result registers out of their specified physreg.
1246 for (auto &VA : RVLocs) {
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001247 // Copy the value out
1248 SDValue RetValue =
1249 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
1250 // Glue the RetValue to the end of the call sequence
Alex Bradburya3376752017-11-08 13:41:21 +00001251 Chain = RetValue.getValue(1);
1252 Glue = RetValue.getValue(2);
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001253 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
1254 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
1255 SDValue RetValue2 =
1256 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
1257 Chain = RetValue2.getValue(1);
1258 Glue = RetValue2.getValue(2);
1259 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
1260 RetValue2);
1261 }
Alex Bradburya3376752017-11-08 13:41:21 +00001262
Alex Bradbury76c29ee2018-03-20 12:45:35 +00001263 switch (VA.getLocInfo()) {
1264 default:
1265 llvm_unreachable("Unknown loc info!");
1266 case CCValAssign::Full:
1267 break;
1268 case CCValAssign::BCvt:
1269 RetValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), RetValue);
1270 break;
1271 }
1272
Alex Bradburydc31c612017-12-11 12:49:02 +00001273 InVals.push_back(RetValue);
Alex Bradburya3376752017-11-08 13:41:21 +00001274 }
1275
1276 return Chain;
1277}
1278
Alex Bradburydc31c612017-12-11 12:49:02 +00001279bool RISCVTargetLowering::CanLowerReturn(
1280 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
1281 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
1282 SmallVector<CCValAssign, 16> RVLocs;
1283 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
1284 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1285 MVT VT = Outs[i].VT;
1286 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1287 if (CC_RISCV(MF.getDataLayout(), i, VT, VT, CCValAssign::Full, ArgFlags,
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001288 CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr))
Alex Bradburydc31c612017-12-11 12:49:02 +00001289 return false;
1290 }
1291 return true;
1292}
1293
Alex Bradbury76c29ee2018-03-20 12:45:35 +00001294static SDValue packIntoRegLoc(SelectionDAG &DAG, SDValue Val,
1295 const CCValAssign &VA, const SDLoc &DL) {
1296 EVT LocVT = VA.getLocVT();
1297
1298 switch (VA.getLocInfo()) {
1299 default:
1300 llvm_unreachable("Unexpected CCValAssign::LocInfo");
1301 case CCValAssign::Full:
1302 break;
1303 case CCValAssign::BCvt:
1304 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
1305 break;
1306 }
1307 return Val;
1308}
1309
Alex Bradbury89718422017-10-19 21:37:38 +00001310SDValue
1311RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1312 bool IsVarArg,
1313 const SmallVectorImpl<ISD::OutputArg> &Outs,
1314 const SmallVectorImpl<SDValue> &OutVals,
1315 const SDLoc &DL, SelectionDAG &DAG) const {
Alex Bradbury89718422017-10-19 21:37:38 +00001316 // Stores the assignment of the return value to a location.
1317 SmallVector<CCValAssign, 16> RVLocs;
1318
1319 // Info about the registers and stack slot.
1320 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
1321 *DAG.getContext());
1322
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001323 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
1324 nullptr);
Alex Bradbury89718422017-10-19 21:37:38 +00001325
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001326 SDValue Glue;
Alex Bradbury89718422017-10-19 21:37:38 +00001327 SmallVector<SDValue, 4> RetOps(1, Chain);
1328
1329 // Copy the result values into the output registers.
1330 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
Alex Bradburydc31c612017-12-11 12:49:02 +00001331 SDValue Val = OutVals[i];
Alex Bradbury89718422017-10-19 21:37:38 +00001332 CCValAssign &VA = RVLocs[i];
1333 assert(VA.isRegLoc() && "Can only return in registers!");
1334
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001335 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
1336 // Handle returning f64 on RV32D with a soft float ABI.
1337 assert(VA.isRegLoc() && "Expected return via registers");
1338 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
1339 DAG.getVTList(MVT::i32, MVT::i32), Val);
1340 SDValue Lo = SplitF64.getValue(0);
1341 SDValue Hi = SplitF64.getValue(1);
1342 unsigned RegLo = VA.getLocReg();
1343 unsigned RegHi = RegLo + 1;
1344 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
1345 Glue = Chain.getValue(1);
1346 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
1347 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
1348 Glue = Chain.getValue(1);
1349 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
1350 } else {
1351 // Handle a 'normal' return.
1352 Val = packIntoRegLoc(DAG, Val, VA, DL);
1353 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
Alex Bradbury89718422017-10-19 21:37:38 +00001354
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001355 // Guarantee that all emitted copies are stuck together.
1356 Glue = Chain.getValue(1);
1357 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1358 }
Alex Bradbury89718422017-10-19 21:37:38 +00001359 }
1360
1361 RetOps[0] = Chain; // Update chain.
1362
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001363 // Add the glue node if we have it.
1364 if (Glue.getNode()) {
1365 RetOps.push_back(Glue);
Alex Bradbury89718422017-10-19 21:37:38 +00001366 }
1367
1368 return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps);
1369}
1370
1371const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
1372 switch ((RISCVISD::NodeType)Opcode) {
1373 case RISCVISD::FIRST_NUMBER:
1374 break;
1375 case RISCVISD::RET_FLAG:
1376 return "RISCVISD::RET_FLAG";
Alex Bradburya3376752017-11-08 13:41:21 +00001377 case RISCVISD::CALL:
1378 return "RISCVISD::CALL";
Alex Bradbury65385162017-11-21 07:51:32 +00001379 case RISCVISD::SELECT_CC:
1380 return "RISCVISD::SELECT_CC";
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001381 case RISCVISD::BuildPairF64:
1382 return "RISCVISD::BuildPairF64";
1383 case RISCVISD::SplitF64:
1384 return "RISCVISD::SplitF64";
Alex Bradbury89718422017-10-19 21:37:38 +00001385 }
1386 return nullptr;
1387}
Alex Bradbury9330e642018-01-10 20:05:09 +00001388
1389std::pair<unsigned, const TargetRegisterClass *>
1390RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
1391 StringRef Constraint,
1392 MVT VT) const {
1393 // First, see if this is a constraint that directly corresponds to a
1394 // RISCV register class.
1395 if (Constraint.size() == 1) {
1396 switch (Constraint[0]) {
1397 case 'r':
1398 return std::make_pair(0U, &RISCV::GPRRegClass);
1399 default:
1400 break;
1401 }
1402 }
1403
1404 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1405}