1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation --------===// 2 // 3 // 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 6 // 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" 16 #include "RISCVMachineFunctionInfo.h" 17 #include "RISCVRegisterInfo.h" 18 #include "RISCVSubtarget.h" 19 #include "RISCVTargetMachine.h" 20 #include "Utils/RISCVMatInt.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/CodeGen/CallingConvLower.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineRegisterInfo.h" 28 #include "llvm/CodeGen/SelectionDAGISel.h" 29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 30 #include "llvm/CodeGen/ValueTypes.h" 31 #include "llvm/IR/DiagnosticInfo.h" 32 #include "llvm/IR/DiagnosticPrinter.h" 33 #include "llvm/IR/IntrinsicsRISCV.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/ErrorHandling.h" 36 #include "llvm/Support/raw_ostream.h" 37 38 using namespace llvm; 39 40 #define DEBUG_TYPE "riscv-lower" 41 42 STATISTIC(NumTailCalls, "Number of tail calls"); 43 44 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 45 const RISCVSubtarget &STI) 46 : TargetLowering(TM), Subtarget(STI) { 47 48 if (Subtarget.isRV32E()) 49 report_fatal_error("Codegen not yet implemented for RV32E"); 50 51 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 52 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 53 54 switch (ABI) { 55 default: 56 report_fatal_error("Don't know how to lower this ABI"); 57 case RISCVABI::ABI_ILP32: 58 case RISCVABI::ABI_ILP32F: 59 case RISCVABI::ABI_ILP32D: 60 case RISCVABI::ABI_LP64: 61 case RISCVABI::ABI_LP64F: 62 case RISCVABI::ABI_LP64D: 63 break; 64 } 65 66 MVT XLenVT = Subtarget.getXLenVT(); 67 68 // Set up the register classes. 69 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 70 71 if (Subtarget.hasStdExtF()) 72 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 73 if (Subtarget.hasStdExtD()) 74 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 75 76 // Compute derived properties from the register classes. 77 computeRegisterProperties(STI.getRegisterInfo()); 78 79 setStackPointerRegisterToSaveRestore(RISCV::X2); 80 81 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 82 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 83 84 // TODO: add all necessary setOperationAction calls. 85 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 86 87 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 88 setOperationAction(ISD::BR_CC, XLenVT, Expand); 89 setOperationAction(ISD::SELECT, XLenVT, Custom); 90 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 91 92 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 93 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 94 95 setOperationAction(ISD::VASTART, MVT::Other, Custom); 96 setOperationAction(ISD::VAARG, MVT::Other, Expand); 97 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 98 setOperationAction(ISD::VAEND, MVT::Other, Expand); 99 100 for (auto VT : {MVT::i1, MVT::i8, MVT::i16}) 101 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 102 103 if (Subtarget.is64Bit()) { 104 setOperationAction(ISD::ADD, MVT::i32, Custom); 105 setOperationAction(ISD::SUB, MVT::i32, Custom); 106 setOperationAction(ISD::SHL, MVT::i32, Custom); 107 setOperationAction(ISD::SRA, MVT::i32, Custom); 108 setOperationAction(ISD::SRL, MVT::i32, Custom); 109 } 110 111 if (!Subtarget.hasStdExtM()) { 112 setOperationAction(ISD::MUL, XLenVT, Expand); 113 setOperationAction(ISD::MULHS, XLenVT, Expand); 114 setOperationAction(ISD::MULHU, XLenVT, Expand); 115 setOperationAction(ISD::SDIV, XLenVT, Expand); 116 setOperationAction(ISD::UDIV, XLenVT, Expand); 117 setOperationAction(ISD::SREM, XLenVT, Expand); 118 setOperationAction(ISD::UREM, XLenVT, Expand); 119 } 120 121 if (Subtarget.is64Bit() && Subtarget.hasStdExtM()) { 122 setOperationAction(ISD::MUL, MVT::i32, Custom); 123 setOperationAction(ISD::SDIV, MVT::i32, Custom); 124 setOperationAction(ISD::UDIV, MVT::i32, Custom); 125 setOperationAction(ISD::UREM, MVT::i32, Custom); 126 } 127 128 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 129 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 130 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 131 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 132 133 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 134 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 135 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 136 137 setOperationAction(ISD::ROTL, XLenVT, Expand); 138 setOperationAction(ISD::ROTR, XLenVT, Expand); 139 setOperationAction(ISD::BSWAP, XLenVT, Expand); 140 setOperationAction(ISD::CTTZ, XLenVT, Expand); 141 setOperationAction(ISD::CTLZ, XLenVT, Expand); 142 setOperationAction(ISD::CTPOP, XLenVT, Expand); 143 144 ISD::CondCode FPCCToExtend[] = { 145 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 146 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 147 ISD::SETGE, ISD::SETNE}; 148 149 ISD::NodeType FPOpToExtend[] = { 150 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FP16_TO_FP, 151 ISD::FP_TO_FP16}; 152 153 if (Subtarget.hasStdExtF()) { 154 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 155 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 156 for (auto CC : FPCCToExtend) 157 setCondCodeAction(CC, MVT::f32, Expand); 158 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 159 setOperationAction(ISD::SELECT, MVT::f32, Custom); 160 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 161 for (auto Op : FPOpToExtend) 162 setOperationAction(Op, MVT::f32, Expand); 163 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 164 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 165 } 166 167 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 168 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 169 170 if (Subtarget.hasStdExtD()) { 171 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 172 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 173 for (auto CC : FPCCToExtend) 174 setCondCodeAction(CC, MVT::f64, Expand); 175 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 176 setOperationAction(ISD::SELECT, MVT::f64, Custom); 177 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 178 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 179 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 180 for (auto Op : FPOpToExtend) 181 setOperationAction(Op, MVT::f64, Expand); 182 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 183 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 184 } 185 186 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 187 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 188 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 189 190 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 191 192 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 193 // Unfortunately this can't be determined just from the ISA naming string. 194 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 195 Subtarget.is64Bit() ? Legal : Custom); 196 197 setOperationAction(ISD::TRAP, MVT::Other, Legal); 198 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 199 200 if (Subtarget.hasStdExtA()) { 201 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 202 setMinCmpXchgSizeInBits(32); 203 } else { 204 setMaxAtomicSizeInBitsSupported(0); 205 } 206 207 setBooleanContents(ZeroOrOneBooleanContent); 208 209 // Function alignments. 210 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 211 setMinFunctionAlignment(FunctionAlignment); 212 setPrefFunctionAlignment(FunctionAlignment); 213 214 // Effectively disable jump table generation. 215 setMinimumJumpTableEntries(INT_MAX); 216 } 217 218 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 219 EVT VT) const { 220 if (!VT.isVector()) 221 return getPointerTy(DL); 222 return VT.changeVectorElementTypeToInteger(); 223 } 224 225 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 226 const CallInst &I, 227 MachineFunction &MF, 228 unsigned Intrinsic) const { 229 switch (Intrinsic) { 230 default: 231 return false; 232 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 233 case Intrinsic::riscv_masked_atomicrmw_add_i32: 234 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 235 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 236 case Intrinsic::riscv_masked_atomicrmw_max_i32: 237 case Intrinsic::riscv_masked_atomicrmw_min_i32: 238 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 239 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 240 case Intrinsic::riscv_masked_cmpxchg_i32: 241 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 242 Info.opc = ISD::INTRINSIC_W_CHAIN; 243 Info.memVT = MVT::getVT(PtrTy->getElementType()); 244 Info.ptrVal = I.getArgOperand(0); 245 Info.offset = 0; 246 Info.align = Align(4); 247 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 248 MachineMemOperand::MOVolatile; 249 return true; 250 } 251 } 252 253 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 254 const AddrMode &AM, Type *Ty, 255 unsigned AS, 256 Instruction *I) const { 257 // No global is ever allowed as a base. 258 if (AM.BaseGV) 259 return false; 260 261 // Require a 12-bit signed offset. 262 if (!isInt<12>(AM.BaseOffs)) 263 return false; 264 265 switch (AM.Scale) { 266 case 0: // "r+i" or just "i", depending on HasBaseReg. 267 break; 268 case 1: 269 if (!AM.HasBaseReg) // allow "r+i". 270 break; 271 return false; // disallow "r+r" or "r+r+i". 272 default: 273 return false; 274 } 275 276 return true; 277 } 278 279 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 280 return isInt<12>(Imm); 281 } 282 283 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 284 return isInt<12>(Imm); 285 } 286 287 // On RV32, 64-bit integers are split into their high and low parts and held 288 // in two different registers, so the trunc is free since the low register can 289 // just be used. 290 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 291 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 292 return false; 293 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 294 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 295 return (SrcBits == 64 && DestBits == 32); 296 } 297 298 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 299 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 300 !SrcVT.isInteger() || !DstVT.isInteger()) 301 return false; 302 unsigned SrcBits = SrcVT.getSizeInBits(); 303 unsigned DestBits = DstVT.getSizeInBits(); 304 return (SrcBits == 64 && DestBits == 32); 305 } 306 307 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 308 // Zexts are free if they can be combined with a load. 309 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 310 EVT MemVT = LD->getMemoryVT(); 311 if ((MemVT == MVT::i8 || MemVT == MVT::i16 || 312 (Subtarget.is64Bit() && MemVT == MVT::i32)) && 313 (LD->getExtensionType() == ISD::NON_EXTLOAD || 314 LD->getExtensionType() == ISD::ZEXTLOAD)) 315 return true; 316 } 317 318 return TargetLowering::isZExtFree(Val, VT2); 319 } 320 321 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 322 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 323 } 324 325 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 326 return (VT == MVT::f32 && Subtarget.hasStdExtF()) || 327 (VT == MVT::f64 && Subtarget.hasStdExtD()); 328 } 329 330 // Changes the condition code and swaps operands if necessary, so the SetCC 331 // operation matches one of the comparisons supported directly in the RISC-V 332 // ISA. 333 static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) { 334 switch (CC) { 335 default: 336 break; 337 case ISD::SETGT: 338 case ISD::SETLE: 339 case ISD::SETUGT: 340 case ISD::SETULE: 341 CC = ISD::getSetCCSwappedOperands(CC); 342 std::swap(LHS, RHS); 343 break; 344 } 345 } 346 347 // Return the RISC-V branch opcode that matches the given DAG integer 348 // condition code. The CondCode must be one of those supported by the RISC-V 349 // ISA (see normaliseSetCC). 350 static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) { 351 switch (CC) { 352 default: 353 llvm_unreachable("Unsupported CondCode"); 354 case ISD::SETEQ: 355 return RISCV::BEQ; 356 case ISD::SETNE: 357 return RISCV::BNE; 358 case ISD::SETLT: 359 return RISCV::BLT; 360 case ISD::SETGE: 361 return RISCV::BGE; 362 case ISD::SETULT: 363 return RISCV::BLTU; 364 case ISD::SETUGE: 365 return RISCV::BGEU; 366 } 367 } 368 369 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 370 SelectionDAG &DAG) const { 371 switch (Op.getOpcode()) { 372 default: 373 report_fatal_error("unimplemented operand"); 374 case ISD::GlobalAddress: 375 return lowerGlobalAddress(Op, DAG); 376 case ISD::BlockAddress: 377 return lowerBlockAddress(Op, DAG); 378 case ISD::ConstantPool: 379 return lowerConstantPool(Op, DAG); 380 case ISD::GlobalTLSAddress: 381 return lowerGlobalTLSAddress(Op, DAG); 382 case ISD::SELECT: 383 return lowerSELECT(Op, DAG); 384 case ISD::VASTART: 385 return lowerVASTART(Op, DAG); 386 case ISD::FRAMEADDR: 387 return lowerFRAMEADDR(Op, DAG); 388 case ISD::RETURNADDR: 389 return lowerRETURNADDR(Op, DAG); 390 case ISD::SHL_PARTS: 391 return lowerShiftLeftParts(Op, DAG); 392 case ISD::SRA_PARTS: 393 return lowerShiftRightParts(Op, DAG, true); 394 case ISD::SRL_PARTS: 395 return lowerShiftRightParts(Op, DAG, false); 396 case ISD::BITCAST: { 397 assert(Subtarget.is64Bit() && Subtarget.hasStdExtF() && 398 "Unexpected custom legalisation"); 399 SDLoc DL(Op); 400 SDValue Op0 = Op.getOperand(0); 401 if (Op.getValueType() != MVT::f32 || Op0.getValueType() != MVT::i32) 402 return SDValue(); 403 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 404 SDValue FPConv = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 405 return FPConv; 406 } 407 } 408 } 409 410 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 411 SelectionDAG &DAG, unsigned Flags) { 412 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 413 } 414 415 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 416 SelectionDAG &DAG, unsigned Flags) { 417 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 418 Flags); 419 } 420 421 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 422 SelectionDAG &DAG, unsigned Flags) { 423 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(), 424 N->getOffset(), Flags); 425 } 426 427 template <class NodeTy> 428 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 429 bool IsLocal) const { 430 SDLoc DL(N); 431 EVT Ty = getPointerTy(DAG.getDataLayout()); 432 433 if (isPositionIndependent()) { 434 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 435 if (IsLocal) 436 // Use PC-relative addressing to access the symbol. This generates the 437 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 438 // %pcrel_lo(auipc)). 439 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 440 441 // Use PC-relative addressing to access the GOT for this symbol, then load 442 // the address from the GOT. This generates the pattern (PseudoLA sym), 443 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 444 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 445 } 446 447 switch (getTargetMachine().getCodeModel()) { 448 default: 449 report_fatal_error("Unsupported code model for lowering"); 450 case CodeModel::Small: { 451 // Generate a sequence for accessing addresses within the first 2 GiB of 452 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 453 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 454 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 455 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 456 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 457 } 458 case CodeModel::Medium: { 459 // Generate a sequence for accessing addresses within any 2GiB range within 460 // the address space. This generates the pattern (PseudoLLA sym), which 461 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 462 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 463 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 464 } 465 } 466 } 467 468 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 469 SelectionDAG &DAG) const { 470 SDLoc DL(Op); 471 EVT Ty = Op.getValueType(); 472 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 473 int64_t Offset = N->getOffset(); 474 MVT XLenVT = Subtarget.getXLenVT(); 475 476 const GlobalValue *GV = N->getGlobal(); 477 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 478 SDValue Addr = getAddr(N, DAG, IsLocal); 479 480 // In order to maximise the opportunity for common subexpression elimination, 481 // emit a separate ADD node for the global address offset instead of folding 482 // it in the global address node. Later peephole optimisations may choose to 483 // fold it back in when profitable. 484 if (Offset != 0) 485 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 486 DAG.getConstant(Offset, DL, XLenVT)); 487 return Addr; 488 } 489 490 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 491 SelectionDAG &DAG) const { 492 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 493 494 return getAddr(N, DAG); 495 } 496 497 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 498 SelectionDAG &DAG) const { 499 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 500 501 return getAddr(N, DAG); 502 } 503 504 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 505 SelectionDAG &DAG, 506 bool UseGOT) const { 507 SDLoc DL(N); 508 EVT Ty = getPointerTy(DAG.getDataLayout()); 509 const GlobalValue *GV = N->getGlobal(); 510 MVT XLenVT = Subtarget.getXLenVT(); 511 512 if (UseGOT) { 513 // Use PC-relative addressing to access the GOT for this TLS symbol, then 514 // load the address from the GOT and add the thread pointer. This generates 515 // the pattern (PseudoLA_TLS_IE sym), which expands to 516 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 517 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 518 SDValue Load = 519 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 520 521 // Add the thread pointer. 522 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 523 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 524 } 525 526 // Generate a sequence for accessing the address relative to the thread 527 // pointer, with the appropriate adjustment for the thread pointer offset. 528 // This generates the pattern 529 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 530 SDValue AddrHi = 531 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 532 SDValue AddrAdd = 533 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 534 SDValue AddrLo = 535 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 536 537 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 538 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 539 SDValue MNAdd = SDValue( 540 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 541 0); 542 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 543 } 544 545 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 546 SelectionDAG &DAG) const { 547 SDLoc DL(N); 548 EVT Ty = getPointerTy(DAG.getDataLayout()); 549 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 550 const GlobalValue *GV = N->getGlobal(); 551 552 // Use a PC-relative addressing mode to access the global dynamic GOT address. 553 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 554 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 555 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 556 SDValue Load = 557 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 558 559 // Prepare argument list to generate call. 560 ArgListTy Args; 561 ArgListEntry Entry; 562 Entry.Node = Load; 563 Entry.Ty = CallTy; 564 Args.push_back(Entry); 565 566 // Setup call to __tls_get_addr. 567 TargetLowering::CallLoweringInfo CLI(DAG); 568 CLI.setDebugLoc(DL) 569 .setChain(DAG.getEntryNode()) 570 .setLibCallee(CallingConv::C, CallTy, 571 DAG.getExternalSymbol("__tls_get_addr", Ty), 572 std::move(Args)); 573 574 return LowerCallTo(CLI).first; 575 } 576 577 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 578 SelectionDAG &DAG) const { 579 SDLoc DL(Op); 580 EVT Ty = Op.getValueType(); 581 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 582 int64_t Offset = N->getOffset(); 583 MVT XLenVT = Subtarget.getXLenVT(); 584 585 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 586 587 SDValue Addr; 588 switch (Model) { 589 case TLSModel::LocalExec: 590 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 591 break; 592 case TLSModel::InitialExec: 593 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 594 break; 595 case TLSModel::LocalDynamic: 596 case TLSModel::GeneralDynamic: 597 Addr = getDynamicTLSAddr(N, DAG); 598 break; 599 } 600 601 // In order to maximise the opportunity for common subexpression elimination, 602 // emit a separate ADD node for the global address offset instead of folding 603 // it in the global address node. Later peephole optimisations may choose to 604 // fold it back in when profitable. 605 if (Offset != 0) 606 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 607 DAG.getConstant(Offset, DL, XLenVT)); 608 return Addr; 609 } 610 611 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 612 SDValue CondV = Op.getOperand(0); 613 SDValue TrueV = Op.getOperand(1); 614 SDValue FalseV = Op.getOperand(2); 615 SDLoc DL(Op); 616 MVT XLenVT = Subtarget.getXLenVT(); 617 618 // If the result type is XLenVT and CondV is the output of a SETCC node 619 // which also operated on XLenVT inputs, then merge the SETCC node into the 620 // lowered RISCVISD::SELECT_CC to take advantage of the integer 621 // compare+branch instructions. i.e.: 622 // (select (setcc lhs, rhs, cc), truev, falsev) 623 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 624 if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC && 625 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 626 SDValue LHS = CondV.getOperand(0); 627 SDValue RHS = CondV.getOperand(1); 628 auto CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 629 ISD::CondCode CCVal = CC->get(); 630 631 normaliseSetCC(LHS, RHS, CCVal); 632 633 SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT); 634 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); 635 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 636 return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops); 637 } 638 639 // Otherwise: 640 // (select condv, truev, falsev) 641 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 642 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 643 SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT); 644 645 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); 646 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 647 648 return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops); 649 } 650 651 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 652 MachineFunction &MF = DAG.getMachineFunction(); 653 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 654 655 SDLoc DL(Op); 656 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 657 getPointerTy(MF.getDataLayout())); 658 659 // vastart just stores the address of the VarArgsFrameIndex slot into the 660 // memory location argument. 661 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 662 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 663 MachinePointerInfo(SV)); 664 } 665 666 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 667 SelectionDAG &DAG) const { 668 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 669 MachineFunction &MF = DAG.getMachineFunction(); 670 MachineFrameInfo &MFI = MF.getFrameInfo(); 671 MFI.setFrameAddressIsTaken(true); 672 Register FrameReg = RI.getFrameRegister(MF); 673 int XLenInBytes = Subtarget.getXLen() / 8; 674 675 EVT VT = Op.getValueType(); 676 SDLoc DL(Op); 677 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 678 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 679 while (Depth--) { 680 int Offset = -(XLenInBytes * 2); 681 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 682 DAG.getIntPtrConstant(Offset, DL)); 683 FrameAddr = 684 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 685 } 686 return FrameAddr; 687 } 688 689 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 690 SelectionDAG &DAG) const { 691 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 692 MachineFunction &MF = DAG.getMachineFunction(); 693 MachineFrameInfo &MFI = MF.getFrameInfo(); 694 MFI.setReturnAddressIsTaken(true); 695 MVT XLenVT = Subtarget.getXLenVT(); 696 int XLenInBytes = Subtarget.getXLen() / 8; 697 698 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 699 return SDValue(); 700 701 EVT VT = Op.getValueType(); 702 SDLoc DL(Op); 703 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 704 if (Depth) { 705 int Off = -XLenInBytes; 706 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 707 SDValue Offset = DAG.getConstant(Off, DL, VT); 708 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 709 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 710 MachinePointerInfo()); 711 } 712 713 // Return the value of the return address register, marking it an implicit 714 // live-in. 715 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 716 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 717 } 718 719 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 720 SelectionDAG &DAG) const { 721 SDLoc DL(Op); 722 SDValue Lo = Op.getOperand(0); 723 SDValue Hi = Op.getOperand(1); 724 SDValue Shamt = Op.getOperand(2); 725 EVT VT = Lo.getValueType(); 726 727 // if Shamt-XLEN < 0: // Shamt < XLEN 728 // Lo = Lo << Shamt 729 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 730 // else: 731 // Lo = 0 732 // Hi = Lo << (Shamt-XLEN) 733 734 SDValue Zero = DAG.getConstant(0, DL, VT); 735 SDValue One = DAG.getConstant(1, DL, VT); 736 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 737 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 738 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 739 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 740 741 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 742 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 743 SDValue ShiftRightLo = 744 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 745 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 746 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 747 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 748 749 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 750 751 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 752 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 753 754 SDValue Parts[2] = {Lo, Hi}; 755 return DAG.getMergeValues(Parts, DL); 756 } 757 758 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 759 bool IsSRA) const { 760 SDLoc DL(Op); 761 SDValue Lo = Op.getOperand(0); 762 SDValue Hi = Op.getOperand(1); 763 SDValue Shamt = Op.getOperand(2); 764 EVT VT = Lo.getValueType(); 765 766 // SRA expansion: 767 // if Shamt-XLEN < 0: // Shamt < XLEN 768 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 769 // Hi = Hi >>s Shamt 770 // else: 771 // Lo = Hi >>s (Shamt-XLEN); 772 // Hi = Hi >>s (XLEN-1) 773 // 774 // SRL expansion: 775 // if Shamt-XLEN < 0: // Shamt < XLEN 776 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 777 // Hi = Hi >>u Shamt 778 // else: 779 // Lo = Hi >>u (Shamt-XLEN); 780 // Hi = 0; 781 782 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 783 784 SDValue Zero = DAG.getConstant(0, DL, VT); 785 SDValue One = DAG.getConstant(1, DL, VT); 786 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 787 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 788 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 789 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 790 791 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 792 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 793 SDValue ShiftLeftHi = 794 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 795 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 796 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 797 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 798 SDValue HiFalse = 799 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 800 801 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 802 803 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 804 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 805 806 SDValue Parts[2] = {Lo, Hi}; 807 return DAG.getMergeValues(Parts, DL); 808 } 809 810 // Returns the opcode of the target-specific SDNode that implements the 32-bit 811 // form of the given Opcode. 812 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 813 switch (Opcode) { 814 default: 815 llvm_unreachable("Unexpected opcode"); 816 case ISD::SHL: 817 return RISCVISD::SLLW; 818 case ISD::SRA: 819 return RISCVISD::SRAW; 820 case ISD::SRL: 821 return RISCVISD::SRLW; 822 case ISD::SDIV: 823 return RISCVISD::DIVW; 824 case ISD::UDIV: 825 return RISCVISD::DIVUW; 826 case ISD::UREM: 827 return RISCVISD::REMUW; 828 } 829 } 830 831 // Converts the given 32-bit operation to a target-specific SelectionDAG node. 832 // Because i32 isn't a legal type for RV64, these operations would otherwise 833 // be promoted to i64, making it difficult to select the SLLW/DIVUW/.../*W 834 // later one because the fact the operation was originally of type i32 is 835 // lost. 836 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG) { 837 SDLoc DL(N); 838 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 839 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 840 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 841 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 842 // ReplaceNodeResults requires we maintain the same type for the return value. 843 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 844 } 845 846 // Converts the given 32-bit operation to a i64 operation with signed extension 847 // semantic to reduce the signed extension instructions. 848 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 849 SDLoc DL(N); 850 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 851 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 852 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 853 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 854 DAG.getValueType(MVT::i32)); 855 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 856 } 857 858 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 859 SmallVectorImpl<SDValue> &Results, 860 SelectionDAG &DAG) const { 861 SDLoc DL(N); 862 switch (N->getOpcode()) { 863 default: 864 llvm_unreachable("Don't know how to custom type legalize this operation!"); 865 case ISD::READCYCLECOUNTER: { 866 assert(!Subtarget.is64Bit() && 867 "READCYCLECOUNTER only has custom type legalization on riscv32"); 868 869 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 870 SDValue RCW = 871 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 872 873 Results.push_back(RCW); 874 Results.push_back(RCW.getValue(1)); 875 Results.push_back(RCW.getValue(2)); 876 break; 877 } 878 case ISD::ADD: 879 case ISD::SUB: 880 case ISD::MUL: 881 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 882 "Unexpected custom legalisation"); 883 if (N->getOperand(1).getOpcode() == ISD::Constant) 884 return; 885 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 886 break; 887 case ISD::SHL: 888 case ISD::SRA: 889 case ISD::SRL: 890 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 891 "Unexpected custom legalisation"); 892 if (N->getOperand(1).getOpcode() == ISD::Constant) 893 return; 894 Results.push_back(customLegalizeToWOp(N, DAG)); 895 break; 896 case ISD::SDIV: 897 case ISD::UDIV: 898 case ISD::UREM: 899 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 900 Subtarget.hasStdExtM() && "Unexpected custom legalisation"); 901 if (N->getOperand(0).getOpcode() == ISD::Constant || 902 N->getOperand(1).getOpcode() == ISD::Constant) 903 return; 904 Results.push_back(customLegalizeToWOp(N, DAG)); 905 break; 906 case ISD::BITCAST: { 907 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 908 Subtarget.hasStdExtF() && "Unexpected custom legalisation"); 909 SDLoc DL(N); 910 SDValue Op0 = N->getOperand(0); 911 if (Op0.getValueType() != MVT::f32) 912 return; 913 SDValue FPConv = 914 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 915 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 916 break; 917 } 918 } 919 } 920 921 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 922 DAGCombinerInfo &DCI) const { 923 SelectionDAG &DAG = DCI.DAG; 924 925 switch (N->getOpcode()) { 926 default: 927 break; 928 case RISCVISD::SplitF64: { 929 SDValue Op0 = N->getOperand(0); 930 // If the input to SplitF64 is just BuildPairF64 then the operation is 931 // redundant. Instead, use BuildPairF64's operands directly. 932 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 933 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 934 935 SDLoc DL(N); 936 937 // It's cheaper to materialise two 32-bit integers than to load a double 938 // from the constant pool and transfer it to integer registers through the 939 // stack. 940 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 941 APInt V = C->getValueAPF().bitcastToAPInt(); 942 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 943 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 944 return DCI.CombineTo(N, Lo, Hi); 945 } 946 947 // This is a target-specific version of a DAGCombine performed in 948 // DAGCombiner::visitBITCAST. It performs the equivalent of: 949 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 950 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 951 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 952 !Op0.getNode()->hasOneUse()) 953 break; 954 SDValue NewSplitF64 = 955 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 956 Op0.getOperand(0)); 957 SDValue Lo = NewSplitF64.getValue(0); 958 SDValue Hi = NewSplitF64.getValue(1); 959 APInt SignBit = APInt::getSignMask(32); 960 if (Op0.getOpcode() == ISD::FNEG) { 961 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 962 DAG.getConstant(SignBit, DL, MVT::i32)); 963 return DCI.CombineTo(N, Lo, NewHi); 964 } 965 assert(Op0.getOpcode() == ISD::FABS); 966 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 967 DAG.getConstant(~SignBit, DL, MVT::i32)); 968 return DCI.CombineTo(N, Lo, NewHi); 969 } 970 case RISCVISD::SLLW: 971 case RISCVISD::SRAW: 972 case RISCVISD::SRLW: { 973 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 974 SDValue LHS = N->getOperand(0); 975 SDValue RHS = N->getOperand(1); 976 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32); 977 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 5); 978 if ((SimplifyDemandedBits(N->getOperand(0), LHSMask, DCI)) || 979 (SimplifyDemandedBits(N->getOperand(1), RHSMask, DCI))) 980 return SDValue(); 981 break; 982 } 983 case RISCVISD::FMV_X_ANYEXTW_RV64: { 984 SDLoc DL(N); 985 SDValue Op0 = N->getOperand(0); 986 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 987 // conversion is unnecessary and can be replaced with an ANY_EXTEND 988 // of the FMV_W_X_RV64 operand. 989 if (Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) { 990 SDValue AExtOp = 991 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0.getOperand(0)); 992 return DCI.CombineTo(N, AExtOp); 993 } 994 995 // This is a target-specific version of a DAGCombine performed in 996 // DAGCombiner::visitBITCAST. It performs the equivalent of: 997 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 998 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 999 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 1000 !Op0.getNode()->hasOneUse()) 1001 break; 1002 SDValue NewFMV = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, 1003 Op0.getOperand(0)); 1004 APInt SignBit = APInt::getSignMask(32).sext(64); 1005 if (Op0.getOpcode() == ISD::FNEG) { 1006 return DCI.CombineTo(N, 1007 DAG.getNode(ISD::XOR, DL, MVT::i64, NewFMV, 1008 DAG.getConstant(SignBit, DL, MVT::i64))); 1009 } 1010 assert(Op0.getOpcode() == ISD::FABS); 1011 return DCI.CombineTo(N, 1012 DAG.getNode(ISD::AND, DL, MVT::i64, NewFMV, 1013 DAG.getConstant(~SignBit, DL, MVT::i64))); 1014 } 1015 } 1016 1017 return SDValue(); 1018 } 1019 1020 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 1021 const SDNode *N, CombineLevel Level) const { 1022 // The following folds are only desirable if `(OP _, c1 << c2)` can be 1023 // materialised in fewer instructions than `(OP _, c1)`: 1024 // 1025 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 1026 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 1027 SDValue N0 = N->getOperand(0); 1028 EVT Ty = N0.getValueType(); 1029 if (Ty.isScalarInteger() && 1030 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 1031 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 1032 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 1033 if (C1 && C2) { 1034 APInt C1Int = C1->getAPIntValue(); 1035 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 1036 1037 // We can materialise `c1 << c2` into an add immediate, so it's "free", 1038 // and the combine should happen, to potentially allow further combines 1039 // later. 1040 if (ShiftedC1Int.getMinSignedBits() <= 64 && 1041 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 1042 return true; 1043 1044 // We can materialise `c1` in an add immediate, so it's "free", and the 1045 // combine should be prevented. 1046 if (C1Int.getMinSignedBits() <= 64 && 1047 isLegalAddImmediate(C1Int.getSExtValue())) 1048 return false; 1049 1050 // Neither constant will fit into an immediate, so find materialisation 1051 // costs. 1052 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 1053 Subtarget.is64Bit()); 1054 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 1055 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.is64Bit()); 1056 1057 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 1058 // combine should be prevented. 1059 if (C1Cost < ShiftedC1Cost) 1060 return false; 1061 } 1062 } 1063 return true; 1064 } 1065 1066 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 1067 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 1068 unsigned Depth) const { 1069 switch (Op.getOpcode()) { 1070 default: 1071 break; 1072 case RISCVISD::SLLW: 1073 case RISCVISD::SRAW: 1074 case RISCVISD::SRLW: 1075 case RISCVISD::DIVW: 1076 case RISCVISD::DIVUW: 1077 case RISCVISD::REMUW: 1078 // TODO: As the result is sign-extended, this is conservatively correct. A 1079 // more precise answer could be calculated for SRAW depending on known 1080 // bits in the shift amount. 1081 return 33; 1082 } 1083 1084 return 1; 1085 } 1086 1087 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 1088 MachineBasicBlock *BB) { 1089 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 1090 1091 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 1092 // Should the count have wrapped while it was being read, we need to try 1093 // again. 1094 // ... 1095 // read: 1096 // rdcycleh x3 # load high word of cycle 1097 // rdcycle x2 # load low word of cycle 1098 // rdcycleh x4 # load high word of cycle 1099 // bne x3, x4, read # check if high word reads match, otherwise try again 1100 // ... 1101 1102 MachineFunction &MF = *BB->getParent(); 1103 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 1104 MachineFunction::iterator It = ++BB->getIterator(); 1105 1106 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 1107 MF.insert(It, LoopMBB); 1108 1109 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 1110 MF.insert(It, DoneMBB); 1111 1112 // Transfer the remainder of BB and its successor edges to DoneMBB. 1113 DoneMBB->splice(DoneMBB->begin(), BB, 1114 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 1115 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 1116 1117 BB->addSuccessor(LoopMBB); 1118 1119 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 1120 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 1121 Register LoReg = MI.getOperand(0).getReg(); 1122 Register HiReg = MI.getOperand(1).getReg(); 1123 DebugLoc DL = MI.getDebugLoc(); 1124 1125 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 1126 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 1127 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 1128 .addReg(RISCV::X0); 1129 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 1130 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 1131 .addReg(RISCV::X0); 1132 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 1133 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 1134 .addReg(RISCV::X0); 1135 1136 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 1137 .addReg(HiReg) 1138 .addReg(ReadAgainReg) 1139 .addMBB(LoopMBB); 1140 1141 LoopMBB->addSuccessor(LoopMBB); 1142 LoopMBB->addSuccessor(DoneMBB); 1143 1144 MI.eraseFromParent(); 1145 1146 return DoneMBB; 1147 } 1148 1149 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 1150 MachineBasicBlock *BB) { 1151 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 1152 1153 MachineFunction &MF = *BB->getParent(); 1154 DebugLoc DL = MI.getDebugLoc(); 1155 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1156 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 1157 Register LoReg = MI.getOperand(0).getReg(); 1158 Register HiReg = MI.getOperand(1).getReg(); 1159 Register SrcReg = MI.getOperand(2).getReg(); 1160 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 1161 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(); 1162 1163 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 1164 RI); 1165 MachineMemOperand *MMO = 1166 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI), 1167 MachineMemOperand::MOLoad, 8, 8); 1168 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 1169 .addFrameIndex(FI) 1170 .addImm(0) 1171 .addMemOperand(MMO); 1172 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 1173 .addFrameIndex(FI) 1174 .addImm(4) 1175 .addMemOperand(MMO); 1176 MI.eraseFromParent(); // The pseudo instruction is gone now. 1177 return BB; 1178 } 1179 1180 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 1181 MachineBasicBlock *BB) { 1182 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 1183 "Unexpected instruction"); 1184 1185 MachineFunction &MF = *BB->getParent(); 1186 DebugLoc DL = MI.getDebugLoc(); 1187 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1188 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 1189 Register DstReg = MI.getOperand(0).getReg(); 1190 Register LoReg = MI.getOperand(1).getReg(); 1191 Register HiReg = MI.getOperand(2).getReg(); 1192 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 1193 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(); 1194 1195 MachineMemOperand *MMO = 1196 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI), 1197 MachineMemOperand::MOStore, 8, 8); 1198 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 1199 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 1200 .addFrameIndex(FI) 1201 .addImm(0) 1202 .addMemOperand(MMO); 1203 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 1204 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 1205 .addFrameIndex(FI) 1206 .addImm(4) 1207 .addMemOperand(MMO); 1208 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 1209 MI.eraseFromParent(); // The pseudo instruction is gone now. 1210 return BB; 1211 } 1212 1213 static bool isSelectPseudo(MachineInstr &MI) { 1214 switch (MI.getOpcode()) { 1215 default: 1216 return false; 1217 case RISCV::Select_GPR_Using_CC_GPR: 1218 case RISCV::Select_FPR32_Using_CC_GPR: 1219 case RISCV::Select_FPR64_Using_CC_GPR: 1220 return true; 1221 } 1222 } 1223 1224 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 1225 MachineBasicBlock *BB) { 1226 // To "insert" Select_* instructions, we actually have to insert the triangle 1227 // control-flow pattern. The incoming instructions know the destination vreg 1228 // to set, the condition code register to branch on, the true/false values to 1229 // select between, and the condcode to use to select the appropriate branch. 1230 // 1231 // We produce the following control flow: 1232 // HeadMBB 1233 // | \ 1234 // | IfFalseMBB 1235 // | / 1236 // TailMBB 1237 // 1238 // When we find a sequence of selects we attempt to optimize their emission 1239 // by sharing the control flow. Currently we only handle cases where we have 1240 // multiple selects with the exact same condition (same LHS, RHS and CC). 1241 // The selects may be interleaved with other instructions if the other 1242 // instructions meet some requirements we deem safe: 1243 // - They are debug instructions. Otherwise, 1244 // - They do not have side-effects, do not access memory and their inputs do 1245 // not depend on the results of the select pseudo-instructions. 1246 // The TrueV/FalseV operands of the selects cannot depend on the result of 1247 // previous selects in the sequence. 1248 // These conditions could be further relaxed. See the X86 target for a 1249 // related approach and more information. 1250 Register LHS = MI.getOperand(1).getReg(); 1251 Register RHS = MI.getOperand(2).getReg(); 1252 auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm()); 1253 1254 SmallVector<MachineInstr *, 4> SelectDebugValues; 1255 SmallSet<Register, 4> SelectDests; 1256 SelectDests.insert(MI.getOperand(0).getReg()); 1257 1258 MachineInstr *LastSelectPseudo = &MI; 1259 1260 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 1261 SequenceMBBI != E; ++SequenceMBBI) { 1262 if (SequenceMBBI->isDebugInstr()) 1263 continue; 1264 else if (isSelectPseudo(*SequenceMBBI)) { 1265 if (SequenceMBBI->getOperand(1).getReg() != LHS || 1266 SequenceMBBI->getOperand(2).getReg() != RHS || 1267 SequenceMBBI->getOperand(3).getImm() != CC || 1268 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 1269 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 1270 break; 1271 LastSelectPseudo = &*SequenceMBBI; 1272 SequenceMBBI->collectDebugValues(SelectDebugValues); 1273 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 1274 } else { 1275 if (SequenceMBBI->hasUnmodeledSideEffects() || 1276 SequenceMBBI->mayLoadOrStore()) 1277 break; 1278 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 1279 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 1280 })) 1281 break; 1282 } 1283 } 1284 1285 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 1286 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 1287 DebugLoc DL = MI.getDebugLoc(); 1288 MachineFunction::iterator I = ++BB->getIterator(); 1289 1290 MachineBasicBlock *HeadMBB = BB; 1291 MachineFunction *F = BB->getParent(); 1292 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 1293 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 1294 1295 F->insert(I, IfFalseMBB); 1296 F->insert(I, TailMBB); 1297 1298 // Transfer debug instructions associated with the selects to TailMBB. 1299 for (MachineInstr *DebugInstr : SelectDebugValues) { 1300 TailMBB->push_back(DebugInstr->removeFromParent()); 1301 } 1302 1303 // Move all instructions after the sequence to TailMBB. 1304 TailMBB->splice(TailMBB->end(), HeadMBB, 1305 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 1306 // Update machine-CFG edges by transferring all successors of the current 1307 // block to the new block which will contain the Phi nodes for the selects. 1308 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 1309 // Set the successors for HeadMBB. 1310 HeadMBB->addSuccessor(IfFalseMBB); 1311 HeadMBB->addSuccessor(TailMBB); 1312 1313 // Insert appropriate branch. 1314 unsigned Opcode = getBranchOpcodeForIntCondCode(CC); 1315 1316 BuildMI(HeadMBB, DL, TII.get(Opcode)) 1317 .addReg(LHS) 1318 .addReg(RHS) 1319 .addMBB(TailMBB); 1320 1321 // IfFalseMBB just falls through to TailMBB. 1322 IfFalseMBB->addSuccessor(TailMBB); 1323 1324 // Create PHIs for all of the select pseudo-instructions. 1325 auto SelectMBBI = MI.getIterator(); 1326 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 1327 auto InsertionPoint = TailMBB->begin(); 1328 while (SelectMBBI != SelectEnd) { 1329 auto Next = std::next(SelectMBBI); 1330 if (isSelectPseudo(*SelectMBBI)) { 1331 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 1332 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 1333 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 1334 .addReg(SelectMBBI->getOperand(4).getReg()) 1335 .addMBB(HeadMBB) 1336 .addReg(SelectMBBI->getOperand(5).getReg()) 1337 .addMBB(IfFalseMBB); 1338 SelectMBBI->eraseFromParent(); 1339 } 1340 SelectMBBI = Next; 1341 } 1342 1343 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 1344 return TailMBB; 1345 } 1346 1347 MachineBasicBlock * 1348 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 1349 MachineBasicBlock *BB) const { 1350 switch (MI.getOpcode()) { 1351 default: 1352 llvm_unreachable("Unexpected instr type to insert"); 1353 case RISCV::ReadCycleWide: 1354 assert(!Subtarget.is64Bit() && 1355 "ReadCycleWrite is only to be used on riscv32"); 1356 return emitReadCycleWidePseudo(MI, BB); 1357 case RISCV::Select_GPR_Using_CC_GPR: 1358 case RISCV::Select_FPR32_Using_CC_GPR: 1359 case RISCV::Select_FPR64_Using_CC_GPR: 1360 return emitSelectPseudo(MI, BB); 1361 case RISCV::BuildPairF64Pseudo: 1362 return emitBuildPairF64Pseudo(MI, BB); 1363 case RISCV::SplitF64Pseudo: 1364 return emitSplitF64Pseudo(MI, BB); 1365 } 1366 } 1367 1368 // Calling Convention Implementation. 1369 // The expectations for frontend ABI lowering vary from target to target. 1370 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 1371 // details, but this is a longer term goal. For now, we simply try to keep the 1372 // role of the frontend as simple and well-defined as possible. The rules can 1373 // be summarised as: 1374 // * Never split up large scalar arguments. We handle them here. 1375 // * If a hardfloat calling convention is being used, and the struct may be 1376 // passed in a pair of registers (fp+fp, int+fp), and both registers are 1377 // available, then pass as two separate arguments. If either the GPRs or FPRs 1378 // are exhausted, then pass according to the rule below. 1379 // * If a struct could never be passed in registers or directly in a stack 1380 // slot (as it is larger than 2*XLEN and the floating point rules don't 1381 // apply), then pass it using a pointer with the byval attribute. 1382 // * If a struct is less than 2*XLEN, then coerce to either a two-element 1383 // word-sized array or a 2*XLEN scalar (depending on alignment). 1384 // * The frontend can determine whether a struct is returned by reference or 1385 // not based on its size and fields. If it will be returned by reference, the 1386 // frontend must modify the prototype so a pointer with the sret annotation is 1387 // passed as the first argument. This is not necessary for large scalar 1388 // returns. 1389 // * Struct return values and varargs should be coerced to structs containing 1390 // register-size fields in the same situations they would be for fixed 1391 // arguments. 1392 1393 static const MCPhysReg ArgGPRs[] = { 1394 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 1395 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 1396 }; 1397 static const MCPhysReg ArgFPR32s[] = { 1398 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 1399 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 1400 }; 1401 static const MCPhysReg ArgFPR64s[] = { 1402 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 1403 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 1404 }; 1405 1406 // Pass a 2*XLEN argument that has been split into two XLEN values through 1407 // registers or the stack as necessary. 1408 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 1409 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 1410 MVT ValVT2, MVT LocVT2, 1411 ISD::ArgFlagsTy ArgFlags2) { 1412 unsigned XLenInBytes = XLen / 8; 1413 if (Register Reg = State.AllocateReg(ArgGPRs)) { 1414 // At least one half can be passed via register. 1415 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 1416 VA1.getLocVT(), CCValAssign::Full)); 1417 } else { 1418 // Both halves must be passed on the stack, with proper alignment. 1419 unsigned StackAlign = std::max(XLenInBytes, ArgFlags1.getOrigAlign()); 1420 State.addLoc( 1421 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 1422 State.AllocateStack(XLenInBytes, StackAlign), 1423 VA1.getLocVT(), CCValAssign::Full)); 1424 State.addLoc(CCValAssign::getMem( 1425 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2, 1426 CCValAssign::Full)); 1427 return false; 1428 } 1429 1430 if (Register Reg = State.AllocateReg(ArgGPRs)) { 1431 // The second half can also be passed via register. 1432 State.addLoc( 1433 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 1434 } else { 1435 // The second half is passed via the stack, without additional alignment. 1436 State.addLoc(CCValAssign::getMem( 1437 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2, 1438 CCValAssign::Full)); 1439 } 1440 1441 return false; 1442 } 1443 1444 // Implements the RISC-V calling convention. Returns true upon failure. 1445 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 1446 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 1447 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 1448 bool IsRet, Type *OrigTy) { 1449 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 1450 assert(XLen == 32 || XLen == 64); 1451 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 1452 1453 // Any return value split in to more than two values can't be returned 1454 // directly. 1455 if (IsRet && ValNo > 1) 1456 return true; 1457 1458 // UseGPRForF32 if targeting one of the soft-float ABIs, if passing a 1459 // variadic argument, or if no F32 argument registers are available. 1460 bool UseGPRForF32 = true; 1461 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 1462 // variadic argument, or if no F64 argument registers are available. 1463 bool UseGPRForF64 = true; 1464 1465 switch (ABI) { 1466 default: 1467 llvm_unreachable("Unexpected ABI"); 1468 case RISCVABI::ABI_ILP32: 1469 case RISCVABI::ABI_LP64: 1470 break; 1471 case RISCVABI::ABI_ILP32F: 1472 case RISCVABI::ABI_LP64F: 1473 UseGPRForF32 = !IsFixed; 1474 break; 1475 case RISCVABI::ABI_ILP32D: 1476 case RISCVABI::ABI_LP64D: 1477 UseGPRForF32 = !IsFixed; 1478 UseGPRForF64 = !IsFixed; 1479 break; 1480 } 1481 1482 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) 1483 UseGPRForF32 = true; 1484 if (State.getFirstUnallocated(ArgFPR64s) == array_lengthof(ArgFPR64s)) 1485 UseGPRForF64 = true; 1486 1487 // From this point on, rely on UseGPRForF32, UseGPRForF64 and similar local 1488 // variables rather than directly checking against the target ABI. 1489 1490 if (UseGPRForF32 && ValVT == MVT::f32) { 1491 LocVT = XLenVT; 1492 LocInfo = CCValAssign::BCvt; 1493 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 1494 LocVT = MVT::i64; 1495 LocInfo = CCValAssign::BCvt; 1496 } 1497 1498 // If this is a variadic argument, the RISC-V calling convention requires 1499 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 1500 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 1501 // be used regardless of whether the original argument was split during 1502 // legalisation or not. The argument will not be passed by registers if the 1503 // original type is larger than 2*XLEN, so the register alignment rule does 1504 // not apply. 1505 unsigned TwoXLenInBytes = (2 * XLen) / 8; 1506 if (!IsFixed && ArgFlags.getOrigAlign() == TwoXLenInBytes && 1507 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 1508 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 1509 // Skip 'odd' register if necessary. 1510 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 1511 State.AllocateReg(ArgGPRs); 1512 } 1513 1514 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 1515 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 1516 State.getPendingArgFlags(); 1517 1518 assert(PendingLocs.size() == PendingArgFlags.size() && 1519 "PendingLocs and PendingArgFlags out of sync"); 1520 1521 // Handle passing f64 on RV32D with a soft float ABI or when floating point 1522 // registers are exhausted. 1523 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 1524 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 1525 "Can't lower f64 if it is split"); 1526 // Depending on available argument GPRS, f64 may be passed in a pair of 1527 // GPRs, split between a GPR and the stack, or passed completely on the 1528 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 1529 // cases. 1530 Register Reg = State.AllocateReg(ArgGPRs); 1531 LocVT = MVT::i32; 1532 if (!Reg) { 1533 unsigned StackOffset = State.AllocateStack(8, 8); 1534 State.addLoc( 1535 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 1536 return false; 1537 } 1538 if (!State.AllocateReg(ArgGPRs)) 1539 State.AllocateStack(4, 4); 1540 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 1541 return false; 1542 } 1543 1544 // Split arguments might be passed indirectly, so keep track of the pending 1545 // values. 1546 if (ArgFlags.isSplit() || !PendingLocs.empty()) { 1547 LocVT = XLenVT; 1548 LocInfo = CCValAssign::Indirect; 1549 PendingLocs.push_back( 1550 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 1551 PendingArgFlags.push_back(ArgFlags); 1552 if (!ArgFlags.isSplitEnd()) { 1553 return false; 1554 } 1555 } 1556 1557 // If the split argument only had two elements, it should be passed directly 1558 // in registers or on the stack. 1559 if (ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) { 1560 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 1561 // Apply the normal calling convention rules to the first half of the 1562 // split argument. 1563 CCValAssign VA = PendingLocs[0]; 1564 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 1565 PendingLocs.clear(); 1566 PendingArgFlags.clear(); 1567 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 1568 ArgFlags); 1569 } 1570 1571 // Allocate to a register if possible, or else a stack slot. 1572 Register Reg; 1573 if (ValVT == MVT::f32 && !UseGPRForF32) 1574 Reg = State.AllocateReg(ArgFPR32s, ArgFPR64s); 1575 else if (ValVT == MVT::f64 && !UseGPRForF64) 1576 Reg = State.AllocateReg(ArgFPR64s, ArgFPR32s); 1577 else 1578 Reg = State.AllocateReg(ArgGPRs); 1579 unsigned StackOffset = Reg ? 0 : State.AllocateStack(XLen / 8, XLen / 8); 1580 1581 // If we reach this point and PendingLocs is non-empty, we must be at the 1582 // end of a split argument that must be passed indirectly. 1583 if (!PendingLocs.empty()) { 1584 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 1585 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 1586 1587 for (auto &It : PendingLocs) { 1588 if (Reg) 1589 It.convertToReg(Reg); 1590 else 1591 It.convertToMem(StackOffset); 1592 State.addLoc(It); 1593 } 1594 PendingLocs.clear(); 1595 PendingArgFlags.clear(); 1596 return false; 1597 } 1598 1599 assert((!UseGPRForF32 || !UseGPRForF64 || LocVT == XLenVT) && 1600 "Expected an XLenVT at this stage"); 1601 1602 if (Reg) { 1603 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 1604 return false; 1605 } 1606 1607 // When an f32 or f64 is passed on the stack, no bit-conversion is needed. 1608 if (ValVT == MVT::f32 || ValVT == MVT::f64) { 1609 LocVT = ValVT; 1610 LocInfo = CCValAssign::Full; 1611 } 1612 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 1613 return false; 1614 } 1615 1616 void RISCVTargetLowering::analyzeInputArgs( 1617 MachineFunction &MF, CCState &CCInfo, 1618 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const { 1619 unsigned NumArgs = Ins.size(); 1620 FunctionType *FType = MF.getFunction().getFunctionType(); 1621 1622 for (unsigned i = 0; i != NumArgs; ++i) { 1623 MVT ArgVT = Ins[i].VT; 1624 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 1625 1626 Type *ArgTy = nullptr; 1627 if (IsRet) 1628 ArgTy = FType->getReturnType(); 1629 else if (Ins[i].isOrigArg()) 1630 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 1631 1632 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 1633 if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 1634 ArgFlags, CCInfo, /*IsRet=*/true, IsRet, ArgTy)) { 1635 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 1636 << EVT(ArgVT).getEVTString() << '\n'); 1637 llvm_unreachable(nullptr); 1638 } 1639 } 1640 } 1641 1642 void RISCVTargetLowering::analyzeOutputArgs( 1643 MachineFunction &MF, CCState &CCInfo, 1644 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 1645 CallLoweringInfo *CLI) const { 1646 unsigned NumArgs = Outs.size(); 1647 1648 for (unsigned i = 0; i != NumArgs; i++) { 1649 MVT ArgVT = Outs[i].VT; 1650 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 1651 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 1652 1653 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 1654 if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 1655 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy)) { 1656 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 1657 << EVT(ArgVT).getEVTString() << "\n"); 1658 llvm_unreachable(nullptr); 1659 } 1660 } 1661 } 1662 1663 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 1664 // values. 1665 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 1666 const CCValAssign &VA, const SDLoc &DL) { 1667 switch (VA.getLocInfo()) { 1668 default: 1669 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 1670 case CCValAssign::Full: 1671 break; 1672 case CCValAssign::BCvt: 1673 if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) { 1674 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 1675 break; 1676 } 1677 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 1678 break; 1679 } 1680 return Val; 1681 } 1682 1683 // The caller is responsible for loading the full value if the argument is 1684 // passed with CCValAssign::Indirect. 1685 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 1686 const CCValAssign &VA, const SDLoc &DL) { 1687 MachineFunction &MF = DAG.getMachineFunction(); 1688 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 1689 EVT LocVT = VA.getLocVT(); 1690 SDValue Val; 1691 const TargetRegisterClass *RC; 1692 1693 switch (LocVT.getSimpleVT().SimpleTy) { 1694 default: 1695 llvm_unreachable("Unexpected register type"); 1696 case MVT::i32: 1697 case MVT::i64: 1698 RC = &RISCV::GPRRegClass; 1699 break; 1700 case MVT::f32: 1701 RC = &RISCV::FPR32RegClass; 1702 break; 1703 case MVT::f64: 1704 RC = &RISCV::FPR64RegClass; 1705 break; 1706 } 1707 1708 Register VReg = RegInfo.createVirtualRegister(RC); 1709 RegInfo.addLiveIn(VA.getLocReg(), VReg); 1710 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 1711 1712 if (VA.getLocInfo() == CCValAssign::Indirect) 1713 return Val; 1714 1715 return convertLocVTToValVT(DAG, Val, VA, DL); 1716 } 1717 1718 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 1719 const CCValAssign &VA, const SDLoc &DL) { 1720 EVT LocVT = VA.getLocVT(); 1721 1722 switch (VA.getLocInfo()) { 1723 default: 1724 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 1725 case CCValAssign::Full: 1726 break; 1727 case CCValAssign::BCvt: 1728 if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) { 1729 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 1730 break; 1731 } 1732 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 1733 break; 1734 } 1735 return Val; 1736 } 1737 1738 // The caller is responsible for loading the full value if the argument is 1739 // passed with CCValAssign::Indirect. 1740 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 1741 const CCValAssign &VA, const SDLoc &DL) { 1742 MachineFunction &MF = DAG.getMachineFunction(); 1743 MachineFrameInfo &MFI = MF.getFrameInfo(); 1744 EVT LocVT = VA.getLocVT(); 1745 EVT ValVT = VA.getValVT(); 1746 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 1747 int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8, 1748 VA.getLocMemOffset(), /*Immutable=*/true); 1749 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 1750 SDValue Val; 1751 1752 ISD::LoadExtType ExtType; 1753 switch (VA.getLocInfo()) { 1754 default: 1755 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 1756 case CCValAssign::Full: 1757 case CCValAssign::Indirect: 1758 case CCValAssign::BCvt: 1759 ExtType = ISD::NON_EXTLOAD; 1760 break; 1761 } 1762 Val = DAG.getExtLoad( 1763 ExtType, DL, LocVT, Chain, FIN, 1764 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 1765 return Val; 1766 } 1767 1768 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 1769 const CCValAssign &VA, const SDLoc &DL) { 1770 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 1771 "Unexpected VA"); 1772 MachineFunction &MF = DAG.getMachineFunction(); 1773 MachineFrameInfo &MFI = MF.getFrameInfo(); 1774 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 1775 1776 if (VA.isMemLoc()) { 1777 // f64 is passed on the stack. 1778 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true); 1779 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1780 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 1781 MachinePointerInfo::getFixedStack(MF, FI)); 1782 } 1783 1784 assert(VA.isRegLoc() && "Expected register VA assignment"); 1785 1786 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 1787 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 1788 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 1789 SDValue Hi; 1790 if (VA.getLocReg() == RISCV::X17) { 1791 // Second half of f64 is passed on the stack. 1792 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true); 1793 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1794 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 1795 MachinePointerInfo::getFixedStack(MF, FI)); 1796 } else { 1797 // Second half of f64 is passed in another GPR. 1798 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 1799 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 1800 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 1801 } 1802 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 1803 } 1804 1805 // FastCC has less than 1% performance improvement for some particular 1806 // benchmark. But theoretically, it may has benenfit for some cases. 1807 static bool CC_RISCV_FastCC(unsigned ValNo, MVT ValVT, MVT LocVT, 1808 CCValAssign::LocInfo LocInfo, 1809 ISD::ArgFlagsTy ArgFlags, CCState &State) { 1810 1811 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 1812 // X5 and X6 might be used for save-restore libcall. 1813 static const MCPhysReg GPRList[] = { 1814 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 1815 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 1816 RISCV::X29, RISCV::X30, RISCV::X31}; 1817 if (unsigned Reg = State.AllocateReg(GPRList)) { 1818 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 1819 return false; 1820 } 1821 } 1822 1823 if (LocVT == MVT::f32) { 1824 static const MCPhysReg FPR32List[] = { 1825 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 1826 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 1827 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 1828 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 1829 if (unsigned Reg = State.AllocateReg(FPR32List)) { 1830 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 1831 return false; 1832 } 1833 } 1834 1835 if (LocVT == MVT::f64) { 1836 static const MCPhysReg FPR64List[] = { 1837 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 1838 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 1839 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 1840 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 1841 if (unsigned Reg = State.AllocateReg(FPR64List)) { 1842 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 1843 return false; 1844 } 1845 } 1846 1847 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 1848 unsigned Offset4 = State.AllocateStack(4, 4); 1849 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 1850 return false; 1851 } 1852 1853 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 1854 unsigned Offset5 = State.AllocateStack(8, 8); 1855 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 1856 return false; 1857 } 1858 1859 return true; // CC didn't match. 1860 } 1861 1862 // Transform physical registers into virtual registers. 1863 SDValue RISCVTargetLowering::LowerFormalArguments( 1864 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 1865 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 1866 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 1867 1868 switch (CallConv) { 1869 default: 1870 report_fatal_error("Unsupported calling convention"); 1871 case CallingConv::C: 1872 case CallingConv::Fast: 1873 break; 1874 } 1875 1876 MachineFunction &MF = DAG.getMachineFunction(); 1877 1878 const Function &Func = MF.getFunction(); 1879 if (Func.hasFnAttribute("interrupt")) { 1880 if (!Func.arg_empty()) 1881 report_fatal_error( 1882 "Functions with the interrupt attribute cannot have arguments!"); 1883 1884 StringRef Kind = 1885 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 1886 1887 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 1888 report_fatal_error( 1889 "Function interrupt attribute argument not supported!"); 1890 } 1891 1892 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 1893 MVT XLenVT = Subtarget.getXLenVT(); 1894 unsigned XLenInBytes = Subtarget.getXLen() / 8; 1895 // Used with vargs to acumulate store chains. 1896 std::vector<SDValue> OutChains; 1897 1898 // Assign locations to all of the incoming arguments. 1899 SmallVector<CCValAssign, 16> ArgLocs; 1900 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 1901 1902 if (CallConv == CallingConv::Fast) 1903 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_FastCC); 1904 else 1905 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false); 1906 1907 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 1908 CCValAssign &VA = ArgLocs[i]; 1909 SDValue ArgValue; 1910 // Passing f64 on RV32D with a soft float ABI must be handled as a special 1911 // case. 1912 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 1913 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 1914 else if (VA.isRegLoc()) 1915 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL); 1916 else 1917 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 1918 1919 if (VA.getLocInfo() == CCValAssign::Indirect) { 1920 // If the original argument was split and passed by reference (e.g. i128 1921 // on RV32), we need to load all parts of it here (using the same 1922 // address). 1923 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 1924 MachinePointerInfo())); 1925 unsigned ArgIndex = Ins[i].OrigArgIndex; 1926 assert(Ins[i].PartOffset == 0); 1927 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 1928 CCValAssign &PartVA = ArgLocs[i + 1]; 1929 unsigned PartOffset = Ins[i + 1].PartOffset; 1930 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, 1931 DAG.getIntPtrConstant(PartOffset, DL)); 1932 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 1933 MachinePointerInfo())); 1934 ++i; 1935 } 1936 continue; 1937 } 1938 InVals.push_back(ArgValue); 1939 } 1940 1941 if (IsVarArg) { 1942 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 1943 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 1944 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 1945 MachineFrameInfo &MFI = MF.getFrameInfo(); 1946 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 1947 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 1948 1949 // Offset of the first variable argument from stack pointer, and size of 1950 // the vararg save area. For now, the varargs save area is either zero or 1951 // large enough to hold a0-a7. 1952 int VaArgOffset, VarArgsSaveSize; 1953 1954 // If all registers are allocated, then all varargs must be passed on the 1955 // stack and we don't need to save any argregs. 1956 if (ArgRegs.size() == Idx) { 1957 VaArgOffset = CCInfo.getNextStackOffset(); 1958 VarArgsSaveSize = 0; 1959 } else { 1960 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 1961 VaArgOffset = -VarArgsSaveSize; 1962 } 1963 1964 // Record the frame index of the first variable argument 1965 // which is a value necessary to VASTART. 1966 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 1967 RVFI->setVarArgsFrameIndex(FI); 1968 1969 // If saving an odd number of registers then create an extra stack slot to 1970 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 1971 // offsets to even-numbered registered remain 2*XLEN-aligned. 1972 if (Idx % 2) { 1973 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 1974 VarArgsSaveSize += XLenInBytes; 1975 } 1976 1977 // Copy the integer registers that may have been used for passing varargs 1978 // to the vararg save area. 1979 for (unsigned I = Idx; I < ArgRegs.size(); 1980 ++I, VaArgOffset += XLenInBytes) { 1981 const Register Reg = RegInfo.createVirtualRegister(RC); 1982 RegInfo.addLiveIn(ArgRegs[I], Reg); 1983 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 1984 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 1985 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 1986 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 1987 MachinePointerInfo::getFixedStack(MF, FI)); 1988 cast<StoreSDNode>(Store.getNode()) 1989 ->getMemOperand() 1990 ->setValue((Value *)nullptr); 1991 OutChains.push_back(Store); 1992 } 1993 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 1994 } 1995 1996 // All stores are grouped in one node to allow the matching between 1997 // the size of Ins and InVals. This only happens for vararg functions. 1998 if (!OutChains.empty()) { 1999 OutChains.push_back(Chain); 2000 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 2001 } 2002 2003 return Chain; 2004 } 2005 2006 /// isEligibleForTailCallOptimization - Check whether the call is eligible 2007 /// for tail call optimization. 2008 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 2009 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 2010 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 2011 const SmallVector<CCValAssign, 16> &ArgLocs) const { 2012 2013 auto &Callee = CLI.Callee; 2014 auto CalleeCC = CLI.CallConv; 2015 auto &Outs = CLI.Outs; 2016 auto &Caller = MF.getFunction(); 2017 auto CallerCC = Caller.getCallingConv(); 2018 2019 // Do not tail call opt functions with "disable-tail-calls" attribute. 2020 if (Caller.getFnAttribute("disable-tail-calls").getValueAsString() == "true") 2021 return false; 2022 2023 // Exception-handling functions need a special set of instructions to 2024 // indicate a return to the hardware. Tail-calling another function would 2025 // probably break this. 2026 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 2027 // should be expanded as new function attributes are introduced. 2028 if (Caller.hasFnAttribute("interrupt")) 2029 return false; 2030 2031 // Do not tail call opt if the stack is used to pass parameters. 2032 if (CCInfo.getNextStackOffset() != 0) 2033 return false; 2034 2035 // Do not tail call opt if any parameters need to be passed indirectly. 2036 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 2037 // passed indirectly. So the address of the value will be passed in a 2038 // register, or if not available, then the address is put on the stack. In 2039 // order to pass indirectly, space on the stack often needs to be allocated 2040 // in order to store the value. In this case the CCInfo.getNextStackOffset() 2041 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 2042 // are passed CCValAssign::Indirect. 2043 for (auto &VA : ArgLocs) 2044 if (VA.getLocInfo() == CCValAssign::Indirect) 2045 return false; 2046 2047 // Do not tail call opt if either caller or callee uses struct return 2048 // semantics. 2049 auto IsCallerStructRet = Caller.hasStructRetAttr(); 2050 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 2051 if (IsCallerStructRet || IsCalleeStructRet) 2052 return false; 2053 2054 // Externally-defined functions with weak linkage should not be 2055 // tail-called. The behaviour of branch instructions in this situation (as 2056 // used for tail calls) is implementation-defined, so we cannot rely on the 2057 // linker replacing the tail call with a return. 2058 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2059 const GlobalValue *GV = G->getGlobal(); 2060 if (GV->hasExternalWeakLinkage()) 2061 return false; 2062 } 2063 2064 // The callee has to preserve all registers the caller needs to preserve. 2065 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 2066 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2067 if (CalleeCC != CallerCC) { 2068 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2069 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2070 return false; 2071 } 2072 2073 // Byval parameters hand the function a pointer directly into the stack area 2074 // we want to reuse during a tail call. Working around this *is* possible 2075 // but less efficient and uglier in LowerCall. 2076 for (auto &Arg : Outs) 2077 if (Arg.Flags.isByVal()) 2078 return false; 2079 2080 return true; 2081 } 2082 2083 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 2084 // and output parameter nodes. 2085 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 2086 SmallVectorImpl<SDValue> &InVals) const { 2087 SelectionDAG &DAG = CLI.DAG; 2088 SDLoc &DL = CLI.DL; 2089 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 2090 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 2091 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 2092 SDValue Chain = CLI.Chain; 2093 SDValue Callee = CLI.Callee; 2094 bool &IsTailCall = CLI.IsTailCall; 2095 CallingConv::ID CallConv = CLI.CallConv; 2096 bool IsVarArg = CLI.IsVarArg; 2097 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2098 MVT XLenVT = Subtarget.getXLenVT(); 2099 2100 MachineFunction &MF = DAG.getMachineFunction(); 2101 2102 // Analyze the operands of the call, assigning locations to each operand. 2103 SmallVector<CCValAssign, 16> ArgLocs; 2104 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2105 2106 if (CallConv == CallingConv::Fast) 2107 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_FastCC); 2108 else 2109 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI); 2110 2111 // Check if it's really possible to do a tail call. 2112 if (IsTailCall) 2113 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 2114 2115 if (IsTailCall) 2116 ++NumTailCalls; 2117 else if (CLI.CS && CLI.CS.isMustTailCall()) 2118 report_fatal_error("failed to perform tail call elimination on a call " 2119 "site marked musttail"); 2120 2121 // Get a count of how many bytes are to be pushed on the stack. 2122 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 2123 2124 // Create local copies for byval args 2125 SmallVector<SDValue, 8> ByValArgs; 2126 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 2127 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2128 if (!Flags.isByVal()) 2129 continue; 2130 2131 SDValue Arg = OutVals[i]; 2132 unsigned Size = Flags.getByValSize(); 2133 unsigned Align = Flags.getByValAlign(); 2134 2135 int FI = MF.getFrameInfo().CreateStackObject(Size, Align, /*isSS=*/false); 2136 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 2137 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 2138 2139 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Align, 2140 /*IsVolatile=*/false, 2141 /*AlwaysInline=*/false, 2142 IsTailCall, MachinePointerInfo(), 2143 MachinePointerInfo()); 2144 ByValArgs.push_back(FIPtr); 2145 } 2146 2147 if (!IsTailCall) 2148 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 2149 2150 // Copy argument values to their designated locations. 2151 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 2152 SmallVector<SDValue, 8> MemOpChains; 2153 SDValue StackPtr; 2154 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 2155 CCValAssign &VA = ArgLocs[i]; 2156 SDValue ArgValue = OutVals[i]; 2157 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2158 2159 // Handle passing f64 on RV32D with a soft float ABI as a special case. 2160 bool IsF64OnRV32DSoftABI = 2161 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 2162 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 2163 SDValue SplitF64 = DAG.getNode( 2164 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 2165 SDValue Lo = SplitF64.getValue(0); 2166 SDValue Hi = SplitF64.getValue(1); 2167 2168 Register RegLo = VA.getLocReg(); 2169 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 2170 2171 if (RegLo == RISCV::X17) { 2172 // Second half of f64 is passed on the stack. 2173 // Work out the address of the stack slot. 2174 if (!StackPtr.getNode()) 2175 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 2176 // Emit the store. 2177 MemOpChains.push_back( 2178 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 2179 } else { 2180 // Second half of f64 is passed in another GPR. 2181 assert(RegLo < RISCV::X31 && "Invalid register pair"); 2182 Register RegHigh = RegLo + 1; 2183 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 2184 } 2185 continue; 2186 } 2187 2188 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 2189 // as any other MemLoc. 2190 2191 // Promote the value if needed. 2192 // For now, only handle fully promoted and indirect arguments. 2193 if (VA.getLocInfo() == CCValAssign::Indirect) { 2194 // Store the argument in a stack slot and pass its address. 2195 SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT); 2196 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 2197 MemOpChains.push_back( 2198 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 2199 MachinePointerInfo::getFixedStack(MF, FI))); 2200 // If the original argument was split (e.g. i128), we need 2201 // to store all parts of it here (and pass just one address). 2202 unsigned ArgIndex = Outs[i].OrigArgIndex; 2203 assert(Outs[i].PartOffset == 0); 2204 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 2205 SDValue PartValue = OutVals[i + 1]; 2206 unsigned PartOffset = Outs[i + 1].PartOffset; 2207 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, 2208 DAG.getIntPtrConstant(PartOffset, DL)); 2209 MemOpChains.push_back( 2210 DAG.getStore(Chain, DL, PartValue, Address, 2211 MachinePointerInfo::getFixedStack(MF, FI))); 2212 ++i; 2213 } 2214 ArgValue = SpillSlot; 2215 } else { 2216 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL); 2217 } 2218 2219 // Use local copy if it is a byval arg. 2220 if (Flags.isByVal()) 2221 ArgValue = ByValArgs[j++]; 2222 2223 if (VA.isRegLoc()) { 2224 // Queue up the argument copies and emit them at the end. 2225 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 2226 } else { 2227 assert(VA.isMemLoc() && "Argument not register or memory"); 2228 assert(!IsTailCall && "Tail call not allowed if stack is used " 2229 "for passing parameters"); 2230 2231 // Work out the address of the stack slot. 2232 if (!StackPtr.getNode()) 2233 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 2234 SDValue Address = 2235 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 2236 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 2237 2238 // Emit the store. 2239 MemOpChains.push_back( 2240 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 2241 } 2242 } 2243 2244 // Join the stores, which are independent of one another. 2245 if (!MemOpChains.empty()) 2246 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2247 2248 SDValue Glue; 2249 2250 // Build a sequence of copy-to-reg nodes, chained and glued together. 2251 for (auto &Reg : RegsToPass) { 2252 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 2253 Glue = Chain.getValue(1); 2254 } 2255 2256 // Validate that none of the argument registers have been marked as 2257 // reserved, if so report an error. Do the same for the return address if this 2258 // is not a tailcall. 2259 validateCCReservedRegs(RegsToPass, MF); 2260 if (!IsTailCall && 2261 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 2262 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 2263 MF.getFunction(), 2264 "Return address register required, but has been reserved."}); 2265 2266 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 2267 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 2268 // split it and then direct call can be matched by PseudoCALL. 2269 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 2270 const GlobalValue *GV = S->getGlobal(); 2271 2272 unsigned OpFlags = RISCVII::MO_CALL; 2273 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 2274 OpFlags = RISCVII::MO_PLT; 2275 2276 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 2277 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2278 unsigned OpFlags = RISCVII::MO_CALL; 2279 2280 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 2281 nullptr)) 2282 OpFlags = RISCVII::MO_PLT; 2283 2284 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 2285 } 2286 2287 // The first call operand is the chain and the second is the target address. 2288 SmallVector<SDValue, 8> Ops; 2289 Ops.push_back(Chain); 2290 Ops.push_back(Callee); 2291 2292 // Add argument registers to the end of the list so that they are 2293 // known live into the call. 2294 for (auto &Reg : RegsToPass) 2295 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 2296 2297 if (!IsTailCall) { 2298 // Add a register mask operand representing the call-preserved registers. 2299 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 2300 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2301 assert(Mask && "Missing call preserved mask for calling convention"); 2302 Ops.push_back(DAG.getRegisterMask(Mask)); 2303 } 2304 2305 // Glue the call to the argument copies, if any. 2306 if (Glue.getNode()) 2307 Ops.push_back(Glue); 2308 2309 // Emit the call. 2310 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2311 2312 if (IsTailCall) { 2313 MF.getFrameInfo().setHasTailCall(); 2314 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 2315 } 2316 2317 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 2318 Glue = Chain.getValue(1); 2319 2320 // Mark the end of the call, which is glued to the call itself. 2321 Chain = DAG.getCALLSEQ_END(Chain, 2322 DAG.getConstant(NumBytes, DL, PtrVT, true), 2323 DAG.getConstant(0, DL, PtrVT, true), 2324 Glue, DL); 2325 Glue = Chain.getValue(1); 2326 2327 // Assign locations to each value returned by this call. 2328 SmallVector<CCValAssign, 16> RVLocs; 2329 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 2330 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true); 2331 2332 // Copy all of the result registers out of their specified physreg. 2333 for (auto &VA : RVLocs) { 2334 // Copy the value out 2335 SDValue RetValue = 2336 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 2337 // Glue the RetValue to the end of the call sequence 2338 Chain = RetValue.getValue(1); 2339 Glue = RetValue.getValue(2); 2340 2341 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 2342 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 2343 SDValue RetValue2 = 2344 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 2345 Chain = RetValue2.getValue(1); 2346 Glue = RetValue2.getValue(2); 2347 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 2348 RetValue2); 2349 } 2350 2351 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL); 2352 2353 InVals.push_back(RetValue); 2354 } 2355 2356 return Chain; 2357 } 2358 2359 bool RISCVTargetLowering::CanLowerReturn( 2360 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 2361 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 2362 SmallVector<CCValAssign, 16> RVLocs; 2363 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2364 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 2365 MVT VT = Outs[i].VT; 2366 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 2367 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 2368 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 2369 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr)) 2370 return false; 2371 } 2372 return true; 2373 } 2374 2375 SDValue 2376 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2377 bool IsVarArg, 2378 const SmallVectorImpl<ISD::OutputArg> &Outs, 2379 const SmallVectorImpl<SDValue> &OutVals, 2380 const SDLoc &DL, SelectionDAG &DAG) const { 2381 const MachineFunction &MF = DAG.getMachineFunction(); 2382 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 2383 2384 // Stores the assignment of the return value to a location. 2385 SmallVector<CCValAssign, 16> RVLocs; 2386 2387 // Info about the registers and stack slot. 2388 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2389 *DAG.getContext()); 2390 2391 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 2392 nullptr); 2393 2394 SDValue Glue; 2395 SmallVector<SDValue, 4> RetOps(1, Chain); 2396 2397 // Copy the result values into the output registers. 2398 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 2399 SDValue Val = OutVals[i]; 2400 CCValAssign &VA = RVLocs[i]; 2401 assert(VA.isRegLoc() && "Can only return in registers!"); 2402 2403 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 2404 // Handle returning f64 on RV32D with a soft float ABI. 2405 assert(VA.isRegLoc() && "Expected return via registers"); 2406 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 2407 DAG.getVTList(MVT::i32, MVT::i32), Val); 2408 SDValue Lo = SplitF64.getValue(0); 2409 SDValue Hi = SplitF64.getValue(1); 2410 Register RegLo = VA.getLocReg(); 2411 assert(RegLo < RISCV::X31 && "Invalid register pair"); 2412 Register RegHi = RegLo + 1; 2413 2414 if (STI.isRegisterReservedByUser(RegLo) || 2415 STI.isRegisterReservedByUser(RegHi)) 2416 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 2417 MF.getFunction(), 2418 "Return value register required, but has been reserved."}); 2419 2420 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 2421 Glue = Chain.getValue(1); 2422 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 2423 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 2424 Glue = Chain.getValue(1); 2425 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 2426 } else { 2427 // Handle a 'normal' return. 2428 Val = convertValVTToLocVT(DAG, Val, VA, DL); 2429 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 2430 2431 if (STI.isRegisterReservedByUser(VA.getLocReg())) 2432 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 2433 MF.getFunction(), 2434 "Return value register required, but has been reserved."}); 2435 2436 // Guarantee that all emitted copies are stuck together. 2437 Glue = Chain.getValue(1); 2438 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2439 } 2440 } 2441 2442 RetOps[0] = Chain; // Update chain. 2443 2444 // Add the glue node if we have it. 2445 if (Glue.getNode()) { 2446 RetOps.push_back(Glue); 2447 } 2448 2449 // Interrupt service routines use different return instructions. 2450 const Function &Func = DAG.getMachineFunction().getFunction(); 2451 if (Func.hasFnAttribute("interrupt")) { 2452 if (!Func.getReturnType()->isVoidTy()) 2453 report_fatal_error( 2454 "Functions with the interrupt attribute must have void return type!"); 2455 2456 MachineFunction &MF = DAG.getMachineFunction(); 2457 StringRef Kind = 2458 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 2459 2460 unsigned RetOpc; 2461 if (Kind == "user") 2462 RetOpc = RISCVISD::URET_FLAG; 2463 else if (Kind == "supervisor") 2464 RetOpc = RISCVISD::SRET_FLAG; 2465 else 2466 RetOpc = RISCVISD::MRET_FLAG; 2467 2468 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 2469 } 2470 2471 return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps); 2472 } 2473 2474 void RISCVTargetLowering::validateCCReservedRegs( 2475 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 2476 MachineFunction &MF) const { 2477 const Function &F = MF.getFunction(); 2478 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 2479 2480 if (std::any_of(std::begin(Regs), std::end(Regs), [&STI](auto Reg) { 2481 return STI.isRegisterReservedByUser(Reg.first); 2482 })) 2483 F.getContext().diagnose(DiagnosticInfoUnsupported{ 2484 F, "Argument register required, but has been reserved."}); 2485 } 2486 2487 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 2488 switch ((RISCVISD::NodeType)Opcode) { 2489 case RISCVISD::FIRST_NUMBER: 2490 break; 2491 case RISCVISD::RET_FLAG: 2492 return "RISCVISD::RET_FLAG"; 2493 case RISCVISD::URET_FLAG: 2494 return "RISCVISD::URET_FLAG"; 2495 case RISCVISD::SRET_FLAG: 2496 return "RISCVISD::SRET_FLAG"; 2497 case RISCVISD::MRET_FLAG: 2498 return "RISCVISD::MRET_FLAG"; 2499 case RISCVISD::CALL: 2500 return "RISCVISD::CALL"; 2501 case RISCVISD::SELECT_CC: 2502 return "RISCVISD::SELECT_CC"; 2503 case RISCVISD::BuildPairF64: 2504 return "RISCVISD::BuildPairF64"; 2505 case RISCVISD::SplitF64: 2506 return "RISCVISD::SplitF64"; 2507 case RISCVISD::TAIL: 2508 return "RISCVISD::TAIL"; 2509 case RISCVISD::SLLW: 2510 return "RISCVISD::SLLW"; 2511 case RISCVISD::SRAW: 2512 return "RISCVISD::SRAW"; 2513 case RISCVISD::SRLW: 2514 return "RISCVISD::SRLW"; 2515 case RISCVISD::DIVW: 2516 return "RISCVISD::DIVW"; 2517 case RISCVISD::DIVUW: 2518 return "RISCVISD::DIVUW"; 2519 case RISCVISD::REMUW: 2520 return "RISCVISD::REMUW"; 2521 case RISCVISD::FMV_W_X_RV64: 2522 return "RISCVISD::FMV_W_X_RV64"; 2523 case RISCVISD::FMV_X_ANYEXTW_RV64: 2524 return "RISCVISD::FMV_X_ANYEXTW_RV64"; 2525 case RISCVISD::READ_CYCLE_WIDE: 2526 return "RISCVISD::READ_CYCLE_WIDE"; 2527 } 2528 return nullptr; 2529 } 2530 2531 /// getConstraintType - Given a constraint letter, return the type of 2532 /// constraint it is for this target. 2533 RISCVTargetLowering::ConstraintType 2534 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 2535 if (Constraint.size() == 1) { 2536 switch (Constraint[0]) { 2537 default: 2538 break; 2539 case 'f': 2540 return C_RegisterClass; 2541 case 'I': 2542 case 'J': 2543 case 'K': 2544 return C_Immediate; 2545 case 'A': 2546 return C_Memory; 2547 } 2548 } 2549 return TargetLowering::getConstraintType(Constraint); 2550 } 2551 2552 std::pair<unsigned, const TargetRegisterClass *> 2553 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 2554 StringRef Constraint, 2555 MVT VT) const { 2556 // First, see if this is a constraint that directly corresponds to a 2557 // RISCV register class. 2558 if (Constraint.size() == 1) { 2559 switch (Constraint[0]) { 2560 case 'r': 2561 return std::make_pair(0U, &RISCV::GPRRegClass); 2562 case 'f': 2563 if (Subtarget.hasStdExtF() && VT == MVT::f32) 2564 return std::make_pair(0U, &RISCV::FPR32RegClass); 2565 if (Subtarget.hasStdExtD() && VT == MVT::f64) 2566 return std::make_pair(0U, &RISCV::FPR64RegClass); 2567 break; 2568 default: 2569 break; 2570 } 2571 } 2572 2573 // Clang will correctly decode the usage of register name aliases into their 2574 // official names. However, other frontends like `rustc` do not. This allows 2575 // users of these frontends to use the ABI names for registers in LLVM-style 2576 // register constraints. 2577 Register XRegFromAlias = StringSwitch<Register>(Constraint.lower()) 2578 .Case("{zero}", RISCV::X0) 2579 .Case("{ra}", RISCV::X1) 2580 .Case("{sp}", RISCV::X2) 2581 .Case("{gp}", RISCV::X3) 2582 .Case("{tp}", RISCV::X4) 2583 .Case("{t0}", RISCV::X5) 2584 .Case("{t1}", RISCV::X6) 2585 .Case("{t2}", RISCV::X7) 2586 .Cases("{s0}", "{fp}", RISCV::X8) 2587 .Case("{s1}", RISCV::X9) 2588 .Case("{a0}", RISCV::X10) 2589 .Case("{a1}", RISCV::X11) 2590 .Case("{a2}", RISCV::X12) 2591 .Case("{a3}", RISCV::X13) 2592 .Case("{a4}", RISCV::X14) 2593 .Case("{a5}", RISCV::X15) 2594 .Case("{a6}", RISCV::X16) 2595 .Case("{a7}", RISCV::X17) 2596 .Case("{s2}", RISCV::X18) 2597 .Case("{s3}", RISCV::X19) 2598 .Case("{s4}", RISCV::X20) 2599 .Case("{s5}", RISCV::X21) 2600 .Case("{s6}", RISCV::X22) 2601 .Case("{s7}", RISCV::X23) 2602 .Case("{s8}", RISCV::X24) 2603 .Case("{s9}", RISCV::X25) 2604 .Case("{s10}", RISCV::X26) 2605 .Case("{s11}", RISCV::X27) 2606 .Case("{t3}", RISCV::X28) 2607 .Case("{t4}", RISCV::X29) 2608 .Case("{t5}", RISCV::X30) 2609 .Case("{t6}", RISCV::X31) 2610 .Default(RISCV::NoRegister); 2611 if (XRegFromAlias != RISCV::NoRegister) 2612 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 2613 2614 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 2615 // TableGen record rather than the AsmName to choose registers for InlineAsm 2616 // constraints, plus we want to match those names to the widest floating point 2617 // register type available, manually select floating point registers here. 2618 // 2619 // The second case is the ABI name of the register, so that frontends can also 2620 // use the ABI names in register constraint lists. 2621 if (Subtarget.hasStdExtF() || Subtarget.hasStdExtD()) { 2622 std::pair<Register, Register> FReg = 2623 StringSwitch<std::pair<Register, Register>>(Constraint.lower()) 2624 .Cases("{f0}", "{ft0}", {RISCV::F0_F, RISCV::F0_D}) 2625 .Cases("{f1}", "{ft1}", {RISCV::F1_F, RISCV::F1_D}) 2626 .Cases("{f2}", "{ft2}", {RISCV::F2_F, RISCV::F2_D}) 2627 .Cases("{f3}", "{ft3}", {RISCV::F3_F, RISCV::F3_D}) 2628 .Cases("{f4}", "{ft4}", {RISCV::F4_F, RISCV::F4_D}) 2629 .Cases("{f5}", "{ft5}", {RISCV::F5_F, RISCV::F5_D}) 2630 .Cases("{f6}", "{ft6}", {RISCV::F6_F, RISCV::F6_D}) 2631 .Cases("{f7}", "{ft7}", {RISCV::F7_F, RISCV::F7_D}) 2632 .Cases("{f8}", "{fs0}", {RISCV::F8_F, RISCV::F8_D}) 2633 .Cases("{f9}", "{fs1}", {RISCV::F9_F, RISCV::F9_D}) 2634 .Cases("{f10}", "{fa0}", {RISCV::F10_F, RISCV::F10_D}) 2635 .Cases("{f11}", "{fa1}", {RISCV::F11_F, RISCV::F11_D}) 2636 .Cases("{f12}", "{fa2}", {RISCV::F12_F, RISCV::F12_D}) 2637 .Cases("{f13}", "{fa3}", {RISCV::F13_F, RISCV::F13_D}) 2638 .Cases("{f14}", "{fa4}", {RISCV::F14_F, RISCV::F14_D}) 2639 .Cases("{f15}", "{fa5}", {RISCV::F15_F, RISCV::F15_D}) 2640 .Cases("{f16}", "{fa6}", {RISCV::F16_F, RISCV::F16_D}) 2641 .Cases("{f17}", "{fa7}", {RISCV::F17_F, RISCV::F17_D}) 2642 .Cases("{f18}", "{fs2}", {RISCV::F18_F, RISCV::F18_D}) 2643 .Cases("{f19}", "{fs3}", {RISCV::F19_F, RISCV::F19_D}) 2644 .Cases("{f20}", "{fs4}", {RISCV::F20_F, RISCV::F20_D}) 2645 .Cases("{f21}", "{fs5}", {RISCV::F21_F, RISCV::F21_D}) 2646 .Cases("{f22}", "{fs6}", {RISCV::F22_F, RISCV::F22_D}) 2647 .Cases("{f23}", "{fs7}", {RISCV::F23_F, RISCV::F23_D}) 2648 .Cases("{f24}", "{fs8}", {RISCV::F24_F, RISCV::F24_D}) 2649 .Cases("{f25}", "{fs9}", {RISCV::F25_F, RISCV::F25_D}) 2650 .Cases("{f26}", "{fs10}", {RISCV::F26_F, RISCV::F26_D}) 2651 .Cases("{f27}", "{fs11}", {RISCV::F27_F, RISCV::F27_D}) 2652 .Cases("{f28}", "{ft8}", {RISCV::F28_F, RISCV::F28_D}) 2653 .Cases("{f29}", "{ft9}", {RISCV::F29_F, RISCV::F29_D}) 2654 .Cases("{f30}", "{ft10}", {RISCV::F30_F, RISCV::F30_D}) 2655 .Cases("{f31}", "{ft11}", {RISCV::F31_F, RISCV::F31_D}) 2656 .Default({RISCV::NoRegister, RISCV::NoRegister}); 2657 if (FReg.first != RISCV::NoRegister) 2658 return Subtarget.hasStdExtD() 2659 ? std::make_pair(FReg.second, &RISCV::FPR64RegClass) 2660 : std::make_pair(FReg.first, &RISCV::FPR32RegClass); 2661 } 2662 2663 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 2664 } 2665 2666 unsigned 2667 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 2668 // Currently only support length 1 constraints. 2669 if (ConstraintCode.size() == 1) { 2670 switch (ConstraintCode[0]) { 2671 case 'A': 2672 return InlineAsm::Constraint_A; 2673 default: 2674 break; 2675 } 2676 } 2677 2678 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 2679 } 2680 2681 void RISCVTargetLowering::LowerAsmOperandForConstraint( 2682 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 2683 SelectionDAG &DAG) const { 2684 // Currently only support length 1 constraints. 2685 if (Constraint.length() == 1) { 2686 switch (Constraint[0]) { 2687 case 'I': 2688 // Validate & create a 12-bit signed immediate operand. 2689 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2690 uint64_t CVal = C->getSExtValue(); 2691 if (isInt<12>(CVal)) 2692 Ops.push_back( 2693 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 2694 } 2695 return; 2696 case 'J': 2697 // Validate & create an integer zero operand. 2698 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 2699 if (C->getZExtValue() == 0) 2700 Ops.push_back( 2701 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 2702 return; 2703 case 'K': 2704 // Validate & create a 5-bit unsigned immediate operand. 2705 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2706 uint64_t CVal = C->getZExtValue(); 2707 if (isUInt<5>(CVal)) 2708 Ops.push_back( 2709 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 2710 } 2711 return; 2712 default: 2713 break; 2714 } 2715 } 2716 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 2717 } 2718 2719 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 2720 Instruction *Inst, 2721 AtomicOrdering Ord) const { 2722 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 2723 return Builder.CreateFence(Ord); 2724 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 2725 return Builder.CreateFence(AtomicOrdering::Release); 2726 return nullptr; 2727 } 2728 2729 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 2730 Instruction *Inst, 2731 AtomicOrdering Ord) const { 2732 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 2733 return Builder.CreateFence(AtomicOrdering::Acquire); 2734 return nullptr; 2735 } 2736 2737 TargetLowering::AtomicExpansionKind 2738 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 2739 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 2740 // point operations can't be used in an lr/sc sequence without breaking the 2741 // forward-progress guarantee. 2742 if (AI->isFloatingPointOperation()) 2743 return AtomicExpansionKind::CmpXChg; 2744 2745 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 2746 if (Size == 8 || Size == 16) 2747 return AtomicExpansionKind::MaskedIntrinsic; 2748 return AtomicExpansionKind::None; 2749 } 2750 2751 static Intrinsic::ID 2752 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 2753 if (XLen == 32) { 2754 switch (BinOp) { 2755 default: 2756 llvm_unreachable("Unexpected AtomicRMW BinOp"); 2757 case AtomicRMWInst::Xchg: 2758 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 2759 case AtomicRMWInst::Add: 2760 return Intrinsic::riscv_masked_atomicrmw_add_i32; 2761 case AtomicRMWInst::Sub: 2762 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 2763 case AtomicRMWInst::Nand: 2764 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 2765 case AtomicRMWInst::Max: 2766 return Intrinsic::riscv_masked_atomicrmw_max_i32; 2767 case AtomicRMWInst::Min: 2768 return Intrinsic::riscv_masked_atomicrmw_min_i32; 2769 case AtomicRMWInst::UMax: 2770 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 2771 case AtomicRMWInst::UMin: 2772 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 2773 } 2774 } 2775 2776 if (XLen == 64) { 2777 switch (BinOp) { 2778 default: 2779 llvm_unreachable("Unexpected AtomicRMW BinOp"); 2780 case AtomicRMWInst::Xchg: 2781 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 2782 case AtomicRMWInst::Add: 2783 return Intrinsic::riscv_masked_atomicrmw_add_i64; 2784 case AtomicRMWInst::Sub: 2785 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 2786 case AtomicRMWInst::Nand: 2787 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 2788 case AtomicRMWInst::Max: 2789 return Intrinsic::riscv_masked_atomicrmw_max_i64; 2790 case AtomicRMWInst::Min: 2791 return Intrinsic::riscv_masked_atomicrmw_min_i64; 2792 case AtomicRMWInst::UMax: 2793 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 2794 case AtomicRMWInst::UMin: 2795 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 2796 } 2797 } 2798 2799 llvm_unreachable("Unexpected XLen\n"); 2800 } 2801 2802 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 2803 IRBuilder<> &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 2804 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 2805 unsigned XLen = Subtarget.getXLen(); 2806 Value *Ordering = 2807 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 2808 Type *Tys[] = {AlignedAddr->getType()}; 2809 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 2810 AI->getModule(), 2811 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 2812 2813 if (XLen == 64) { 2814 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 2815 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 2816 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 2817 } 2818 2819 Value *Result; 2820 2821 // Must pass the shift amount needed to sign extend the loaded value prior 2822 // to performing a signed comparison for min/max. ShiftAmt is the number of 2823 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 2824 // is the number of bits to left+right shift the value in order to 2825 // sign-extend. 2826 if (AI->getOperation() == AtomicRMWInst::Min || 2827 AI->getOperation() == AtomicRMWInst::Max) { 2828 const DataLayout &DL = AI->getModule()->getDataLayout(); 2829 unsigned ValWidth = 2830 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 2831 Value *SextShamt = 2832 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 2833 Result = Builder.CreateCall(LrwOpScwLoop, 2834 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 2835 } else { 2836 Result = 2837 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 2838 } 2839 2840 if (XLen == 64) 2841 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 2842 return Result; 2843 } 2844 2845 TargetLowering::AtomicExpansionKind 2846 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 2847 AtomicCmpXchgInst *CI) const { 2848 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 2849 if (Size == 8 || Size == 16) 2850 return AtomicExpansionKind::MaskedIntrinsic; 2851 return AtomicExpansionKind::None; 2852 } 2853 2854 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 2855 IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 2856 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 2857 unsigned XLen = Subtarget.getXLen(); 2858 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 2859 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 2860 if (XLen == 64) { 2861 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 2862 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 2863 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 2864 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 2865 } 2866 Type *Tys[] = {AlignedAddr->getType()}; 2867 Function *MaskedCmpXchg = 2868 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 2869 Value *Result = Builder.CreateCall( 2870 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 2871 if (XLen == 64) 2872 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 2873 return Result; 2874 } 2875 2876 unsigned RISCVTargetLowering::getExceptionPointerRegister( 2877 const Constant *PersonalityFn) const { 2878 return RISCV::X10; 2879 } 2880 2881 unsigned RISCVTargetLowering::getExceptionSelectorRegister( 2882 const Constant *PersonalityFn) const { 2883 return RISCV::X11; 2884 } 2885 2886 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 2887 // Return false to suppress the unnecessary extensions if the LibCall 2888 // arguments or return value is f32 type for LP64 ABI. 2889 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 2890 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 2891 return false; 2892 2893 return true; 2894 } 2895 2896 #define GET_REGISTER_MATCHER 2897 #include "RISCVGenAsmMatcher.inc" 2898 2899 Register 2900 RISCVTargetLowering::getRegisterByName(const char *RegName, EVT VT, 2901 const MachineFunction &MF) const { 2902 Register Reg = MatchRegisterAltName(RegName); 2903 if (Reg == RISCV::NoRegister) 2904 Reg = MatchRegisterName(RegName); 2905 if (Reg == RISCV::NoRegister) 2906 report_fatal_error( 2907 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 2908 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 2909 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 2910 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 2911 StringRef(RegName) + "\".")); 2912 return Reg; 2913 } 2914