blob: 4bbdd860bd1a0c28f98b8087aa8ec4a11513ab6e [file] [log] [blame]
Alex Bradbury89718422017-10-19 21:37:38 +00001//===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation --------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alex Bradbury89718422017-10-19 21:37:38 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the interfaces that RISCV uses to lower LLVM code into a
10// selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
14#include "RISCVISelLowering.h"
15#include "RISCV.h"
Alex Bradburyc85be0d2018-01-10 19:41:03 +000016#include "RISCVMachineFunctionInfo.h"
Alex Bradbury89718422017-10-19 21:37:38 +000017#include "RISCVRegisterInfo.h"
18#include "RISCVSubtarget.h"
19#include "RISCVTargetMachine.h"
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +000020#include "llvm/ADT/Statistic.h"
Alex Bradbury89718422017-10-19 21:37:38 +000021#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
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +000039STATISTIC(NumTailCalls, "Number of tail calls");
40
Alex Bradbury89718422017-10-19 21:37:38 +000041RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
42 const RISCVSubtarget &STI)
43 : TargetLowering(TM), Subtarget(STI) {
44
45 MVT XLenVT = Subtarget.getXLenVT();
46
47 // Set up the register classes.
48 addRegisterClass(XLenVT, &RISCV::GPRRegClass);
49
Alex Bradbury76c29ee2018-03-20 12:45:35 +000050 if (Subtarget.hasStdExtF())
51 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
Alex Bradbury0b4175f2018-04-12 05:34:25 +000052 if (Subtarget.hasStdExtD())
53 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
Alex Bradbury76c29ee2018-03-20 12:45:35 +000054
Alex Bradbury89718422017-10-19 21:37:38 +000055 // Compute derived properties from the register classes.
56 computeRegisterProperties(STI.getRegisterInfo());
57
58 setStackPointerRegisterToSaveRestore(RISCV::X2);
59
Alex Bradburycfa62912017-11-08 12:20:01 +000060 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
61 setLoadExtAction(N, XLenVT, MVT::i1, Promote);
62
Alex Bradbury89718422017-10-19 21:37:38 +000063 // TODO: add all necessary setOperationAction calls.
Alex Bradburybfb00d42017-12-11 12:38:17 +000064 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
65
Alex Bradburyffc435e2017-11-21 08:11:03 +000066 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
Alex Bradbury74913e12017-11-08 13:31:40 +000067 setOperationAction(ISD::BR_CC, XLenVT, Expand);
Alex Bradbury65385162017-11-21 07:51:32 +000068 setOperationAction(ISD::SELECT, XLenVT, Custom);
69 setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
70
Alex Bradburybfb00d42017-12-11 12:38:17 +000071 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
72 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
73
Alex Bradburyc85be0d2018-01-10 19:41:03 +000074 setOperationAction(ISD::VASTART, MVT::Other, Custom);
75 setOperationAction(ISD::VAARG, MVT::Other, Expand);
76 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
77 setOperationAction(ISD::VAEND, MVT::Other, Expand);
78
Alex Bradburyffc435e2017-11-21 08:11:03 +000079 for (auto VT : {MVT::i1, MVT::i8, MVT::i16})
80 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
81
Alex Bradburyd05eae72019-01-12 07:32:31 +000082 if (Subtarget.is64Bit()) {
Alex Bradburyd05eae72019-01-12 07:32:31 +000083 setTargetDAGCombine(ISD::ANY_EXTEND);
Alex Bradbury299d6902019-01-25 05:04:00 +000084 setOperationAction(ISD::SHL, MVT::i32, Custom);
85 setOperationAction(ISD::SRA, MVT::i32, Custom);
86 setOperationAction(ISD::SRL, MVT::i32, Custom);
Alex Bradburyd05eae72019-01-12 07:32:31 +000087 }
88
Alex Bradbury92138382018-01-18 12:36:38 +000089 if (!Subtarget.hasStdExtM()) {
90 setOperationAction(ISD::MUL, XLenVT, Expand);
91 setOperationAction(ISD::MULHS, XLenVT, Expand);
92 setOperationAction(ISD::MULHU, XLenVT, Expand);
93 setOperationAction(ISD::SDIV, XLenVT, Expand);
94 setOperationAction(ISD::UDIV, XLenVT, Expand);
95 setOperationAction(ISD::SREM, XLenVT, Expand);
96 setOperationAction(ISD::UREM, XLenVT, Expand);
97 }
Alex Bradburyffc435e2017-11-21 08:11:03 +000098
Alex Bradbury92138382018-01-18 12:36:38 +000099 setOperationAction(ISD::SDIVREM, XLenVT, Expand);
100 setOperationAction(ISD::UDIVREM, XLenVT, Expand);
Alex Bradburyffc435e2017-11-21 08:11:03 +0000101 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
102 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
Alex Bradburyffc435e2017-11-21 08:11:03 +0000103
104 setOperationAction(ISD::SHL_PARTS, XLenVT, Expand);
105 setOperationAction(ISD::SRL_PARTS, XLenVT, Expand);
106 setOperationAction(ISD::SRA_PARTS, XLenVT, Expand);
107
108 setOperationAction(ISD::ROTL, XLenVT, Expand);
109 setOperationAction(ISD::ROTR, XLenVT, Expand);
110 setOperationAction(ISD::BSWAP, XLenVT, Expand);
111 setOperationAction(ISD::CTTZ, XLenVT, Expand);
112 setOperationAction(ISD::CTLZ, XLenVT, Expand);
113 setOperationAction(ISD::CTPOP, XLenVT, Expand);
114
Alex Bradbury21d28fe2018-04-12 05:50:06 +0000115 ISD::CondCode FPCCToExtend[] = {
116 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETO, ISD::SETUEQ,
117 ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE,
118 ISD::SETGT, ISD::SETGE, ISD::SETNE};
119
Alex Bradbury52c27782018-11-02 19:50:38 +0000120 ISD::NodeType FPOpToExtend[] = {
Alex Bradbury919f5fb2018-12-13 10:49:05 +0000121 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM};
Alex Bradbury52c27782018-11-02 19:50:38 +0000122
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000123 if (Subtarget.hasStdExtF()) {
124 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
125 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
Alex Bradbury21d28fe2018-04-12 05:50:06 +0000126 for (auto CC : FPCCToExtend)
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000127 setCondCodeAction(CC, MVT::f32, Expand);
128 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
129 setOperationAction(ISD::SELECT, MVT::f32, Custom);
130 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
Alex Bradbury52c27782018-11-02 19:50:38 +0000131 for (auto Op : FPOpToExtend)
132 setOperationAction(Op, MVT::f32, Expand);
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000133 }
134
Alex Bradbury5d0dfa52018-04-12 05:42:42 +0000135 if (Subtarget.hasStdExtD()) {
136 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
137 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
Alex Bradbury21d28fe2018-04-12 05:50:06 +0000138 for (auto CC : FPCCToExtend)
139 setCondCodeAction(CC, MVT::f64, Expand);
140 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
141 setOperationAction(ISD::SELECT, MVT::f64, Custom);
142 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000143 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
Alex Bradbury60baa2e2018-04-12 05:47:15 +0000144 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
Alex Bradbury52c27782018-11-02 19:50:38 +0000145 for (auto Op : FPOpToExtend)
146 setOperationAction(Op, MVT::f64, Expand);
Alex Bradbury5d0dfa52018-04-12 05:42:42 +0000147 }
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000148
Alex Bradburyffc435e2017-11-21 08:11:03 +0000149 setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
150 setOperationAction(ISD::BlockAddress, XLenVT, Custom);
Alex Bradbury80c8eb72018-03-20 13:26:12 +0000151 setOperationAction(ISD::ConstantPool, XLenVT, Custom);
Alex Bradburyffc435e2017-11-21 08:11:03 +0000152
Alex Bradbury21aea512018-09-19 10:54:22 +0000153 if (Subtarget.hasStdExtA()) {
Alex Bradbury96f492d2018-06-13 12:04:51 +0000154 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
Alex Bradbury21aea512018-09-19 10:54:22 +0000155 setMinCmpXchgSizeInBits(32);
156 } else {
Alex Bradbury96f492d2018-06-13 12:04:51 +0000157 setMaxAtomicSizeInBitsSupported(0);
Alex Bradbury21aea512018-09-19 10:54:22 +0000158 }
Alex Bradburydc790dd2018-06-13 11:58:46 +0000159
Alex Bradbury89718422017-10-19 21:37:38 +0000160 setBooleanContents(ZeroOrOneBooleanContent);
161
162 // Function alignments (log2).
Shiva Chenb48b0272018-04-12 11:30:59 +0000163 unsigned FunctionAlignment = Subtarget.hasStdExtC() ? 1 : 2;
164 setMinFunctionAlignment(FunctionAlignment);
165 setPrefFunctionAlignment(FunctionAlignment);
Alex Bradburyffc435e2017-11-21 08:11:03 +0000166
167 // Effectively disable jump table generation.
168 setMinimumJumpTableEntries(INT_MAX);
Alex Bradbury89718422017-10-19 21:37:38 +0000169}
170
Shiva Chenbbf4c5c2018-02-02 02:43:18 +0000171EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
172 EVT VT) const {
173 if (!VT.isVector())
174 return getPointerTy(DL);
175 return VT.changeVectorElementTypeToInteger();
176}
177
Alex Bradbury21aea512018-09-19 10:54:22 +0000178bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
179 const CallInst &I,
180 MachineFunction &MF,
181 unsigned Intrinsic) const {
182 switch (Intrinsic) {
183 default:
184 return false;
185 case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
186 case Intrinsic::riscv_masked_atomicrmw_add_i32:
187 case Intrinsic::riscv_masked_atomicrmw_sub_i32:
188 case Intrinsic::riscv_masked_atomicrmw_nand_i32:
189 case Intrinsic::riscv_masked_atomicrmw_max_i32:
190 case Intrinsic::riscv_masked_atomicrmw_min_i32:
191 case Intrinsic::riscv_masked_atomicrmw_umax_i32:
192 case Intrinsic::riscv_masked_atomicrmw_umin_i32:
Alex Bradbury66d9a752018-11-29 20:43:42 +0000193 case Intrinsic::riscv_masked_cmpxchg_i32:
Alex Bradbury21aea512018-09-19 10:54:22 +0000194 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
195 Info.opc = ISD::INTRINSIC_W_CHAIN;
196 Info.memVT = MVT::getVT(PtrTy->getElementType());
197 Info.ptrVal = I.getArgOperand(0);
198 Info.offset = 0;
199 Info.align = 4;
200 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
201 MachineMemOperand::MOVolatile;
202 return true;
203 }
204}
205
Alex Bradbury09926292018-04-26 12:13:48 +0000206bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
207 const AddrMode &AM, Type *Ty,
208 unsigned AS,
209 Instruction *I) const {
210 // No global is ever allowed as a base.
211 if (AM.BaseGV)
212 return false;
213
214 // Require a 12-bit signed offset.
215 if (!isInt<12>(AM.BaseOffs))
216 return false;
217
218 switch (AM.Scale) {
219 case 0: // "r+i" or just "i", depending on HasBaseReg.
220 break;
221 case 1:
222 if (!AM.HasBaseReg) // allow "r+i".
223 break;
224 return false; // disallow "r+r" or "r+r+i".
225 default:
226 return false;
227 }
228
229 return true;
230}
231
Alex Bradburydcbff632018-04-26 13:15:17 +0000232bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
233 return isInt<12>(Imm);
234}
235
Alex Bradbury5c41ece2018-04-26 13:00:37 +0000236bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
237 return isInt<12>(Imm);
238}
239
Alex Bradbury130b8b32018-04-26 13:37:00 +0000240// On RV32, 64-bit integers are split into their high and low parts and held
241// in two different registers, so the trunc is free since the low register can
242// just be used.
243bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
244 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
245 return false;
246 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
247 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
248 return (SrcBits == 64 && DestBits == 32);
249}
250
251bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
252 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
253 !SrcVT.isInteger() || !DstVT.isInteger())
254 return false;
255 unsigned SrcBits = SrcVT.getSizeInBits();
256 unsigned DestBits = DstVT.getSizeInBits();
257 return (SrcBits == 64 && DestBits == 32);
258}
259
Alex Bradbury15e894b2018-04-26 14:04:18 +0000260bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
261 // Zexts are free if they can be combined with a load.
262 if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
263 EVT MemVT = LD->getMemoryVT();
264 if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
265 (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
266 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
267 LD->getExtensionType() == ISD::ZEXTLOAD))
268 return true;
269 }
270
271 return TargetLowering::isZExtFree(Val, VT2);
272}
273
Alex Bradburye0e62e92018-11-30 09:56:54 +0000274bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
275 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
276}
277
Alex Bradbury65385162017-11-21 07:51:32 +0000278// Changes the condition code and swaps operands if necessary, so the SetCC
279// operation matches one of the comparisons supported directly in the RISC-V
280// ISA.
281static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) {
282 switch (CC) {
283 default:
284 break;
285 case ISD::SETGT:
286 case ISD::SETLE:
287 case ISD::SETUGT:
288 case ISD::SETULE:
289 CC = ISD::getSetCCSwappedOperands(CC);
290 std::swap(LHS, RHS);
291 break;
292 }
293}
294
295// Return the RISC-V branch opcode that matches the given DAG integer
296// condition code. The CondCode must be one of those supported by the RISC-V
297// ISA (see normaliseSetCC).
298static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) {
299 switch (CC) {
300 default:
301 llvm_unreachable("Unsupported CondCode");
302 case ISD::SETEQ:
303 return RISCV::BEQ;
304 case ISD::SETNE:
305 return RISCV::BNE;
306 case ISD::SETLT:
307 return RISCV::BLT;
308 case ISD::SETGE:
309 return RISCV::BGE;
310 case ISD::SETULT:
311 return RISCV::BLTU;
312 case ISD::SETUGE:
313 return RISCV::BGEU;
314 }
315}
316
Alex Bradbury89718422017-10-19 21:37:38 +0000317SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
318 SelectionDAG &DAG) const {
319 switch (Op.getOpcode()) {
320 default:
321 report_fatal_error("unimplemented operand");
Alex Bradburyec8aa912017-11-08 13:24:21 +0000322 case ISD::GlobalAddress:
323 return lowerGlobalAddress(Op, DAG);
Alex Bradburyffc435e2017-11-21 08:11:03 +0000324 case ISD::BlockAddress:
325 return lowerBlockAddress(Op, DAG);
Alex Bradbury80c8eb72018-03-20 13:26:12 +0000326 case ISD::ConstantPool:
327 return lowerConstantPool(Op, DAG);
Alex Bradbury65385162017-11-21 07:51:32 +0000328 case ISD::SELECT:
329 return lowerSELECT(Op, DAG);
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000330 case ISD::VASTART:
331 return lowerVASTART(Op, DAG);
Alex Bradbury70f137b2018-01-10 20:12:00 +0000332 case ISD::FRAMEADDR:
Alex Bradbury0e167662018-10-04 05:27:50 +0000333 return lowerFRAMEADDR(Op, DAG);
Alex Bradbury70f137b2018-01-10 20:12:00 +0000334 case ISD::RETURNADDR:
Alex Bradbury0e167662018-10-04 05:27:50 +0000335 return lowerRETURNADDR(Op, DAG);
Alex Bradburyec8aa912017-11-08 13:24:21 +0000336 }
337}
338
339SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
340 SelectionDAG &DAG) const {
341 SDLoc DL(Op);
342 EVT Ty = Op.getValueType();
343 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
344 const GlobalValue *GV = N->getGlobal();
345 int64_t Offset = N->getOffset();
Sameer AbuAsal1dc0a8f2018-05-17 18:14:53 +0000346 MVT XLenVT = Subtarget.getXLenVT();
Alex Bradburyec8aa912017-11-08 13:24:21 +0000347
Alex Bradbury5bf3b202018-10-04 14:30:03 +0000348 if (isPositionIndependent())
Alex Bradburyec8aa912017-11-08 13:24:21 +0000349 report_fatal_error("Unable to lowerGlobalAddress");
Sameer AbuAsal1dc0a8f2018-05-17 18:14:53 +0000350 // In order to maximise the opportunity for common subexpression elimination,
351 // emit a separate ADD node for the global address offset instead of folding
352 // it in the global address node. Later peephole optimisations may choose to
353 // fold it back in when profitable.
354 SDValue GAHi = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_HI);
355 SDValue GALo = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_LO);
Alex Bradburyffc435e2017-11-21 08:11:03 +0000356 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, GAHi), 0);
357 SDValue MNLo =
358 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, GALo), 0);
Sameer AbuAsal1dc0a8f2018-05-17 18:14:53 +0000359 if (Offset != 0)
360 return DAG.getNode(ISD::ADD, DL, Ty, MNLo,
361 DAG.getConstant(Offset, DL, XLenVT));
Alex Bradburyffc435e2017-11-21 08:11:03 +0000362 return MNLo;
363}
364
365SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
366 SelectionDAG &DAG) const {
367 SDLoc DL(Op);
368 EVT Ty = Op.getValueType();
369 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
370 const BlockAddress *BA = N->getBlockAddress();
371 int64_t Offset = N->getOffset();
372
Alex Bradbury5bf3b202018-10-04 14:30:03 +0000373 if (isPositionIndependent())
Alex Bradburyffc435e2017-11-21 08:11:03 +0000374 report_fatal_error("Unable to lowerBlockAddress");
375
376 SDValue BAHi = DAG.getTargetBlockAddress(BA, Ty, Offset, RISCVII::MO_HI);
377 SDValue BALo = DAG.getTargetBlockAddress(BA, Ty, Offset, RISCVII::MO_LO);
378 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, BAHi), 0);
379 SDValue MNLo =
380 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, BALo), 0);
381 return MNLo;
382}
383
Alex Bradbury80c8eb72018-03-20 13:26:12 +0000384SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
385 SelectionDAG &DAG) const {
386 SDLoc DL(Op);
387 EVT Ty = Op.getValueType();
388 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
389 const Constant *CPA = N->getConstVal();
390 int64_t Offset = N->getOffset();
391 unsigned Alignment = N->getAlignment();
392
393 if (!isPositionIndependent()) {
394 SDValue CPAHi =
395 DAG.getTargetConstantPool(CPA, Ty, Alignment, Offset, RISCVII::MO_HI);
396 SDValue CPALo =
397 DAG.getTargetConstantPool(CPA, Ty, Alignment, Offset, RISCVII::MO_LO);
398 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, CPAHi), 0);
399 SDValue MNLo =
400 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, CPALo), 0);
401 return MNLo;
402 } else {
403 report_fatal_error("Unable to lowerConstantPool");
404 }
405}
406
Alex Bradbury65385162017-11-21 07:51:32 +0000407SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
408 SDValue CondV = Op.getOperand(0);
409 SDValue TrueV = Op.getOperand(1);
410 SDValue FalseV = Op.getOperand(2);
411 SDLoc DL(Op);
412 MVT XLenVT = Subtarget.getXLenVT();
413
414 // If the result type is XLenVT and CondV is the output of a SETCC node
415 // which also operated on XLenVT inputs, then merge the SETCC node into the
416 // lowered RISCVISD::SELECT_CC to take advantage of the integer
417 // compare+branch instructions. i.e.:
418 // (select (setcc lhs, rhs, cc), truev, falsev)
419 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
420 if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC &&
421 CondV.getOperand(0).getSimpleValueType() == XLenVT) {
422 SDValue LHS = CondV.getOperand(0);
423 SDValue RHS = CondV.getOperand(1);
424 auto CC = cast<CondCodeSDNode>(CondV.getOperand(2));
425 ISD::CondCode CCVal = CC->get();
426
427 normaliseSetCC(LHS, RHS, CCVal);
428
429 SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT);
430 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
431 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
432 return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
433 }
434
435 // Otherwise:
436 // (select condv, truev, falsev)
437 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
438 SDValue Zero = DAG.getConstant(0, DL, XLenVT);
439 SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT);
440
441 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
442 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
443
444 return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
445}
446
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000447SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
448 MachineFunction &MF = DAG.getMachineFunction();
449 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
450
451 SDLoc DL(Op);
452 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
453 getPointerTy(MF.getDataLayout()));
454
455 // vastart just stores the address of the VarArgsFrameIndex slot into the
456 // memory location argument.
457 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
458 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
459 MachinePointerInfo(SV));
460}
461
Alex Bradbury0e167662018-10-04 05:27:50 +0000462SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
Alex Bradbury70f137b2018-01-10 20:12:00 +0000463 SelectionDAG &DAG) const {
464 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
465 MachineFunction &MF = DAG.getMachineFunction();
466 MachineFrameInfo &MFI = MF.getFrameInfo();
467 MFI.setFrameAddressIsTaken(true);
468 unsigned FrameReg = RI.getFrameRegister(MF);
469 int XLenInBytes = Subtarget.getXLen() / 8;
470
471 EVT VT = Op.getValueType();
472 SDLoc DL(Op);
473 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
474 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
475 while (Depth--) {
476 int Offset = -(XLenInBytes * 2);
477 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
478 DAG.getIntPtrConstant(Offset, DL));
479 FrameAddr =
480 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
481 }
482 return FrameAddr;
483}
484
Alex Bradbury0e167662018-10-04 05:27:50 +0000485SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
Alex Bradbury70f137b2018-01-10 20:12:00 +0000486 SelectionDAG &DAG) const {
487 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
488 MachineFunction &MF = DAG.getMachineFunction();
489 MachineFrameInfo &MFI = MF.getFrameInfo();
490 MFI.setReturnAddressIsTaken(true);
491 MVT XLenVT = Subtarget.getXLenVT();
492 int XLenInBytes = Subtarget.getXLen() / 8;
493
494 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
495 return SDValue();
496
497 EVT VT = Op.getValueType();
498 SDLoc DL(Op);
499 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
500 if (Depth) {
501 int Off = -XLenInBytes;
Alex Bradbury0e167662018-10-04 05:27:50 +0000502 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
Alex Bradbury70f137b2018-01-10 20:12:00 +0000503 SDValue Offset = DAG.getConstant(Off, DL, VT);
504 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
505 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
506 MachinePointerInfo());
507 }
508
509 // Return the value of the return address register, marking it an implicit
510 // live-in.
511 unsigned Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
512 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
513}
514
Alex Bradbury299d6902019-01-25 05:04:00 +0000515// Returns the opcode of the target-specific SDNode that implements the 32-bit
516// form of the given Opcode.
517static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
518 switch (Opcode) {
Alex Bradburyd05eae72019-01-12 07:32:31 +0000519 default:
Alex Bradbury299d6902019-01-25 05:04:00 +0000520 llvm_unreachable("Unexpected opcode");
521 case ISD::SHL:
522 return RISCVISD::SLLW;
523 case ISD::SRA:
524 return RISCVISD::SRAW;
525 case ISD::SRL:
526 return RISCVISD::SRLW;
527 }
528}
529
530// Converts the given 32-bit operation to a target-specific SelectionDAG node.
531// Because i32 isn't a legal type for RV64, these operations would otherwise
532// be promoted to i64, making it difficult to select the SLLW/DIVUW/.../*W
533// later one because the fact the operation was originally of type i32 is
534// lost.
535static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG) {
536 SDLoc DL(N);
537 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
538 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
539 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
540 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
541 // ReplaceNodeResults requires we maintain the same type for the return value.
542 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
543}
544
545void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
546 SmallVectorImpl<SDValue> &Results,
547 SelectionDAG &DAG) const {
548 SDLoc DL(N);
549 switch (N->getOpcode()) {
550 default:
551 llvm_unreachable("Don't know how to custom type legalize this operation!");
Alex Bradburyd05eae72019-01-12 07:32:31 +0000552 case ISD::SHL:
553 case ISD::SRA:
554 case ISD::SRL:
Alex Bradbury299d6902019-01-25 05:04:00 +0000555 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
556 "Unexpected custom legalisation");
557 if (N->getOperand(1).getOpcode() == ISD::Constant)
558 return;
559 Results.push_back(customLegalizeToWOp(N, DAG));
560 break;
Alex Bradburyd05eae72019-01-12 07:32:31 +0000561 }
562}
563
Alex Bradbury61aa9402019-01-12 07:43:06 +0000564// Returns true if the given node is an sdiv, udiv, or urem with non-constant
565// operands.
566static bool isVariableSDivUDivURem(SDValue Val) {
567 switch (Val.getOpcode()) {
568 default:
569 return false;
570 case ISD::SDIV:
571 case ISD::UDIV:
572 case ISD::UREM:
573 return Val.getOperand(0).getOpcode() != ISD::Constant &&
574 Val.getOperand(1).getOpcode() != ISD::Constant;
575 }
576}
577
Alex Bradbury5ac0a2f2018-10-03 23:30:16 +0000578SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
579 DAGCombinerInfo &DCI) const {
Alex Bradburyd05eae72019-01-12 07:32:31 +0000580 SelectionDAG &DAG = DCI.DAG;
581
Alex Bradbury5ac0a2f2018-10-03 23:30:16 +0000582 switch (N->getOpcode()) {
583 default:
584 break;
Alex Bradburyd05eae72019-01-12 07:32:31 +0000585 case ISD::ANY_EXTEND: {
Alex Bradbury299d6902019-01-25 05:04:00 +0000586 // If any-extending an i32 sdiv/udiv/urem to i64, then instead sign-extend
587 // in order to increase the chance of being able to select the
588 // divw/divuw/remuw instructions.
Alex Bradburyd05eae72019-01-12 07:32:31 +0000589 SDValue Src = N->getOperand(0);
Alex Bradbury61aa9402019-01-12 07:43:06 +0000590 if (N->getValueType(0) != MVT::i64 || Src.getValueType() != MVT::i32)
591 break;
Alex Bradbury299d6902019-01-25 05:04:00 +0000592 if (!(Subtarget.hasStdExtM() && isVariableSDivUDivURem(Src)))
Alex Bradburyd05eae72019-01-12 07:32:31 +0000593 break;
594 SDLoc DL(N);
Alex Bradburycd265602019-01-22 12:11:53 +0000595 // Don't add the new node to the DAGCombiner worklist, in order to avoid
596 // an infinite cycle due to SimplifyDemandedBits converting the
597 // SIGN_EXTEND back to ANY_EXTEND.
598 return DCI.CombineTo(N, DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src),
599 false);
Alex Bradburyd05eae72019-01-12 07:32:31 +0000600 }
Alex Bradbury5ac0a2f2018-10-03 23:30:16 +0000601 case RISCVISD::SplitF64: {
602 // If the input to SplitF64 is just BuildPairF64 then the operation is
603 // redundant. Instead, use BuildPairF64's operands directly.
604 SDValue Op0 = N->getOperand(0);
605 if (Op0->getOpcode() != RISCVISD::BuildPairF64)
606 break;
607 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
608 }
Alex Bradbury299d6902019-01-25 05:04:00 +0000609 case RISCVISD::SLLW:
610 case RISCVISD::SRAW:
611 case RISCVISD::SRLW: {
612 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
613 SDValue LHS = N->getOperand(0);
614 SDValue RHS = N->getOperand(1);
615 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
616 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 5);
617 if ((SimplifyDemandedBits(N->getOperand(0), LHSMask, DCI)) ||
618 (SimplifyDemandedBits(N->getOperand(1), RHSMask, DCI)))
619 return SDValue();
620 break;
621 }
Alex Bradbury5ac0a2f2018-10-03 23:30:16 +0000622 }
623
624 return SDValue();
625}
626
Alex Bradbury299d6902019-01-25 05:04:00 +0000627unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
628 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
629 unsigned Depth) const {
630 switch (Op.getOpcode()) {
631 default:
632 break;
633 case RISCVISD::SLLW:
634 case RISCVISD::SRAW:
635 case RISCVISD::SRLW:
636 // TODO: As the result is sign-extended, this is conservatively correct. A
637 // more precise answer could be calculated for SRAW depending on known
638 // bits in the shift amount.
639 return 33;
640 }
641
642 return 1;
643}
644
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000645static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
646 MachineBasicBlock *BB) {
647 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
648
649 MachineFunction &MF = *BB->getParent();
650 DebugLoc DL = MI.getDebugLoc();
651 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
652 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
653 unsigned LoReg = MI.getOperand(0).getReg();
654 unsigned HiReg = MI.getOperand(1).getReg();
655 unsigned SrcReg = MI.getOperand(2).getReg();
656 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
657 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
658
659 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
660 RI);
661 MachineMemOperand *MMO =
662 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
663 MachineMemOperand::MOLoad, 8, 8);
664 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
665 .addFrameIndex(FI)
666 .addImm(0)
667 .addMemOperand(MMO);
668 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
669 .addFrameIndex(FI)
670 .addImm(4)
671 .addMemOperand(MMO);
672 MI.eraseFromParent(); // The pseudo instruction is gone now.
673 return BB;
674}
675
676static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
677 MachineBasicBlock *BB) {
678 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
679 "Unexpected instruction");
680
681 MachineFunction &MF = *BB->getParent();
682 DebugLoc DL = MI.getDebugLoc();
683 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
684 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
685 unsigned DstReg = MI.getOperand(0).getReg();
686 unsigned LoReg = MI.getOperand(1).getReg();
687 unsigned HiReg = MI.getOperand(2).getReg();
688 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
689 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
690
691 MachineMemOperand *MMO =
692 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
693 MachineMemOperand::MOStore, 8, 8);
694 BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
695 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
696 .addFrameIndex(FI)
697 .addImm(0)
698 .addMemOperand(MMO);
699 BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
700 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
701 .addFrameIndex(FI)
702 .addImm(4)
703 .addMemOperand(MMO);
704 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
705 MI.eraseFromParent(); // The pseudo instruction is gone now.
706 return BB;
707}
708
Alex Bradbury65385162017-11-21 07:51:32 +0000709MachineBasicBlock *
710RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
711 MachineBasicBlock *BB) const {
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000712 switch (MI.getOpcode()) {
713 default:
714 llvm_unreachable("Unexpected instr type to insert");
715 case RISCV::Select_GPR_Using_CC_GPR:
716 case RISCV::Select_FPR32_Using_CC_GPR:
Alex Bradbury21d28fe2018-04-12 05:50:06 +0000717 case RISCV::Select_FPR64_Using_CC_GPR:
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000718 break;
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000719 case RISCV::BuildPairF64Pseudo:
720 return emitBuildPairF64Pseudo(MI, BB);
721 case RISCV::SplitF64Pseudo:
722 return emitSplitF64Pseudo(MI, BB);
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000723 }
Alex Bradbury65385162017-11-21 07:51:32 +0000724
725 // To "insert" a SELECT instruction, we actually have to insert the triangle
726 // control-flow pattern. The incoming instruction knows the destination vreg
727 // to set, the condition code register to branch on, the true/false values to
728 // select between, and the condcode to use to select the appropriate branch.
729 //
730 // We produce the following control flow:
731 // HeadMBB
732 // | \
733 // | IfFalseMBB
734 // | /
735 // TailMBB
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000736 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
Alex Bradbury65385162017-11-21 07:51:32 +0000737 const BasicBlock *LLVM_BB = BB->getBasicBlock();
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000738 DebugLoc DL = MI.getDebugLoc();
Alex Bradbury65385162017-11-21 07:51:32 +0000739 MachineFunction::iterator I = ++BB->getIterator();
740
741 MachineBasicBlock *HeadMBB = BB;
742 MachineFunction *F = BB->getParent();
743 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
744 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
745
746 F->insert(I, IfFalseMBB);
747 F->insert(I, TailMBB);
748 // Move all remaining instructions to TailMBB.
749 TailMBB->splice(TailMBB->begin(), HeadMBB,
750 std::next(MachineBasicBlock::iterator(MI)), HeadMBB->end());
751 // Update machine-CFG edges by transferring all successors of the current
752 // block to the new block which will contain the Phi node for the select.
753 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
754 // Set the successors for HeadMBB.
755 HeadMBB->addSuccessor(IfFalseMBB);
756 HeadMBB->addSuccessor(TailMBB);
757
758 // Insert appropriate branch.
759 unsigned LHS = MI.getOperand(1).getReg();
760 unsigned RHS = MI.getOperand(2).getReg();
761 auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm());
762 unsigned Opcode = getBranchOpcodeForIntCondCode(CC);
763
764 BuildMI(HeadMBB, DL, TII.get(Opcode))
765 .addReg(LHS)
766 .addReg(RHS)
767 .addMBB(TailMBB);
768
769 // IfFalseMBB just falls through to TailMBB.
770 IfFalseMBB->addSuccessor(TailMBB);
771
772 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
773 BuildMI(*TailMBB, TailMBB->begin(), DL, TII.get(RISCV::PHI),
774 MI.getOperand(0).getReg())
775 .addReg(MI.getOperand(4).getReg())
776 .addMBB(HeadMBB)
777 .addReg(MI.getOperand(5).getReg())
778 .addMBB(IfFalseMBB);
779
780 MI.eraseFromParent(); // The pseudo instruction is gone now.
781 return TailMBB;
782}
783
Alex Bradbury89718422017-10-19 21:37:38 +0000784// Calling Convention Implementation.
Alex Bradburydc31c612017-12-11 12:49:02 +0000785// The expectations for frontend ABI lowering vary from target to target.
786// Ideally, an LLVM frontend would be able to avoid worrying about many ABI
787// details, but this is a longer term goal. For now, we simply try to keep the
788// role of the frontend as simple and well-defined as possible. The rules can
789// be summarised as:
790// * Never split up large scalar arguments. We handle them here.
791// * If a hardfloat calling convention is being used, and the struct may be
792// passed in a pair of registers (fp+fp, int+fp), and both registers are
793// available, then pass as two separate arguments. If either the GPRs or FPRs
794// are exhausted, then pass according to the rule below.
795// * If a struct could never be passed in registers or directly in a stack
796// slot (as it is larger than 2*XLEN and the floating point rules don't
797// apply), then pass it using a pointer with the byval attribute.
798// * If a struct is less than 2*XLEN, then coerce to either a two-element
799// word-sized array or a 2*XLEN scalar (depending on alignment).
800// * The frontend can determine whether a struct is returned by reference or
801// not based on its size and fields. If it will be returned by reference, the
802// frontend must modify the prototype so a pointer with the sret annotation is
803// passed as the first argument. This is not necessary for large scalar
804// returns.
805// * Struct return values and varargs should be coerced to structs containing
806// register-size fields in the same situations they would be for fixed
807// arguments.
808
809static const MCPhysReg ArgGPRs[] = {
810 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
811 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
812};
813
814// Pass a 2*XLEN argument that has been split into two XLEN values through
815// registers or the stack as necessary.
816static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
817 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
818 MVT ValVT2, MVT LocVT2,
819 ISD::ArgFlagsTy ArgFlags2) {
820 unsigned XLenInBytes = XLen / 8;
821 if (unsigned Reg = State.AllocateReg(ArgGPRs)) {
822 // At least one half can be passed via register.
823 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
824 VA1.getLocVT(), CCValAssign::Full));
825 } else {
826 // Both halves must be passed on the stack, with proper alignment.
827 unsigned StackAlign = std::max(XLenInBytes, ArgFlags1.getOrigAlign());
828 State.addLoc(
829 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
830 State.AllocateStack(XLenInBytes, StackAlign),
831 VA1.getLocVT(), CCValAssign::Full));
832 State.addLoc(CCValAssign::getMem(
833 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
834 CCValAssign::Full));
835 return false;
836 }
837
838 if (unsigned Reg = State.AllocateReg(ArgGPRs)) {
839 // The second half can also be passed via register.
840 State.addLoc(
841 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
842 } else {
843 // The second half is passed via the stack, without additional alignment.
844 State.addLoc(CCValAssign::getMem(
845 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
846 CCValAssign::Full));
847 }
848
849 return false;
850}
851
852// Implements the RISC-V calling convention. Returns true upon failure.
853static bool CC_RISCV(const DataLayout &DL, unsigned ValNo, MVT ValVT, MVT LocVT,
854 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000855 CCState &State, bool IsFixed, bool IsRet, Type *OrigTy) {
Alex Bradburydc31c612017-12-11 12:49:02 +0000856 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
857 assert(XLen == 32 || XLen == 64);
858 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000859 if (ValVT == MVT::f32) {
860 LocVT = MVT::i32;
861 LocInfo = CCValAssign::BCvt;
862 }
Alex Bradburydc31c612017-12-11 12:49:02 +0000863
864 // Any return value split in to more than two values can't be returned
865 // directly.
866 if (IsRet && ValNo > 1)
867 return true;
868
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000869 // If this is a variadic argument, the RISC-V calling convention requires
870 // that it is assigned an 'even' or 'aligned' register if it has 8-byte
871 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
872 // be used regardless of whether the original argument was split during
873 // legalisation or not. The argument will not be passed by registers if the
874 // original type is larger than 2*XLEN, so the register alignment rule does
875 // not apply.
876 unsigned TwoXLenInBytes = (2 * XLen) / 8;
877 if (!IsFixed && ArgFlags.getOrigAlign() == TwoXLenInBytes &&
878 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
879 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
880 // Skip 'odd' register if necessary.
881 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
882 State.AllocateReg(ArgGPRs);
883 }
884
Alex Bradburydc31c612017-12-11 12:49:02 +0000885 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
886 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
887 State.getPendingArgFlags();
888
889 assert(PendingLocs.size() == PendingArgFlags.size() &&
890 "PendingLocs and PendingArgFlags out of sync");
891
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000892 // Handle passing f64 on RV32D with a soft float ABI.
893 if (XLen == 32 && ValVT == MVT::f64) {
Mandeep Singh Grang88a8b262018-04-16 18:56:10 +0000894 assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000895 "Can't lower f64 if it is split");
896 // Depending on available argument GPRS, f64 may be passed in a pair of
897 // GPRs, split between a GPR and the stack, or passed completely on the
898 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
899 // cases.
900 unsigned Reg = State.AllocateReg(ArgGPRs);
901 LocVT = MVT::i32;
902 if (!Reg) {
903 unsigned StackOffset = State.AllocateStack(8, 8);
904 State.addLoc(
905 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
906 return false;
907 }
908 if (!State.AllocateReg(ArgGPRs))
909 State.AllocateStack(4, 4);
910 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
911 return false;
912 }
913
Alex Bradburydc31c612017-12-11 12:49:02 +0000914 // Split arguments might be passed indirectly, so keep track of the pending
915 // values.
916 if (ArgFlags.isSplit() || !PendingLocs.empty()) {
917 LocVT = XLenVT;
918 LocInfo = CCValAssign::Indirect;
919 PendingLocs.push_back(
920 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
921 PendingArgFlags.push_back(ArgFlags);
922 if (!ArgFlags.isSplitEnd()) {
923 return false;
924 }
925 }
926
927 // If the split argument only had two elements, it should be passed directly
928 // in registers or on the stack.
929 if (ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) {
930 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
931 // Apply the normal calling convention rules to the first half of the
932 // split argument.
933 CCValAssign VA = PendingLocs[0];
934 ISD::ArgFlagsTy AF = PendingArgFlags[0];
935 PendingLocs.clear();
936 PendingArgFlags.clear();
937 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
938 ArgFlags);
939 }
940
941 // Allocate to a register if possible, or else a stack slot.
942 unsigned Reg = State.AllocateReg(ArgGPRs);
943 unsigned StackOffset = Reg ? 0 : State.AllocateStack(XLen / 8, XLen / 8);
944
945 // If we reach this point and PendingLocs is non-empty, we must be at the
946 // end of a split argument that must be passed indirectly.
947 if (!PendingLocs.empty()) {
948 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
949 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
950
951 for (auto &It : PendingLocs) {
952 if (Reg)
953 It.convertToReg(Reg);
954 else
955 It.convertToMem(StackOffset);
956 State.addLoc(It);
957 }
958 PendingLocs.clear();
959 PendingArgFlags.clear();
960 return false;
961 }
962
963 assert(LocVT == XLenVT && "Expected an XLenVT at this stage");
964
965 if (Reg) {
966 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
Alex Bradburye96b7c882018-10-04 07:28:49 +0000967 return false;
Alex Bradburydc31c612017-12-11 12:49:02 +0000968 }
Alex Bradburye96b7c882018-10-04 07:28:49 +0000969
970 if (ValVT == MVT::f32) {
971 LocVT = MVT::f32;
972 LocInfo = CCValAssign::Full;
973 }
974 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
Alex Bradburydc31c612017-12-11 12:49:02 +0000975 return false;
976}
977
978void RISCVTargetLowering::analyzeInputArgs(
979 MachineFunction &MF, CCState &CCInfo,
980 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const {
981 unsigned NumArgs = Ins.size();
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000982 FunctionType *FType = MF.getFunction().getFunctionType();
Alex Bradburydc31c612017-12-11 12:49:02 +0000983
984 for (unsigned i = 0; i != NumArgs; ++i) {
985 MVT ArgVT = Ins[i].VT;
986 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
987
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000988 Type *ArgTy = nullptr;
989 if (IsRet)
990 ArgTy = FType->getReturnType();
991 else if (Ins[i].isOrigArg())
992 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
993
Alex Bradburydc31c612017-12-11 12:49:02 +0000994 if (CC_RISCV(MF.getDataLayout(), i, ArgVT, ArgVT, CCValAssign::Full,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000995 ArgFlags, CCInfo, /*IsRet=*/true, IsRet, ArgTy)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000996 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
997 << EVT(ArgVT).getEVTString() << '\n');
Alex Bradburydc31c612017-12-11 12:49:02 +0000998 llvm_unreachable(nullptr);
999 }
1000 }
1001}
1002
1003void RISCVTargetLowering::analyzeOutputArgs(
1004 MachineFunction &MF, CCState &CCInfo,
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001005 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
1006 CallLoweringInfo *CLI) const {
Alex Bradburydc31c612017-12-11 12:49:02 +00001007 unsigned NumArgs = Outs.size();
1008
1009 for (unsigned i = 0; i != NumArgs; i++) {
1010 MVT ArgVT = Outs[i].VT;
1011 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001012 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
Alex Bradburydc31c612017-12-11 12:49:02 +00001013
1014 if (CC_RISCV(MF.getDataLayout(), i, ArgVT, ArgVT, CCValAssign::Full,
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001015 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001016 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
1017 << EVT(ArgVT).getEVTString() << "\n");
Alex Bradburydc31c612017-12-11 12:49:02 +00001018 llvm_unreachable(nullptr);
1019 }
1020 }
1021}
1022
Alex Bradbury1dbfdeb2018-10-03 22:53:25 +00001023// Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
1024// values.
1025static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
1026 const CCValAssign &VA, const SDLoc &DL) {
1027 switch (VA.getLocInfo()) {
1028 default:
1029 llvm_unreachable("Unexpected CCValAssign::LocInfo");
1030 case CCValAssign::Full:
1031 break;
1032 case CCValAssign::BCvt:
1033 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
1034 break;
1035 }
1036 return Val;
1037}
1038
Alex Bradburydc31c612017-12-11 12:49:02 +00001039// The caller is responsible for loading the full value if the argument is
1040// passed with CCValAssign::Indirect.
1041static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
1042 const CCValAssign &VA, const SDLoc &DL) {
1043 MachineFunction &MF = DAG.getMachineFunction();
1044 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1045 EVT LocVT = VA.getLocVT();
1046 SDValue Val;
1047
1048 unsigned VReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
1049 RegInfo.addLiveIn(VA.getLocReg(), VReg);
1050 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
1051
Alex Bradbury1dbfdeb2018-10-03 22:53:25 +00001052 if (VA.getLocInfo() == CCValAssign::Indirect)
1053 return Val;
1054
1055 return convertLocVTToValVT(DAG, Val, VA, DL);
1056}
1057
1058static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
1059 const CCValAssign &VA, const SDLoc &DL) {
1060 EVT LocVT = VA.getLocVT();
1061
Alex Bradburydc31c612017-12-11 12:49:02 +00001062 switch (VA.getLocInfo()) {
1063 default:
1064 llvm_unreachable("Unexpected CCValAssign::LocInfo");
1065 case CCValAssign::Full:
Alex Bradbury76c29ee2018-03-20 12:45:35 +00001066 break;
1067 case CCValAssign::BCvt:
Alex Bradbury1dbfdeb2018-10-03 22:53:25 +00001068 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
Alex Bradbury76c29ee2018-03-20 12:45:35 +00001069 break;
Alex Bradburydc31c612017-12-11 12:49:02 +00001070 }
Alex Bradbury76c29ee2018-03-20 12:45:35 +00001071 return Val;
Alex Bradburydc31c612017-12-11 12:49:02 +00001072}
1073
1074// The caller is responsible for loading the full value if the argument is
1075// passed with CCValAssign::Indirect.
1076static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
1077 const CCValAssign &VA, const SDLoc &DL) {
1078 MachineFunction &MF = DAG.getMachineFunction();
1079 MachineFrameInfo &MFI = MF.getFrameInfo();
1080 EVT LocVT = VA.getLocVT();
1081 EVT ValVT = VA.getValVT();
1082 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
1083 int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
1084 VA.getLocMemOffset(), /*Immutable=*/true);
1085 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1086 SDValue Val;
1087
1088 ISD::LoadExtType ExtType;
1089 switch (VA.getLocInfo()) {
1090 default:
1091 llvm_unreachable("Unexpected CCValAssign::LocInfo");
1092 case CCValAssign::Full:
1093 case CCValAssign::Indirect:
1094 ExtType = ISD::NON_EXTLOAD;
1095 break;
1096 }
1097 Val = DAG.getExtLoad(
1098 ExtType, DL, LocVT, Chain, FIN,
1099 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
1100 return Val;
1101}
Alex Bradbury89718422017-10-19 21:37:38 +00001102
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001103static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
1104 const CCValAssign &VA, const SDLoc &DL) {
1105 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
1106 "Unexpected VA");
1107 MachineFunction &MF = DAG.getMachineFunction();
1108 MachineFrameInfo &MFI = MF.getFrameInfo();
1109 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1110
1111 if (VA.isMemLoc()) {
1112 // f64 is passed on the stack.
1113 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
1114 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1115 return DAG.getLoad(MVT::f64, DL, Chain, FIN,
1116 MachinePointerInfo::getFixedStack(MF, FI));
1117 }
1118
1119 assert(VA.isRegLoc() && "Expected register VA assignment");
1120
1121 unsigned LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
1122 RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
1123 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
1124 SDValue Hi;
1125 if (VA.getLocReg() == RISCV::X17) {
1126 // Second half of f64 is passed on the stack.
1127 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
1128 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1129 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
1130 MachinePointerInfo::getFixedStack(MF, FI));
1131 } else {
1132 // Second half of f64 is passed in another GPR.
1133 unsigned HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
1134 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
1135 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
1136 }
1137 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
1138}
1139
Alex Bradbury89718422017-10-19 21:37:38 +00001140// Transform physical registers into virtual registers.
1141SDValue RISCVTargetLowering::LowerFormalArguments(
1142 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
1143 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1144 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1145
1146 switch (CallConv) {
1147 default:
1148 report_fatal_error("Unsupported calling convention");
1149 case CallingConv::C:
Alex Bradburya3376752017-11-08 13:41:21 +00001150 case CallingConv::Fast:
Alex Bradbury89718422017-10-19 21:37:38 +00001151 break;
1152 }
1153
1154 MachineFunction &MF = DAG.getMachineFunction();
Ana Pazos2e4106b2018-07-26 17:49:43 +00001155
1156 const Function &Func = MF.getFunction();
1157 if (Func.hasFnAttribute("interrupt")) {
1158 if (!Func.arg_empty())
1159 report_fatal_error(
1160 "Functions with the interrupt attribute cannot have arguments!");
1161
1162 StringRef Kind =
1163 MF.getFunction().getFnAttribute("interrupt").getValueAsString();
1164
1165 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
1166 report_fatal_error(
1167 "Function interrupt attribute argument not supported!");
1168 }
1169
Alex Bradburydc31c612017-12-11 12:49:02 +00001170 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001171 MVT XLenVT = Subtarget.getXLenVT();
1172 unsigned XLenInBytes = Subtarget.getXLen() / 8;
1173 // Used with vargs to acumulate store chains.
1174 std::vector<SDValue> OutChains;
Alex Bradbury89718422017-10-19 21:37:38 +00001175
1176 // Assign locations to all of the incoming arguments.
1177 SmallVector<CCValAssign, 16> ArgLocs;
1178 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
Alex Bradburydc31c612017-12-11 12:49:02 +00001179 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false);
Alex Bradbury89718422017-10-19 21:37:38 +00001180
Alex Bradburydc31c612017-12-11 12:49:02 +00001181 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1182 CCValAssign &VA = ArgLocs[i];
Alex Bradburydc31c612017-12-11 12:49:02 +00001183 SDValue ArgValue;
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001184 // Passing f64 on RV32D with a soft float ABI must be handled as a special
1185 // case.
1186 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
1187 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
1188 else if (VA.isRegLoc())
Alex Bradburydc31c612017-12-11 12:49:02 +00001189 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL);
1190 else
1191 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
Alex Bradbury89718422017-10-19 21:37:38 +00001192
Alex Bradburydc31c612017-12-11 12:49:02 +00001193 if (VA.getLocInfo() == CCValAssign::Indirect) {
1194 // If the original argument was split and passed by reference (e.g. i128
1195 // on RV32), we need to load all parts of it here (using the same
1196 // address).
1197 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
1198 MachinePointerInfo()));
1199 unsigned ArgIndex = Ins[i].OrigArgIndex;
1200 assert(Ins[i].PartOffset == 0);
1201 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
1202 CCValAssign &PartVA = ArgLocs[i + 1];
1203 unsigned PartOffset = Ins[i + 1].PartOffset;
1204 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
1205 DAG.getIntPtrConstant(PartOffset, DL));
1206 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
1207 MachinePointerInfo()));
1208 ++i;
1209 }
1210 continue;
Alex Bradbury89718422017-10-19 21:37:38 +00001211 }
Alex Bradburydc31c612017-12-11 12:49:02 +00001212 InVals.push_back(ArgValue);
Alex Bradbury89718422017-10-19 21:37:38 +00001213 }
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001214
1215 if (IsVarArg) {
1216 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
1217 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
1218 const TargetRegisterClass *RC = &RISCV::GPRRegClass;
1219 MachineFrameInfo &MFI = MF.getFrameInfo();
1220 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1221 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1222
1223 // Offset of the first variable argument from stack pointer, and size of
1224 // the vararg save area. For now, the varargs save area is either zero or
1225 // large enough to hold a0-a7.
1226 int VaArgOffset, VarArgsSaveSize;
1227
1228 // If all registers are allocated, then all varargs must be passed on the
1229 // stack and we don't need to save any argregs.
1230 if (ArgRegs.size() == Idx) {
1231 VaArgOffset = CCInfo.getNextStackOffset();
1232 VarArgsSaveSize = 0;
1233 } else {
1234 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
1235 VaArgOffset = -VarArgsSaveSize;
1236 }
1237
1238 // Record the frame index of the first variable argument
1239 // which is a value necessary to VASTART.
1240 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1241 RVFI->setVarArgsFrameIndex(FI);
1242
1243 // If saving an odd number of registers then create an extra stack slot to
1244 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
1245 // offsets to even-numbered registered remain 2*XLEN-aligned.
1246 if (Idx % 2) {
1247 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes,
1248 true);
1249 VarArgsSaveSize += XLenInBytes;
1250 }
1251
1252 // Copy the integer registers that may have been used for passing varargs
1253 // to the vararg save area.
1254 for (unsigned I = Idx; I < ArgRegs.size();
1255 ++I, VaArgOffset += XLenInBytes) {
1256 const unsigned Reg = RegInfo.createVirtualRegister(RC);
1257 RegInfo.addLiveIn(ArgRegs[I], Reg);
1258 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
1259 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1260 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1261 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
1262 MachinePointerInfo::getFixedStack(MF, FI));
1263 cast<StoreSDNode>(Store.getNode())
1264 ->getMemOperand()
1265 ->setValue((Value *)nullptr);
1266 OutChains.push_back(Store);
1267 }
1268 RVFI->setVarArgsSaveSize(VarArgsSaveSize);
1269 }
1270
1271 // All stores are grouped in one node to allow the matching between
1272 // the size of Ins and InVals. This only happens for vararg functions.
1273 if (!OutChains.empty()) {
1274 OutChains.push_back(Chain);
1275 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
1276 }
1277
Alex Bradbury89718422017-10-19 21:37:38 +00001278 return Chain;
1279}
1280
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +00001281/// IsEligibleForTailCallOptimization - Check whether the call is eligible
1282/// for tail call optimization.
1283/// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
1284bool RISCVTargetLowering::IsEligibleForTailCallOptimization(
1285 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
1286 const SmallVector<CCValAssign, 16> &ArgLocs) const {
1287
1288 auto &Callee = CLI.Callee;
1289 auto CalleeCC = CLI.CallConv;
1290 auto IsVarArg = CLI.IsVarArg;
1291 auto &Outs = CLI.Outs;
1292 auto &Caller = MF.getFunction();
1293 auto CallerCC = Caller.getCallingConv();
1294
1295 // Do not tail call opt functions with "disable-tail-calls" attribute.
1296 if (Caller.getFnAttribute("disable-tail-calls").getValueAsString() == "true")
1297 return false;
1298
1299 // Exception-handling functions need a special set of instructions to
1300 // indicate a return to the hardware. Tail-calling another function would
1301 // probably break this.
1302 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
1303 // should be expanded as new function attributes are introduced.
1304 if (Caller.hasFnAttribute("interrupt"))
1305 return false;
1306
1307 // Do not tail call opt functions with varargs.
1308 if (IsVarArg)
1309 return false;
1310
1311 // Do not tail call opt if the stack is used to pass parameters.
1312 if (CCInfo.getNextStackOffset() != 0)
1313 return false;
1314
1315 // Do not tail call opt if any parameters need to be passed indirectly.
1316 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
1317 // passed indirectly. So the address of the value will be passed in a
1318 // register, or if not available, then the address is put on the stack. In
1319 // order to pass indirectly, space on the stack often needs to be allocated
1320 // in order to store the value. In this case the CCInfo.getNextStackOffset()
1321 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
1322 // are passed CCValAssign::Indirect.
1323 for (auto &VA : ArgLocs)
1324 if (VA.getLocInfo() == CCValAssign::Indirect)
1325 return false;
1326
1327 // Do not tail call opt if either caller or callee uses struct return
1328 // semantics.
1329 auto IsCallerStructRet = Caller.hasStructRetAttr();
1330 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
1331 if (IsCallerStructRet || IsCalleeStructRet)
1332 return false;
1333
1334 // Externally-defined functions with weak linkage should not be
1335 // tail-called. The behaviour of branch instructions in this situation (as
1336 // used for tail calls) is implementation-defined, so we cannot rely on the
1337 // linker replacing the tail call with a return.
1338 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1339 const GlobalValue *GV = G->getGlobal();
1340 if (GV->hasExternalWeakLinkage())
1341 return false;
1342 }
1343
1344 // The callee has to preserve all registers the caller needs to preserve.
1345 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
1346 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
1347 if (CalleeCC != CallerCC) {
1348 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
1349 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
1350 return false;
1351 }
1352
1353 // Byval parameters hand the function a pointer directly into the stack area
1354 // we want to reuse during a tail call. Working around this *is* possible
1355 // but less efficient and uglier in LowerCall.
1356 for (auto &Arg : Outs)
1357 if (Arg.Flags.isByVal())
1358 return false;
1359
1360 return true;
1361}
1362
Alex Bradburya3376752017-11-08 13:41:21 +00001363// Lower a call to a callseq_start + CALL + callseq_end chain, and add input
1364// and output parameter nodes.
1365SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
1366 SmallVectorImpl<SDValue> &InVals) const {
1367 SelectionDAG &DAG = CLI.DAG;
1368 SDLoc &DL = CLI.DL;
1369 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1370 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1371 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1372 SDValue Chain = CLI.Chain;
1373 SDValue Callee = CLI.Callee;
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +00001374 bool &IsTailCall = CLI.IsTailCall;
Alex Bradburya3376752017-11-08 13:41:21 +00001375 CallingConv::ID CallConv = CLI.CallConv;
1376 bool IsVarArg = CLI.IsVarArg;
1377 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Alex Bradburydc31c612017-12-11 12:49:02 +00001378 MVT XLenVT = Subtarget.getXLenVT();
Alex Bradburya3376752017-11-08 13:41:21 +00001379
Alex Bradburya3376752017-11-08 13:41:21 +00001380 MachineFunction &MF = DAG.getMachineFunction();
1381
1382 // Analyze the operands of the call, assigning locations to each operand.
1383 SmallVector<CCValAssign, 16> ArgLocs;
1384 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001385 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI);
Alex Bradburya3376752017-11-08 13:41:21 +00001386
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +00001387 // Check if it's really possible to do a tail call.
1388 if (IsTailCall)
1389 IsTailCall = IsEligibleForTailCallOptimization(ArgCCInfo, CLI, MF,
1390 ArgLocs);
1391
1392 if (IsTailCall)
1393 ++NumTailCalls;
1394 else if (CLI.CS && CLI.CS.isMustTailCall())
1395 report_fatal_error("failed to perform tail call elimination on a call "
1396 "site marked musttail");
1397
Alex Bradburya3376752017-11-08 13:41:21 +00001398 // Get a count of how many bytes are to be pushed on the stack.
1399 unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1400
Alex Bradburydc31c612017-12-11 12:49:02 +00001401 // Create local copies for byval args
1402 SmallVector<SDValue, 8> ByValArgs;
1403 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1404 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1405 if (!Flags.isByVal())
Alex Bradburya3376752017-11-08 13:41:21 +00001406 continue;
Alex Bradburydc31c612017-12-11 12:49:02 +00001407
1408 SDValue Arg = OutVals[i];
1409 unsigned Size = Flags.getByValSize();
1410 unsigned Align = Flags.getByValAlign();
1411
1412 int FI = MF.getFrameInfo().CreateStackObject(Size, Align, /*isSS=*/false);
1413 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1414 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
1415
1416 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Align,
1417 /*IsVolatile=*/false,
1418 /*AlwaysInline=*/false,
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +00001419 IsTailCall, MachinePointerInfo(),
Alex Bradburydc31c612017-12-11 12:49:02 +00001420 MachinePointerInfo());
1421 ByValArgs.push_back(FIPtr);
Alex Bradburya3376752017-11-08 13:41:21 +00001422 }
1423
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +00001424 if (!IsTailCall)
1425 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
Alex Bradburya3376752017-11-08 13:41:21 +00001426
1427 // Copy argument values to their designated locations.
1428 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
Alex Bradburydc31c612017-12-11 12:49:02 +00001429 SmallVector<SDValue, 8> MemOpChains;
Alex Bradburya3376752017-11-08 13:41:21 +00001430 SDValue StackPtr;
Alex Bradburydc31c612017-12-11 12:49:02 +00001431 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
1432 CCValAssign &VA = ArgLocs[i];
1433 SDValue ArgValue = OutVals[i];
1434 ISD::ArgFlagsTy Flags = Outs[i].Flags;
Alex Bradburya3376752017-11-08 13:41:21 +00001435
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001436 // Handle passing f64 on RV32D with a soft float ABI as a special case.
1437 bool IsF64OnRV32DSoftABI =
1438 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
1439 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
1440 SDValue SplitF64 = DAG.getNode(
1441 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
1442 SDValue Lo = SplitF64.getValue(0);
1443 SDValue Hi = SplitF64.getValue(1);
1444
1445 unsigned RegLo = VA.getLocReg();
1446 RegsToPass.push_back(std::make_pair(RegLo, Lo));
1447
1448 if (RegLo == RISCV::X17) {
1449 // Second half of f64 is passed on the stack.
1450 // Work out the address of the stack slot.
1451 if (!StackPtr.getNode())
1452 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
1453 // Emit the store.
1454 MemOpChains.push_back(
1455 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
1456 } else {
1457 // Second half of f64 is passed in another GPR.
1458 unsigned RegHigh = RegLo + 1;
1459 RegsToPass.push_back(std::make_pair(RegHigh, Hi));
1460 }
1461 continue;
1462 }
1463
1464 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
1465 // as any other MemLoc.
1466
Alex Bradburya3376752017-11-08 13:41:21 +00001467 // Promote the value if needed.
Alex Bradburydc31c612017-12-11 12:49:02 +00001468 // For now, only handle fully promoted and indirect arguments.
Alex Bradbury1dbfdeb2018-10-03 22:53:25 +00001469 if (VA.getLocInfo() == CCValAssign::Indirect) {
Alex Bradburydc31c612017-12-11 12:49:02 +00001470 // Store the argument in a stack slot and pass its address.
1471 SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT);
1472 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1473 MemOpChains.push_back(
1474 DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1475 MachinePointerInfo::getFixedStack(MF, FI)));
1476 // If the original argument was split (e.g. i128), we need
1477 // to store all parts of it here (and pass just one address).
1478 unsigned ArgIndex = Outs[i].OrigArgIndex;
1479 assert(Outs[i].PartOffset == 0);
1480 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
1481 SDValue PartValue = OutVals[i + 1];
1482 unsigned PartOffset = Outs[i + 1].PartOffset;
1483 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
1484 DAG.getIntPtrConstant(PartOffset, DL));
1485 MemOpChains.push_back(
1486 DAG.getStore(Chain, DL, PartValue, Address,
1487 MachinePointerInfo::getFixedStack(MF, FI)));
1488 ++i;
1489 }
1490 ArgValue = SpillSlot;
Alex Bradbury1dbfdeb2018-10-03 22:53:25 +00001491 } else {
1492 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL);
Alex Bradburya3376752017-11-08 13:41:21 +00001493 }
1494
Alex Bradburydc31c612017-12-11 12:49:02 +00001495 // Use local copy if it is a byval arg.
1496 if (Flags.isByVal())
1497 ArgValue = ByValArgs[j++];
1498
Alex Bradburya3376752017-11-08 13:41:21 +00001499 if (VA.isRegLoc()) {
1500 // Queue up the argument copies and emit them at the end.
1501 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1502 } else {
1503 assert(VA.isMemLoc() && "Argument not register or memory");
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +00001504 assert(!IsTailCall && "Tail call not allowed if stack is used "
1505 "for passing parameters");
Alex Bradburydc31c612017-12-11 12:49:02 +00001506
1507 // Work out the address of the stack slot.
1508 if (!StackPtr.getNode())
1509 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
1510 SDValue Address =
1511 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1512 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
1513
1514 // Emit the store.
1515 MemOpChains.push_back(
1516 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
Alex Bradburya3376752017-11-08 13:41:21 +00001517 }
1518 }
1519
Alex Bradburydc31c612017-12-11 12:49:02 +00001520 // Join the stores, which are independent of one another.
1521 if (!MemOpChains.empty())
1522 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1523
Alex Bradburya3376752017-11-08 13:41:21 +00001524 SDValue Glue;
1525
1526 // Build a sequence of copy-to-reg nodes, chained and glued together.
1527 for (auto &Reg : RegsToPass) {
1528 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
1529 Glue = Chain.getValue(1);
1530 }
1531
Shiva Chend58bd8d2018-04-25 14:19:12 +00001532 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
1533 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
1534 // split it and then direct call can be matched by PseudoCALL.
1535 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
1536 Callee = DAG.getTargetGlobalAddress(S->getGlobal(), DL, PtrVT, 0, 0);
1537 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1538 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, 0);
Alex Bradburya3376752017-11-08 13:41:21 +00001539 }
1540
1541 // The first call operand is the chain and the second is the target address.
1542 SmallVector<SDValue, 8> Ops;
1543 Ops.push_back(Chain);
1544 Ops.push_back(Callee);
1545
1546 // Add argument registers to the end of the list so that they are
1547 // known live into the call.
1548 for (auto &Reg : RegsToPass)
1549 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
1550
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +00001551 if (!IsTailCall) {
1552 // Add a register mask operand representing the call-preserved registers.
1553 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1554 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1555 assert(Mask && "Missing call preserved mask for calling convention");
1556 Ops.push_back(DAG.getRegisterMask(Mask));
1557 }
Alex Bradburya3376752017-11-08 13:41:21 +00001558
1559 // Glue the call to the argument copies, if any.
1560 if (Glue.getNode())
1561 Ops.push_back(Glue);
1562
1563 // Emit the call.
1564 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +00001565
1566 if (IsTailCall) {
1567 MF.getFrameInfo().setHasTailCall();
1568 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
1569 }
1570
Alex Bradburya3376752017-11-08 13:41:21 +00001571 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
1572 Glue = Chain.getValue(1);
1573
1574 // Mark the end of the call, which is glued to the call itself.
1575 Chain = DAG.getCALLSEQ_END(Chain,
1576 DAG.getConstant(NumBytes, DL, PtrVT, true),
1577 DAG.getConstant(0, DL, PtrVT, true),
1578 Glue, DL);
1579 Glue = Chain.getValue(1);
1580
1581 // Assign locations to each value returned by this call.
1582 SmallVector<CCValAssign, 16> RVLocs;
1583 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
Alex Bradburydc31c612017-12-11 12:49:02 +00001584 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true);
Alex Bradburya3376752017-11-08 13:41:21 +00001585
1586 // Copy all of the result registers out of their specified physreg.
1587 for (auto &VA : RVLocs) {
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001588 // Copy the value out
1589 SDValue RetValue =
1590 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
1591 // Glue the RetValue to the end of the call sequence
Alex Bradburya3376752017-11-08 13:41:21 +00001592 Chain = RetValue.getValue(1);
1593 Glue = RetValue.getValue(2);
Alex Bradbury1dbfdeb2018-10-03 22:53:25 +00001594
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001595 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
1596 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
1597 SDValue RetValue2 =
1598 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
1599 Chain = RetValue2.getValue(1);
1600 Glue = RetValue2.getValue(2);
1601 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
1602 RetValue2);
1603 }
Alex Bradburya3376752017-11-08 13:41:21 +00001604
Alex Bradbury1dbfdeb2018-10-03 22:53:25 +00001605 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL);
Alex Bradbury76c29ee2018-03-20 12:45:35 +00001606
Alex Bradburydc31c612017-12-11 12:49:02 +00001607 InVals.push_back(RetValue);
Alex Bradburya3376752017-11-08 13:41:21 +00001608 }
1609
1610 return Chain;
1611}
1612
Alex Bradburydc31c612017-12-11 12:49:02 +00001613bool RISCVTargetLowering::CanLowerReturn(
1614 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
1615 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
1616 SmallVector<CCValAssign, 16> RVLocs;
1617 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
1618 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1619 MVT VT = Outs[i].VT;
1620 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1621 if (CC_RISCV(MF.getDataLayout(), i, VT, VT, CCValAssign::Full, ArgFlags,
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001622 CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr))
Alex Bradburydc31c612017-12-11 12:49:02 +00001623 return false;
1624 }
1625 return true;
1626}
1627
Alex Bradbury89718422017-10-19 21:37:38 +00001628SDValue
1629RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1630 bool IsVarArg,
1631 const SmallVectorImpl<ISD::OutputArg> &Outs,
1632 const SmallVectorImpl<SDValue> &OutVals,
1633 const SDLoc &DL, SelectionDAG &DAG) const {
Alex Bradbury89718422017-10-19 21:37:38 +00001634 // Stores the assignment of the return value to a location.
1635 SmallVector<CCValAssign, 16> RVLocs;
1636
1637 // Info about the registers and stack slot.
1638 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
1639 *DAG.getContext());
1640
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001641 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
1642 nullptr);
Alex Bradbury89718422017-10-19 21:37:38 +00001643
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001644 SDValue Glue;
Alex Bradbury89718422017-10-19 21:37:38 +00001645 SmallVector<SDValue, 4> RetOps(1, Chain);
1646
1647 // Copy the result values into the output registers.
1648 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
Alex Bradburydc31c612017-12-11 12:49:02 +00001649 SDValue Val = OutVals[i];
Alex Bradbury89718422017-10-19 21:37:38 +00001650 CCValAssign &VA = RVLocs[i];
1651 assert(VA.isRegLoc() && "Can only return in registers!");
1652
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001653 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
1654 // Handle returning f64 on RV32D with a soft float ABI.
1655 assert(VA.isRegLoc() && "Expected return via registers");
1656 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
1657 DAG.getVTList(MVT::i32, MVT::i32), Val);
1658 SDValue Lo = SplitF64.getValue(0);
1659 SDValue Hi = SplitF64.getValue(1);
1660 unsigned RegLo = VA.getLocReg();
1661 unsigned RegHi = RegLo + 1;
1662 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
1663 Glue = Chain.getValue(1);
1664 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
1665 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
1666 Glue = Chain.getValue(1);
1667 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
1668 } else {
1669 // Handle a 'normal' return.
Alex Bradbury1dbfdeb2018-10-03 22:53:25 +00001670 Val = convertValVTToLocVT(DAG, Val, VA, DL);
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001671 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
Alex Bradbury89718422017-10-19 21:37:38 +00001672
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001673 // Guarantee that all emitted copies are stuck together.
1674 Glue = Chain.getValue(1);
1675 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1676 }
Alex Bradbury89718422017-10-19 21:37:38 +00001677 }
1678
1679 RetOps[0] = Chain; // Update chain.
1680
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001681 // Add the glue node if we have it.
1682 if (Glue.getNode()) {
1683 RetOps.push_back(Glue);
Alex Bradbury89718422017-10-19 21:37:38 +00001684 }
1685
Ana Pazos2e4106b2018-07-26 17:49:43 +00001686 // Interrupt service routines use different return instructions.
1687 const Function &Func = DAG.getMachineFunction().getFunction();
1688 if (Func.hasFnAttribute("interrupt")) {
1689 if (!Func.getReturnType()->isVoidTy())
1690 report_fatal_error(
1691 "Functions with the interrupt attribute must have void return type!");
1692
1693 MachineFunction &MF = DAG.getMachineFunction();
1694 StringRef Kind =
1695 MF.getFunction().getFnAttribute("interrupt").getValueAsString();
1696
1697 unsigned RetOpc;
1698 if (Kind == "user")
1699 RetOpc = RISCVISD::URET_FLAG;
1700 else if (Kind == "supervisor")
1701 RetOpc = RISCVISD::SRET_FLAG;
1702 else
1703 RetOpc = RISCVISD::MRET_FLAG;
1704
1705 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
1706 }
1707
Alex Bradbury89718422017-10-19 21:37:38 +00001708 return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps);
1709}
1710
1711const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
1712 switch ((RISCVISD::NodeType)Opcode) {
1713 case RISCVISD::FIRST_NUMBER:
1714 break;
1715 case RISCVISD::RET_FLAG:
1716 return "RISCVISD::RET_FLAG";
Ana Pazos2e4106b2018-07-26 17:49:43 +00001717 case RISCVISD::URET_FLAG:
1718 return "RISCVISD::URET_FLAG";
1719 case RISCVISD::SRET_FLAG:
1720 return "RISCVISD::SRET_FLAG";
1721 case RISCVISD::MRET_FLAG:
1722 return "RISCVISD::MRET_FLAG";
Alex Bradburya3376752017-11-08 13:41:21 +00001723 case RISCVISD::CALL:
1724 return "RISCVISD::CALL";
Alex Bradbury65385162017-11-21 07:51:32 +00001725 case RISCVISD::SELECT_CC:
1726 return "RISCVISD::SELECT_CC";
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001727 case RISCVISD::BuildPairF64:
1728 return "RISCVISD::BuildPairF64";
1729 case RISCVISD::SplitF64:
1730 return "RISCVISD::SplitF64";
Mandeep Singh Grangddcb9562018-05-23 22:44:08 +00001731 case RISCVISD::TAIL:
1732 return "RISCVISD::TAIL";
Alex Bradbury299d6902019-01-25 05:04:00 +00001733 case RISCVISD::SLLW:
1734 return "RISCVISD::SLLW";
1735 case RISCVISD::SRAW:
1736 return "RISCVISD::SRAW";
1737 case RISCVISD::SRLW:
1738 return "RISCVISD::SRLW";
Alex Bradbury89718422017-10-19 21:37:38 +00001739 }
1740 return nullptr;
1741}
Alex Bradbury9330e642018-01-10 20:05:09 +00001742
1743std::pair<unsigned, const TargetRegisterClass *>
1744RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
1745 StringRef Constraint,
1746 MVT VT) const {
1747 // First, see if this is a constraint that directly corresponds to a
1748 // RISCV register class.
1749 if (Constraint.size() == 1) {
1750 switch (Constraint[0]) {
1751 case 'r':
1752 return std::make_pair(0U, &RISCV::GPRRegClass);
1753 default:
1754 break;
1755 }
1756 }
1757
1758 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1759}
Alex Bradbury96f492d2018-06-13 12:04:51 +00001760
1761Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
1762 Instruction *Inst,
1763 AtomicOrdering Ord) const {
1764 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
1765 return Builder.CreateFence(Ord);
1766 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
1767 return Builder.CreateFence(AtomicOrdering::Release);
1768 return nullptr;
1769}
1770
1771Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
1772 Instruction *Inst,
1773 AtomicOrdering Ord) const {
1774 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
1775 return Builder.CreateFence(AtomicOrdering::Acquire);
1776 return nullptr;
1777}
Alex Bradbury21aea512018-09-19 10:54:22 +00001778
1779TargetLowering::AtomicExpansionKind
1780RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Matt Arsenault39508332019-01-22 18:18:02 +00001781 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
1782 // point operations can't be used in an lr/sc sequence without breaking the
1783 // forward-progress guarantee.
1784 if (AI->isFloatingPointOperation())
1785 return AtomicExpansionKind::CmpXChg;
1786
Alex Bradbury21aea512018-09-19 10:54:22 +00001787 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
1788 if (Size == 8 || Size == 16)
1789 return AtomicExpansionKind::MaskedIntrinsic;
1790 return AtomicExpansionKind::None;
1791}
1792
1793static Intrinsic::ID
Alex Bradbury07f1c622019-01-17 10:04:39 +00001794getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
1795 if (XLen == 32) {
1796 switch (BinOp) {
1797 default:
1798 llvm_unreachable("Unexpected AtomicRMW BinOp");
1799 case AtomicRMWInst::Xchg:
1800 return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
1801 case AtomicRMWInst::Add:
1802 return Intrinsic::riscv_masked_atomicrmw_add_i32;
1803 case AtomicRMWInst::Sub:
1804 return Intrinsic::riscv_masked_atomicrmw_sub_i32;
1805 case AtomicRMWInst::Nand:
1806 return Intrinsic::riscv_masked_atomicrmw_nand_i32;
1807 case AtomicRMWInst::Max:
1808 return Intrinsic::riscv_masked_atomicrmw_max_i32;
1809 case AtomicRMWInst::Min:
1810 return Intrinsic::riscv_masked_atomicrmw_min_i32;
1811 case AtomicRMWInst::UMax:
1812 return Intrinsic::riscv_masked_atomicrmw_umax_i32;
1813 case AtomicRMWInst::UMin:
1814 return Intrinsic::riscv_masked_atomicrmw_umin_i32;
1815 }
Alex Bradbury21aea512018-09-19 10:54:22 +00001816 }
Alex Bradbury07f1c622019-01-17 10:04:39 +00001817
1818 if (XLen == 64) {
1819 switch (BinOp) {
1820 default:
1821 llvm_unreachable("Unexpected AtomicRMW BinOp");
1822 case AtomicRMWInst::Xchg:
1823 return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
1824 case AtomicRMWInst::Add:
1825 return Intrinsic::riscv_masked_atomicrmw_add_i64;
1826 case AtomicRMWInst::Sub:
1827 return Intrinsic::riscv_masked_atomicrmw_sub_i64;
1828 case AtomicRMWInst::Nand:
1829 return Intrinsic::riscv_masked_atomicrmw_nand_i64;
1830 case AtomicRMWInst::Max:
1831 return Intrinsic::riscv_masked_atomicrmw_max_i64;
1832 case AtomicRMWInst::Min:
1833 return Intrinsic::riscv_masked_atomicrmw_min_i64;
1834 case AtomicRMWInst::UMax:
1835 return Intrinsic::riscv_masked_atomicrmw_umax_i64;
1836 case AtomicRMWInst::UMin:
1837 return Intrinsic::riscv_masked_atomicrmw_umin_i64;
1838 }
1839 }
1840
1841 llvm_unreachable("Unexpected XLen\n");
Alex Bradbury21aea512018-09-19 10:54:22 +00001842}
1843
1844Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
1845 IRBuilder<> &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
1846 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
Alex Bradbury07f1c622019-01-17 10:04:39 +00001847 unsigned XLen = Subtarget.getXLen();
1848 Value *Ordering =
1849 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
Alex Bradbury21aea512018-09-19 10:54:22 +00001850 Type *Tys[] = {AlignedAddr->getType()};
1851 Function *LrwOpScwLoop = Intrinsic::getDeclaration(
1852 AI->getModule(),
Alex Bradbury07f1c622019-01-17 10:04:39 +00001853 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
1854
1855 if (XLen == 64) {
1856 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
1857 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
1858 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
1859 }
1860
1861 Value *Result;
Alex Bradbury21aea512018-09-19 10:54:22 +00001862
1863 // Must pass the shift amount needed to sign extend the loaded value prior
1864 // to performing a signed comparison for min/max. ShiftAmt is the number of
1865 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
1866 // is the number of bits to left+right shift the value in order to
1867 // sign-extend.
1868 if (AI->getOperation() == AtomicRMWInst::Min ||
1869 AI->getOperation() == AtomicRMWInst::Max) {
1870 const DataLayout &DL = AI->getModule()->getDataLayout();
1871 unsigned ValWidth =
1872 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
Alex Bradbury07f1c622019-01-17 10:04:39 +00001873 Value *SextShamt =
1874 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
1875 Result = Builder.CreateCall(LrwOpScwLoop,
1876 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
1877 } else {
1878 Result =
1879 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
Alex Bradbury21aea512018-09-19 10:54:22 +00001880 }
1881
Alex Bradbury07f1c622019-01-17 10:04:39 +00001882 if (XLen == 64)
1883 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
1884 return Result;
Alex Bradbury21aea512018-09-19 10:54:22 +00001885}
Alex Bradbury66d9a752018-11-29 20:43:42 +00001886
1887TargetLowering::AtomicExpansionKind
1888RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
1889 AtomicCmpXchgInst *CI) const {
1890 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
1891 if (Size == 8 || Size == 16)
1892 return AtomicExpansionKind::MaskedIntrinsic;
1893 return AtomicExpansionKind::None;
1894}
1895
1896Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
1897 IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
1898 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
Alex Bradbury07f1c622019-01-17 10:04:39 +00001899 unsigned XLen = Subtarget.getXLen();
1900 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
1901 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
1902 if (XLen == 64) {
1903 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
1904 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
1905 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
1906 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
1907 }
Alex Bradbury66d9a752018-11-29 20:43:42 +00001908 Type *Tys[] = {AlignedAddr->getType()};
Alex Bradbury07f1c622019-01-17 10:04:39 +00001909 Function *MaskedCmpXchg =
1910 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
1911 Value *Result = Builder.CreateCall(
1912 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
1913 if (XLen == 64)
1914 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
1915 return Result;
Alex Bradbury66d9a752018-11-29 20:43:42 +00001916}