blob: d1ad453fbf8ab970f0e480dd007ac79c7196c1ce [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 Bradbury130b8b32018-04-26 13:37:00 +0000194// On RV32, 64-bit integers are split into their high and low parts and held
195// in two different registers, so the trunc is free since the low register can
196// just be used.
197bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
198 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
199 return false;
200 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
201 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
202 return (SrcBits == 64 && DestBits == 32);
203}
204
205bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
206 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
207 !SrcVT.isInteger() || !DstVT.isInteger())
208 return false;
209 unsigned SrcBits = SrcVT.getSizeInBits();
210 unsigned DestBits = DstVT.getSizeInBits();
211 return (SrcBits == 64 && DestBits == 32);
212}
213
Alex Bradbury65385162017-11-21 07:51:32 +0000214// Changes the condition code and swaps operands if necessary, so the SetCC
215// operation matches one of the comparisons supported directly in the RISC-V
216// ISA.
217static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) {
218 switch (CC) {
219 default:
220 break;
221 case ISD::SETGT:
222 case ISD::SETLE:
223 case ISD::SETUGT:
224 case ISD::SETULE:
225 CC = ISD::getSetCCSwappedOperands(CC);
226 std::swap(LHS, RHS);
227 break;
228 }
229}
230
231// Return the RISC-V branch opcode that matches the given DAG integer
232// condition code. The CondCode must be one of those supported by the RISC-V
233// ISA (see normaliseSetCC).
234static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) {
235 switch (CC) {
236 default:
237 llvm_unreachable("Unsupported CondCode");
238 case ISD::SETEQ:
239 return RISCV::BEQ;
240 case ISD::SETNE:
241 return RISCV::BNE;
242 case ISD::SETLT:
243 return RISCV::BLT;
244 case ISD::SETGE:
245 return RISCV::BGE;
246 case ISD::SETULT:
247 return RISCV::BLTU;
248 case ISD::SETUGE:
249 return RISCV::BGEU;
250 }
251}
252
Alex Bradbury89718422017-10-19 21:37:38 +0000253SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
254 SelectionDAG &DAG) const {
255 switch (Op.getOpcode()) {
256 default:
257 report_fatal_error("unimplemented operand");
Alex Bradburyec8aa912017-11-08 13:24:21 +0000258 case ISD::GlobalAddress:
259 return lowerGlobalAddress(Op, DAG);
Alex Bradburyffc435e2017-11-21 08:11:03 +0000260 case ISD::BlockAddress:
261 return lowerBlockAddress(Op, DAG);
Alex Bradbury80c8eb72018-03-20 13:26:12 +0000262 case ISD::ConstantPool:
263 return lowerConstantPool(Op, DAG);
Alex Bradbury65385162017-11-21 07:51:32 +0000264 case ISD::SELECT:
265 return lowerSELECT(Op, DAG);
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000266 case ISD::VASTART:
267 return lowerVASTART(Op, DAG);
Alex Bradbury70f137b2018-01-10 20:12:00 +0000268 case ISD::FRAMEADDR:
269 return LowerFRAMEADDR(Op, DAG);
270 case ISD::RETURNADDR:
271 return LowerRETURNADDR(Op, DAG);
Alex Bradburyec8aa912017-11-08 13:24:21 +0000272 }
273}
274
275SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
276 SelectionDAG &DAG) const {
277 SDLoc DL(Op);
278 EVT Ty = Op.getValueType();
279 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
280 const GlobalValue *GV = N->getGlobal();
281 int64_t Offset = N->getOffset();
282
Alex Bradburyffc435e2017-11-21 08:11:03 +0000283 if (isPositionIndependent() || Subtarget.is64Bit())
Alex Bradburyec8aa912017-11-08 13:24:21 +0000284 report_fatal_error("Unable to lowerGlobalAddress");
Alex Bradburyffc435e2017-11-21 08:11:03 +0000285
286 SDValue GAHi =
287 DAG.getTargetGlobalAddress(GV, DL, Ty, Offset, RISCVII::MO_HI);
288 SDValue GALo =
289 DAG.getTargetGlobalAddress(GV, DL, Ty, Offset, RISCVII::MO_LO);
290 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, GAHi), 0);
291 SDValue MNLo =
292 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, GALo), 0);
293 return MNLo;
294}
295
296SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
297 SelectionDAG &DAG) const {
298 SDLoc DL(Op);
299 EVT Ty = Op.getValueType();
300 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
301 const BlockAddress *BA = N->getBlockAddress();
302 int64_t Offset = N->getOffset();
303
304 if (isPositionIndependent() || Subtarget.is64Bit())
305 report_fatal_error("Unable to lowerBlockAddress");
306
307 SDValue BAHi = DAG.getTargetBlockAddress(BA, Ty, Offset, RISCVII::MO_HI);
308 SDValue BALo = DAG.getTargetBlockAddress(BA, Ty, Offset, RISCVII::MO_LO);
309 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, BAHi), 0);
310 SDValue MNLo =
311 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, BALo), 0);
312 return MNLo;
313}
314
Alex Bradbury80c8eb72018-03-20 13:26:12 +0000315SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
316 SelectionDAG &DAG) const {
317 SDLoc DL(Op);
318 EVT Ty = Op.getValueType();
319 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
320 const Constant *CPA = N->getConstVal();
321 int64_t Offset = N->getOffset();
322 unsigned Alignment = N->getAlignment();
323
324 if (!isPositionIndependent()) {
325 SDValue CPAHi =
326 DAG.getTargetConstantPool(CPA, Ty, Alignment, Offset, RISCVII::MO_HI);
327 SDValue CPALo =
328 DAG.getTargetConstantPool(CPA, Ty, Alignment, Offset, RISCVII::MO_LO);
329 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, CPAHi), 0);
330 SDValue MNLo =
331 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, CPALo), 0);
332 return MNLo;
333 } else {
334 report_fatal_error("Unable to lowerConstantPool");
335 }
336}
337
Alex Bradburyffc435e2017-11-21 08:11:03 +0000338SDValue RISCVTargetLowering::lowerExternalSymbol(SDValue Op,
339 SelectionDAG &DAG) const {
340 SDLoc DL(Op);
341 EVT Ty = Op.getValueType();
342 ExternalSymbolSDNode *N = cast<ExternalSymbolSDNode>(Op);
343 const char *Sym = N->getSymbol();
344
345 // TODO: should also handle gp-relative loads.
346
347 if (isPositionIndependent() || Subtarget.is64Bit())
348 report_fatal_error("Unable to lowerExternalSymbol");
349
350 SDValue GAHi = DAG.getTargetExternalSymbol(Sym, Ty, RISCVII::MO_HI);
351 SDValue GALo = DAG.getTargetExternalSymbol(Sym, Ty, RISCVII::MO_LO);
352 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, GAHi), 0);
353 SDValue MNLo =
354 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, GALo), 0);
355 return MNLo;
Alex Bradbury89718422017-10-19 21:37:38 +0000356}
357
Alex Bradbury65385162017-11-21 07:51:32 +0000358SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
359 SDValue CondV = Op.getOperand(0);
360 SDValue TrueV = Op.getOperand(1);
361 SDValue FalseV = Op.getOperand(2);
362 SDLoc DL(Op);
363 MVT XLenVT = Subtarget.getXLenVT();
364
365 // If the result type is XLenVT and CondV is the output of a SETCC node
366 // which also operated on XLenVT inputs, then merge the SETCC node into the
367 // lowered RISCVISD::SELECT_CC to take advantage of the integer
368 // compare+branch instructions. i.e.:
369 // (select (setcc lhs, rhs, cc), truev, falsev)
370 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
371 if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC &&
372 CondV.getOperand(0).getSimpleValueType() == XLenVT) {
373 SDValue LHS = CondV.getOperand(0);
374 SDValue RHS = CondV.getOperand(1);
375 auto CC = cast<CondCodeSDNode>(CondV.getOperand(2));
376 ISD::CondCode CCVal = CC->get();
377
378 normaliseSetCC(LHS, RHS, CCVal);
379
380 SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT);
381 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
382 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
383 return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
384 }
385
386 // Otherwise:
387 // (select condv, truev, falsev)
388 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
389 SDValue Zero = DAG.getConstant(0, DL, XLenVT);
390 SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT);
391
392 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
393 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
394
395 return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
396}
397
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000398SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
399 MachineFunction &MF = DAG.getMachineFunction();
400 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
401
402 SDLoc DL(Op);
403 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
404 getPointerTy(MF.getDataLayout()));
405
406 // vastart just stores the address of the VarArgsFrameIndex slot into the
407 // memory location argument.
408 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
409 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
410 MachinePointerInfo(SV));
411}
412
Alex Bradbury70f137b2018-01-10 20:12:00 +0000413SDValue RISCVTargetLowering::LowerFRAMEADDR(SDValue Op,
414 SelectionDAG &DAG) const {
415 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
416 MachineFunction &MF = DAG.getMachineFunction();
417 MachineFrameInfo &MFI = MF.getFrameInfo();
418 MFI.setFrameAddressIsTaken(true);
419 unsigned FrameReg = RI.getFrameRegister(MF);
420 int XLenInBytes = Subtarget.getXLen() / 8;
421
422 EVT VT = Op.getValueType();
423 SDLoc DL(Op);
424 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
425 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
426 while (Depth--) {
427 int Offset = -(XLenInBytes * 2);
428 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
429 DAG.getIntPtrConstant(Offset, DL));
430 FrameAddr =
431 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
432 }
433 return FrameAddr;
434}
435
436SDValue RISCVTargetLowering::LowerRETURNADDR(SDValue Op,
437 SelectionDAG &DAG) const {
438 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
439 MachineFunction &MF = DAG.getMachineFunction();
440 MachineFrameInfo &MFI = MF.getFrameInfo();
441 MFI.setReturnAddressIsTaken(true);
442 MVT XLenVT = Subtarget.getXLenVT();
443 int XLenInBytes = Subtarget.getXLen() / 8;
444
445 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
446 return SDValue();
447
448 EVT VT = Op.getValueType();
449 SDLoc DL(Op);
450 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
451 if (Depth) {
452 int Off = -XLenInBytes;
453 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
454 SDValue Offset = DAG.getConstant(Off, DL, VT);
455 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
456 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
457 MachinePointerInfo());
458 }
459
460 // Return the value of the return address register, marking it an implicit
461 // live-in.
462 unsigned Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
463 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
464}
465
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000466static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
467 MachineBasicBlock *BB) {
468 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
469
470 MachineFunction &MF = *BB->getParent();
471 DebugLoc DL = MI.getDebugLoc();
472 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
473 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
474 unsigned LoReg = MI.getOperand(0).getReg();
475 unsigned HiReg = MI.getOperand(1).getReg();
476 unsigned SrcReg = MI.getOperand(2).getReg();
477 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
478 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
479
480 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
481 RI);
482 MachineMemOperand *MMO =
483 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
484 MachineMemOperand::MOLoad, 8, 8);
485 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
486 .addFrameIndex(FI)
487 .addImm(0)
488 .addMemOperand(MMO);
489 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
490 .addFrameIndex(FI)
491 .addImm(4)
492 .addMemOperand(MMO);
493 MI.eraseFromParent(); // The pseudo instruction is gone now.
494 return BB;
495}
496
497static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
498 MachineBasicBlock *BB) {
499 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
500 "Unexpected instruction");
501
502 MachineFunction &MF = *BB->getParent();
503 DebugLoc DL = MI.getDebugLoc();
504 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
505 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
506 unsigned DstReg = MI.getOperand(0).getReg();
507 unsigned LoReg = MI.getOperand(1).getReg();
508 unsigned HiReg = MI.getOperand(2).getReg();
509 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
510 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
511
512 MachineMemOperand *MMO =
513 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
514 MachineMemOperand::MOStore, 8, 8);
515 BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
516 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
517 .addFrameIndex(FI)
518 .addImm(0)
519 .addMemOperand(MMO);
520 BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
521 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
522 .addFrameIndex(FI)
523 .addImm(4)
524 .addMemOperand(MMO);
525 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
526 MI.eraseFromParent(); // The pseudo instruction is gone now.
527 return BB;
528}
529
Alex Bradbury65385162017-11-21 07:51:32 +0000530MachineBasicBlock *
531RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
532 MachineBasicBlock *BB) const {
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000533 switch (MI.getOpcode()) {
534 default:
535 llvm_unreachable("Unexpected instr type to insert");
536 case RISCV::Select_GPR_Using_CC_GPR:
537 case RISCV::Select_FPR32_Using_CC_GPR:
Alex Bradbury21d28fe2018-04-12 05:50:06 +0000538 case RISCV::Select_FPR64_Using_CC_GPR:
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000539 break;
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000540 case RISCV::BuildPairF64Pseudo:
541 return emitBuildPairF64Pseudo(MI, BB);
542 case RISCV::SplitF64Pseudo:
543 return emitSplitF64Pseudo(MI, BB);
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000544 }
Alex Bradbury65385162017-11-21 07:51:32 +0000545
546 // To "insert" a SELECT instruction, we actually have to insert the triangle
547 // control-flow pattern. The incoming instruction knows the destination vreg
548 // to set, the condition code register to branch on, the true/false values to
549 // select between, and the condcode to use to select the appropriate branch.
550 //
551 // We produce the following control flow:
552 // HeadMBB
553 // | \
554 // | IfFalseMBB
555 // | /
556 // TailMBB
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000557 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
Alex Bradbury65385162017-11-21 07:51:32 +0000558 const BasicBlock *LLVM_BB = BB->getBasicBlock();
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000559 DebugLoc DL = MI.getDebugLoc();
Alex Bradbury65385162017-11-21 07:51:32 +0000560 MachineFunction::iterator I = ++BB->getIterator();
561
562 MachineBasicBlock *HeadMBB = BB;
563 MachineFunction *F = BB->getParent();
564 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
565 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
566
567 F->insert(I, IfFalseMBB);
568 F->insert(I, TailMBB);
569 // Move all remaining instructions to TailMBB.
570 TailMBB->splice(TailMBB->begin(), HeadMBB,
571 std::next(MachineBasicBlock::iterator(MI)), HeadMBB->end());
572 // Update machine-CFG edges by transferring all successors of the current
573 // block to the new block which will contain the Phi node for the select.
574 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
575 // Set the successors for HeadMBB.
576 HeadMBB->addSuccessor(IfFalseMBB);
577 HeadMBB->addSuccessor(TailMBB);
578
579 // Insert appropriate branch.
580 unsigned LHS = MI.getOperand(1).getReg();
581 unsigned RHS = MI.getOperand(2).getReg();
582 auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm());
583 unsigned Opcode = getBranchOpcodeForIntCondCode(CC);
584
585 BuildMI(HeadMBB, DL, TII.get(Opcode))
586 .addReg(LHS)
587 .addReg(RHS)
588 .addMBB(TailMBB);
589
590 // IfFalseMBB just falls through to TailMBB.
591 IfFalseMBB->addSuccessor(TailMBB);
592
593 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
594 BuildMI(*TailMBB, TailMBB->begin(), DL, TII.get(RISCV::PHI),
595 MI.getOperand(0).getReg())
596 .addReg(MI.getOperand(4).getReg())
597 .addMBB(HeadMBB)
598 .addReg(MI.getOperand(5).getReg())
599 .addMBB(IfFalseMBB);
600
601 MI.eraseFromParent(); // The pseudo instruction is gone now.
602 return TailMBB;
603}
604
Alex Bradbury89718422017-10-19 21:37:38 +0000605// Calling Convention Implementation.
Alex Bradburydc31c612017-12-11 12:49:02 +0000606// The expectations for frontend ABI lowering vary from target to target.
607// Ideally, an LLVM frontend would be able to avoid worrying about many ABI
608// details, but this is a longer term goal. For now, we simply try to keep the
609// role of the frontend as simple and well-defined as possible. The rules can
610// be summarised as:
611// * Never split up large scalar arguments. We handle them here.
612// * If a hardfloat calling convention is being used, and the struct may be
613// passed in a pair of registers (fp+fp, int+fp), and both registers are
614// available, then pass as two separate arguments. If either the GPRs or FPRs
615// are exhausted, then pass according to the rule below.
616// * If a struct could never be passed in registers or directly in a stack
617// slot (as it is larger than 2*XLEN and the floating point rules don't
618// apply), then pass it using a pointer with the byval attribute.
619// * If a struct is less than 2*XLEN, then coerce to either a two-element
620// word-sized array or a 2*XLEN scalar (depending on alignment).
621// * The frontend can determine whether a struct is returned by reference or
622// not based on its size and fields. If it will be returned by reference, the
623// frontend must modify the prototype so a pointer with the sret annotation is
624// passed as the first argument. This is not necessary for large scalar
625// returns.
626// * Struct return values and varargs should be coerced to structs containing
627// register-size fields in the same situations they would be for fixed
628// arguments.
629
630static const MCPhysReg ArgGPRs[] = {
631 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
632 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
633};
634
635// Pass a 2*XLEN argument that has been split into two XLEN values through
636// registers or the stack as necessary.
637static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
638 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
639 MVT ValVT2, MVT LocVT2,
640 ISD::ArgFlagsTy ArgFlags2) {
641 unsigned XLenInBytes = XLen / 8;
642 if (unsigned Reg = State.AllocateReg(ArgGPRs)) {
643 // At least one half can be passed via register.
644 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
645 VA1.getLocVT(), CCValAssign::Full));
646 } else {
647 // Both halves must be passed on the stack, with proper alignment.
648 unsigned StackAlign = std::max(XLenInBytes, ArgFlags1.getOrigAlign());
649 State.addLoc(
650 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
651 State.AllocateStack(XLenInBytes, StackAlign),
652 VA1.getLocVT(), CCValAssign::Full));
653 State.addLoc(CCValAssign::getMem(
654 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
655 CCValAssign::Full));
656 return false;
657 }
658
659 if (unsigned Reg = State.AllocateReg(ArgGPRs)) {
660 // The second half can also be passed via register.
661 State.addLoc(
662 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
663 } else {
664 // The second half is passed via the stack, without additional alignment.
665 State.addLoc(CCValAssign::getMem(
666 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
667 CCValAssign::Full));
668 }
669
670 return false;
671}
672
673// Implements the RISC-V calling convention. Returns true upon failure.
674static bool CC_RISCV(const DataLayout &DL, unsigned ValNo, MVT ValVT, MVT LocVT,
675 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000676 CCState &State, bool IsFixed, bool IsRet, Type *OrigTy) {
Alex Bradburydc31c612017-12-11 12:49:02 +0000677 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
678 assert(XLen == 32 || XLen == 64);
679 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000680 if (ValVT == MVT::f32) {
681 LocVT = MVT::i32;
682 LocInfo = CCValAssign::BCvt;
683 }
Alex Bradburydc31c612017-12-11 12:49:02 +0000684
685 // Any return value split in to more than two values can't be returned
686 // directly.
687 if (IsRet && ValNo > 1)
688 return true;
689
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000690 // If this is a variadic argument, the RISC-V calling convention requires
691 // that it is assigned an 'even' or 'aligned' register if it has 8-byte
692 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
693 // be used regardless of whether the original argument was split during
694 // legalisation or not. The argument will not be passed by registers if the
695 // original type is larger than 2*XLEN, so the register alignment rule does
696 // not apply.
697 unsigned TwoXLenInBytes = (2 * XLen) / 8;
698 if (!IsFixed && ArgFlags.getOrigAlign() == TwoXLenInBytes &&
699 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
700 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
701 // Skip 'odd' register if necessary.
702 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
703 State.AllocateReg(ArgGPRs);
704 }
705
Alex Bradburydc31c612017-12-11 12:49:02 +0000706 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
707 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
708 State.getPendingArgFlags();
709
710 assert(PendingLocs.size() == PendingArgFlags.size() &&
711 "PendingLocs and PendingArgFlags out of sync");
712
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000713 // Handle passing f64 on RV32D with a soft float ABI.
714 if (XLen == 32 && ValVT == MVT::f64) {
Mandeep Singh Grang88a8b262018-04-16 18:56:10 +0000715 assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000716 "Can't lower f64 if it is split");
717 // Depending on available argument GPRS, f64 may be passed in a pair of
718 // GPRs, split between a GPR and the stack, or passed completely on the
719 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
720 // cases.
721 unsigned Reg = State.AllocateReg(ArgGPRs);
722 LocVT = MVT::i32;
723 if (!Reg) {
724 unsigned StackOffset = State.AllocateStack(8, 8);
725 State.addLoc(
726 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
727 return false;
728 }
729 if (!State.AllocateReg(ArgGPRs))
730 State.AllocateStack(4, 4);
731 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
732 return false;
733 }
734
Alex Bradburydc31c612017-12-11 12:49:02 +0000735 // Split arguments might be passed indirectly, so keep track of the pending
736 // values.
737 if (ArgFlags.isSplit() || !PendingLocs.empty()) {
738 LocVT = XLenVT;
739 LocInfo = CCValAssign::Indirect;
740 PendingLocs.push_back(
741 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
742 PendingArgFlags.push_back(ArgFlags);
743 if (!ArgFlags.isSplitEnd()) {
744 return false;
745 }
746 }
747
748 // If the split argument only had two elements, it should be passed directly
749 // in registers or on the stack.
750 if (ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) {
751 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
752 // Apply the normal calling convention rules to the first half of the
753 // split argument.
754 CCValAssign VA = PendingLocs[0];
755 ISD::ArgFlagsTy AF = PendingArgFlags[0];
756 PendingLocs.clear();
757 PendingArgFlags.clear();
758 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
759 ArgFlags);
760 }
761
762 // Allocate to a register if possible, or else a stack slot.
763 unsigned Reg = State.AllocateReg(ArgGPRs);
764 unsigned StackOffset = Reg ? 0 : State.AllocateStack(XLen / 8, XLen / 8);
765
766 // If we reach this point and PendingLocs is non-empty, we must be at the
767 // end of a split argument that must be passed indirectly.
768 if (!PendingLocs.empty()) {
769 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
770 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
771
772 for (auto &It : PendingLocs) {
773 if (Reg)
774 It.convertToReg(Reg);
775 else
776 It.convertToMem(StackOffset);
777 State.addLoc(It);
778 }
779 PendingLocs.clear();
780 PendingArgFlags.clear();
781 return false;
782 }
783
784 assert(LocVT == XLenVT && "Expected an XLenVT at this stage");
785
786 if (Reg) {
787 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
788 } else {
789 State.addLoc(
790 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
791 }
792 return false;
793}
794
795void RISCVTargetLowering::analyzeInputArgs(
796 MachineFunction &MF, CCState &CCInfo,
797 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const {
798 unsigned NumArgs = Ins.size();
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000799 FunctionType *FType = MF.getFunction().getFunctionType();
Alex Bradburydc31c612017-12-11 12:49:02 +0000800
801 for (unsigned i = 0; i != NumArgs; ++i) {
802 MVT ArgVT = Ins[i].VT;
803 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
804
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000805 Type *ArgTy = nullptr;
806 if (IsRet)
807 ArgTy = FType->getReturnType();
808 else if (Ins[i].isOrigArg())
809 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
810
Alex Bradburydc31c612017-12-11 12:49:02 +0000811 if (CC_RISCV(MF.getDataLayout(), i, ArgVT, ArgVT, CCValAssign::Full,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000812 ArgFlags, CCInfo, /*IsRet=*/true, IsRet, ArgTy)) {
Alex Bradburydc31c612017-12-11 12:49:02 +0000813 DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
814 << EVT(ArgVT).getEVTString() << '\n');
815 llvm_unreachable(nullptr);
816 }
817 }
818}
819
820void RISCVTargetLowering::analyzeOutputArgs(
821 MachineFunction &MF, CCState &CCInfo,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000822 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
823 CallLoweringInfo *CLI) const {
Alex Bradburydc31c612017-12-11 12:49:02 +0000824 unsigned NumArgs = Outs.size();
825
826 for (unsigned i = 0; i != NumArgs; i++) {
827 MVT ArgVT = Outs[i].VT;
828 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000829 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
Alex Bradburydc31c612017-12-11 12:49:02 +0000830
831 if (CC_RISCV(MF.getDataLayout(), i, ArgVT, ArgVT, CCValAssign::Full,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000832 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy)) {
Alex Bradburydc31c612017-12-11 12:49:02 +0000833 DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
834 << EVT(ArgVT).getEVTString() << "\n");
835 llvm_unreachable(nullptr);
836 }
837 }
838}
839
840// The caller is responsible for loading the full value if the argument is
841// passed with CCValAssign::Indirect.
842static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
843 const CCValAssign &VA, const SDLoc &DL) {
844 MachineFunction &MF = DAG.getMachineFunction();
845 MachineRegisterInfo &RegInfo = MF.getRegInfo();
846 EVT LocVT = VA.getLocVT();
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000847 EVT ValVT = VA.getValVT();
Alex Bradburydc31c612017-12-11 12:49:02 +0000848 SDValue Val;
849
850 unsigned VReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
851 RegInfo.addLiveIn(VA.getLocReg(), VReg);
852 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
853
854 switch (VA.getLocInfo()) {
855 default:
856 llvm_unreachable("Unexpected CCValAssign::LocInfo");
857 case CCValAssign::Full:
858 case CCValAssign::Indirect:
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000859 break;
860 case CCValAssign::BCvt:
861 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
862 break;
Alex Bradburydc31c612017-12-11 12:49:02 +0000863 }
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000864 return Val;
Alex Bradburydc31c612017-12-11 12:49:02 +0000865}
866
867// The caller is responsible for loading the full value if the argument is
868// passed with CCValAssign::Indirect.
869static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
870 const CCValAssign &VA, const SDLoc &DL) {
871 MachineFunction &MF = DAG.getMachineFunction();
872 MachineFrameInfo &MFI = MF.getFrameInfo();
873 EVT LocVT = VA.getLocVT();
874 EVT ValVT = VA.getValVT();
875 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
876 int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
877 VA.getLocMemOffset(), /*Immutable=*/true);
878 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
879 SDValue Val;
880
881 ISD::LoadExtType ExtType;
882 switch (VA.getLocInfo()) {
883 default:
884 llvm_unreachable("Unexpected CCValAssign::LocInfo");
885 case CCValAssign::Full:
886 case CCValAssign::Indirect:
887 ExtType = ISD::NON_EXTLOAD;
888 break;
889 }
890 Val = DAG.getExtLoad(
891 ExtType, DL, LocVT, Chain, FIN,
892 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
893 return Val;
894}
Alex Bradbury89718422017-10-19 21:37:38 +0000895
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000896static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
897 const CCValAssign &VA, const SDLoc &DL) {
898 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
899 "Unexpected VA");
900 MachineFunction &MF = DAG.getMachineFunction();
901 MachineFrameInfo &MFI = MF.getFrameInfo();
902 MachineRegisterInfo &RegInfo = MF.getRegInfo();
903
904 if (VA.isMemLoc()) {
905 // f64 is passed on the stack.
906 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
907 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
908 return DAG.getLoad(MVT::f64, DL, Chain, FIN,
909 MachinePointerInfo::getFixedStack(MF, FI));
910 }
911
912 assert(VA.isRegLoc() && "Expected register VA assignment");
913
914 unsigned LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
915 RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
916 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
917 SDValue Hi;
918 if (VA.getLocReg() == RISCV::X17) {
919 // Second half of f64 is passed on the stack.
920 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
921 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
922 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
923 MachinePointerInfo::getFixedStack(MF, FI));
924 } else {
925 // Second half of f64 is passed in another GPR.
926 unsigned HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
927 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
928 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
929 }
930 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
931}
932
Alex Bradbury89718422017-10-19 21:37:38 +0000933// Transform physical registers into virtual registers.
934SDValue RISCVTargetLowering::LowerFormalArguments(
935 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
936 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
937 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
938
939 switch (CallConv) {
940 default:
941 report_fatal_error("Unsupported calling convention");
942 case CallingConv::C:
Alex Bradburya3376752017-11-08 13:41:21 +0000943 case CallingConv::Fast:
Alex Bradbury89718422017-10-19 21:37:38 +0000944 break;
945 }
946
947 MachineFunction &MF = DAG.getMachineFunction();
Alex Bradburydc31c612017-12-11 12:49:02 +0000948 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000949 MVT XLenVT = Subtarget.getXLenVT();
950 unsigned XLenInBytes = Subtarget.getXLen() / 8;
951 // Used with vargs to acumulate store chains.
952 std::vector<SDValue> OutChains;
Alex Bradbury89718422017-10-19 21:37:38 +0000953
954 // Assign locations to all of the incoming arguments.
955 SmallVector<CCValAssign, 16> ArgLocs;
956 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
Alex Bradburydc31c612017-12-11 12:49:02 +0000957 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false);
Alex Bradbury89718422017-10-19 21:37:38 +0000958
Alex Bradburydc31c612017-12-11 12:49:02 +0000959 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
960 CCValAssign &VA = ArgLocs[i];
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000961 assert(VA.getLocVT() == XLenVT && "Unhandled argument type");
Alex Bradburydc31c612017-12-11 12:49:02 +0000962 SDValue ArgValue;
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000963 // Passing f64 on RV32D with a soft float ABI must be handled as a special
964 // case.
965 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
966 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
967 else if (VA.isRegLoc())
Alex Bradburydc31c612017-12-11 12:49:02 +0000968 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL);
969 else
970 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
Alex Bradbury89718422017-10-19 21:37:38 +0000971
Alex Bradburydc31c612017-12-11 12:49:02 +0000972 if (VA.getLocInfo() == CCValAssign::Indirect) {
973 // If the original argument was split and passed by reference (e.g. i128
974 // on RV32), we need to load all parts of it here (using the same
975 // address).
976 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
977 MachinePointerInfo()));
978 unsigned ArgIndex = Ins[i].OrigArgIndex;
979 assert(Ins[i].PartOffset == 0);
980 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
981 CCValAssign &PartVA = ArgLocs[i + 1];
982 unsigned PartOffset = Ins[i + 1].PartOffset;
983 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
984 DAG.getIntPtrConstant(PartOffset, DL));
985 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
986 MachinePointerInfo()));
987 ++i;
988 }
989 continue;
Alex Bradbury89718422017-10-19 21:37:38 +0000990 }
Alex Bradburydc31c612017-12-11 12:49:02 +0000991 InVals.push_back(ArgValue);
Alex Bradbury89718422017-10-19 21:37:38 +0000992 }
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000993
994 if (IsVarArg) {
995 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
996 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
997 const TargetRegisterClass *RC = &RISCV::GPRRegClass;
998 MachineFrameInfo &MFI = MF.getFrameInfo();
999 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1000 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1001
1002 // Offset of the first variable argument from stack pointer, and size of
1003 // the vararg save area. For now, the varargs save area is either zero or
1004 // large enough to hold a0-a7.
1005 int VaArgOffset, VarArgsSaveSize;
1006
1007 // If all registers are allocated, then all varargs must be passed on the
1008 // stack and we don't need to save any argregs.
1009 if (ArgRegs.size() == Idx) {
1010 VaArgOffset = CCInfo.getNextStackOffset();
1011 VarArgsSaveSize = 0;
1012 } else {
1013 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
1014 VaArgOffset = -VarArgsSaveSize;
1015 }
1016
1017 // Record the frame index of the first variable argument
1018 // which is a value necessary to VASTART.
1019 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1020 RVFI->setVarArgsFrameIndex(FI);
1021
1022 // If saving an odd number of registers then create an extra stack slot to
1023 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
1024 // offsets to even-numbered registered remain 2*XLEN-aligned.
1025 if (Idx % 2) {
1026 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes,
1027 true);
1028 VarArgsSaveSize += XLenInBytes;
1029 }
1030
1031 // Copy the integer registers that may have been used for passing varargs
1032 // to the vararg save area.
1033 for (unsigned I = Idx; I < ArgRegs.size();
1034 ++I, VaArgOffset += XLenInBytes) {
1035 const unsigned Reg = RegInfo.createVirtualRegister(RC);
1036 RegInfo.addLiveIn(ArgRegs[I], Reg);
1037 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
1038 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1039 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1040 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
1041 MachinePointerInfo::getFixedStack(MF, FI));
1042 cast<StoreSDNode>(Store.getNode())
1043 ->getMemOperand()
1044 ->setValue((Value *)nullptr);
1045 OutChains.push_back(Store);
1046 }
1047 RVFI->setVarArgsSaveSize(VarArgsSaveSize);
1048 }
1049
1050 // All stores are grouped in one node to allow the matching between
1051 // the size of Ins and InVals. This only happens for vararg functions.
1052 if (!OutChains.empty()) {
1053 OutChains.push_back(Chain);
1054 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
1055 }
1056
Alex Bradbury89718422017-10-19 21:37:38 +00001057 return Chain;
1058}
1059
Alex Bradburya3376752017-11-08 13:41:21 +00001060// Lower a call to a callseq_start + CALL + callseq_end chain, and add input
1061// and output parameter nodes.
1062SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
1063 SmallVectorImpl<SDValue> &InVals) const {
1064 SelectionDAG &DAG = CLI.DAG;
1065 SDLoc &DL = CLI.DL;
1066 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1067 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1068 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1069 SDValue Chain = CLI.Chain;
1070 SDValue Callee = CLI.Callee;
1071 CLI.IsTailCall = false;
1072 CallingConv::ID CallConv = CLI.CallConv;
1073 bool IsVarArg = CLI.IsVarArg;
1074 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Alex Bradburydc31c612017-12-11 12:49:02 +00001075 MVT XLenVT = Subtarget.getXLenVT();
Alex Bradburya3376752017-11-08 13:41:21 +00001076
Alex Bradburya3376752017-11-08 13:41:21 +00001077 MachineFunction &MF = DAG.getMachineFunction();
1078
1079 // Analyze the operands of the call, assigning locations to each operand.
1080 SmallVector<CCValAssign, 16> ArgLocs;
1081 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001082 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI);
Alex Bradburya3376752017-11-08 13:41:21 +00001083
1084 // Get a count of how many bytes are to be pushed on the stack.
1085 unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1086
Alex Bradburydc31c612017-12-11 12:49:02 +00001087 // Create local copies for byval args
1088 SmallVector<SDValue, 8> ByValArgs;
1089 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1090 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1091 if (!Flags.isByVal())
Alex Bradburya3376752017-11-08 13:41:21 +00001092 continue;
Alex Bradburydc31c612017-12-11 12:49:02 +00001093
1094 SDValue Arg = OutVals[i];
1095 unsigned Size = Flags.getByValSize();
1096 unsigned Align = Flags.getByValAlign();
1097
1098 int FI = MF.getFrameInfo().CreateStackObject(Size, Align, /*isSS=*/false);
1099 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1100 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
1101
1102 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Align,
1103 /*IsVolatile=*/false,
1104 /*AlwaysInline=*/false,
1105 /*isTailCall=*/false, MachinePointerInfo(),
1106 MachinePointerInfo());
1107 ByValArgs.push_back(FIPtr);
Alex Bradburya3376752017-11-08 13:41:21 +00001108 }
1109
1110 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
1111
1112 // Copy argument values to their designated locations.
1113 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
Alex Bradburydc31c612017-12-11 12:49:02 +00001114 SmallVector<SDValue, 8> MemOpChains;
Alex Bradburya3376752017-11-08 13:41:21 +00001115 SDValue StackPtr;
Alex Bradburydc31c612017-12-11 12:49:02 +00001116 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
1117 CCValAssign &VA = ArgLocs[i];
1118 SDValue ArgValue = OutVals[i];
1119 ISD::ArgFlagsTy Flags = Outs[i].Flags;
Alex Bradburya3376752017-11-08 13:41:21 +00001120
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001121 // Handle passing f64 on RV32D with a soft float ABI as a special case.
1122 bool IsF64OnRV32DSoftABI =
1123 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
1124 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
1125 SDValue SplitF64 = DAG.getNode(
1126 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
1127 SDValue Lo = SplitF64.getValue(0);
1128 SDValue Hi = SplitF64.getValue(1);
1129
1130 unsigned RegLo = VA.getLocReg();
1131 RegsToPass.push_back(std::make_pair(RegLo, Lo));
1132
1133 if (RegLo == RISCV::X17) {
1134 // Second half of f64 is passed on the stack.
1135 // Work out the address of the stack slot.
1136 if (!StackPtr.getNode())
1137 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
1138 // Emit the store.
1139 MemOpChains.push_back(
1140 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
1141 } else {
1142 // Second half of f64 is passed in another GPR.
1143 unsigned RegHigh = RegLo + 1;
1144 RegsToPass.push_back(std::make_pair(RegHigh, Hi));
1145 }
1146 continue;
1147 }
1148
1149 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
1150 // as any other MemLoc.
1151
Alex Bradburya3376752017-11-08 13:41:21 +00001152 // Promote the value if needed.
Alex Bradburydc31c612017-12-11 12:49:02 +00001153 // For now, only handle fully promoted and indirect arguments.
Alex Bradburya3376752017-11-08 13:41:21 +00001154 switch (VA.getLocInfo()) {
1155 case CCValAssign::Full:
1156 break;
Alex Bradbury76c29ee2018-03-20 12:45:35 +00001157 case CCValAssign::BCvt:
1158 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), ArgValue);
1159 break;
Alex Bradburydc31c612017-12-11 12:49:02 +00001160 case CCValAssign::Indirect: {
1161 // Store the argument in a stack slot and pass its address.
1162 SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT);
1163 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1164 MemOpChains.push_back(
1165 DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1166 MachinePointerInfo::getFixedStack(MF, FI)));
1167 // If the original argument was split (e.g. i128), we need
1168 // to store all parts of it here (and pass just one address).
1169 unsigned ArgIndex = Outs[i].OrigArgIndex;
1170 assert(Outs[i].PartOffset == 0);
1171 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
1172 SDValue PartValue = OutVals[i + 1];
1173 unsigned PartOffset = Outs[i + 1].PartOffset;
1174 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
1175 DAG.getIntPtrConstant(PartOffset, DL));
1176 MemOpChains.push_back(
1177 DAG.getStore(Chain, DL, PartValue, Address,
1178 MachinePointerInfo::getFixedStack(MF, FI)));
1179 ++i;
1180 }
1181 ArgValue = SpillSlot;
1182 break;
1183 }
Alex Bradburya3376752017-11-08 13:41:21 +00001184 default:
1185 llvm_unreachable("Unknown loc info!");
1186 }
1187
Alex Bradburydc31c612017-12-11 12:49:02 +00001188 // Use local copy if it is a byval arg.
1189 if (Flags.isByVal())
1190 ArgValue = ByValArgs[j++];
1191
Alex Bradburya3376752017-11-08 13:41:21 +00001192 if (VA.isRegLoc()) {
1193 // Queue up the argument copies and emit them at the end.
1194 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1195 } else {
1196 assert(VA.isMemLoc() && "Argument not register or memory");
Alex Bradburydc31c612017-12-11 12:49:02 +00001197
1198 // Work out the address of the stack slot.
1199 if (!StackPtr.getNode())
1200 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
1201 SDValue Address =
1202 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1203 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
1204
1205 // Emit the store.
1206 MemOpChains.push_back(
1207 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
Alex Bradburya3376752017-11-08 13:41:21 +00001208 }
1209 }
1210
Alex Bradburydc31c612017-12-11 12:49:02 +00001211 // Join the stores, which are independent of one another.
1212 if (!MemOpChains.empty())
1213 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1214
Alex Bradburya3376752017-11-08 13:41:21 +00001215 SDValue Glue;
1216
1217 // Build a sequence of copy-to-reg nodes, chained and glued together.
1218 for (auto &Reg : RegsToPass) {
1219 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
1220 Glue = Chain.getValue(1);
1221 }
1222
Shiva Chend58bd8d2018-04-25 14:19:12 +00001223 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
1224 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
1225 // split it and then direct call can be matched by PseudoCALL.
1226 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
1227 Callee = DAG.getTargetGlobalAddress(S->getGlobal(), DL, PtrVT, 0, 0);
1228 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1229 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, 0);
Alex Bradburya3376752017-11-08 13:41:21 +00001230 }
1231
1232 // The first call operand is the chain and the second is the target address.
1233 SmallVector<SDValue, 8> Ops;
1234 Ops.push_back(Chain);
1235 Ops.push_back(Callee);
1236
1237 // Add argument registers to the end of the list so that they are
1238 // known live into the call.
1239 for (auto &Reg : RegsToPass)
1240 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
1241
1242 // Add a register mask operand representing the call-preserved registers.
1243 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1244 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1245 assert(Mask && "Missing call preserved mask for calling convention");
1246 Ops.push_back(DAG.getRegisterMask(Mask));
1247
1248 // Glue the call to the argument copies, if any.
1249 if (Glue.getNode())
1250 Ops.push_back(Glue);
1251
1252 // Emit the call.
1253 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1254 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
1255 Glue = Chain.getValue(1);
1256
1257 // Mark the end of the call, which is glued to the call itself.
1258 Chain = DAG.getCALLSEQ_END(Chain,
1259 DAG.getConstant(NumBytes, DL, PtrVT, true),
1260 DAG.getConstant(0, DL, PtrVT, true),
1261 Glue, DL);
1262 Glue = Chain.getValue(1);
1263
1264 // Assign locations to each value returned by this call.
1265 SmallVector<CCValAssign, 16> RVLocs;
1266 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
Alex Bradburydc31c612017-12-11 12:49:02 +00001267 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true);
Alex Bradburya3376752017-11-08 13:41:21 +00001268
1269 // Copy all of the result registers out of their specified physreg.
1270 for (auto &VA : RVLocs) {
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001271 // Copy the value out
1272 SDValue RetValue =
1273 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
1274 // Glue the RetValue to the end of the call sequence
Alex Bradburya3376752017-11-08 13:41:21 +00001275 Chain = RetValue.getValue(1);
1276 Glue = RetValue.getValue(2);
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001277 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
1278 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
1279 SDValue RetValue2 =
1280 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
1281 Chain = RetValue2.getValue(1);
1282 Glue = RetValue2.getValue(2);
1283 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
1284 RetValue2);
1285 }
Alex Bradburya3376752017-11-08 13:41:21 +00001286
Alex Bradbury76c29ee2018-03-20 12:45:35 +00001287 switch (VA.getLocInfo()) {
1288 default:
1289 llvm_unreachable("Unknown loc info!");
1290 case CCValAssign::Full:
1291 break;
1292 case CCValAssign::BCvt:
1293 RetValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), RetValue);
1294 break;
1295 }
1296
Alex Bradburydc31c612017-12-11 12:49:02 +00001297 InVals.push_back(RetValue);
Alex Bradburya3376752017-11-08 13:41:21 +00001298 }
1299
1300 return Chain;
1301}
1302
Alex Bradburydc31c612017-12-11 12:49:02 +00001303bool RISCVTargetLowering::CanLowerReturn(
1304 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
1305 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
1306 SmallVector<CCValAssign, 16> RVLocs;
1307 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
1308 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1309 MVT VT = Outs[i].VT;
1310 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1311 if (CC_RISCV(MF.getDataLayout(), i, VT, VT, CCValAssign::Full, ArgFlags,
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001312 CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr))
Alex Bradburydc31c612017-12-11 12:49:02 +00001313 return false;
1314 }
1315 return true;
1316}
1317
Alex Bradbury76c29ee2018-03-20 12:45:35 +00001318static SDValue packIntoRegLoc(SelectionDAG &DAG, SDValue Val,
1319 const CCValAssign &VA, const SDLoc &DL) {
1320 EVT LocVT = VA.getLocVT();
1321
1322 switch (VA.getLocInfo()) {
1323 default:
1324 llvm_unreachable("Unexpected CCValAssign::LocInfo");
1325 case CCValAssign::Full:
1326 break;
1327 case CCValAssign::BCvt:
1328 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
1329 break;
1330 }
1331 return Val;
1332}
1333
Alex Bradbury89718422017-10-19 21:37:38 +00001334SDValue
1335RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1336 bool IsVarArg,
1337 const SmallVectorImpl<ISD::OutputArg> &Outs,
1338 const SmallVectorImpl<SDValue> &OutVals,
1339 const SDLoc &DL, SelectionDAG &DAG) const {
Alex Bradbury89718422017-10-19 21:37:38 +00001340 // Stores the assignment of the return value to a location.
1341 SmallVector<CCValAssign, 16> RVLocs;
1342
1343 // Info about the registers and stack slot.
1344 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
1345 *DAG.getContext());
1346
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001347 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
1348 nullptr);
Alex Bradbury89718422017-10-19 21:37:38 +00001349
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001350 SDValue Glue;
Alex Bradbury89718422017-10-19 21:37:38 +00001351 SmallVector<SDValue, 4> RetOps(1, Chain);
1352
1353 // Copy the result values into the output registers.
1354 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
Alex Bradburydc31c612017-12-11 12:49:02 +00001355 SDValue Val = OutVals[i];
Alex Bradbury89718422017-10-19 21:37:38 +00001356 CCValAssign &VA = RVLocs[i];
1357 assert(VA.isRegLoc() && "Can only return in registers!");
1358
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001359 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
1360 // Handle returning f64 on RV32D with a soft float ABI.
1361 assert(VA.isRegLoc() && "Expected return via registers");
1362 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
1363 DAG.getVTList(MVT::i32, MVT::i32), Val);
1364 SDValue Lo = SplitF64.getValue(0);
1365 SDValue Hi = SplitF64.getValue(1);
1366 unsigned RegLo = VA.getLocReg();
1367 unsigned RegHi = RegLo + 1;
1368 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
1369 Glue = Chain.getValue(1);
1370 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
1371 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
1372 Glue = Chain.getValue(1);
1373 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
1374 } else {
1375 // Handle a 'normal' return.
1376 Val = packIntoRegLoc(DAG, Val, VA, DL);
1377 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
Alex Bradbury89718422017-10-19 21:37:38 +00001378
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001379 // Guarantee that all emitted copies are stuck together.
1380 Glue = Chain.getValue(1);
1381 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1382 }
Alex Bradbury89718422017-10-19 21:37:38 +00001383 }
1384
1385 RetOps[0] = Chain; // Update chain.
1386
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001387 // Add the glue node if we have it.
1388 if (Glue.getNode()) {
1389 RetOps.push_back(Glue);
Alex Bradbury89718422017-10-19 21:37:38 +00001390 }
1391
1392 return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps);
1393}
1394
1395const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
1396 switch ((RISCVISD::NodeType)Opcode) {
1397 case RISCVISD::FIRST_NUMBER:
1398 break;
1399 case RISCVISD::RET_FLAG:
1400 return "RISCVISD::RET_FLAG";
Alex Bradburya3376752017-11-08 13:41:21 +00001401 case RISCVISD::CALL:
1402 return "RISCVISD::CALL";
Alex Bradbury65385162017-11-21 07:51:32 +00001403 case RISCVISD::SELECT_CC:
1404 return "RISCVISD::SELECT_CC";
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001405 case RISCVISD::BuildPairF64:
1406 return "RISCVISD::BuildPairF64";
1407 case RISCVISD::SplitF64:
1408 return "RISCVISD::SplitF64";
Alex Bradbury89718422017-10-19 21:37:38 +00001409 }
1410 return nullptr;
1411}
Alex Bradbury9330e642018-01-10 20:05:09 +00001412
1413std::pair<unsigned, const TargetRegisterClass *>
1414RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
1415 StringRef Constraint,
1416 MVT VT) const {
1417 // First, see if this is a constraint that directly corresponds to a
1418 // RISCV register class.
1419 if (Constraint.size() == 1) {
1420 switch (Constraint[0]) {
1421 case 'r':
1422 return std::make_pair(0U, &RISCV::GPRRegClass);
1423 default:
1424 break;
1425 }
1426 }
1427
1428 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1429}