blob: 16b4bddcd5c48f9384513a88f9a440e8ce4ac15a [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 Bradburydcbff632018-04-26 13:15:17 +0000186bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
187 return isInt<12>(Imm);
188}
189
Alex Bradbury5c41ece2018-04-26 13:00:37 +0000190bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
191 return isInt<12>(Imm);
192}
193
Alex Bradbury65385162017-11-21 07:51:32 +0000194// Changes the condition code and swaps operands if necessary, so the SetCC
195// operation matches one of the comparisons supported directly in the RISC-V
196// ISA.
197static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) {
198 switch (CC) {
199 default:
200 break;
201 case ISD::SETGT:
202 case ISD::SETLE:
203 case ISD::SETUGT:
204 case ISD::SETULE:
205 CC = ISD::getSetCCSwappedOperands(CC);
206 std::swap(LHS, RHS);
207 break;
208 }
209}
210
211// Return the RISC-V branch opcode that matches the given DAG integer
212// condition code. The CondCode must be one of those supported by the RISC-V
213// ISA (see normaliseSetCC).
214static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) {
215 switch (CC) {
216 default:
217 llvm_unreachable("Unsupported CondCode");
218 case ISD::SETEQ:
219 return RISCV::BEQ;
220 case ISD::SETNE:
221 return RISCV::BNE;
222 case ISD::SETLT:
223 return RISCV::BLT;
224 case ISD::SETGE:
225 return RISCV::BGE;
226 case ISD::SETULT:
227 return RISCV::BLTU;
228 case ISD::SETUGE:
229 return RISCV::BGEU;
230 }
231}
232
Alex Bradbury89718422017-10-19 21:37:38 +0000233SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
234 SelectionDAG &DAG) const {
235 switch (Op.getOpcode()) {
236 default:
237 report_fatal_error("unimplemented operand");
Alex Bradburyec8aa912017-11-08 13:24:21 +0000238 case ISD::GlobalAddress:
239 return lowerGlobalAddress(Op, DAG);
Alex Bradburyffc435e2017-11-21 08:11:03 +0000240 case ISD::BlockAddress:
241 return lowerBlockAddress(Op, DAG);
Alex Bradbury80c8eb72018-03-20 13:26:12 +0000242 case ISD::ConstantPool:
243 return lowerConstantPool(Op, DAG);
Alex Bradbury65385162017-11-21 07:51:32 +0000244 case ISD::SELECT:
245 return lowerSELECT(Op, DAG);
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000246 case ISD::VASTART:
247 return lowerVASTART(Op, DAG);
Alex Bradbury70f137b2018-01-10 20:12:00 +0000248 case ISD::FRAMEADDR:
249 return LowerFRAMEADDR(Op, DAG);
250 case ISD::RETURNADDR:
251 return LowerRETURNADDR(Op, DAG);
Alex Bradburyec8aa912017-11-08 13:24:21 +0000252 }
253}
254
255SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
256 SelectionDAG &DAG) const {
257 SDLoc DL(Op);
258 EVT Ty = Op.getValueType();
259 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
260 const GlobalValue *GV = N->getGlobal();
261 int64_t Offset = N->getOffset();
262
Alex Bradburyffc435e2017-11-21 08:11:03 +0000263 if (isPositionIndependent() || Subtarget.is64Bit())
Alex Bradburyec8aa912017-11-08 13:24:21 +0000264 report_fatal_error("Unable to lowerGlobalAddress");
Alex Bradburyffc435e2017-11-21 08:11:03 +0000265
266 SDValue GAHi =
267 DAG.getTargetGlobalAddress(GV, DL, Ty, Offset, RISCVII::MO_HI);
268 SDValue GALo =
269 DAG.getTargetGlobalAddress(GV, DL, Ty, Offset, RISCVII::MO_LO);
270 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, GAHi), 0);
271 SDValue MNLo =
272 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, GALo), 0);
273 return MNLo;
274}
275
276SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
277 SelectionDAG &DAG) const {
278 SDLoc DL(Op);
279 EVT Ty = Op.getValueType();
280 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
281 const BlockAddress *BA = N->getBlockAddress();
282 int64_t Offset = N->getOffset();
283
284 if (isPositionIndependent() || Subtarget.is64Bit())
285 report_fatal_error("Unable to lowerBlockAddress");
286
287 SDValue BAHi = DAG.getTargetBlockAddress(BA, Ty, Offset, RISCVII::MO_HI);
288 SDValue BALo = DAG.getTargetBlockAddress(BA, Ty, Offset, RISCVII::MO_LO);
289 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, BAHi), 0);
290 SDValue MNLo =
291 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, BALo), 0);
292 return MNLo;
293}
294
Alex Bradbury80c8eb72018-03-20 13:26:12 +0000295SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
296 SelectionDAG &DAG) const {
297 SDLoc DL(Op);
298 EVT Ty = Op.getValueType();
299 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
300 const Constant *CPA = N->getConstVal();
301 int64_t Offset = N->getOffset();
302 unsigned Alignment = N->getAlignment();
303
304 if (!isPositionIndependent()) {
305 SDValue CPAHi =
306 DAG.getTargetConstantPool(CPA, Ty, Alignment, Offset, RISCVII::MO_HI);
307 SDValue CPALo =
308 DAG.getTargetConstantPool(CPA, Ty, Alignment, Offset, RISCVII::MO_LO);
309 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, CPAHi), 0);
310 SDValue MNLo =
311 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, CPALo), 0);
312 return MNLo;
313 } else {
314 report_fatal_error("Unable to lowerConstantPool");
315 }
316}
317
Alex Bradburyffc435e2017-11-21 08:11:03 +0000318SDValue RISCVTargetLowering::lowerExternalSymbol(SDValue Op,
319 SelectionDAG &DAG) const {
320 SDLoc DL(Op);
321 EVT Ty = Op.getValueType();
322 ExternalSymbolSDNode *N = cast<ExternalSymbolSDNode>(Op);
323 const char *Sym = N->getSymbol();
324
325 // TODO: should also handle gp-relative loads.
326
327 if (isPositionIndependent() || Subtarget.is64Bit())
328 report_fatal_error("Unable to lowerExternalSymbol");
329
330 SDValue GAHi = DAG.getTargetExternalSymbol(Sym, Ty, RISCVII::MO_HI);
331 SDValue GALo = DAG.getTargetExternalSymbol(Sym, Ty, RISCVII::MO_LO);
332 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, GAHi), 0);
333 SDValue MNLo =
334 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, GALo), 0);
335 return MNLo;
Alex Bradbury89718422017-10-19 21:37:38 +0000336}
337
Alex Bradbury65385162017-11-21 07:51:32 +0000338SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
339 SDValue CondV = Op.getOperand(0);
340 SDValue TrueV = Op.getOperand(1);
341 SDValue FalseV = Op.getOperand(2);
342 SDLoc DL(Op);
343 MVT XLenVT = Subtarget.getXLenVT();
344
345 // If the result type is XLenVT and CondV is the output of a SETCC node
346 // which also operated on XLenVT inputs, then merge the SETCC node into the
347 // lowered RISCVISD::SELECT_CC to take advantage of the integer
348 // compare+branch instructions. i.e.:
349 // (select (setcc lhs, rhs, cc), truev, falsev)
350 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
351 if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC &&
352 CondV.getOperand(0).getSimpleValueType() == XLenVT) {
353 SDValue LHS = CondV.getOperand(0);
354 SDValue RHS = CondV.getOperand(1);
355 auto CC = cast<CondCodeSDNode>(CondV.getOperand(2));
356 ISD::CondCode CCVal = CC->get();
357
358 normaliseSetCC(LHS, RHS, CCVal);
359
360 SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT);
361 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
362 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
363 return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
364 }
365
366 // Otherwise:
367 // (select condv, truev, falsev)
368 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
369 SDValue Zero = DAG.getConstant(0, DL, XLenVT);
370 SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT);
371
372 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
373 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
374
375 return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
376}
377
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000378SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
379 MachineFunction &MF = DAG.getMachineFunction();
380 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
381
382 SDLoc DL(Op);
383 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
384 getPointerTy(MF.getDataLayout()));
385
386 // vastart just stores the address of the VarArgsFrameIndex slot into the
387 // memory location argument.
388 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
389 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
390 MachinePointerInfo(SV));
391}
392
Alex Bradbury70f137b2018-01-10 20:12:00 +0000393SDValue RISCVTargetLowering::LowerFRAMEADDR(SDValue Op,
394 SelectionDAG &DAG) const {
395 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
396 MachineFunction &MF = DAG.getMachineFunction();
397 MachineFrameInfo &MFI = MF.getFrameInfo();
398 MFI.setFrameAddressIsTaken(true);
399 unsigned FrameReg = RI.getFrameRegister(MF);
400 int XLenInBytes = Subtarget.getXLen() / 8;
401
402 EVT VT = Op.getValueType();
403 SDLoc DL(Op);
404 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
405 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
406 while (Depth--) {
407 int Offset = -(XLenInBytes * 2);
408 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
409 DAG.getIntPtrConstant(Offset, DL));
410 FrameAddr =
411 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
412 }
413 return FrameAddr;
414}
415
416SDValue RISCVTargetLowering::LowerRETURNADDR(SDValue Op,
417 SelectionDAG &DAG) const {
418 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
419 MachineFunction &MF = DAG.getMachineFunction();
420 MachineFrameInfo &MFI = MF.getFrameInfo();
421 MFI.setReturnAddressIsTaken(true);
422 MVT XLenVT = Subtarget.getXLenVT();
423 int XLenInBytes = Subtarget.getXLen() / 8;
424
425 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
426 return SDValue();
427
428 EVT VT = Op.getValueType();
429 SDLoc DL(Op);
430 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
431 if (Depth) {
432 int Off = -XLenInBytes;
433 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
434 SDValue Offset = DAG.getConstant(Off, DL, VT);
435 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
436 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
437 MachinePointerInfo());
438 }
439
440 // Return the value of the return address register, marking it an implicit
441 // live-in.
442 unsigned Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
443 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
444}
445
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000446static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
447 MachineBasicBlock *BB) {
448 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
449
450 MachineFunction &MF = *BB->getParent();
451 DebugLoc DL = MI.getDebugLoc();
452 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
453 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
454 unsigned LoReg = MI.getOperand(0).getReg();
455 unsigned HiReg = MI.getOperand(1).getReg();
456 unsigned SrcReg = MI.getOperand(2).getReg();
457 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
458 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
459
460 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
461 RI);
462 MachineMemOperand *MMO =
463 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
464 MachineMemOperand::MOLoad, 8, 8);
465 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
466 .addFrameIndex(FI)
467 .addImm(0)
468 .addMemOperand(MMO);
469 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
470 .addFrameIndex(FI)
471 .addImm(4)
472 .addMemOperand(MMO);
473 MI.eraseFromParent(); // The pseudo instruction is gone now.
474 return BB;
475}
476
477static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
478 MachineBasicBlock *BB) {
479 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
480 "Unexpected instruction");
481
482 MachineFunction &MF = *BB->getParent();
483 DebugLoc DL = MI.getDebugLoc();
484 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
485 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
486 unsigned DstReg = MI.getOperand(0).getReg();
487 unsigned LoReg = MI.getOperand(1).getReg();
488 unsigned HiReg = MI.getOperand(2).getReg();
489 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
490 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
491
492 MachineMemOperand *MMO =
493 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
494 MachineMemOperand::MOStore, 8, 8);
495 BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
496 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
497 .addFrameIndex(FI)
498 .addImm(0)
499 .addMemOperand(MMO);
500 BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
501 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
502 .addFrameIndex(FI)
503 .addImm(4)
504 .addMemOperand(MMO);
505 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
506 MI.eraseFromParent(); // The pseudo instruction is gone now.
507 return BB;
508}
509
Alex Bradbury65385162017-11-21 07:51:32 +0000510MachineBasicBlock *
511RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
512 MachineBasicBlock *BB) const {
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000513 switch (MI.getOpcode()) {
514 default:
515 llvm_unreachable("Unexpected instr type to insert");
516 case RISCV::Select_GPR_Using_CC_GPR:
517 case RISCV::Select_FPR32_Using_CC_GPR:
Alex Bradbury21d28fe2018-04-12 05:50:06 +0000518 case RISCV::Select_FPR64_Using_CC_GPR:
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000519 break;
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000520 case RISCV::BuildPairF64Pseudo:
521 return emitBuildPairF64Pseudo(MI, BB);
522 case RISCV::SplitF64Pseudo:
523 return emitSplitF64Pseudo(MI, BB);
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000524 }
Alex Bradbury65385162017-11-21 07:51:32 +0000525
526 // To "insert" a SELECT instruction, we actually have to insert the triangle
527 // control-flow pattern. The incoming instruction knows the destination vreg
528 // to set, the condition code register to branch on, the true/false values to
529 // select between, and the condcode to use to select the appropriate branch.
530 //
531 // We produce the following control flow:
532 // HeadMBB
533 // | \
534 // | IfFalseMBB
535 // | /
536 // TailMBB
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000537 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
Alex Bradbury65385162017-11-21 07:51:32 +0000538 const BasicBlock *LLVM_BB = BB->getBasicBlock();
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000539 DebugLoc DL = MI.getDebugLoc();
Alex Bradbury65385162017-11-21 07:51:32 +0000540 MachineFunction::iterator I = ++BB->getIterator();
541
542 MachineBasicBlock *HeadMBB = BB;
543 MachineFunction *F = BB->getParent();
544 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
545 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
546
547 F->insert(I, IfFalseMBB);
548 F->insert(I, TailMBB);
549 // Move all remaining instructions to TailMBB.
550 TailMBB->splice(TailMBB->begin(), HeadMBB,
551 std::next(MachineBasicBlock::iterator(MI)), HeadMBB->end());
552 // Update machine-CFG edges by transferring all successors of the current
553 // block to the new block which will contain the Phi node for the select.
554 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
555 // Set the successors for HeadMBB.
556 HeadMBB->addSuccessor(IfFalseMBB);
557 HeadMBB->addSuccessor(TailMBB);
558
559 // Insert appropriate branch.
560 unsigned LHS = MI.getOperand(1).getReg();
561 unsigned RHS = MI.getOperand(2).getReg();
562 auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm());
563 unsigned Opcode = getBranchOpcodeForIntCondCode(CC);
564
565 BuildMI(HeadMBB, DL, TII.get(Opcode))
566 .addReg(LHS)
567 .addReg(RHS)
568 .addMBB(TailMBB);
569
570 // IfFalseMBB just falls through to TailMBB.
571 IfFalseMBB->addSuccessor(TailMBB);
572
573 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
574 BuildMI(*TailMBB, TailMBB->begin(), DL, TII.get(RISCV::PHI),
575 MI.getOperand(0).getReg())
576 .addReg(MI.getOperand(4).getReg())
577 .addMBB(HeadMBB)
578 .addReg(MI.getOperand(5).getReg())
579 .addMBB(IfFalseMBB);
580
581 MI.eraseFromParent(); // The pseudo instruction is gone now.
582 return TailMBB;
583}
584
Alex Bradbury89718422017-10-19 21:37:38 +0000585// Calling Convention Implementation.
Alex Bradburydc31c612017-12-11 12:49:02 +0000586// The expectations for frontend ABI lowering vary from target to target.
587// Ideally, an LLVM frontend would be able to avoid worrying about many ABI
588// details, but this is a longer term goal. For now, we simply try to keep the
589// role of the frontend as simple and well-defined as possible. The rules can
590// be summarised as:
591// * Never split up large scalar arguments. We handle them here.
592// * If a hardfloat calling convention is being used, and the struct may be
593// passed in a pair of registers (fp+fp, int+fp), and both registers are
594// available, then pass as two separate arguments. If either the GPRs or FPRs
595// are exhausted, then pass according to the rule below.
596// * If a struct could never be passed in registers or directly in a stack
597// slot (as it is larger than 2*XLEN and the floating point rules don't
598// apply), then pass it using a pointer with the byval attribute.
599// * If a struct is less than 2*XLEN, then coerce to either a two-element
600// word-sized array or a 2*XLEN scalar (depending on alignment).
601// * The frontend can determine whether a struct is returned by reference or
602// not based on its size and fields. If it will be returned by reference, the
603// frontend must modify the prototype so a pointer with the sret annotation is
604// passed as the first argument. This is not necessary for large scalar
605// returns.
606// * Struct return values and varargs should be coerced to structs containing
607// register-size fields in the same situations they would be for fixed
608// arguments.
609
610static const MCPhysReg ArgGPRs[] = {
611 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
612 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
613};
614
615// Pass a 2*XLEN argument that has been split into two XLEN values through
616// registers or the stack as necessary.
617static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
618 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
619 MVT ValVT2, MVT LocVT2,
620 ISD::ArgFlagsTy ArgFlags2) {
621 unsigned XLenInBytes = XLen / 8;
622 if (unsigned Reg = State.AllocateReg(ArgGPRs)) {
623 // At least one half can be passed via register.
624 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
625 VA1.getLocVT(), CCValAssign::Full));
626 } else {
627 // Both halves must be passed on the stack, with proper alignment.
628 unsigned StackAlign = std::max(XLenInBytes, ArgFlags1.getOrigAlign());
629 State.addLoc(
630 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
631 State.AllocateStack(XLenInBytes, StackAlign),
632 VA1.getLocVT(), CCValAssign::Full));
633 State.addLoc(CCValAssign::getMem(
634 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
635 CCValAssign::Full));
636 return false;
637 }
638
639 if (unsigned Reg = State.AllocateReg(ArgGPRs)) {
640 // The second half can also be passed via register.
641 State.addLoc(
642 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
643 } else {
644 // The second half is passed via the stack, without additional alignment.
645 State.addLoc(CCValAssign::getMem(
646 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
647 CCValAssign::Full));
648 }
649
650 return false;
651}
652
653// Implements the RISC-V calling convention. Returns true upon failure.
654static bool CC_RISCV(const DataLayout &DL, unsigned ValNo, MVT ValVT, MVT LocVT,
655 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000656 CCState &State, bool IsFixed, bool IsRet, Type *OrigTy) {
Alex Bradburydc31c612017-12-11 12:49:02 +0000657 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
658 assert(XLen == 32 || XLen == 64);
659 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000660 if (ValVT == MVT::f32) {
661 LocVT = MVT::i32;
662 LocInfo = CCValAssign::BCvt;
663 }
Alex Bradburydc31c612017-12-11 12:49:02 +0000664
665 // Any return value split in to more than two values can't be returned
666 // directly.
667 if (IsRet && ValNo > 1)
668 return true;
669
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000670 // If this is a variadic argument, the RISC-V calling convention requires
671 // that it is assigned an 'even' or 'aligned' register if it has 8-byte
672 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
673 // be used regardless of whether the original argument was split during
674 // legalisation or not. The argument will not be passed by registers if the
675 // original type is larger than 2*XLEN, so the register alignment rule does
676 // not apply.
677 unsigned TwoXLenInBytes = (2 * XLen) / 8;
678 if (!IsFixed && ArgFlags.getOrigAlign() == TwoXLenInBytes &&
679 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
680 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
681 // Skip 'odd' register if necessary.
682 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
683 State.AllocateReg(ArgGPRs);
684 }
685
Alex Bradburydc31c612017-12-11 12:49:02 +0000686 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
687 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
688 State.getPendingArgFlags();
689
690 assert(PendingLocs.size() == PendingArgFlags.size() &&
691 "PendingLocs and PendingArgFlags out of sync");
692
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000693 // Handle passing f64 on RV32D with a soft float ABI.
694 if (XLen == 32 && ValVT == MVT::f64) {
Mandeep Singh Grang88a8b262018-04-16 18:56:10 +0000695 assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000696 "Can't lower f64 if it is split");
697 // Depending on available argument GPRS, f64 may be passed in a pair of
698 // GPRs, split between a GPR and the stack, or passed completely on the
699 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
700 // cases.
701 unsigned Reg = State.AllocateReg(ArgGPRs);
702 LocVT = MVT::i32;
703 if (!Reg) {
704 unsigned StackOffset = State.AllocateStack(8, 8);
705 State.addLoc(
706 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
707 return false;
708 }
709 if (!State.AllocateReg(ArgGPRs))
710 State.AllocateStack(4, 4);
711 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
712 return false;
713 }
714
Alex Bradburydc31c612017-12-11 12:49:02 +0000715 // Split arguments might be passed indirectly, so keep track of the pending
716 // values.
717 if (ArgFlags.isSplit() || !PendingLocs.empty()) {
718 LocVT = XLenVT;
719 LocInfo = CCValAssign::Indirect;
720 PendingLocs.push_back(
721 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
722 PendingArgFlags.push_back(ArgFlags);
723 if (!ArgFlags.isSplitEnd()) {
724 return false;
725 }
726 }
727
728 // If the split argument only had two elements, it should be passed directly
729 // in registers or on the stack.
730 if (ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) {
731 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
732 // Apply the normal calling convention rules to the first half of the
733 // split argument.
734 CCValAssign VA = PendingLocs[0];
735 ISD::ArgFlagsTy AF = PendingArgFlags[0];
736 PendingLocs.clear();
737 PendingArgFlags.clear();
738 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
739 ArgFlags);
740 }
741
742 // Allocate to a register if possible, or else a stack slot.
743 unsigned Reg = State.AllocateReg(ArgGPRs);
744 unsigned StackOffset = Reg ? 0 : State.AllocateStack(XLen / 8, XLen / 8);
745
746 // If we reach this point and PendingLocs is non-empty, we must be at the
747 // end of a split argument that must be passed indirectly.
748 if (!PendingLocs.empty()) {
749 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
750 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
751
752 for (auto &It : PendingLocs) {
753 if (Reg)
754 It.convertToReg(Reg);
755 else
756 It.convertToMem(StackOffset);
757 State.addLoc(It);
758 }
759 PendingLocs.clear();
760 PendingArgFlags.clear();
761 return false;
762 }
763
764 assert(LocVT == XLenVT && "Expected an XLenVT at this stage");
765
766 if (Reg) {
767 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
768 } else {
769 State.addLoc(
770 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
771 }
772 return false;
773}
774
775void RISCVTargetLowering::analyzeInputArgs(
776 MachineFunction &MF, CCState &CCInfo,
777 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const {
778 unsigned NumArgs = Ins.size();
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000779 FunctionType *FType = MF.getFunction().getFunctionType();
Alex Bradburydc31c612017-12-11 12:49:02 +0000780
781 for (unsigned i = 0; i != NumArgs; ++i) {
782 MVT ArgVT = Ins[i].VT;
783 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
784
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000785 Type *ArgTy = nullptr;
786 if (IsRet)
787 ArgTy = FType->getReturnType();
788 else if (Ins[i].isOrigArg())
789 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
790
Alex Bradburydc31c612017-12-11 12:49:02 +0000791 if (CC_RISCV(MF.getDataLayout(), i, ArgVT, ArgVT, CCValAssign::Full,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000792 ArgFlags, CCInfo, /*IsRet=*/true, IsRet, ArgTy)) {
Alex Bradburydc31c612017-12-11 12:49:02 +0000793 DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
794 << EVT(ArgVT).getEVTString() << '\n');
795 llvm_unreachable(nullptr);
796 }
797 }
798}
799
800void RISCVTargetLowering::analyzeOutputArgs(
801 MachineFunction &MF, CCState &CCInfo,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000802 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
803 CallLoweringInfo *CLI) const {
Alex Bradburydc31c612017-12-11 12:49:02 +0000804 unsigned NumArgs = Outs.size();
805
806 for (unsigned i = 0; i != NumArgs; i++) {
807 MVT ArgVT = Outs[i].VT;
808 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000809 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
Alex Bradburydc31c612017-12-11 12:49:02 +0000810
811 if (CC_RISCV(MF.getDataLayout(), i, ArgVT, ArgVT, CCValAssign::Full,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000812 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy)) {
Alex Bradburydc31c612017-12-11 12:49:02 +0000813 DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
814 << EVT(ArgVT).getEVTString() << "\n");
815 llvm_unreachable(nullptr);
816 }
817 }
818}
819
820// The caller is responsible for loading the full value if the argument is
821// passed with CCValAssign::Indirect.
822static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
823 const CCValAssign &VA, const SDLoc &DL) {
824 MachineFunction &MF = DAG.getMachineFunction();
825 MachineRegisterInfo &RegInfo = MF.getRegInfo();
826 EVT LocVT = VA.getLocVT();
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000827 EVT ValVT = VA.getValVT();
Alex Bradburydc31c612017-12-11 12:49:02 +0000828 SDValue Val;
829
830 unsigned VReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
831 RegInfo.addLiveIn(VA.getLocReg(), VReg);
832 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
833
834 switch (VA.getLocInfo()) {
835 default:
836 llvm_unreachable("Unexpected CCValAssign::LocInfo");
837 case CCValAssign::Full:
838 case CCValAssign::Indirect:
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000839 break;
840 case CCValAssign::BCvt:
841 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
842 break;
Alex Bradburydc31c612017-12-11 12:49:02 +0000843 }
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000844 return Val;
Alex Bradburydc31c612017-12-11 12:49:02 +0000845}
846
847// The caller is responsible for loading the full value if the argument is
848// passed with CCValAssign::Indirect.
849static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
850 const CCValAssign &VA, const SDLoc &DL) {
851 MachineFunction &MF = DAG.getMachineFunction();
852 MachineFrameInfo &MFI = MF.getFrameInfo();
853 EVT LocVT = VA.getLocVT();
854 EVT ValVT = VA.getValVT();
855 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
856 int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
857 VA.getLocMemOffset(), /*Immutable=*/true);
858 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
859 SDValue Val;
860
861 ISD::LoadExtType ExtType;
862 switch (VA.getLocInfo()) {
863 default:
864 llvm_unreachable("Unexpected CCValAssign::LocInfo");
865 case CCValAssign::Full:
866 case CCValAssign::Indirect:
867 ExtType = ISD::NON_EXTLOAD;
868 break;
869 }
870 Val = DAG.getExtLoad(
871 ExtType, DL, LocVT, Chain, FIN,
872 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
873 return Val;
874}
Alex Bradbury89718422017-10-19 21:37:38 +0000875
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000876static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
877 const CCValAssign &VA, const SDLoc &DL) {
878 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
879 "Unexpected VA");
880 MachineFunction &MF = DAG.getMachineFunction();
881 MachineFrameInfo &MFI = MF.getFrameInfo();
882 MachineRegisterInfo &RegInfo = MF.getRegInfo();
883
884 if (VA.isMemLoc()) {
885 // f64 is passed on the stack.
886 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
887 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
888 return DAG.getLoad(MVT::f64, DL, Chain, FIN,
889 MachinePointerInfo::getFixedStack(MF, FI));
890 }
891
892 assert(VA.isRegLoc() && "Expected register VA assignment");
893
894 unsigned LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
895 RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
896 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
897 SDValue Hi;
898 if (VA.getLocReg() == RISCV::X17) {
899 // Second half of f64 is passed on the stack.
900 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
901 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
902 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
903 MachinePointerInfo::getFixedStack(MF, FI));
904 } else {
905 // Second half of f64 is passed in another GPR.
906 unsigned HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
907 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
908 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
909 }
910 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
911}
912
Alex Bradbury89718422017-10-19 21:37:38 +0000913// Transform physical registers into virtual registers.
914SDValue RISCVTargetLowering::LowerFormalArguments(
915 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
916 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
917 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
918
919 switch (CallConv) {
920 default:
921 report_fatal_error("Unsupported calling convention");
922 case CallingConv::C:
Alex Bradburya3376752017-11-08 13:41:21 +0000923 case CallingConv::Fast:
Alex Bradbury89718422017-10-19 21:37:38 +0000924 break;
925 }
926
927 MachineFunction &MF = DAG.getMachineFunction();
Alex Bradburydc31c612017-12-11 12:49:02 +0000928 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000929 MVT XLenVT = Subtarget.getXLenVT();
930 unsigned XLenInBytes = Subtarget.getXLen() / 8;
931 // Used with vargs to acumulate store chains.
932 std::vector<SDValue> OutChains;
Alex Bradbury89718422017-10-19 21:37:38 +0000933
934 // Assign locations to all of the incoming arguments.
935 SmallVector<CCValAssign, 16> ArgLocs;
936 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
Alex Bradburydc31c612017-12-11 12:49:02 +0000937 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false);
Alex Bradbury89718422017-10-19 21:37:38 +0000938
Alex Bradburydc31c612017-12-11 12:49:02 +0000939 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
940 CCValAssign &VA = ArgLocs[i];
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000941 assert(VA.getLocVT() == XLenVT && "Unhandled argument type");
Alex Bradburydc31c612017-12-11 12:49:02 +0000942 SDValue ArgValue;
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000943 // Passing f64 on RV32D with a soft float ABI must be handled as a special
944 // case.
945 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
946 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
947 else if (VA.isRegLoc())
Alex Bradburydc31c612017-12-11 12:49:02 +0000948 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL);
949 else
950 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
Alex Bradbury89718422017-10-19 21:37:38 +0000951
Alex Bradburydc31c612017-12-11 12:49:02 +0000952 if (VA.getLocInfo() == CCValAssign::Indirect) {
953 // If the original argument was split and passed by reference (e.g. i128
954 // on RV32), we need to load all parts of it here (using the same
955 // address).
956 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
957 MachinePointerInfo()));
958 unsigned ArgIndex = Ins[i].OrigArgIndex;
959 assert(Ins[i].PartOffset == 0);
960 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
961 CCValAssign &PartVA = ArgLocs[i + 1];
962 unsigned PartOffset = Ins[i + 1].PartOffset;
963 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
964 DAG.getIntPtrConstant(PartOffset, DL));
965 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
966 MachinePointerInfo()));
967 ++i;
968 }
969 continue;
Alex Bradbury89718422017-10-19 21:37:38 +0000970 }
Alex Bradburydc31c612017-12-11 12:49:02 +0000971 InVals.push_back(ArgValue);
Alex Bradbury89718422017-10-19 21:37:38 +0000972 }
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000973
974 if (IsVarArg) {
975 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
976 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
977 const TargetRegisterClass *RC = &RISCV::GPRRegClass;
978 MachineFrameInfo &MFI = MF.getFrameInfo();
979 MachineRegisterInfo &RegInfo = MF.getRegInfo();
980 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
981
982 // Offset of the first variable argument from stack pointer, and size of
983 // the vararg save area. For now, the varargs save area is either zero or
984 // large enough to hold a0-a7.
985 int VaArgOffset, VarArgsSaveSize;
986
987 // If all registers are allocated, then all varargs must be passed on the
988 // stack and we don't need to save any argregs.
989 if (ArgRegs.size() == Idx) {
990 VaArgOffset = CCInfo.getNextStackOffset();
991 VarArgsSaveSize = 0;
992 } else {
993 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
994 VaArgOffset = -VarArgsSaveSize;
995 }
996
997 // Record the frame index of the first variable argument
998 // which is a value necessary to VASTART.
999 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1000 RVFI->setVarArgsFrameIndex(FI);
1001
1002 // If saving an odd number of registers then create an extra stack slot to
1003 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
1004 // offsets to even-numbered registered remain 2*XLEN-aligned.
1005 if (Idx % 2) {
1006 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes,
1007 true);
1008 VarArgsSaveSize += XLenInBytes;
1009 }
1010
1011 // Copy the integer registers that may have been used for passing varargs
1012 // to the vararg save area.
1013 for (unsigned I = Idx; I < ArgRegs.size();
1014 ++I, VaArgOffset += XLenInBytes) {
1015 const unsigned Reg = RegInfo.createVirtualRegister(RC);
1016 RegInfo.addLiveIn(ArgRegs[I], Reg);
1017 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
1018 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1019 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1020 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
1021 MachinePointerInfo::getFixedStack(MF, FI));
1022 cast<StoreSDNode>(Store.getNode())
1023 ->getMemOperand()
1024 ->setValue((Value *)nullptr);
1025 OutChains.push_back(Store);
1026 }
1027 RVFI->setVarArgsSaveSize(VarArgsSaveSize);
1028 }
1029
1030 // All stores are grouped in one node to allow the matching between
1031 // the size of Ins and InVals. This only happens for vararg functions.
1032 if (!OutChains.empty()) {
1033 OutChains.push_back(Chain);
1034 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
1035 }
1036
Alex Bradbury89718422017-10-19 21:37:38 +00001037 return Chain;
1038}
1039
Alex Bradburya3376752017-11-08 13:41:21 +00001040// Lower a call to a callseq_start + CALL + callseq_end chain, and add input
1041// and output parameter nodes.
1042SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
1043 SmallVectorImpl<SDValue> &InVals) const {
1044 SelectionDAG &DAG = CLI.DAG;
1045 SDLoc &DL = CLI.DL;
1046 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1047 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1048 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1049 SDValue Chain = CLI.Chain;
1050 SDValue Callee = CLI.Callee;
1051 CLI.IsTailCall = false;
1052 CallingConv::ID CallConv = CLI.CallConv;
1053 bool IsVarArg = CLI.IsVarArg;
1054 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Alex Bradburydc31c612017-12-11 12:49:02 +00001055 MVT XLenVT = Subtarget.getXLenVT();
Alex Bradburya3376752017-11-08 13:41:21 +00001056
Alex Bradburya3376752017-11-08 13:41:21 +00001057 MachineFunction &MF = DAG.getMachineFunction();
1058
1059 // Analyze the operands of the call, assigning locations to each operand.
1060 SmallVector<CCValAssign, 16> ArgLocs;
1061 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001062 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI);
Alex Bradburya3376752017-11-08 13:41:21 +00001063
1064 // Get a count of how many bytes are to be pushed on the stack.
1065 unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1066
Alex Bradburydc31c612017-12-11 12:49:02 +00001067 // Create local copies for byval args
1068 SmallVector<SDValue, 8> ByValArgs;
1069 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1070 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1071 if (!Flags.isByVal())
Alex Bradburya3376752017-11-08 13:41:21 +00001072 continue;
Alex Bradburydc31c612017-12-11 12:49:02 +00001073
1074 SDValue Arg = OutVals[i];
1075 unsigned Size = Flags.getByValSize();
1076 unsigned Align = Flags.getByValAlign();
1077
1078 int FI = MF.getFrameInfo().CreateStackObject(Size, Align, /*isSS=*/false);
1079 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1080 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
1081
1082 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Align,
1083 /*IsVolatile=*/false,
1084 /*AlwaysInline=*/false,
1085 /*isTailCall=*/false, MachinePointerInfo(),
1086 MachinePointerInfo());
1087 ByValArgs.push_back(FIPtr);
Alex Bradburya3376752017-11-08 13:41:21 +00001088 }
1089
1090 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
1091
1092 // Copy argument values to their designated locations.
1093 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
Alex Bradburydc31c612017-12-11 12:49:02 +00001094 SmallVector<SDValue, 8> MemOpChains;
Alex Bradburya3376752017-11-08 13:41:21 +00001095 SDValue StackPtr;
Alex Bradburydc31c612017-12-11 12:49:02 +00001096 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
1097 CCValAssign &VA = ArgLocs[i];
1098 SDValue ArgValue = OutVals[i];
1099 ISD::ArgFlagsTy Flags = Outs[i].Flags;
Alex Bradburya3376752017-11-08 13:41:21 +00001100
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001101 // Handle passing f64 on RV32D with a soft float ABI as a special case.
1102 bool IsF64OnRV32DSoftABI =
1103 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
1104 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
1105 SDValue SplitF64 = DAG.getNode(
1106 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
1107 SDValue Lo = SplitF64.getValue(0);
1108 SDValue Hi = SplitF64.getValue(1);
1109
1110 unsigned RegLo = VA.getLocReg();
1111 RegsToPass.push_back(std::make_pair(RegLo, Lo));
1112
1113 if (RegLo == RISCV::X17) {
1114 // Second half of f64 is passed on the stack.
1115 // Work out the address of the stack slot.
1116 if (!StackPtr.getNode())
1117 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
1118 // Emit the store.
1119 MemOpChains.push_back(
1120 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
1121 } else {
1122 // Second half of f64 is passed in another GPR.
1123 unsigned RegHigh = RegLo + 1;
1124 RegsToPass.push_back(std::make_pair(RegHigh, Hi));
1125 }
1126 continue;
1127 }
1128
1129 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
1130 // as any other MemLoc.
1131
Alex Bradburya3376752017-11-08 13:41:21 +00001132 // Promote the value if needed.
Alex Bradburydc31c612017-12-11 12:49:02 +00001133 // For now, only handle fully promoted and indirect arguments.
Alex Bradburya3376752017-11-08 13:41:21 +00001134 switch (VA.getLocInfo()) {
1135 case CCValAssign::Full:
1136 break;
Alex Bradbury76c29ee2018-03-20 12:45:35 +00001137 case CCValAssign::BCvt:
1138 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), ArgValue);
1139 break;
Alex Bradburydc31c612017-12-11 12:49:02 +00001140 case CCValAssign::Indirect: {
1141 // Store the argument in a stack slot and pass its address.
1142 SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT);
1143 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1144 MemOpChains.push_back(
1145 DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1146 MachinePointerInfo::getFixedStack(MF, FI)));
1147 // If the original argument was split (e.g. i128), we need
1148 // to store all parts of it here (and pass just one address).
1149 unsigned ArgIndex = Outs[i].OrigArgIndex;
1150 assert(Outs[i].PartOffset == 0);
1151 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
1152 SDValue PartValue = OutVals[i + 1];
1153 unsigned PartOffset = Outs[i + 1].PartOffset;
1154 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
1155 DAG.getIntPtrConstant(PartOffset, DL));
1156 MemOpChains.push_back(
1157 DAG.getStore(Chain, DL, PartValue, Address,
1158 MachinePointerInfo::getFixedStack(MF, FI)));
1159 ++i;
1160 }
1161 ArgValue = SpillSlot;
1162 break;
1163 }
Alex Bradburya3376752017-11-08 13:41:21 +00001164 default:
1165 llvm_unreachable("Unknown loc info!");
1166 }
1167
Alex Bradburydc31c612017-12-11 12:49:02 +00001168 // Use local copy if it is a byval arg.
1169 if (Flags.isByVal())
1170 ArgValue = ByValArgs[j++];
1171
Alex Bradburya3376752017-11-08 13:41:21 +00001172 if (VA.isRegLoc()) {
1173 // Queue up the argument copies and emit them at the end.
1174 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1175 } else {
1176 assert(VA.isMemLoc() && "Argument not register or memory");
Alex Bradburydc31c612017-12-11 12:49:02 +00001177
1178 // Work out the address of the stack slot.
1179 if (!StackPtr.getNode())
1180 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
1181 SDValue Address =
1182 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1183 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
1184
1185 // Emit the store.
1186 MemOpChains.push_back(
1187 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
Alex Bradburya3376752017-11-08 13:41:21 +00001188 }
1189 }
1190
Alex Bradburydc31c612017-12-11 12:49:02 +00001191 // Join the stores, which are independent of one another.
1192 if (!MemOpChains.empty())
1193 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1194
Alex Bradburya3376752017-11-08 13:41:21 +00001195 SDValue Glue;
1196
1197 // Build a sequence of copy-to-reg nodes, chained and glued together.
1198 for (auto &Reg : RegsToPass) {
1199 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
1200 Glue = Chain.getValue(1);
1201 }
1202
Shiva Chend58bd8d2018-04-25 14:19:12 +00001203 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
1204 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
1205 // split it and then direct call can be matched by PseudoCALL.
1206 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
1207 Callee = DAG.getTargetGlobalAddress(S->getGlobal(), DL, PtrVT, 0, 0);
1208 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1209 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, 0);
Alex Bradburya3376752017-11-08 13:41:21 +00001210 }
1211
1212 // The first call operand is the chain and the second is the target address.
1213 SmallVector<SDValue, 8> Ops;
1214 Ops.push_back(Chain);
1215 Ops.push_back(Callee);
1216
1217 // Add argument registers to the end of the list so that they are
1218 // known live into the call.
1219 for (auto &Reg : RegsToPass)
1220 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
1221
1222 // Add a register mask operand representing the call-preserved registers.
1223 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1224 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1225 assert(Mask && "Missing call preserved mask for calling convention");
1226 Ops.push_back(DAG.getRegisterMask(Mask));
1227
1228 // Glue the call to the argument copies, if any.
1229 if (Glue.getNode())
1230 Ops.push_back(Glue);
1231
1232 // Emit the call.
1233 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1234 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
1235 Glue = Chain.getValue(1);
1236
1237 // Mark the end of the call, which is glued to the call itself.
1238 Chain = DAG.getCALLSEQ_END(Chain,
1239 DAG.getConstant(NumBytes, DL, PtrVT, true),
1240 DAG.getConstant(0, DL, PtrVT, true),
1241 Glue, DL);
1242 Glue = Chain.getValue(1);
1243
1244 // Assign locations to each value returned by this call.
1245 SmallVector<CCValAssign, 16> RVLocs;
1246 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
Alex Bradburydc31c612017-12-11 12:49:02 +00001247 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true);
Alex Bradburya3376752017-11-08 13:41:21 +00001248
1249 // Copy all of the result registers out of their specified physreg.
1250 for (auto &VA : RVLocs) {
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001251 // Copy the value out
1252 SDValue RetValue =
1253 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
1254 // Glue the RetValue to the end of the call sequence
Alex Bradburya3376752017-11-08 13:41:21 +00001255 Chain = RetValue.getValue(1);
1256 Glue = RetValue.getValue(2);
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001257 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
1258 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
1259 SDValue RetValue2 =
1260 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
1261 Chain = RetValue2.getValue(1);
1262 Glue = RetValue2.getValue(2);
1263 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
1264 RetValue2);
1265 }
Alex Bradburya3376752017-11-08 13:41:21 +00001266
Alex Bradbury76c29ee2018-03-20 12:45:35 +00001267 switch (VA.getLocInfo()) {
1268 default:
1269 llvm_unreachable("Unknown loc info!");
1270 case CCValAssign::Full:
1271 break;
1272 case CCValAssign::BCvt:
1273 RetValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), RetValue);
1274 break;
1275 }
1276
Alex Bradburydc31c612017-12-11 12:49:02 +00001277 InVals.push_back(RetValue);
Alex Bradburya3376752017-11-08 13:41:21 +00001278 }
1279
1280 return Chain;
1281}
1282
Alex Bradburydc31c612017-12-11 12:49:02 +00001283bool RISCVTargetLowering::CanLowerReturn(
1284 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
1285 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
1286 SmallVector<CCValAssign, 16> RVLocs;
1287 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
1288 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1289 MVT VT = Outs[i].VT;
1290 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1291 if (CC_RISCV(MF.getDataLayout(), i, VT, VT, CCValAssign::Full, ArgFlags,
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001292 CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr))
Alex Bradburydc31c612017-12-11 12:49:02 +00001293 return false;
1294 }
1295 return true;
1296}
1297
Alex Bradbury76c29ee2018-03-20 12:45:35 +00001298static SDValue packIntoRegLoc(SelectionDAG &DAG, SDValue Val,
1299 const CCValAssign &VA, const SDLoc &DL) {
1300 EVT LocVT = VA.getLocVT();
1301
1302 switch (VA.getLocInfo()) {
1303 default:
1304 llvm_unreachable("Unexpected CCValAssign::LocInfo");
1305 case CCValAssign::Full:
1306 break;
1307 case CCValAssign::BCvt:
1308 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
1309 break;
1310 }
1311 return Val;
1312}
1313
Alex Bradbury89718422017-10-19 21:37:38 +00001314SDValue
1315RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1316 bool IsVarArg,
1317 const SmallVectorImpl<ISD::OutputArg> &Outs,
1318 const SmallVectorImpl<SDValue> &OutVals,
1319 const SDLoc &DL, SelectionDAG &DAG) const {
Alex Bradbury89718422017-10-19 21:37:38 +00001320 // Stores the assignment of the return value to a location.
1321 SmallVector<CCValAssign, 16> RVLocs;
1322
1323 // Info about the registers and stack slot.
1324 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
1325 *DAG.getContext());
1326
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001327 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
1328 nullptr);
Alex Bradbury89718422017-10-19 21:37:38 +00001329
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001330 SDValue Glue;
Alex Bradbury89718422017-10-19 21:37:38 +00001331 SmallVector<SDValue, 4> RetOps(1, Chain);
1332
1333 // Copy the result values into the output registers.
1334 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
Alex Bradburydc31c612017-12-11 12:49:02 +00001335 SDValue Val = OutVals[i];
Alex Bradbury89718422017-10-19 21:37:38 +00001336 CCValAssign &VA = RVLocs[i];
1337 assert(VA.isRegLoc() && "Can only return in registers!");
1338
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001339 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
1340 // Handle returning f64 on RV32D with a soft float ABI.
1341 assert(VA.isRegLoc() && "Expected return via registers");
1342 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
1343 DAG.getVTList(MVT::i32, MVT::i32), Val);
1344 SDValue Lo = SplitF64.getValue(0);
1345 SDValue Hi = SplitF64.getValue(1);
1346 unsigned RegLo = VA.getLocReg();
1347 unsigned RegHi = RegLo + 1;
1348 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
1349 Glue = Chain.getValue(1);
1350 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
1351 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
1352 Glue = Chain.getValue(1);
1353 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
1354 } else {
1355 // Handle a 'normal' return.
1356 Val = packIntoRegLoc(DAG, Val, VA, DL);
1357 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
Alex Bradbury89718422017-10-19 21:37:38 +00001358
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001359 // Guarantee that all emitted copies are stuck together.
1360 Glue = Chain.getValue(1);
1361 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1362 }
Alex Bradbury89718422017-10-19 21:37:38 +00001363 }
1364
1365 RetOps[0] = Chain; // Update chain.
1366
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001367 // Add the glue node if we have it.
1368 if (Glue.getNode()) {
1369 RetOps.push_back(Glue);
Alex Bradbury89718422017-10-19 21:37:38 +00001370 }
1371
1372 return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps);
1373}
1374
1375const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
1376 switch ((RISCVISD::NodeType)Opcode) {
1377 case RISCVISD::FIRST_NUMBER:
1378 break;
1379 case RISCVISD::RET_FLAG:
1380 return "RISCVISD::RET_FLAG";
Alex Bradburya3376752017-11-08 13:41:21 +00001381 case RISCVISD::CALL:
1382 return "RISCVISD::CALL";
Alex Bradbury65385162017-11-21 07:51:32 +00001383 case RISCVISD::SELECT_CC:
1384 return "RISCVISD::SELECT_CC";
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001385 case RISCVISD::BuildPairF64:
1386 return "RISCVISD::BuildPairF64";
1387 case RISCVISD::SplitF64:
1388 return "RISCVISD::SplitF64";
Alex Bradbury89718422017-10-19 21:37:38 +00001389 }
1390 return nullptr;
1391}
Alex Bradbury9330e642018-01-10 20:05:09 +00001392
1393std::pair<unsigned, const TargetRegisterClass *>
1394RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
1395 StringRef Constraint,
1396 MVT VT) const {
1397 // First, see if this is a constraint that directly corresponds to a
1398 // RISCV register class.
1399 if (Constraint.size() == 1) {
1400 switch (Constraint[0]) {
1401 case 'r':
1402 return std::make_pair(0U, &RISCV::GPRRegClass);
1403 default:
1404 break;
1405 }
1406 }
1407
1408 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1409}