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