blob: 44da49c23d5a3d6c2282d682cb046b1dd0610c23 [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"
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +000021#include "llvm/ADT/Statistic.h"
Alex Bradbury89718422017-10-19 21:37:38 +000022#include "llvm/CodeGen/CallingConvLower.h"
23#include "llvm/CodeGen/MachineFrameInfo.h"
24#include "llvm/CodeGen/MachineFunction.h"
25#include "llvm/CodeGen/MachineInstrBuilder.h"
26#include "llvm/CodeGen/MachineRegisterInfo.h"
27#include "llvm/CodeGen/SelectionDAGISel.h"
28#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
Craig Topper2fa14362018-03-29 17:21:10 +000029#include "llvm/CodeGen/ValueTypes.h"
Alex Bradbury89718422017-10-19 21:37:38 +000030#include "llvm/IR/DiagnosticInfo.h"
31#include "llvm/IR/DiagnosticPrinter.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/raw_ostream.h"
35
36using namespace llvm;
37
38#define DEBUG_TYPE "riscv-lower"
39
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +000040STATISTIC(NumTailCalls, "Number of tail calls");
41
Alex Bradbury89718422017-10-19 21:37:38 +000042RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
43 const RISCVSubtarget &STI)
44 : TargetLowering(TM), Subtarget(STI) {
45
46 MVT XLenVT = Subtarget.getXLenVT();
47
48 // Set up the register classes.
49 addRegisterClass(XLenVT, &RISCV::GPRRegClass);
50
Alex Bradbury76c29ee2018-03-20 12:45:35 +000051 if (Subtarget.hasStdExtF())
52 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
Alex Bradbury0b4175f2018-04-12 05:34:25 +000053 if (Subtarget.hasStdExtD())
54 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
Alex Bradbury76c29ee2018-03-20 12:45:35 +000055
Alex Bradbury89718422017-10-19 21:37:38 +000056 // Compute derived properties from the register classes.
57 computeRegisterProperties(STI.getRegisterInfo());
58
59 setStackPointerRegisterToSaveRestore(RISCV::X2);
60
Alex Bradburycfa62912017-11-08 12:20:01 +000061 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
62 setLoadExtAction(N, XLenVT, MVT::i1, Promote);
63
Alex Bradbury89718422017-10-19 21:37:38 +000064 // TODO: add all necessary setOperationAction calls.
Alex Bradburybfb00d42017-12-11 12:38:17 +000065 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
66
Alex Bradburyffc435e2017-11-21 08:11:03 +000067 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
Alex Bradbury74913e12017-11-08 13:31:40 +000068 setOperationAction(ISD::BR_CC, XLenVT, Expand);
Alex Bradbury65385162017-11-21 07:51:32 +000069 setOperationAction(ISD::SELECT, XLenVT, Custom);
70 setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
71
Alex Bradburybfb00d42017-12-11 12:38:17 +000072 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
73 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
74
Alex Bradburyc85be0d2018-01-10 19:41:03 +000075 setOperationAction(ISD::VASTART, MVT::Other, Custom);
76 setOperationAction(ISD::VAARG, MVT::Other, Expand);
77 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
78 setOperationAction(ISD::VAEND, MVT::Other, Expand);
79
Alex Bradburyffc435e2017-11-21 08:11:03 +000080 for (auto VT : {MVT::i1, MVT::i8, MVT::i16})
81 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
82
Alex Bradbury92138382018-01-18 12:36:38 +000083 if (!Subtarget.hasStdExtM()) {
84 setOperationAction(ISD::MUL, XLenVT, Expand);
85 setOperationAction(ISD::MULHS, XLenVT, Expand);
86 setOperationAction(ISD::MULHU, XLenVT, Expand);
87 setOperationAction(ISD::SDIV, XLenVT, Expand);
88 setOperationAction(ISD::UDIV, XLenVT, Expand);
89 setOperationAction(ISD::SREM, XLenVT, Expand);
90 setOperationAction(ISD::UREM, XLenVT, Expand);
91 }
Alex Bradburyffc435e2017-11-21 08:11:03 +000092
Alex Bradbury92138382018-01-18 12:36:38 +000093 setOperationAction(ISD::SDIVREM, XLenVT, Expand);
94 setOperationAction(ISD::UDIVREM, XLenVT, Expand);
Alex Bradburyffc435e2017-11-21 08:11:03 +000095 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
96 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
Alex Bradburyffc435e2017-11-21 08:11:03 +000097
98 setOperationAction(ISD::SHL_PARTS, XLenVT, Expand);
99 setOperationAction(ISD::SRL_PARTS, XLenVT, Expand);
100 setOperationAction(ISD::SRA_PARTS, XLenVT, Expand);
101
102 setOperationAction(ISD::ROTL, XLenVT, Expand);
103 setOperationAction(ISD::ROTR, XLenVT, Expand);
104 setOperationAction(ISD::BSWAP, XLenVT, Expand);
105 setOperationAction(ISD::CTTZ, XLenVT, Expand);
106 setOperationAction(ISD::CTLZ, XLenVT, Expand);
107 setOperationAction(ISD::CTPOP, XLenVT, Expand);
108
Alex Bradbury21d28fe2018-04-12 05:50:06 +0000109 ISD::CondCode FPCCToExtend[] = {
110 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETO, ISD::SETUEQ,
111 ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE,
112 ISD::SETGT, ISD::SETGE, ISD::SETNE};
113
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000114 if (Subtarget.hasStdExtF()) {
115 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
116 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
Alex Bradbury21d28fe2018-04-12 05:50:06 +0000117 for (auto CC : FPCCToExtend)
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000118 setCondCodeAction(CC, MVT::f32, Expand);
119 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
120 setOperationAction(ISD::SELECT, MVT::f32, Custom);
121 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000122 }
123
Alex Bradbury5d0dfa52018-04-12 05:42:42 +0000124 if (Subtarget.hasStdExtD()) {
125 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
126 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
Alex Bradbury21d28fe2018-04-12 05:50:06 +0000127 for (auto CC : FPCCToExtend)
128 setCondCodeAction(CC, MVT::f64, Expand);
129 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
130 setOperationAction(ISD::SELECT, MVT::f64, Custom);
131 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000132 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
Alex Bradbury60baa2e2018-04-12 05:47:15 +0000133 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
Alex Bradbury5d0dfa52018-04-12 05:42:42 +0000134 }
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000135
Alex Bradburyffc435e2017-11-21 08:11:03 +0000136 setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
137 setOperationAction(ISD::BlockAddress, XLenVT, Custom);
Alex Bradbury80c8eb72018-03-20 13:26:12 +0000138 setOperationAction(ISD::ConstantPool, XLenVT, Custom);
Alex Bradburyffc435e2017-11-21 08:11:03 +0000139
Alex Bradbury21aea512018-09-19 10:54:22 +0000140 if (Subtarget.hasStdExtA()) {
Alex Bradbury96f492d2018-06-13 12:04:51 +0000141 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
Alex Bradbury21aea512018-09-19 10:54:22 +0000142 setMinCmpXchgSizeInBits(32);
143 } else {
Alex Bradbury96f492d2018-06-13 12:04:51 +0000144 setMaxAtomicSizeInBitsSupported(0);
Alex Bradbury21aea512018-09-19 10:54:22 +0000145 }
Alex Bradburydc790dd2018-06-13 11:58:46 +0000146
Alex Bradbury89718422017-10-19 21:37:38 +0000147 setBooleanContents(ZeroOrOneBooleanContent);
148
149 // Function alignments (log2).
Shiva Chenb48b0272018-04-12 11:30:59 +0000150 unsigned FunctionAlignment = Subtarget.hasStdExtC() ? 1 : 2;
151 setMinFunctionAlignment(FunctionAlignment);
152 setPrefFunctionAlignment(FunctionAlignment);
Alex Bradburyffc435e2017-11-21 08:11:03 +0000153
154 // Effectively disable jump table generation.
155 setMinimumJumpTableEntries(INT_MAX);
Alex Bradbury89718422017-10-19 21:37:38 +0000156}
157
Shiva Chenbbf4c5c2018-02-02 02:43:18 +0000158EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
159 EVT VT) const {
160 if (!VT.isVector())
161 return getPointerTy(DL);
162 return VT.changeVectorElementTypeToInteger();
163}
164
Alex Bradbury21aea512018-09-19 10:54:22 +0000165bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
166 const CallInst &I,
167 MachineFunction &MF,
168 unsigned Intrinsic) const {
169 switch (Intrinsic) {
170 default:
171 return false;
172 case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
173 case Intrinsic::riscv_masked_atomicrmw_add_i32:
174 case Intrinsic::riscv_masked_atomicrmw_sub_i32:
175 case Intrinsic::riscv_masked_atomicrmw_nand_i32:
176 case Intrinsic::riscv_masked_atomicrmw_max_i32:
177 case Intrinsic::riscv_masked_atomicrmw_min_i32:
178 case Intrinsic::riscv_masked_atomicrmw_umax_i32:
179 case Intrinsic::riscv_masked_atomicrmw_umin_i32:
180 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
181 Info.opc = ISD::INTRINSIC_W_CHAIN;
182 Info.memVT = MVT::getVT(PtrTy->getElementType());
183 Info.ptrVal = I.getArgOperand(0);
184 Info.offset = 0;
185 Info.align = 4;
186 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
187 MachineMemOperand::MOVolatile;
188 return true;
189 }
190}
191
Alex Bradbury09926292018-04-26 12:13:48 +0000192bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
193 const AddrMode &AM, Type *Ty,
194 unsigned AS,
195 Instruction *I) const {
196 // No global is ever allowed as a base.
197 if (AM.BaseGV)
198 return false;
199
200 // Require a 12-bit signed offset.
201 if (!isInt<12>(AM.BaseOffs))
202 return false;
203
204 switch (AM.Scale) {
205 case 0: // "r+i" or just "i", depending on HasBaseReg.
206 break;
207 case 1:
208 if (!AM.HasBaseReg) // allow "r+i".
209 break;
210 return false; // disallow "r+r" or "r+r+i".
211 default:
212 return false;
213 }
214
215 return true;
216}
217
Alex Bradburydcbff632018-04-26 13:15:17 +0000218bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
219 return isInt<12>(Imm);
220}
221
Alex Bradbury5c41ece2018-04-26 13:00:37 +0000222bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
223 return isInt<12>(Imm);
224}
225
Alex Bradbury130b8b32018-04-26 13:37:00 +0000226// On RV32, 64-bit integers are split into their high and low parts and held
227// in two different registers, so the trunc is free since the low register can
228// just be used.
229bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
230 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
231 return false;
232 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
233 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
234 return (SrcBits == 64 && DestBits == 32);
235}
236
237bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
238 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
239 !SrcVT.isInteger() || !DstVT.isInteger())
240 return false;
241 unsigned SrcBits = SrcVT.getSizeInBits();
242 unsigned DestBits = DstVT.getSizeInBits();
243 return (SrcBits == 64 && DestBits == 32);
244}
245
Alex Bradbury15e894b2018-04-26 14:04:18 +0000246bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
247 // Zexts are free if they can be combined with a load.
248 if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
249 EVT MemVT = LD->getMemoryVT();
250 if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
251 (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
252 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
253 LD->getExtensionType() == ISD::ZEXTLOAD))
254 return true;
255 }
256
257 return TargetLowering::isZExtFree(Val, VT2);
258}
259
Alex Bradbury65385162017-11-21 07:51:32 +0000260// Changes the condition code and swaps operands if necessary, so the SetCC
261// operation matches one of the comparisons supported directly in the RISC-V
262// ISA.
263static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) {
264 switch (CC) {
265 default:
266 break;
267 case ISD::SETGT:
268 case ISD::SETLE:
269 case ISD::SETUGT:
270 case ISD::SETULE:
271 CC = ISD::getSetCCSwappedOperands(CC);
272 std::swap(LHS, RHS);
273 break;
274 }
275}
276
277// Return the RISC-V branch opcode that matches the given DAG integer
278// condition code. The CondCode must be one of those supported by the RISC-V
279// ISA (see normaliseSetCC).
280static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) {
281 switch (CC) {
282 default:
283 llvm_unreachable("Unsupported CondCode");
284 case ISD::SETEQ:
285 return RISCV::BEQ;
286 case ISD::SETNE:
287 return RISCV::BNE;
288 case ISD::SETLT:
289 return RISCV::BLT;
290 case ISD::SETGE:
291 return RISCV::BGE;
292 case ISD::SETULT:
293 return RISCV::BLTU;
294 case ISD::SETUGE:
295 return RISCV::BGEU;
296 }
297}
298
Alex Bradbury89718422017-10-19 21:37:38 +0000299SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
300 SelectionDAG &DAG) const {
301 switch (Op.getOpcode()) {
302 default:
303 report_fatal_error("unimplemented operand");
Alex Bradburyec8aa912017-11-08 13:24:21 +0000304 case ISD::GlobalAddress:
305 return lowerGlobalAddress(Op, DAG);
Alex Bradburyffc435e2017-11-21 08:11:03 +0000306 case ISD::BlockAddress:
307 return lowerBlockAddress(Op, DAG);
Alex Bradbury80c8eb72018-03-20 13:26:12 +0000308 case ISD::ConstantPool:
309 return lowerConstantPool(Op, DAG);
Alex Bradbury65385162017-11-21 07:51:32 +0000310 case ISD::SELECT:
311 return lowerSELECT(Op, DAG);
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000312 case ISD::VASTART:
313 return lowerVASTART(Op, DAG);
Alex Bradbury70f137b2018-01-10 20:12:00 +0000314 case ISD::FRAMEADDR:
315 return LowerFRAMEADDR(Op, DAG);
316 case ISD::RETURNADDR:
317 return LowerRETURNADDR(Op, DAG);
Alex Bradburyec8aa912017-11-08 13:24:21 +0000318 }
319}
320
321SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
322 SelectionDAG &DAG) const {
323 SDLoc DL(Op);
324 EVT Ty = Op.getValueType();
325 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
326 const GlobalValue *GV = N->getGlobal();
327 int64_t Offset = N->getOffset();
Sameer AbuAsal1dc0a8f2018-05-17 18:14:53 +0000328 MVT XLenVT = Subtarget.getXLenVT();
Alex Bradburyec8aa912017-11-08 13:24:21 +0000329
Alex Bradburyffc435e2017-11-21 08:11:03 +0000330 if (isPositionIndependent() || Subtarget.is64Bit())
Alex Bradburyec8aa912017-11-08 13:24:21 +0000331 report_fatal_error("Unable to lowerGlobalAddress");
Sameer AbuAsal1dc0a8f2018-05-17 18:14:53 +0000332 // In order to maximise the opportunity for common subexpression elimination,
333 // emit a separate ADD node for the global address offset instead of folding
334 // it in the global address node. Later peephole optimisations may choose to
335 // fold it back in when profitable.
336 SDValue GAHi = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_HI);
337 SDValue GALo = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_LO);
Alex Bradburyffc435e2017-11-21 08:11:03 +0000338 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, GAHi), 0);
339 SDValue MNLo =
340 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, GALo), 0);
Sameer AbuAsal1dc0a8f2018-05-17 18:14:53 +0000341 if (Offset != 0)
342 return DAG.getNode(ISD::ADD, DL, Ty, MNLo,
343 DAG.getConstant(Offset, DL, XLenVT));
Alex Bradburyffc435e2017-11-21 08:11:03 +0000344 return MNLo;
345}
346
347SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
348 SelectionDAG &DAG) const {
349 SDLoc DL(Op);
350 EVT Ty = Op.getValueType();
351 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
352 const BlockAddress *BA = N->getBlockAddress();
353 int64_t Offset = N->getOffset();
354
355 if (isPositionIndependent() || Subtarget.is64Bit())
356 report_fatal_error("Unable to lowerBlockAddress");
357
358 SDValue BAHi = DAG.getTargetBlockAddress(BA, Ty, Offset, RISCVII::MO_HI);
359 SDValue BALo = DAG.getTargetBlockAddress(BA, Ty, Offset, RISCVII::MO_LO);
360 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, BAHi), 0);
361 SDValue MNLo =
362 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, BALo), 0);
363 return MNLo;
364}
365
Alex Bradbury80c8eb72018-03-20 13:26:12 +0000366SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
367 SelectionDAG &DAG) const {
368 SDLoc DL(Op);
369 EVT Ty = Op.getValueType();
370 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
371 const Constant *CPA = N->getConstVal();
372 int64_t Offset = N->getOffset();
373 unsigned Alignment = N->getAlignment();
374
375 if (!isPositionIndependent()) {
376 SDValue CPAHi =
377 DAG.getTargetConstantPool(CPA, Ty, Alignment, Offset, RISCVII::MO_HI);
378 SDValue CPALo =
379 DAG.getTargetConstantPool(CPA, Ty, Alignment, Offset, RISCVII::MO_LO);
380 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, CPAHi), 0);
381 SDValue MNLo =
382 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, CPALo), 0);
383 return MNLo;
384 } else {
385 report_fatal_error("Unable to lowerConstantPool");
386 }
387}
388
Alex Bradbury65385162017-11-21 07:51:32 +0000389SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
390 SDValue CondV = Op.getOperand(0);
391 SDValue TrueV = Op.getOperand(1);
392 SDValue FalseV = Op.getOperand(2);
393 SDLoc DL(Op);
394 MVT XLenVT = Subtarget.getXLenVT();
395
396 // If the result type is XLenVT and CondV is the output of a SETCC node
397 // which also operated on XLenVT inputs, then merge the SETCC node into the
398 // lowered RISCVISD::SELECT_CC to take advantage of the integer
399 // compare+branch instructions. i.e.:
400 // (select (setcc lhs, rhs, cc), truev, falsev)
401 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
402 if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC &&
403 CondV.getOperand(0).getSimpleValueType() == XLenVT) {
404 SDValue LHS = CondV.getOperand(0);
405 SDValue RHS = CondV.getOperand(1);
406 auto CC = cast<CondCodeSDNode>(CondV.getOperand(2));
407 ISD::CondCode CCVal = CC->get();
408
409 normaliseSetCC(LHS, RHS, CCVal);
410
411 SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT);
412 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
413 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
414 return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
415 }
416
417 // Otherwise:
418 // (select condv, truev, falsev)
419 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
420 SDValue Zero = DAG.getConstant(0, DL, XLenVT);
421 SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT);
422
423 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
424 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
425
426 return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
427}
428
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000429SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
430 MachineFunction &MF = DAG.getMachineFunction();
431 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
432
433 SDLoc DL(Op);
434 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
435 getPointerTy(MF.getDataLayout()));
436
437 // vastart just stores the address of the VarArgsFrameIndex slot into the
438 // memory location argument.
439 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
440 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
441 MachinePointerInfo(SV));
442}
443
Alex Bradbury70f137b2018-01-10 20:12:00 +0000444SDValue RISCVTargetLowering::LowerFRAMEADDR(SDValue Op,
445 SelectionDAG &DAG) const {
446 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
447 MachineFunction &MF = DAG.getMachineFunction();
448 MachineFrameInfo &MFI = MF.getFrameInfo();
449 MFI.setFrameAddressIsTaken(true);
450 unsigned FrameReg = RI.getFrameRegister(MF);
451 int XLenInBytes = Subtarget.getXLen() / 8;
452
453 EVT VT = Op.getValueType();
454 SDLoc DL(Op);
455 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
456 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
457 while (Depth--) {
458 int Offset = -(XLenInBytes * 2);
459 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
460 DAG.getIntPtrConstant(Offset, DL));
461 FrameAddr =
462 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
463 }
464 return FrameAddr;
465}
466
467SDValue RISCVTargetLowering::LowerRETURNADDR(SDValue Op,
468 SelectionDAG &DAG) const {
469 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
470 MachineFunction &MF = DAG.getMachineFunction();
471 MachineFrameInfo &MFI = MF.getFrameInfo();
472 MFI.setReturnAddressIsTaken(true);
473 MVT XLenVT = Subtarget.getXLenVT();
474 int XLenInBytes = Subtarget.getXLen() / 8;
475
476 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
477 return SDValue();
478
479 EVT VT = Op.getValueType();
480 SDLoc DL(Op);
481 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
482 if (Depth) {
483 int Off = -XLenInBytes;
484 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
485 SDValue Offset = DAG.getConstant(Off, DL, VT);
486 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
487 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
488 MachinePointerInfo());
489 }
490
491 // Return the value of the return address register, marking it an implicit
492 // live-in.
493 unsigned Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
494 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
495}
496
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000497static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
498 MachineBasicBlock *BB) {
499 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
500
501 MachineFunction &MF = *BB->getParent();
502 DebugLoc DL = MI.getDebugLoc();
503 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
504 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
505 unsigned LoReg = MI.getOperand(0).getReg();
506 unsigned HiReg = MI.getOperand(1).getReg();
507 unsigned SrcReg = MI.getOperand(2).getReg();
508 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
509 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
510
511 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
512 RI);
513 MachineMemOperand *MMO =
514 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
515 MachineMemOperand::MOLoad, 8, 8);
516 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
517 .addFrameIndex(FI)
518 .addImm(0)
519 .addMemOperand(MMO);
520 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
521 .addFrameIndex(FI)
522 .addImm(4)
523 .addMemOperand(MMO);
524 MI.eraseFromParent(); // The pseudo instruction is gone now.
525 return BB;
526}
527
528static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
529 MachineBasicBlock *BB) {
530 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
531 "Unexpected instruction");
532
533 MachineFunction &MF = *BB->getParent();
534 DebugLoc DL = MI.getDebugLoc();
535 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
536 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
537 unsigned DstReg = MI.getOperand(0).getReg();
538 unsigned LoReg = MI.getOperand(1).getReg();
539 unsigned HiReg = MI.getOperand(2).getReg();
540 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
541 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
542
543 MachineMemOperand *MMO =
544 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
545 MachineMemOperand::MOStore, 8, 8);
546 BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
547 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
548 .addFrameIndex(FI)
549 .addImm(0)
550 .addMemOperand(MMO);
551 BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
552 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
553 .addFrameIndex(FI)
554 .addImm(4)
555 .addMemOperand(MMO);
556 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
557 MI.eraseFromParent(); // The pseudo instruction is gone now.
558 return BB;
559}
560
Alex Bradbury65385162017-11-21 07:51:32 +0000561MachineBasicBlock *
562RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
563 MachineBasicBlock *BB) const {
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000564 switch (MI.getOpcode()) {
565 default:
566 llvm_unreachable("Unexpected instr type to insert");
567 case RISCV::Select_GPR_Using_CC_GPR:
568 case RISCV::Select_FPR32_Using_CC_GPR:
Alex Bradbury21d28fe2018-04-12 05:50:06 +0000569 case RISCV::Select_FPR64_Using_CC_GPR:
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000570 break;
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000571 case RISCV::BuildPairF64Pseudo:
572 return emitBuildPairF64Pseudo(MI, BB);
573 case RISCV::SplitF64Pseudo:
574 return emitSplitF64Pseudo(MI, BB);
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000575 }
Alex Bradbury65385162017-11-21 07:51:32 +0000576
577 // To "insert" a SELECT instruction, we actually have to insert the triangle
578 // control-flow pattern. The incoming instruction knows the destination vreg
579 // to set, the condition code register to branch on, the true/false values to
580 // select between, and the condcode to use to select the appropriate branch.
581 //
582 // We produce the following control flow:
583 // HeadMBB
584 // | \
585 // | IfFalseMBB
586 // | /
587 // TailMBB
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000588 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
Alex Bradbury65385162017-11-21 07:51:32 +0000589 const BasicBlock *LLVM_BB = BB->getBasicBlock();
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000590 DebugLoc DL = MI.getDebugLoc();
Alex Bradbury65385162017-11-21 07:51:32 +0000591 MachineFunction::iterator I = ++BB->getIterator();
592
593 MachineBasicBlock *HeadMBB = BB;
594 MachineFunction *F = BB->getParent();
595 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
596 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
597
598 F->insert(I, IfFalseMBB);
599 F->insert(I, TailMBB);
600 // Move all remaining instructions to TailMBB.
601 TailMBB->splice(TailMBB->begin(), HeadMBB,
602 std::next(MachineBasicBlock::iterator(MI)), HeadMBB->end());
603 // Update machine-CFG edges by transferring all successors of the current
604 // block to the new block which will contain the Phi node for the select.
605 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
606 // Set the successors for HeadMBB.
607 HeadMBB->addSuccessor(IfFalseMBB);
608 HeadMBB->addSuccessor(TailMBB);
609
610 // Insert appropriate branch.
611 unsigned LHS = MI.getOperand(1).getReg();
612 unsigned RHS = MI.getOperand(2).getReg();
613 auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm());
614 unsigned Opcode = getBranchOpcodeForIntCondCode(CC);
615
616 BuildMI(HeadMBB, DL, TII.get(Opcode))
617 .addReg(LHS)
618 .addReg(RHS)
619 .addMBB(TailMBB);
620
621 // IfFalseMBB just falls through to TailMBB.
622 IfFalseMBB->addSuccessor(TailMBB);
623
624 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
625 BuildMI(*TailMBB, TailMBB->begin(), DL, TII.get(RISCV::PHI),
626 MI.getOperand(0).getReg())
627 .addReg(MI.getOperand(4).getReg())
628 .addMBB(HeadMBB)
629 .addReg(MI.getOperand(5).getReg())
630 .addMBB(IfFalseMBB);
631
632 MI.eraseFromParent(); // The pseudo instruction is gone now.
633 return TailMBB;
634}
635
Alex Bradbury89718422017-10-19 21:37:38 +0000636// Calling Convention Implementation.
Alex Bradburydc31c612017-12-11 12:49:02 +0000637// The expectations for frontend ABI lowering vary from target to target.
638// Ideally, an LLVM frontend would be able to avoid worrying about many ABI
639// details, but this is a longer term goal. For now, we simply try to keep the
640// role of the frontend as simple and well-defined as possible. The rules can
641// be summarised as:
642// * Never split up large scalar arguments. We handle them here.
643// * If a hardfloat calling convention is being used, and the struct may be
644// passed in a pair of registers (fp+fp, int+fp), and both registers are
645// available, then pass as two separate arguments. If either the GPRs or FPRs
646// are exhausted, then pass according to the rule below.
647// * If a struct could never be passed in registers or directly in a stack
648// slot (as it is larger than 2*XLEN and the floating point rules don't
649// apply), then pass it using a pointer with the byval attribute.
650// * If a struct is less than 2*XLEN, then coerce to either a two-element
651// word-sized array or a 2*XLEN scalar (depending on alignment).
652// * The frontend can determine whether a struct is returned by reference or
653// not based on its size and fields. If it will be returned by reference, the
654// frontend must modify the prototype so a pointer with the sret annotation is
655// passed as the first argument. This is not necessary for large scalar
656// returns.
657// * Struct return values and varargs should be coerced to structs containing
658// register-size fields in the same situations they would be for fixed
659// arguments.
660
661static const MCPhysReg ArgGPRs[] = {
662 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
663 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
664};
665
666// Pass a 2*XLEN argument that has been split into two XLEN values through
667// registers or the stack as necessary.
668static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
669 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
670 MVT ValVT2, MVT LocVT2,
671 ISD::ArgFlagsTy ArgFlags2) {
672 unsigned XLenInBytes = XLen / 8;
673 if (unsigned Reg = State.AllocateReg(ArgGPRs)) {
674 // At least one half can be passed via register.
675 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
676 VA1.getLocVT(), CCValAssign::Full));
677 } else {
678 // Both halves must be passed on the stack, with proper alignment.
679 unsigned StackAlign = std::max(XLenInBytes, ArgFlags1.getOrigAlign());
680 State.addLoc(
681 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
682 State.AllocateStack(XLenInBytes, StackAlign),
683 VA1.getLocVT(), CCValAssign::Full));
684 State.addLoc(CCValAssign::getMem(
685 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
686 CCValAssign::Full));
687 return false;
688 }
689
690 if (unsigned Reg = State.AllocateReg(ArgGPRs)) {
691 // The second half can also be passed via register.
692 State.addLoc(
693 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
694 } else {
695 // The second half is passed via the stack, without additional alignment.
696 State.addLoc(CCValAssign::getMem(
697 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
698 CCValAssign::Full));
699 }
700
701 return false;
702}
703
704// Implements the RISC-V calling convention. Returns true upon failure.
705static bool CC_RISCV(const DataLayout &DL, unsigned ValNo, MVT ValVT, MVT LocVT,
706 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000707 CCState &State, bool IsFixed, bool IsRet, Type *OrigTy) {
Alex Bradburydc31c612017-12-11 12:49:02 +0000708 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
709 assert(XLen == 32 || XLen == 64);
710 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000711 if (ValVT == MVT::f32) {
712 LocVT = MVT::i32;
713 LocInfo = CCValAssign::BCvt;
714 }
Alex Bradburydc31c612017-12-11 12:49:02 +0000715
716 // Any return value split in to more than two values can't be returned
717 // directly.
718 if (IsRet && ValNo > 1)
719 return true;
720
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000721 // If this is a variadic argument, the RISC-V calling convention requires
722 // that it is assigned an 'even' or 'aligned' register if it has 8-byte
723 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
724 // be used regardless of whether the original argument was split during
725 // legalisation or not. The argument will not be passed by registers if the
726 // original type is larger than 2*XLEN, so the register alignment rule does
727 // not apply.
728 unsigned TwoXLenInBytes = (2 * XLen) / 8;
729 if (!IsFixed && ArgFlags.getOrigAlign() == TwoXLenInBytes &&
730 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
731 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
732 // Skip 'odd' register if necessary.
733 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
734 State.AllocateReg(ArgGPRs);
735 }
736
Alex Bradburydc31c612017-12-11 12:49:02 +0000737 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
738 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
739 State.getPendingArgFlags();
740
741 assert(PendingLocs.size() == PendingArgFlags.size() &&
742 "PendingLocs and PendingArgFlags out of sync");
743
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000744 // Handle passing f64 on RV32D with a soft float ABI.
745 if (XLen == 32 && ValVT == MVT::f64) {
Mandeep Singh Grang88a8b262018-04-16 18:56:10 +0000746 assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000747 "Can't lower f64 if it is split");
748 // Depending on available argument GPRS, f64 may be passed in a pair of
749 // GPRs, split between a GPR and the stack, or passed completely on the
750 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
751 // cases.
752 unsigned Reg = State.AllocateReg(ArgGPRs);
753 LocVT = MVT::i32;
754 if (!Reg) {
755 unsigned StackOffset = State.AllocateStack(8, 8);
756 State.addLoc(
757 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
758 return false;
759 }
760 if (!State.AllocateReg(ArgGPRs))
761 State.AllocateStack(4, 4);
762 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
763 return false;
764 }
765
Alex Bradburydc31c612017-12-11 12:49:02 +0000766 // Split arguments might be passed indirectly, so keep track of the pending
767 // values.
768 if (ArgFlags.isSplit() || !PendingLocs.empty()) {
769 LocVT = XLenVT;
770 LocInfo = CCValAssign::Indirect;
771 PendingLocs.push_back(
772 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
773 PendingArgFlags.push_back(ArgFlags);
774 if (!ArgFlags.isSplitEnd()) {
775 return false;
776 }
777 }
778
779 // If the split argument only had two elements, it should be passed directly
780 // in registers or on the stack.
781 if (ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) {
782 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
783 // Apply the normal calling convention rules to the first half of the
784 // split argument.
785 CCValAssign VA = PendingLocs[0];
786 ISD::ArgFlagsTy AF = PendingArgFlags[0];
787 PendingLocs.clear();
788 PendingArgFlags.clear();
789 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
790 ArgFlags);
791 }
792
793 // Allocate to a register if possible, or else a stack slot.
794 unsigned Reg = State.AllocateReg(ArgGPRs);
795 unsigned StackOffset = Reg ? 0 : State.AllocateStack(XLen / 8, XLen / 8);
796
797 // If we reach this point and PendingLocs is non-empty, we must be at the
798 // end of a split argument that must be passed indirectly.
799 if (!PendingLocs.empty()) {
800 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
801 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
802
803 for (auto &It : PendingLocs) {
804 if (Reg)
805 It.convertToReg(Reg);
806 else
807 It.convertToMem(StackOffset);
808 State.addLoc(It);
809 }
810 PendingLocs.clear();
811 PendingArgFlags.clear();
812 return false;
813 }
814
815 assert(LocVT == XLenVT && "Expected an XLenVT at this stage");
816
817 if (Reg) {
818 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
819 } else {
820 State.addLoc(
821 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
822 }
823 return false;
824}
825
826void RISCVTargetLowering::analyzeInputArgs(
827 MachineFunction &MF, CCState &CCInfo,
828 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const {
829 unsigned NumArgs = Ins.size();
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000830 FunctionType *FType = MF.getFunction().getFunctionType();
Alex Bradburydc31c612017-12-11 12:49:02 +0000831
832 for (unsigned i = 0; i != NumArgs; ++i) {
833 MVT ArgVT = Ins[i].VT;
834 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
835
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000836 Type *ArgTy = nullptr;
837 if (IsRet)
838 ArgTy = FType->getReturnType();
839 else if (Ins[i].isOrigArg())
840 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
841
Alex Bradburydc31c612017-12-11 12:49:02 +0000842 if (CC_RISCV(MF.getDataLayout(), i, ArgVT, ArgVT, CCValAssign::Full,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000843 ArgFlags, CCInfo, /*IsRet=*/true, IsRet, ArgTy)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000844 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
845 << EVT(ArgVT).getEVTString() << '\n');
Alex Bradburydc31c612017-12-11 12:49:02 +0000846 llvm_unreachable(nullptr);
847 }
848 }
849}
850
851void RISCVTargetLowering::analyzeOutputArgs(
852 MachineFunction &MF, CCState &CCInfo,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000853 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
854 CallLoweringInfo *CLI) const {
Alex Bradburydc31c612017-12-11 12:49:02 +0000855 unsigned NumArgs = Outs.size();
856
857 for (unsigned i = 0; i != NumArgs; i++) {
858 MVT ArgVT = Outs[i].VT;
859 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000860 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
Alex Bradburydc31c612017-12-11 12:49:02 +0000861
862 if (CC_RISCV(MF.getDataLayout(), i, ArgVT, ArgVT, CCValAssign::Full,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000863 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000864 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
865 << EVT(ArgVT).getEVTString() << "\n");
Alex Bradburydc31c612017-12-11 12:49:02 +0000866 llvm_unreachable(nullptr);
867 }
868 }
869}
870
871// The caller is responsible for loading the full value if the argument is
872// passed with CCValAssign::Indirect.
873static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
874 const CCValAssign &VA, const SDLoc &DL) {
875 MachineFunction &MF = DAG.getMachineFunction();
876 MachineRegisterInfo &RegInfo = MF.getRegInfo();
877 EVT LocVT = VA.getLocVT();
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000878 EVT ValVT = VA.getValVT();
Alex Bradburydc31c612017-12-11 12:49:02 +0000879 SDValue Val;
880
881 unsigned VReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
882 RegInfo.addLiveIn(VA.getLocReg(), VReg);
883 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
884
885 switch (VA.getLocInfo()) {
886 default:
887 llvm_unreachable("Unexpected CCValAssign::LocInfo");
888 case CCValAssign::Full:
889 case CCValAssign::Indirect:
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000890 break;
891 case CCValAssign::BCvt:
892 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
893 break;
Alex Bradburydc31c612017-12-11 12:49:02 +0000894 }
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000895 return Val;
Alex Bradburydc31c612017-12-11 12:49:02 +0000896}
897
898// The caller is responsible for loading the full value if the argument is
899// passed with CCValAssign::Indirect.
900static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
901 const CCValAssign &VA, const SDLoc &DL) {
902 MachineFunction &MF = DAG.getMachineFunction();
903 MachineFrameInfo &MFI = MF.getFrameInfo();
904 EVT LocVT = VA.getLocVT();
905 EVT ValVT = VA.getValVT();
906 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
907 int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
908 VA.getLocMemOffset(), /*Immutable=*/true);
909 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
910 SDValue Val;
911
912 ISD::LoadExtType ExtType;
913 switch (VA.getLocInfo()) {
914 default:
915 llvm_unreachable("Unexpected CCValAssign::LocInfo");
916 case CCValAssign::Full:
917 case CCValAssign::Indirect:
918 ExtType = ISD::NON_EXTLOAD;
919 break;
920 }
921 Val = DAG.getExtLoad(
922 ExtType, DL, LocVT, Chain, FIN,
923 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
924 return Val;
925}
Alex Bradbury89718422017-10-19 21:37:38 +0000926
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000927static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
928 const CCValAssign &VA, const SDLoc &DL) {
929 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
930 "Unexpected VA");
931 MachineFunction &MF = DAG.getMachineFunction();
932 MachineFrameInfo &MFI = MF.getFrameInfo();
933 MachineRegisterInfo &RegInfo = MF.getRegInfo();
934
935 if (VA.isMemLoc()) {
936 // f64 is passed on the stack.
937 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
938 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
939 return DAG.getLoad(MVT::f64, DL, Chain, FIN,
940 MachinePointerInfo::getFixedStack(MF, FI));
941 }
942
943 assert(VA.isRegLoc() && "Expected register VA assignment");
944
945 unsigned LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
946 RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
947 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
948 SDValue Hi;
949 if (VA.getLocReg() == RISCV::X17) {
950 // Second half of f64 is passed on the stack.
951 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
952 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
953 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
954 MachinePointerInfo::getFixedStack(MF, FI));
955 } else {
956 // Second half of f64 is passed in another GPR.
957 unsigned HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
958 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
959 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
960 }
961 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
962}
963
Alex Bradbury89718422017-10-19 21:37:38 +0000964// Transform physical registers into virtual registers.
965SDValue RISCVTargetLowering::LowerFormalArguments(
966 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
967 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
968 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
969
970 switch (CallConv) {
971 default:
972 report_fatal_error("Unsupported calling convention");
973 case CallingConv::C:
Alex Bradburya3376752017-11-08 13:41:21 +0000974 case CallingConv::Fast:
Alex Bradbury89718422017-10-19 21:37:38 +0000975 break;
976 }
977
978 MachineFunction &MF = DAG.getMachineFunction();
Ana Pazos2e4106b2018-07-26 17:49:43 +0000979
980 const Function &Func = MF.getFunction();
981 if (Func.hasFnAttribute("interrupt")) {
982 if (!Func.arg_empty())
983 report_fatal_error(
984 "Functions with the interrupt attribute cannot have arguments!");
985
986 StringRef Kind =
987 MF.getFunction().getFnAttribute("interrupt").getValueAsString();
988
989 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
990 report_fatal_error(
991 "Function interrupt attribute argument not supported!");
992 }
993
Alex Bradburydc31c612017-12-11 12:49:02 +0000994 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000995 MVT XLenVT = Subtarget.getXLenVT();
996 unsigned XLenInBytes = Subtarget.getXLen() / 8;
997 // Used with vargs to acumulate store chains.
998 std::vector<SDValue> OutChains;
Alex Bradbury89718422017-10-19 21:37:38 +0000999
1000 // Assign locations to all of the incoming arguments.
1001 SmallVector<CCValAssign, 16> ArgLocs;
1002 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
Alex Bradburydc31c612017-12-11 12:49:02 +00001003 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false);
Alex Bradbury89718422017-10-19 21:37:38 +00001004
Alex Bradburydc31c612017-12-11 12:49:02 +00001005 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1006 CCValAssign &VA = ArgLocs[i];
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001007 assert(VA.getLocVT() == XLenVT && "Unhandled argument type");
Alex Bradburydc31c612017-12-11 12:49:02 +00001008 SDValue ArgValue;
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001009 // Passing f64 on RV32D with a soft float ABI must be handled as a special
1010 // case.
1011 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
1012 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
1013 else if (VA.isRegLoc())
Alex Bradburydc31c612017-12-11 12:49:02 +00001014 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL);
1015 else
1016 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
Alex Bradbury89718422017-10-19 21:37:38 +00001017
Alex Bradburydc31c612017-12-11 12:49:02 +00001018 if (VA.getLocInfo() == CCValAssign::Indirect) {
1019 // If the original argument was split and passed by reference (e.g. i128
1020 // on RV32), we need to load all parts of it here (using the same
1021 // address).
1022 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
1023 MachinePointerInfo()));
1024 unsigned ArgIndex = Ins[i].OrigArgIndex;
1025 assert(Ins[i].PartOffset == 0);
1026 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
1027 CCValAssign &PartVA = ArgLocs[i + 1];
1028 unsigned PartOffset = Ins[i + 1].PartOffset;
1029 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
1030 DAG.getIntPtrConstant(PartOffset, DL));
1031 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
1032 MachinePointerInfo()));
1033 ++i;
1034 }
1035 continue;
Alex Bradbury89718422017-10-19 21:37:38 +00001036 }
Alex Bradburydc31c612017-12-11 12:49:02 +00001037 InVals.push_back(ArgValue);
Alex Bradbury89718422017-10-19 21:37:38 +00001038 }
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001039
1040 if (IsVarArg) {
1041 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
1042 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
1043 const TargetRegisterClass *RC = &RISCV::GPRRegClass;
1044 MachineFrameInfo &MFI = MF.getFrameInfo();
1045 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1046 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1047
1048 // Offset of the first variable argument from stack pointer, and size of
1049 // the vararg save area. For now, the varargs save area is either zero or
1050 // large enough to hold a0-a7.
1051 int VaArgOffset, VarArgsSaveSize;
1052
1053 // If all registers are allocated, then all varargs must be passed on the
1054 // stack and we don't need to save any argregs.
1055 if (ArgRegs.size() == Idx) {
1056 VaArgOffset = CCInfo.getNextStackOffset();
1057 VarArgsSaveSize = 0;
1058 } else {
1059 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
1060 VaArgOffset = -VarArgsSaveSize;
1061 }
1062
1063 // Record the frame index of the first variable argument
1064 // which is a value necessary to VASTART.
1065 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1066 RVFI->setVarArgsFrameIndex(FI);
1067
1068 // If saving an odd number of registers then create an extra stack slot to
1069 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
1070 // offsets to even-numbered registered remain 2*XLEN-aligned.
1071 if (Idx % 2) {
1072 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes,
1073 true);
1074 VarArgsSaveSize += XLenInBytes;
1075 }
1076
1077 // Copy the integer registers that may have been used for passing varargs
1078 // to the vararg save area.
1079 for (unsigned I = Idx; I < ArgRegs.size();
1080 ++I, VaArgOffset += XLenInBytes) {
1081 const unsigned Reg = RegInfo.createVirtualRegister(RC);
1082 RegInfo.addLiveIn(ArgRegs[I], Reg);
1083 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
1084 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1085 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1086 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
1087 MachinePointerInfo::getFixedStack(MF, FI));
1088 cast<StoreSDNode>(Store.getNode())
1089 ->getMemOperand()
1090 ->setValue((Value *)nullptr);
1091 OutChains.push_back(Store);
1092 }
1093 RVFI->setVarArgsSaveSize(VarArgsSaveSize);
1094 }
1095
1096 // All stores are grouped in one node to allow the matching between
1097 // the size of Ins and InVals. This only happens for vararg functions.
1098 if (!OutChains.empty()) {
1099 OutChains.push_back(Chain);
1100 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
1101 }
1102
Alex Bradbury89718422017-10-19 21:37:38 +00001103 return Chain;
1104}
1105
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +00001106/// IsEligibleForTailCallOptimization - Check whether the call is eligible
1107/// for tail call optimization.
1108/// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
1109bool RISCVTargetLowering::IsEligibleForTailCallOptimization(
1110 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
1111 const SmallVector<CCValAssign, 16> &ArgLocs) const {
1112
1113 auto &Callee = CLI.Callee;
1114 auto CalleeCC = CLI.CallConv;
1115 auto IsVarArg = CLI.IsVarArg;
1116 auto &Outs = CLI.Outs;
1117 auto &Caller = MF.getFunction();
1118 auto CallerCC = Caller.getCallingConv();
1119
1120 // Do not tail call opt functions with "disable-tail-calls" attribute.
1121 if (Caller.getFnAttribute("disable-tail-calls").getValueAsString() == "true")
1122 return false;
1123
1124 // Exception-handling functions need a special set of instructions to
1125 // indicate a return to the hardware. Tail-calling another function would
1126 // probably break this.
1127 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
1128 // should be expanded as new function attributes are introduced.
1129 if (Caller.hasFnAttribute("interrupt"))
1130 return false;
1131
1132 // Do not tail call opt functions with varargs.
1133 if (IsVarArg)
1134 return false;
1135
1136 // Do not tail call opt if the stack is used to pass parameters.
1137 if (CCInfo.getNextStackOffset() != 0)
1138 return false;
1139
1140 // Do not tail call opt if any parameters need to be passed indirectly.
1141 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
1142 // passed indirectly. So the address of the value will be passed in a
1143 // register, or if not available, then the address is put on the stack. In
1144 // order to pass indirectly, space on the stack often needs to be allocated
1145 // in order to store the value. In this case the CCInfo.getNextStackOffset()
1146 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
1147 // are passed CCValAssign::Indirect.
1148 for (auto &VA : ArgLocs)
1149 if (VA.getLocInfo() == CCValAssign::Indirect)
1150 return false;
1151
1152 // Do not tail call opt if either caller or callee uses struct return
1153 // semantics.
1154 auto IsCallerStructRet = Caller.hasStructRetAttr();
1155 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
1156 if (IsCallerStructRet || IsCalleeStructRet)
1157 return false;
1158
1159 // Externally-defined functions with weak linkage should not be
1160 // tail-called. The behaviour of branch instructions in this situation (as
1161 // used for tail calls) is implementation-defined, so we cannot rely on the
1162 // linker replacing the tail call with a return.
1163 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1164 const GlobalValue *GV = G->getGlobal();
1165 if (GV->hasExternalWeakLinkage())
1166 return false;
1167 }
1168
1169 // The callee has to preserve all registers the caller needs to preserve.
1170 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
1171 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
1172 if (CalleeCC != CallerCC) {
1173 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
1174 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
1175 return false;
1176 }
1177
1178 // Byval parameters hand the function a pointer directly into the stack area
1179 // we want to reuse during a tail call. Working around this *is* possible
1180 // but less efficient and uglier in LowerCall.
1181 for (auto &Arg : Outs)
1182 if (Arg.Flags.isByVal())
1183 return false;
1184
1185 return true;
1186}
1187
Alex Bradburya3376752017-11-08 13:41:21 +00001188// Lower a call to a callseq_start + CALL + callseq_end chain, and add input
1189// and output parameter nodes.
1190SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
1191 SmallVectorImpl<SDValue> &InVals) const {
1192 SelectionDAG &DAG = CLI.DAG;
1193 SDLoc &DL = CLI.DL;
1194 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1195 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1196 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1197 SDValue Chain = CLI.Chain;
1198 SDValue Callee = CLI.Callee;
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +00001199 bool &IsTailCall = CLI.IsTailCall;
Alex Bradburya3376752017-11-08 13:41:21 +00001200 CallingConv::ID CallConv = CLI.CallConv;
1201 bool IsVarArg = CLI.IsVarArg;
1202 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Alex Bradburydc31c612017-12-11 12:49:02 +00001203 MVT XLenVT = Subtarget.getXLenVT();
Alex Bradburya3376752017-11-08 13:41:21 +00001204
Alex Bradburya3376752017-11-08 13:41:21 +00001205 MachineFunction &MF = DAG.getMachineFunction();
1206
1207 // Analyze the operands of the call, assigning locations to each operand.
1208 SmallVector<CCValAssign, 16> ArgLocs;
1209 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001210 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI);
Alex Bradburya3376752017-11-08 13:41:21 +00001211
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +00001212 // Check if it's really possible to do a tail call.
1213 if (IsTailCall)
1214 IsTailCall = IsEligibleForTailCallOptimization(ArgCCInfo, CLI, MF,
1215 ArgLocs);
1216
1217 if (IsTailCall)
1218 ++NumTailCalls;
1219 else if (CLI.CS && CLI.CS.isMustTailCall())
1220 report_fatal_error("failed to perform tail call elimination on a call "
1221 "site marked musttail");
1222
Alex Bradburya3376752017-11-08 13:41:21 +00001223 // Get a count of how many bytes are to be pushed on the stack.
1224 unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1225
Alex Bradburydc31c612017-12-11 12:49:02 +00001226 // Create local copies for byval args
1227 SmallVector<SDValue, 8> ByValArgs;
1228 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1229 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1230 if (!Flags.isByVal())
Alex Bradburya3376752017-11-08 13:41:21 +00001231 continue;
Alex Bradburydc31c612017-12-11 12:49:02 +00001232
1233 SDValue Arg = OutVals[i];
1234 unsigned Size = Flags.getByValSize();
1235 unsigned Align = Flags.getByValAlign();
1236
1237 int FI = MF.getFrameInfo().CreateStackObject(Size, Align, /*isSS=*/false);
1238 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1239 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
1240
1241 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Align,
1242 /*IsVolatile=*/false,
1243 /*AlwaysInline=*/false,
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +00001244 IsTailCall, MachinePointerInfo(),
Alex Bradburydc31c612017-12-11 12:49:02 +00001245 MachinePointerInfo());
1246 ByValArgs.push_back(FIPtr);
Alex Bradburya3376752017-11-08 13:41:21 +00001247 }
1248
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +00001249 if (!IsTailCall)
1250 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
Alex Bradburya3376752017-11-08 13:41:21 +00001251
1252 // Copy argument values to their designated locations.
1253 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
Alex Bradburydc31c612017-12-11 12:49:02 +00001254 SmallVector<SDValue, 8> MemOpChains;
Alex Bradburya3376752017-11-08 13:41:21 +00001255 SDValue StackPtr;
Alex Bradburydc31c612017-12-11 12:49:02 +00001256 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
1257 CCValAssign &VA = ArgLocs[i];
1258 SDValue ArgValue = OutVals[i];
1259 ISD::ArgFlagsTy Flags = Outs[i].Flags;
Alex Bradburya3376752017-11-08 13:41:21 +00001260
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001261 // Handle passing f64 on RV32D with a soft float ABI as a special case.
1262 bool IsF64OnRV32DSoftABI =
1263 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
1264 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
1265 SDValue SplitF64 = DAG.getNode(
1266 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
1267 SDValue Lo = SplitF64.getValue(0);
1268 SDValue Hi = SplitF64.getValue(1);
1269
1270 unsigned RegLo = VA.getLocReg();
1271 RegsToPass.push_back(std::make_pair(RegLo, Lo));
1272
1273 if (RegLo == RISCV::X17) {
1274 // Second half of f64 is passed on the stack.
1275 // Work out the address of the stack slot.
1276 if (!StackPtr.getNode())
1277 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
1278 // Emit the store.
1279 MemOpChains.push_back(
1280 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
1281 } else {
1282 // Second half of f64 is passed in another GPR.
1283 unsigned RegHigh = RegLo + 1;
1284 RegsToPass.push_back(std::make_pair(RegHigh, Hi));
1285 }
1286 continue;
1287 }
1288
1289 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
1290 // as any other MemLoc.
1291
Alex Bradburya3376752017-11-08 13:41:21 +00001292 // Promote the value if needed.
Alex Bradburydc31c612017-12-11 12:49:02 +00001293 // For now, only handle fully promoted and indirect arguments.
Alex Bradburya3376752017-11-08 13:41:21 +00001294 switch (VA.getLocInfo()) {
1295 case CCValAssign::Full:
1296 break;
Alex Bradbury76c29ee2018-03-20 12:45:35 +00001297 case CCValAssign::BCvt:
1298 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), ArgValue);
1299 break;
Alex Bradburydc31c612017-12-11 12:49:02 +00001300 case CCValAssign::Indirect: {
1301 // Store the argument in a stack slot and pass its address.
1302 SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT);
1303 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1304 MemOpChains.push_back(
1305 DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1306 MachinePointerInfo::getFixedStack(MF, FI)));
1307 // If the original argument was split (e.g. i128), we need
1308 // to store all parts of it here (and pass just one address).
1309 unsigned ArgIndex = Outs[i].OrigArgIndex;
1310 assert(Outs[i].PartOffset == 0);
1311 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
1312 SDValue PartValue = OutVals[i + 1];
1313 unsigned PartOffset = Outs[i + 1].PartOffset;
1314 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
1315 DAG.getIntPtrConstant(PartOffset, DL));
1316 MemOpChains.push_back(
1317 DAG.getStore(Chain, DL, PartValue, Address,
1318 MachinePointerInfo::getFixedStack(MF, FI)));
1319 ++i;
1320 }
1321 ArgValue = SpillSlot;
1322 break;
1323 }
Alex Bradburya3376752017-11-08 13:41:21 +00001324 default:
1325 llvm_unreachable("Unknown loc info!");
1326 }
1327
Alex Bradburydc31c612017-12-11 12:49:02 +00001328 // Use local copy if it is a byval arg.
1329 if (Flags.isByVal())
1330 ArgValue = ByValArgs[j++];
1331
Alex Bradburya3376752017-11-08 13:41:21 +00001332 if (VA.isRegLoc()) {
1333 // Queue up the argument copies and emit them at the end.
1334 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1335 } else {
1336 assert(VA.isMemLoc() && "Argument not register or memory");
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +00001337 assert(!IsTailCall && "Tail call not allowed if stack is used "
1338 "for passing parameters");
Alex Bradburydc31c612017-12-11 12:49:02 +00001339
1340 // Work out the address of the stack slot.
1341 if (!StackPtr.getNode())
1342 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
1343 SDValue Address =
1344 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1345 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
1346
1347 // Emit the store.
1348 MemOpChains.push_back(
1349 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
Alex Bradburya3376752017-11-08 13:41:21 +00001350 }
1351 }
1352
Alex Bradburydc31c612017-12-11 12:49:02 +00001353 // Join the stores, which are independent of one another.
1354 if (!MemOpChains.empty())
1355 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1356
Alex Bradburya3376752017-11-08 13:41:21 +00001357 SDValue Glue;
1358
1359 // Build a sequence of copy-to-reg nodes, chained and glued together.
1360 for (auto &Reg : RegsToPass) {
1361 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
1362 Glue = Chain.getValue(1);
1363 }
1364
Shiva Chend58bd8d2018-04-25 14:19:12 +00001365 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
1366 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
1367 // split it and then direct call can be matched by PseudoCALL.
1368 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
1369 Callee = DAG.getTargetGlobalAddress(S->getGlobal(), DL, PtrVT, 0, 0);
1370 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1371 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, 0);
Alex Bradburya3376752017-11-08 13:41:21 +00001372 }
1373
1374 // The first call operand is the chain and the second is the target address.
1375 SmallVector<SDValue, 8> Ops;
1376 Ops.push_back(Chain);
1377 Ops.push_back(Callee);
1378
1379 // Add argument registers to the end of the list so that they are
1380 // known live into the call.
1381 for (auto &Reg : RegsToPass)
1382 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
1383
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +00001384 if (!IsTailCall) {
1385 // Add a register mask operand representing the call-preserved registers.
1386 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1387 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1388 assert(Mask && "Missing call preserved mask for calling convention");
1389 Ops.push_back(DAG.getRegisterMask(Mask));
1390 }
Alex Bradburya3376752017-11-08 13:41:21 +00001391
1392 // Glue the call to the argument copies, if any.
1393 if (Glue.getNode())
1394 Ops.push_back(Glue);
1395
1396 // Emit the call.
1397 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +00001398
1399 if (IsTailCall) {
1400 MF.getFrameInfo().setHasTailCall();
1401 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
1402 }
1403
Alex Bradburya3376752017-11-08 13:41:21 +00001404 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
1405 Glue = Chain.getValue(1);
1406
1407 // Mark the end of the call, which is glued to the call itself.
1408 Chain = DAG.getCALLSEQ_END(Chain,
1409 DAG.getConstant(NumBytes, DL, PtrVT, true),
1410 DAG.getConstant(0, DL, PtrVT, true),
1411 Glue, DL);
1412 Glue = Chain.getValue(1);
1413
1414 // Assign locations to each value returned by this call.
1415 SmallVector<CCValAssign, 16> RVLocs;
1416 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
Alex Bradburydc31c612017-12-11 12:49:02 +00001417 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true);
Alex Bradburya3376752017-11-08 13:41:21 +00001418
1419 // Copy all of the result registers out of their specified physreg.
1420 for (auto &VA : RVLocs) {
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001421 // Copy the value out
1422 SDValue RetValue =
1423 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
1424 // Glue the RetValue to the end of the call sequence
Alex Bradburya3376752017-11-08 13:41:21 +00001425 Chain = RetValue.getValue(1);
1426 Glue = RetValue.getValue(2);
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001427 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
1428 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
1429 SDValue RetValue2 =
1430 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
1431 Chain = RetValue2.getValue(1);
1432 Glue = RetValue2.getValue(2);
1433 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
1434 RetValue2);
1435 }
Alex Bradburya3376752017-11-08 13:41:21 +00001436
Alex Bradbury76c29ee2018-03-20 12:45:35 +00001437 switch (VA.getLocInfo()) {
1438 default:
1439 llvm_unreachable("Unknown loc info!");
1440 case CCValAssign::Full:
1441 break;
1442 case CCValAssign::BCvt:
1443 RetValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), RetValue);
1444 break;
1445 }
1446
Alex Bradburydc31c612017-12-11 12:49:02 +00001447 InVals.push_back(RetValue);
Alex Bradburya3376752017-11-08 13:41:21 +00001448 }
1449
1450 return Chain;
1451}
1452
Alex Bradburydc31c612017-12-11 12:49:02 +00001453bool RISCVTargetLowering::CanLowerReturn(
1454 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
1455 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
1456 SmallVector<CCValAssign, 16> RVLocs;
1457 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
1458 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1459 MVT VT = Outs[i].VT;
1460 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1461 if (CC_RISCV(MF.getDataLayout(), i, VT, VT, CCValAssign::Full, ArgFlags,
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001462 CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr))
Alex Bradburydc31c612017-12-11 12:49:02 +00001463 return false;
1464 }
1465 return true;
1466}
1467
Alex Bradbury76c29ee2018-03-20 12:45:35 +00001468static SDValue packIntoRegLoc(SelectionDAG &DAG, SDValue Val,
1469 const CCValAssign &VA, const SDLoc &DL) {
1470 EVT LocVT = VA.getLocVT();
1471
1472 switch (VA.getLocInfo()) {
1473 default:
1474 llvm_unreachable("Unexpected CCValAssign::LocInfo");
1475 case CCValAssign::Full:
1476 break;
1477 case CCValAssign::BCvt:
1478 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
1479 break;
1480 }
1481 return Val;
1482}
1483
Alex Bradbury89718422017-10-19 21:37:38 +00001484SDValue
1485RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1486 bool IsVarArg,
1487 const SmallVectorImpl<ISD::OutputArg> &Outs,
1488 const SmallVectorImpl<SDValue> &OutVals,
1489 const SDLoc &DL, SelectionDAG &DAG) const {
Alex Bradbury89718422017-10-19 21:37:38 +00001490 // Stores the assignment of the return value to a location.
1491 SmallVector<CCValAssign, 16> RVLocs;
1492
1493 // Info about the registers and stack slot.
1494 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
1495 *DAG.getContext());
1496
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001497 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
1498 nullptr);
Alex Bradbury89718422017-10-19 21:37:38 +00001499
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001500 SDValue Glue;
Alex Bradbury89718422017-10-19 21:37:38 +00001501 SmallVector<SDValue, 4> RetOps(1, Chain);
1502
1503 // Copy the result values into the output registers.
1504 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
Alex Bradburydc31c612017-12-11 12:49:02 +00001505 SDValue Val = OutVals[i];
Alex Bradbury89718422017-10-19 21:37:38 +00001506 CCValAssign &VA = RVLocs[i];
1507 assert(VA.isRegLoc() && "Can only return in registers!");
1508
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001509 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
1510 // Handle returning f64 on RV32D with a soft float ABI.
1511 assert(VA.isRegLoc() && "Expected return via registers");
1512 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
1513 DAG.getVTList(MVT::i32, MVT::i32), Val);
1514 SDValue Lo = SplitF64.getValue(0);
1515 SDValue Hi = SplitF64.getValue(1);
1516 unsigned RegLo = VA.getLocReg();
1517 unsigned RegHi = RegLo + 1;
1518 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
1519 Glue = Chain.getValue(1);
1520 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
1521 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
1522 Glue = Chain.getValue(1);
1523 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
1524 } else {
1525 // Handle a 'normal' return.
1526 Val = packIntoRegLoc(DAG, Val, VA, DL);
1527 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
Alex Bradbury89718422017-10-19 21:37:38 +00001528
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001529 // Guarantee that all emitted copies are stuck together.
1530 Glue = Chain.getValue(1);
1531 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1532 }
Alex Bradbury89718422017-10-19 21:37:38 +00001533 }
1534
1535 RetOps[0] = Chain; // Update chain.
1536
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001537 // Add the glue node if we have it.
1538 if (Glue.getNode()) {
1539 RetOps.push_back(Glue);
Alex Bradbury89718422017-10-19 21:37:38 +00001540 }
1541
Ana Pazos2e4106b2018-07-26 17:49:43 +00001542 // Interrupt service routines use different return instructions.
1543 const Function &Func = DAG.getMachineFunction().getFunction();
1544 if (Func.hasFnAttribute("interrupt")) {
1545 if (!Func.getReturnType()->isVoidTy())
1546 report_fatal_error(
1547 "Functions with the interrupt attribute must have void return type!");
1548
1549 MachineFunction &MF = DAG.getMachineFunction();
1550 StringRef Kind =
1551 MF.getFunction().getFnAttribute("interrupt").getValueAsString();
1552
1553 unsigned RetOpc;
1554 if (Kind == "user")
1555 RetOpc = RISCVISD::URET_FLAG;
1556 else if (Kind == "supervisor")
1557 RetOpc = RISCVISD::SRET_FLAG;
1558 else
1559 RetOpc = RISCVISD::MRET_FLAG;
1560
1561 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
1562 }
1563
Alex Bradbury89718422017-10-19 21:37:38 +00001564 return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps);
1565}
1566
1567const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
1568 switch ((RISCVISD::NodeType)Opcode) {
1569 case RISCVISD::FIRST_NUMBER:
1570 break;
1571 case RISCVISD::RET_FLAG:
1572 return "RISCVISD::RET_FLAG";
Ana Pazos2e4106b2018-07-26 17:49:43 +00001573 case RISCVISD::URET_FLAG:
1574 return "RISCVISD::URET_FLAG";
1575 case RISCVISD::SRET_FLAG:
1576 return "RISCVISD::SRET_FLAG";
1577 case RISCVISD::MRET_FLAG:
1578 return "RISCVISD::MRET_FLAG";
Alex Bradburya3376752017-11-08 13:41:21 +00001579 case RISCVISD::CALL:
1580 return "RISCVISD::CALL";
Alex Bradbury65385162017-11-21 07:51:32 +00001581 case RISCVISD::SELECT_CC:
1582 return "RISCVISD::SELECT_CC";
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001583 case RISCVISD::BuildPairF64:
1584 return "RISCVISD::BuildPairF64";
1585 case RISCVISD::SplitF64:
1586 return "RISCVISD::SplitF64";
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +00001587 case RISCVISD::TAIL:
1588 return "RISCVISD::TAIL";
Alex Bradbury89718422017-10-19 21:37:38 +00001589 }
1590 return nullptr;
1591}
Alex Bradbury9330e642018-01-10 20:05:09 +00001592
1593std::pair<unsigned, const TargetRegisterClass *>
1594RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
1595 StringRef Constraint,
1596 MVT VT) const {
1597 // First, see if this is a constraint that directly corresponds to a
1598 // RISCV register class.
1599 if (Constraint.size() == 1) {
1600 switch (Constraint[0]) {
1601 case 'r':
1602 return std::make_pair(0U, &RISCV::GPRRegClass);
1603 default:
1604 break;
1605 }
1606 }
1607
1608 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1609}
Alex Bradbury96f492d2018-06-13 12:04:51 +00001610
1611Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
1612 Instruction *Inst,
1613 AtomicOrdering Ord) const {
1614 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
1615 return Builder.CreateFence(Ord);
1616 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
1617 return Builder.CreateFence(AtomicOrdering::Release);
1618 return nullptr;
1619}
1620
1621Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
1622 Instruction *Inst,
1623 AtomicOrdering Ord) const {
1624 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
1625 return Builder.CreateFence(AtomicOrdering::Acquire);
1626 return nullptr;
1627}
Alex Bradbury21aea512018-09-19 10:54:22 +00001628
1629TargetLowering::AtomicExpansionKind
1630RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
1631 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
1632 if (Size == 8 || Size == 16)
1633 return AtomicExpansionKind::MaskedIntrinsic;
1634 return AtomicExpansionKind::None;
1635}
1636
1637static Intrinsic::ID
1638getIntrinsicForMaskedAtomicRMWBinOp32(AtomicRMWInst::BinOp BinOp) {
1639 switch (BinOp) {
1640 default:
1641 llvm_unreachable("Unexpected AtomicRMW BinOp");
1642 case AtomicRMWInst::Xchg:
1643 return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
1644 case AtomicRMWInst::Add:
1645 return Intrinsic::riscv_masked_atomicrmw_add_i32;
1646 case AtomicRMWInst::Sub:
1647 return Intrinsic::riscv_masked_atomicrmw_sub_i32;
1648 case AtomicRMWInst::Nand:
1649 return Intrinsic::riscv_masked_atomicrmw_nand_i32;
1650 case AtomicRMWInst::Max:
1651 return Intrinsic::riscv_masked_atomicrmw_max_i32;
1652 case AtomicRMWInst::Min:
1653 return Intrinsic::riscv_masked_atomicrmw_min_i32;
1654 case AtomicRMWInst::UMax:
1655 return Intrinsic::riscv_masked_atomicrmw_umax_i32;
1656 case AtomicRMWInst::UMin:
1657 return Intrinsic::riscv_masked_atomicrmw_umin_i32;
1658 }
1659}
1660
1661Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
1662 IRBuilder<> &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
1663 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
1664 Value *Ordering = Builder.getInt32(static_cast<uint32_t>(AI->getOrdering()));
1665 Type *Tys[] = {AlignedAddr->getType()};
1666 Function *LrwOpScwLoop = Intrinsic::getDeclaration(
1667 AI->getModule(),
1668 getIntrinsicForMaskedAtomicRMWBinOp32(AI->getOperation()), Tys);
1669
1670 // Must pass the shift amount needed to sign extend the loaded value prior
1671 // to performing a signed comparison for min/max. ShiftAmt is the number of
1672 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
1673 // is the number of bits to left+right shift the value in order to
1674 // sign-extend.
1675 if (AI->getOperation() == AtomicRMWInst::Min ||
1676 AI->getOperation() == AtomicRMWInst::Max) {
1677 const DataLayout &DL = AI->getModule()->getDataLayout();
1678 unsigned ValWidth =
1679 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
1680 Value *SextShamt = Builder.CreateSub(
1681 Builder.getInt32(Subtarget.getXLen() - ValWidth), ShiftAmt);
1682 return Builder.CreateCall(LrwOpScwLoop,
1683 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
1684 }
1685
1686 return Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
1687}