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